merge: integrate subcontractor, org-settings & commission features from project-refinement

# Conflicts:
#	src/App.jsx
#	src/components/Layout.jsx
#	src/data/mockStore.jsx
#	src/pages/LeadsListPage.jsx
#	src/pages/owner/OwnerProjectDetail.jsx
#	src/pages/owner/OwnerSnapshot.jsx
This commit is contained in:
Satyam Rastogi
2026-05-29 01:11:03 +05:30
13 changed files with 5564 additions and 229 deletions
+22
View File
@@ -20,6 +20,7 @@ import DocumentManagement from './pages/owner/DocumentManagement';
import OwnerProjectList from './pages/owner/OwnerProjectList'; import OwnerProjectList from './pages/owner/OwnerProjectList';
import OwnerProjectDetail from './pages/owner/OwnerProjectDetail'; import OwnerProjectDetail from './pages/owner/OwnerProjectDetail';
import OrgSettings from './pages/owner/OrgSettings'; import OrgSettings from './pages/owner/OrgSettings';
import SubcontractorTasksPage from './pages/owner/SubcontractorTasksPage';
import PlaceholderDashboard from './pages/PlaceholderDashboard'; import PlaceholderDashboard from './pages/PlaceholderDashboard';
import ProCanvas from './pages/ProCanvas'; import ProCanvas from './pages/ProCanvas';
import ProjectList from './pages/contractor/ProjectList'; import ProjectList from './pages/contractor/ProjectList';
@@ -30,6 +31,7 @@ import VendorDashboard from './pages/vendor/VendorDashboard';
import VendorOrders from './pages/vendor/VendorOrders'; import VendorOrders from './pages/vendor/VendorOrders';
import ContractorDashboard from './pages/contractor/ContractorDashboard'; import ContractorDashboard from './pages/contractor/ContractorDashboard';
import SubContractorDashboard from './pages/subcontractor/SubContractorDashboard'; import SubContractorDashboard from './pages/subcontractor/SubContractorDashboard';
import SubcontractorTaskDetailPage from './pages/subcontractor/SubcontractorTaskDetailPage';
import CreateLeadPage from './pages/CreateLeadPage'; import CreateLeadPage from './pages/CreateLeadPage';
import LeadsListPage from './pages/LeadsListPage'; import LeadsListPage from './pages/LeadsListPage';
import LynkDispatchPage from './pages/LynkDispatchPage'; import LynkDispatchPage from './pages/LynkDispatchPage';
@@ -221,6 +223,21 @@ function App() {
<OrgSettings /> <OrgSettings />
</ProtectedRoute> </ProtectedRoute>
} /> } />
<Route path="/admin/settings" element={
<ProtectedRoute allowedRoles={['ADMIN']}>
<OrgSettings />
</ProtectedRoute>
} />
<Route path="/owner/subcontractor-tasks" element={
<ProtectedRoute allowedRoles={['OWNER']}>
<SubcontractorTasksPage />
</ProtectedRoute>
} />
<Route path="/admin/subcontractor-tasks" element={
<ProtectedRoute allowedRoles={['ADMIN', 'OWNER']}>
<SubcontractorTasksPage />
</ProtectedRoute>
} />
{/* Protected Admin Routes — Owner has full admin access */} {/* Protected Admin Routes — Owner has full admin access */}
<Route <Route
@@ -372,6 +389,11 @@ function App() {
<ProjectList /> <ProjectList />
</ProtectedRoute> </ProtectedRoute>
} /> } />
<Route path="/subcontractor/tasks/:taskId" element={
<ProtectedRoute allowedRoles={['SUBCONTRACTOR']}>
<SubcontractorTaskDetailPage />
</ProtectedRoute>
} />
</Route> </Route>
{/* Catch all */} {/* Catch all */}
+5 -2
View File
@@ -5,7 +5,8 @@ import { useTheme } from '../context/ThemeContext';
import { import {
LayoutDashboard, Map, Calendar, LogOut, User, Home, MessageSquare, LayoutDashboard, Map, Calendar, LogOut, User, Home, MessageSquare,
ChevronLeft, ChevronRight, Sun, Moon, Trophy, Users, Briefcase, ChevronLeft, ChevronRight, Sun, Moon, Trophy, Users, Briefcase,
FileText, Menu, X, Calculator, PlusCircle, ClipboardList, Zap, LayoutGrid, Settings, CloudLightning FileText, Menu, X, Calculator, PlusCircle, ClipboardList, Zap, LayoutGrid, Settings, CloudLightning,
HardHat
} from 'lucide-react'; } from 'lucide-react';
import PageTransition from './PageTransition'; import PageTransition from './PageTransition';
@@ -150,6 +151,7 @@ const Layout = () => {
{ to: "/owner/estimates", icon: Calculator, label: "Estimates" }, { to: "/owner/estimates", icon: Calculator, label: "Estimates" },
{ to: "/admin/schedule", icon: Calendar, label: "Team Schedule" }, { to: "/admin/schedule", icon: Calendar, label: "Team Schedule" },
{ to: "/admin/leaderboard", icon: Trophy, label: "Leaderboard" }, { to: "/admin/leaderboard", icon: Trophy, label: "Leaderboard" },
{ to: "/owner/subcontractor-tasks", icon: HardHat, label: "Subcontractor Tasks" },
{ to: "/owner/settings", icon: Settings, label: "Org Settings" }, { to: "/owner/settings", icon: Settings, label: "Org Settings" },
...commonItems, ...commonItems,
]; ];
@@ -169,7 +171,8 @@ const Layout = () => {
label: <span><span className="text-[#fda913]">Pro</span>Canvas</span> label: <span><span className="text-[#fda913]">Pro</span>Canvas</span>
}, },
{ to: "/admin/estimates", icon: Calculator, label: "Estimates" }, { to: "/admin/estimates", icon: Calculator, label: "Estimates" },
{ to: "/owner/settings", icon: Settings, label: "Org Settings" }, { to: "/admin/subcontractor-tasks", icon: HardHat, label: "Subcontractor Tasks" },
{ to: "/admin/settings", icon: Settings, label: "Org Settings" },
...commonItems, ...commonItems,
]; ];
case 'CONTRACTOR': case 'CONTRACTOR':
@@ -0,0 +1,483 @@
import React, { useMemo, useState, useRef, useEffect } from 'react';
import { Wallet, Users, Search, ChevronDown, X, Check, FilterX } from 'lucide-react';
const CATEGORY_COLORS = {
'Electrical': 'text-cyan-500 dark:text-cyan-400 bg-cyan-500/10 border-cyan-500/20',
'Roofing': 'text-orange-500 dark:text-orange-400 bg-orange-500/10 border-orange-500/20',
'Painting': 'text-purple-500 dark:text-purple-400 bg-purple-500/10 border-purple-500/20',
'Plumbing': 'text-blue-500 dark:text-blue-400 bg-blue-500/10 border-blue-500/20',
'Windows & Glazing': 'text-teal-500 dark:text-teal-400 bg-teal-500/10 border-teal-500/20',
};
const PAYMENT_STATUS_COLORS = {
'Paid': 'text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border-emerald-500/20',
'Unpaid': 'text-amber-600 dark:text-amber-400 bg-amber-500/10 border-amber-500/20',
};
function taskTotal(task) {
const expenses = (task.expenses || []).reduce((s, e) => s + (Number(e.amount) || 0), 0);
const fees = (task.fees || []).reduce((s, f) => s + (Number(f.amount) || 0), 0);
return expenses + fees;
}
const fmt = (amt) =>
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(Number(amt) || 0);
const fmtDate = (iso) => {
if (!iso) return '—';
try {
return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
} catch {
return iso;
}
};
// Dark-mode-aware dropdown — replaces native <select> so the option list
// doesn't render with the OS default white background in dark mode.
function FilterPopover({ id, value, onChange, options, allLabel, ariaLabel }) {
const [open, setOpen] = useState(false);
const boxRef = useRef(null);
useEffect(() => {
if (!open) return;
const onClick = (e) => {
if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false);
};
const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
document.addEventListener('mousedown', onClick);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onClick);
document.removeEventListener('keydown', onKey);
};
}, [open]);
const display = value === 'all' ? allLabel : value;
return (
<div className="relative" ref={boxRef}>
<button
id={id}
type="button"
aria-haspopup="listbox"
aria-expanded={open}
aria-label={ariaLabel}
onClick={() => setOpen(o => !o)}
className="w-full flex items-center justify-between gap-2 pl-3 pr-2 py-2 text-sm rounded-xl bg-zinc-100 dark:bg-black/40 border border-zinc-200 dark:border-white/10 text-zinc-900 dark:text-white outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500/40 transition-colors"
>
<span className="truncate text-left">{display}</span>
<ChevronDown size={14} className={`shrink-0 text-zinc-400 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div
role="listbox"
className="absolute z-30 left-0 right-0 mt-1 rounded-xl bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-white/10 shadow-xl shadow-black/10 dark:shadow-black/50 overflow-hidden"
>
<div className="max-h-56 overflow-y-auto custom-scrollbar py-1">
<button
type="button"
role="option"
aria-selected={value === 'all'}
onClick={() => { onChange('all'); setOpen(false); }}
className={`w-full flex items-center justify-between px-3 py-2 text-sm text-left transition-colors ${value === 'all' ? 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10' : 'text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/5'}`}
>
<span>{allLabel}</span>
{value === 'all' && <Check size={12} strokeWidth={2.5} className="shrink-0 opacity-70" />}
</button>
{options.map(opt => {
const isSelected = opt === value;
return (
<button
key={opt}
type="button"
role="option"
aria-selected={isSelected}
onClick={() => { onChange(opt); setOpen(false); }}
className={`w-full flex items-center justify-between px-3 py-2 text-sm text-left transition-colors ${isSelected ? 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10' : 'text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/5'}`}
>
<span className="truncate">{opt}</span>
{isSelected && <Check size={12} strokeWidth={2.5} className="shrink-0 opacity-70" />}
</button>
);
})}
</div>
</div>
)}
</div>
);
}
const SubcontractorPaymentsPanel = ({
subcontractorTasks = [],
subcontractors = [],
projects = [],
}) => {
const subById = useMemo(() => {
const m = new Map();
for (const s of subcontractors) m.set(s.id, s);
return m;
}, [subcontractors]);
const projectById = useMemo(() => {
const m = new Map();
for (const p of projects) m.set(p.id, p);
return m;
}, [projects]);
const rows = useMemo(() => {
const entries = [];
for (const task of subcontractorTasks) {
const amount = taskTotal(task);
if (amount <= 0) continue;
const sub = subById.get(task.subcontractorId);
const project = task.projectId ? projectById.get(task.projectId) : null;
entries.push({
key: task.id,
name: task.subcontractorName,
companyName: sub?.companyName || '',
projectName: project ? (project.projectType || project.address) : '—',
projectAddress: project?.address || '',
projectId: project?.id || null,
workCategory: sub?.tradeType || '—',
amount,
requestedAt: task.paymentRequestedAt || null,
paidAt: task.paidAt || null,
paymentStatus: task.paymentStatus || 'Unpaid',
});
}
return entries;
}, [subcontractorTasks, subById, projectById]);
// ── Filter state ───────────────────────────────────────────────
const [nameQuery, setNameQuery] = useState('');
const [projectFilter, setProjectFilter] = useState('all');
const [categoryFilter, setCategoryFilter] = useState('all');
const [statusFilter, setStatusFilter] = useState('all');
// Searchable project dropdown
const [projectOpen, setProjectOpen] = useState(false);
const [projectQuery, setProjectQuery] = useState('');
const projectBoxRef = useRef(null);
useEffect(() => {
if (!projectOpen) return;
const onClick = (e) => {
if (projectBoxRef.current && !projectBoxRef.current.contains(e.target)) {
setProjectOpen(false);
setProjectQuery('');
}
};
document.addEventListener('mousedown', onClick);
return () => document.removeEventListener('mousedown', onClick);
}, [projectOpen]);
const projectOptions = useMemo(() => {
const map = new Map();
for (const r of rows) {
const key = r.projectName || '—';
if (!map.has(key)) map.set(key, { name: key });
}
return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
}, [rows]);
const categoryOptions = useMemo(() => {
const set = new Set(rows.map(r => r.workCategory).filter(Boolean));
return Array.from(set).sort();
}, [rows]);
const statusOptions = useMemo(() => {
const set = new Set(rows.map(r => r.paymentStatus).filter(Boolean));
return Array.from(set).sort();
}, [rows]);
const filteredProjectOptions = useMemo(() => {
const q = projectQuery.trim().toLowerCase();
if (!q) return projectOptions;
return projectOptions.filter(p => (p.name || '').toLowerCase().includes(q));
}, [projectOptions, projectQuery]);
const selectedProjectLabel = projectFilter === 'all' ? 'All Projects' : projectFilter;
const filteredRows = useMemo(() => {
const q = nameQuery.trim().toLowerCase();
return rows.filter(r => {
if (q && !(r.name || '').toLowerCase().includes(q)) return false;
if (projectFilter !== 'all' && r.projectName !== projectFilter) return false;
if (categoryFilter !== 'all' && r.workCategory !== categoryFilter) return false;
if (statusFilter !== 'all' && r.paymentStatus !== statusFilter) return false;
return true;
});
}, [rows, nameQuery, projectFilter, categoryFilter, statusFilter]);
const total = useMemo(() => filteredRows.reduce((s, r) => s + r.amount, 0), [filteredRows]);
const outstanding = useMemo(
() => filteredRows.filter(r => r.paymentStatus === 'Unpaid').reduce((s, r) => s + r.amount, 0),
[filteredRows]
);
const hasActiveFilters =
nameQuery.trim() !== '' || projectFilter !== 'all' || categoryFilter !== 'all' || statusFilter !== 'all';
const clearFilters = () => {
setNameQuery('');
setProjectFilter('all');
setCategoryFilter('all');
setStatusFilter('all');
setProjectQuery('');
};
return (
<div className="flex flex-col gap-3">
{/* Header */}
<div className="flex items-center gap-3 flex-wrap">
<Wallet className="text-amber-500 dark:text-amber-400 drop-shadow-[0_0_8px_rgba(245,158,11,0.4)]" size={20} />
<h3 className="text-sm font-mono font-bold text-zinc-900 dark:text-white tracking-widest uppercase">
Subcontractor Payments
</h3>
<span className="text-[10px] font-mono text-zinc-500 bg-zinc-100 dark:bg-white/5 border border-zinc-200 dark:border-white/10 rounded-full px-2.5 py-0.5">
{hasActiveFilters
? `${filteredRows.length} of ${rows.length} payment${rows.length === 1 ? '' : 's'}`
: `${rows.length} payment${rows.length === 1 ? '' : 's'}`
}
</span>
</div>
{/* Filter bar */}
{rows.length > 0 && (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2.5 p-3 rounded-xl bg-zinc-50 dark:bg-white/[0.02] border border-zinc-200 dark:border-white/5">
{/* Search by Name */}
<div className="relative">
<label htmlFor="payments-name-search" className="sr-only">Search by subcontractor name</label>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400 pointer-events-none" size={14} />
<input
id="payments-name-search"
type="text"
placeholder="Search by name..."
value={nameQuery}
onChange={(e) => setNameQuery(e.target.value)}
className="w-full bg-zinc-100 dark:bg-black/40 border border-zinc-200 dark:border-white/10 rounded-xl py-2 pl-9 pr-8 text-sm text-zinc-900 dark:text-white placeholder:text-zinc-400 dark:placeholder:text-zinc-500 outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500/40"
/>
{nameQuery && (
<button
type="button"
onClick={() => setNameQuery('')}
aria-label="Clear name search"
className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200"
>
<X size={14} />
</button>
)}
</div>
{/* Project searchable dropdown */}
<div className="relative" ref={projectBoxRef}>
<button
type="button"
onClick={() => setProjectOpen(o => !o)}
className="w-full flex items-center justify-between gap-2 pl-3 pr-2 py-2 text-sm rounded-xl bg-zinc-100 dark:bg-black/40 border border-zinc-200 dark:border-white/10 text-zinc-900 dark:text-white outline-none focus:ring-2 focus:ring-amber-500/20 focus:border-amber-500/40 transition-colors"
>
<span className="truncate text-left">{selectedProjectLabel}</span>
<ChevronDown size={14} className={`shrink-0 text-zinc-400 transition-transform ${projectOpen ? 'rotate-180' : ''}`} />
</button>
{projectOpen && (
<div className="absolute z-30 left-0 right-0 mt-1 rounded-xl bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-white/10 shadow-xl shadow-black/10 dark:shadow-black/50 overflow-hidden">
<div className="relative p-2 border-b border-zinc-100 dark:border-white/5">
<Search className="absolute left-4 top-1/2 -translate-y-1/2 text-zinc-400 pointer-events-none" size={14} />
<input
autoFocus
type="text"
placeholder="Search projects..."
value={projectQuery}
onChange={(e) => setProjectQuery(e.target.value)}
className="w-full bg-zinc-50 dark:bg-black/40 border border-zinc-200 dark:border-white/10 rounded-lg py-1.5 pl-8 pr-2 text-sm text-zinc-900 dark:text-white placeholder:text-zinc-400 dark:placeholder:text-zinc-500 outline-none"
/>
</div>
<div className="max-h-56 overflow-y-auto custom-scrollbar py-1">
<button
type="button"
onClick={() => { setProjectFilter('all'); setProjectOpen(false); setProjectQuery(''); }}
className={`w-full flex items-center justify-between px-3 py-2 text-sm text-left transition-colors ${projectFilter === 'all' ? 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10' : 'text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/5'}`}
>
<span>All Projects</span>
{projectFilter === 'all' && <Check size={12} strokeWidth={2.5} className="shrink-0 opacity-70" />}
</button>
{filteredProjectOptions.length === 0 ? (
<p className="px-3 py-2 text-xs text-zinc-400 dark:text-zinc-500">No projects match "{projectQuery}"</p>
) : (
filteredProjectOptions.map(p => {
const isSelected = p.name === projectFilter;
return (
<button
key={p.name}
type="button"
onClick={() => { setProjectFilter(p.name); setProjectOpen(false); setProjectQuery(''); }}
className={`w-full flex items-center justify-between px-3 py-2 text-sm text-left transition-colors ${isSelected ? 'text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-500/10' : 'text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/5'}`}
>
<span className="truncate font-semibold">{p.name}</span>
{isSelected && <Check size={12} strokeWidth={2.5} className="shrink-0 opacity-70" />}
</button>
);
})
)}
</div>
</div>
)}
</div>
{/* Work Category filter */}
<FilterPopover
id="payments-category-filter"
ariaLabel="Filter by work category"
value={categoryFilter}
onChange={setCategoryFilter}
options={categoryOptions}
allLabel="All Work Categories"
/>
{/* Payment Status filter */}
<FilterPopover
id="payments-status-filter"
ariaLabel="Filter by payment status"
value={statusFilter}
onChange={setStatusFilter}
options={statusOptions}
allLabel="All Payment Statuses"
/>
{hasActiveFilters && (
<div className="sm:col-span-2 lg:col-span-4 flex justify-end">
<button
type="button"
onClick={clearFilters}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white bg-zinc-100 dark:bg-white/5 hover:bg-zinc-200 dark:hover:bg-white/10 border border-zinc-200 dark:border-white/10 transition-colors"
>
<FilterX size={12} /> Clear Filters
</button>
</div>
)}
</div>
)}
{rows.length === 0 ? (
<div className="py-10 text-center">
<Users size={28} className="mx-auto mb-3 text-zinc-400" />
<p className="text-sm text-zinc-500">No subcontractor payments yet.</p>
<p className="text-xs text-zinc-400 mt-1">Tasks with logged fees or expenses will appear here.</p>
</div>
) : (
<div className="overflow-x-auto rounded-xl border border-zinc-200 dark:border-white/5">
<table className="w-full text-left min-w-[860px]">
<thead>
<tr className="border-b border-zinc-200 dark:border-white/5 bg-zinc-50 dark:bg-white/[0.02]">
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Subcontractor</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Project</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Work Category</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest text-right">Amount to Pay</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Requested</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Paid Date</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Payment Status</th>
</tr>
</thead>
<tbody>
{filteredRows.length === 0 && (
<tr>
<td colSpan={7} className="px-4 py-10 text-center">
<Users size={22} className="mx-auto mb-2 text-zinc-400" />
<p className="text-sm text-zinc-500">No payments match the current filters.</p>
<button
type="button"
onClick={clearFilters}
className="mt-3 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider text-amber-600 dark:text-amber-400 hover:bg-amber-50 dark:hover:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 transition-colors"
>
<FilterX size={12} /> Clear Filters
</button>
</td>
</tr>
)}
{filteredRows.map((row) => (
<tr key={row.key} className="border-b border-zinc-100 dark:border-white/[0.03] hover:bg-zinc-50 dark:hover:bg-white/[0.02] transition-colors">
<td className="px-4 py-3">
<div className="flex items-center gap-2.5">
<div className="w-7 h-7 rounded-full bg-amber-500/15 flex items-center justify-center text-[10px] font-black text-amber-600 dark:text-amber-400 flex-shrink-0">
{row.name?.[0] || '?'}
</div>
<div className="min-w-0">
<div className="text-xs font-semibold text-zinc-900 dark:text-white truncate max-w-[180px]">{row.name}</div>
{row.companyName && (
<div className="text-[10px] text-zinc-500 dark:text-zinc-400 truncate max-w-[180px]">{row.companyName}</div>
)}
</div>
</div>
</td>
<td className="px-4 py-3">
<div className="min-w-0">
<div className="text-xs text-zinc-700 dark:text-zinc-300 truncate max-w-[200px]" title={row.projectName}>
{row.projectName}
</div>
{row.projectAddress && (
<div className="text-[10px] text-zinc-500 dark:text-zinc-400 truncate max-w-[200px]" title={row.projectAddress}>
{row.projectAddress}
</div>
)}
</div>
</td>
<td className="px-4 py-3">
<span className={`text-[11px] font-bold rounded-md px-1.5 py-0.5 border whitespace-nowrap ${CATEGORY_COLORS[row.workCategory] || 'text-zinc-400 bg-zinc-500/10 border-zinc-500/20'}`}>
{row.workCategory}
</span>
</td>
<td className="px-4 py-3 text-right">
<span className="font-mono text-xs font-bold text-amber-600 dark:text-amber-400">
{fmt(row.amount)}
</span>
</td>
<td className="px-4 py-3">
<span className="text-[11px] font-mono text-zinc-500 dark:text-zinc-400 whitespace-nowrap">
{fmtDate(row.requestedAt)}
</span>
</td>
<td className="px-4 py-3">
<span className={`text-[11px] font-mono whitespace-nowrap ${row.paidAt ? 'text-emerald-600 dark:text-emerald-400 font-semibold' : 'text-zinc-400 dark:text-zinc-500'}`}>
{fmtDate(row.paidAt)}
</span>
</td>
<td className="px-4 py-3">
<span className={`text-[11px] font-bold rounded-md px-1.5 py-0.5 border whitespace-nowrap ${PAYMENT_STATUS_COLORS[row.paymentStatus] || 'text-zinc-400 bg-zinc-500/10 border-zinc-500/20'}`}>
{row.paymentStatus}
</span>
</td>
</tr>
))}
</tbody>
<tfoot className="border-t-2 border-zinc-300 dark:border-white/10">
<tr className="bg-zinc-50 dark:bg-white/[0.03]">
<td colSpan={3} className="px-4 py-3 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">
{hasActiveFilters ? 'Filtered Total' : 'Total Amount'}
</td>
<td className="px-4 py-3 text-right">
<span className="font-mono text-sm font-extrabold text-amber-600 dark:text-amber-400">
{fmt(total)}
</span>
</td>
<td colSpan={3} />
</tr>
<tr className="bg-zinc-50 dark:bg-white/[0.03]">
<td colSpan={3} className="px-4 py-3 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">
Outstanding (Unpaid)
</td>
<td className="px-4 py-3 text-right">
<span className="font-mono text-sm font-extrabold text-amber-600 dark:text-amber-400">
{fmt(outstanding)}
</span>
</td>
<td colSpan={3} />
</tr>
</tfoot>
</table>
</div>
)}
</div>
);
};
export default SubcontractorPaymentsPanel;
@@ -0,0 +1,476 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { toast } from 'sonner';
import {
X, ClipboardList, MapPin, Calendar, Camera, AlertCircle,
Trash2, User, Star, ImagePlus, Loader2,
} from 'lucide-react';
import { useMockStore } from '../../data/mockStore';
import { useAuth } from '../../context/AuthContext';
const inputBase = "w-full bg-white dark:bg-[#18181b] border border-zinc-200 dark:border-white/10 rounded-xl px-4 py-2.5 text-sm text-zinc-900 dark:text-white placeholder-zinc-400 dark:placeholder-zinc-600 focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all";
const PRIORITY_STYLES = {
low: { activeBg: 'bg-zinc-900 dark:bg-white', activeText: 'text-white dark:text-black', dot: 'bg-zinc-400' },
medium: { activeBg: 'bg-blue-600', activeText: 'text-white', dot: 'bg-blue-500' },
high: { activeBg: 'bg-red-600', activeText: 'text-white', dot: 'bg-red-500' },
};
const todayIso = () => new Date().toISOString().slice(0, 10);
const emptyForm = {
subcontractorId: '',
title: '',
location: '',
description: '',
dueDate: '',
priority: 'medium',
photos: [],
};
const AssignTaskModal = ({ isOpen, onClose, task = null, defaultSubcontractorId = null }) => {
const { user } = useAuth();
const { subcontractors, orgSettings, addSubcontractorTask, updateSubcontractorTask, taskPriorities } = useMockStore();
const fileInputRef = useRef(null);
const isEdit = Boolean(task);
const activeSubs = useMemo(() => subcontractors.filter(s => s.status === 'active'), [subcontractors]);
const [form, setForm] = useState(emptyForm);
const [errors, setErrors] = useState({});
const [submitting, setSubmitting] = useState(false);
// Reset / hydrate when modal opens or task switches
useEffect(() => {
if (!isOpen) return;
if (task) {
setForm({
subcontractorId: task.subcontractorId,
title: task.title,
location: task.location,
description: task.description || '',
dueDate: task.dueDate,
priority: task.priority || 'medium',
photos: (task.photos || []).map(p => ({ ...p, isExisting: true })),
});
} else {
setForm({
...emptyForm,
subcontractorId: defaultSubcontractorId || '',
});
}
setErrors({});
setSubmitting(false);
}, [isOpen, task, defaultSubcontractorId]);
// Escape key
useEffect(() => {
const handler = (e) => { if (e.key === 'Escape') onClose(); };
if (isOpen) window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [isOpen, onClose]);
// Body scroll lock
useEffect(() => {
if (!isOpen) return;
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = prev; };
}, [isOpen]);
// Clean up object URLs we created for newly-picked photos
useEffect(() => () => {
form.photos.forEach(p => { if (p.objectUrl) URL.revokeObjectURL(p.objectUrl); });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
if (!isOpen) return null;
const setField = (k, v) => {
setForm(prev => ({ ...prev, [k]: v }));
setErrors(prev => ({ ...prev, [k]: undefined }));
};
const handleFiles = (e) => {
const incoming = Array.from(e.target.files || []);
if (!incoming.length) return;
const next = incoming.map((file, i) => {
const objectUrl = URL.createObjectURL(file);
return {
id: `new_${Date.now()}_${i}`,
name: file.name,
url: objectUrl,
objectUrl,
annotation: '',
};
});
setForm(prev => ({ ...prev, photos: [...prev.photos, ...next] }));
// reset input so picking the same file again still triggers change
e.target.value = '';
};
const removePhoto = (id) => {
setForm(prev => {
const photo = prev.photos.find(p => p.id === id);
if (photo?.objectUrl) URL.revokeObjectURL(photo.objectUrl);
return { ...prev, photos: prev.photos.filter(p => p.id !== id) };
});
};
const updatePhotoAnnotation = (id, annotation) => {
setForm(prev => ({
...prev,
photos: prev.photos.map(p => p.id === id ? { ...p, annotation } : p),
}));
};
const validate = () => {
const err = {};
if (!form.subcontractorId) err.subcontractorId = 'Select a subcontractor.';
if (!form.title.trim()) err.title = 'Task title is required.';
if (!form.location.trim()) err.location = 'Location is required.';
if (!form.dueDate) err.dueDate = 'Due date is required.';
else if (!isEdit && form.dueDate < todayIso()) err.dueDate = 'Due date must be today or later.';
setErrors(err);
return Object.keys(err).length === 0;
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!validate()) return;
setSubmitting(true);
// Tiny delay to surface the loading state — replace with real API later.
await new Promise(r => setTimeout(r, 400));
const payload = {
companyId: 'lynkeduppro',
companyName: orgSettings?.orgName || 'Your Company',
assignedBy: user?.id || 'unknown',
assignedByName: user?.name || 'Unknown',
subcontractorId: form.subcontractorId,
title: form.title.trim(),
location: form.location.trim(),
description: form.description.trim(),
dueDate: form.dueDate,
priority: form.priority,
photos: form.photos.map(p => ({
id: p.isExisting ? p.id : undefined,
name: p.name,
url: p.url,
annotation: p.annotation || '',
})),
};
try {
if (isEdit) {
updateSubcontractorTask(task.id, {
subcontractorId: payload.subcontractorId,
title: payload.title,
location: payload.location,
description: payload.description,
dueDate: payload.dueDate,
priority: payload.priority,
photos: payload.photos,
});
} else {
addSubcontractorTask(payload);
}
onClose();
} catch {
toast.error('Something went wrong. Please try again.');
} finally {
setSubmitting(false);
}
};
return createPortal(
<div className="fixed inset-0 z-[9999] flex items-end sm:items-center justify-center sm:p-6" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={submitting ? undefined : onClose} />
<div className="relative w-full sm:max-w-2xl h-[92dvh] sm:h-auto sm:max-h-[90vh] bg-white dark:bg-[#121214] rounded-t-2xl sm:rounded-2xl shadow-2xl border border-zinc-200 dark:border-white/10 overflow-hidden flex flex-col animate-in slide-in-from-bottom-10 duration-200">
{/* Header */}
<div className="px-5 sm:px-6 py-4 sm:py-5 border-b border-zinc-200 dark:border-white/10 flex items-center justify-between bg-zinc-50/50 dark:bg-white/5 shrink-0">
<div className="flex items-center gap-3 min-w-0">
<div className="p-2 rounded-xl bg-blue-500/10 text-blue-500 shrink-0">
<ClipboardList size={20} />
</div>
<div className="min-w-0">
<h2 className="text-base sm:text-lg font-bold text-zinc-900 dark:text-white uppercase tracking-wider truncate">
{isEdit ? 'Edit Task' : 'Assign Task'}
</h2>
<p className="text-[11px] text-zinc-500 dark:text-zinc-400 font-mono mt-0.5 truncate">
{isEdit ? task.id : 'New subcontractor task'}
</p>
</div>
</div>
<button
type="button"
onClick={onClose}
disabled={submitting}
className="p-2 rounded-lg bg-zinc-100 dark:bg-white/10 text-zinc-500 hover:text-red-500 transition-colors disabled:opacity-50"
aria-label="Close"
>
<X size={18} />
</button>
</div>
{/* Body */}
<form onSubmit={handleSubmit} className="flex-1 flex flex-col min-h-0">
<div className="flex-1 overflow-y-auto px-5 sm:px-6 py-5 space-y-5 custom-scrollbar">
{/* Subcontractor select */}
<div className="space-y-1.5">
<label htmlFor="sct-subcontractor" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
<User size={12} />
Subcontractor <span className="text-red-500">*</span>
</label>
<select
id="sct-subcontractor"
value={form.subcontractorId}
onChange={(e) => setField('subcontractorId', e.target.value)}
className={inputBase}
aria-invalid={Boolean(errors.subcontractorId)}
>
<option value="" disabled>Select a subcontractor</option>
{activeSubs.map(s => (
<option key={s.id} value={s.id}>
{s.name} {s.tradeType} ({s.companyName})
</option>
))}
</select>
{/* Preview of selected sub */}
{form.subcontractorId && (() => {
const sub = activeSubs.find(s => s.id === form.subcontractorId);
if (!sub) return null;
return (
<div className="mt-2 p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/10 flex items-center justify-between gap-3 text-xs">
<div className="flex items-center gap-3 min-w-0">
<div className="w-9 h-9 rounded-full bg-blue-500/10 text-blue-500 flex items-center justify-center font-bold shrink-0">
{sub.name.charAt(0)}
</div>
<div className="min-w-0">
<div className="font-bold text-zinc-900 dark:text-white truncate">{sub.name}</div>
<div className="text-zinc-500 truncate">{sub.email} · {sub.phone}</div>
</div>
</div>
<span className="flex items-center gap-1 text-amber-500 font-bold shrink-0">
<Star size={12} fill="currentColor" />
{sub.rating?.toFixed?.(1) ?? '—'}
</span>
</div>
);
})()}
{errors.subcontractorId && <FieldError msg={errors.subcontractorId} />}
</div>
{/* Title */}
<div className="space-y-1.5">
<label htmlFor="sct-title" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400">
Task Title <span className="text-red-500">*</span>
</label>
<input
id="sct-title"
type="text"
value={form.title}
onChange={(e) => setField('title', e.target.value)}
className={inputBase}
placeholder="e.g. Replace damaged ridge cap"
maxLength={120}
aria-invalid={Boolean(errors.title)}
/>
{errors.title && <FieldError msg={errors.title} />}
</div>
{/* Location */}
<div className="space-y-1.5">
<label htmlFor="sct-location" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
<MapPin size={12} />
Location / Address <span className="text-red-500">*</span>
</label>
<input
id="sct-location"
type="text"
value={form.location}
onChange={(e) => setField('location', e.target.value)}
className={inputBase}
placeholder="2612 Dunwick Dr, Plano, TX 75023"
aria-invalid={Boolean(errors.location)}
/>
{errors.location && <FieldError msg={errors.location} />}
</div>
{/* Description */}
<div className="space-y-1.5">
<label htmlFor="sct-description" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400">
Task Description
</label>
<textarea
id="sct-description"
value={form.description}
onChange={(e) => setField('description', e.target.value)}
className={inputBase}
rows={3}
placeholder="Scope of work, access notes, materials staged…"
/>
</div>
{/* Due date + Priority */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-1.5">
<label htmlFor="sct-due" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
<Calendar size={12} />
Due Date <span className="text-red-500">*</span>
</label>
<input
id="sct-due"
type="date"
value={form.dueDate}
min={isEdit ? undefined : todayIso()}
onChange={(e) => setField('dueDate', e.target.value)}
className={inputBase}
aria-invalid={Boolean(errors.dueDate)}
/>
{errors.dueDate && <FieldError msg={errors.dueDate} />}
</div>
<div className="space-y-1.5">
<span className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 block">
Priority <span className="text-red-500">*</span>
</span>
<div className="flex gap-2" role="radiogroup" aria-label="Priority">
{taskPriorities.map(p => {
const style = PRIORITY_STYLES[p.value] || PRIORITY_STYLES.medium;
const active = form.priority === p.value;
return (
<button
key={p.value}
type="button"
role="radio"
aria-checked={active}
onClick={() => setField('priority', p.value)}
className={`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wider border transition-all ${
active
? `${style.activeBg} ${style.activeText} border-transparent shadow-sm`
: 'bg-zinc-100 dark:bg-white/5 text-zinc-500 dark:text-zinc-400 border-zinc-200 dark:border-white/10 hover:bg-zinc-200 dark:hover:bg-white/10'
}`}
>
<span className={`w-2 h-2 rounded-full ${style.dot}`} />
{p.label}
</button>
);
})}
</div>
</div>
</div>
{/* Photos */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
<Camera size={12} />
Photos & Annotations
</span>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider bg-blue-500/10 text-blue-600 dark:text-blue-400 hover:bg-blue-500/20 transition-colors"
>
<ImagePlus size={12} />
Add Photo
</button>
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
onChange={handleFiles}
className="hidden"
/>
</div>
{form.photos.length === 0 ? (
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="w-full border-2 border-dashed border-zinc-300 dark:border-white/10 rounded-xl py-8 flex flex-col items-center justify-center text-zinc-500 hover:border-blue-500/50 hover:bg-blue-500/5 transition-colors"
>
<Camera size={28} className="mb-2 opacity-60" />
<p className="text-xs font-semibold">Click to upload photos</p>
<p className="text-[10px] text-zinc-400 mt-1">Add an annotation note for each (e.g. "Paint here")</p>
</button>
) : (
<div className="space-y-2">
{form.photos.map((p, idx) => (
<div key={p.id} className="flex gap-3 p-2.5 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/10">
<div className="w-20 h-20 rounded-lg overflow-hidden bg-zinc-200 dark:bg-zinc-800 shrink-0">
<img src={p.url} alt={p.name || `Photo ${idx + 1}`} className="w-full h-full object-cover" />
</div>
<div className="flex-1 min-w-0 flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<span className="text-xs font-mono text-zinc-500 truncate">{p.name}</span>
<button
type="button"
onClick={() => removePhoto(p.id)}
className="p-1.5 rounded-md text-zinc-400 hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0"
aria-label="Remove photo"
>
<Trash2 size={14} />
</button>
</div>
<input
type="text"
value={p.annotation}
onChange={(e) => updatePhotoAnnotation(p.id, e.target.value)}
placeholder='Annotation (e.g. "Paint here", "Repair this corner")'
className="w-full bg-white dark:bg-[#18181b] border border-zinc-200 dark:border-white/10 rounded-lg px-2.5 py-1.5 text-xs text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:border-blue-500"
maxLength={140}
/>
</div>
</div>
))}
</div>
)}
</div>
{/* Status indicator (informational) */}
{!isEdit && (
<div className="flex items-center gap-2 text-xs text-zinc-500 dark:text-zinc-400 p-3 rounded-xl bg-blue-500/5 border border-blue-500/10">
<AlertCircle size={14} className="text-blue-500 shrink-0" />
Task will be created with status <span className="font-bold text-zinc-900 dark:text-white">Assigned</span> and the subcontractor will be notified.
</div>
)}
</div>
{/* Footer */}
<div className="px-5 sm:px-6 py-4 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/[0.02] flex flex-col-reverse sm:flex-row sm:justify-end gap-2 sm:gap-3 shrink-0">
<button
type="button"
onClick={onClose}
disabled={submitting}
className="px-5 py-2.5 text-sm font-bold rounded-xl border border-zinc-200 dark:border-white/10 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-white/5 hover:text-zinc-900 dark:hover:text-white transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
type="submit"
disabled={submitting}
className="inline-flex items-center justify-center gap-2 px-6 py-2.5 text-sm font-bold rounded-xl bg-blue-600 hover:bg-blue-500 text-white shadow-lg shadow-blue-500/20 transition-all disabled:opacity-60"
>
{submitting && <Loader2 size={14} className="animate-spin" />}
{isEdit ? 'Save Changes' : 'Assign Task'}
</button>
</div>
</form>
</div>
</div>,
document.body,
);
};
const FieldError = ({ msg }) => (
<p className="text-[11px] font-semibold text-red-500 flex items-center gap-1 mt-1">
<AlertCircle size={11} />
{msg}
</p>
);
export default AssignTaskModal;
@@ -0,0 +1,197 @@
import React, { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { SpotlightCard } from '../SpotlightCard';
import {
Bell, ClipboardList, MessageSquare, RefreshCcw, CheckCircle, AlertCircle,
} from 'lucide-react';
// Allowed notification types for the subcontractor dashboard.
// Keep keys in sync with mockStore notification.type values.
const NOTIF_CONFIG = {
task_assigned: {
label: 'New Task Assigned',
tone: 'text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-500/15',
icon: ClipboardList,
side: 'border-l-blue-500',
},
message_received: {
label: 'Message Received',
tone: 'text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-500/15',
icon: MessageSquare,
side: 'border-l-emerald-500',
},
task_updated: {
label: 'Task Updated',
tone: 'text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-500/15',
icon: RefreshCcw,
side: 'border-l-amber-500',
},
status_changed: {
label: 'Status Changed',
tone: 'text-purple-600 bg-purple-100 dark:text-purple-400 dark:bg-purple-500/15',
icon: CheckCircle,
side: 'border-l-purple-500',
},
};
const ALLOWED_TYPES = Object.keys(NOTIF_CONFIG);
const formatDateTime = (iso) => {
if (!iso) return '—';
try {
const d = new Date(iso);
const dateStr = d.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
const timeStr = d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
return `${dateStr} · ${timeStr}`;
} catch { return iso; }
};
const TABS = [
{ key: 'all', label: 'All' },
{ key: 'task_assigned', label: 'New Task' },
{ key: 'message_received', label: 'Message' },
{ key: 'task_updated', label: 'Updates' },
{ key: 'status_changed', label: 'Status' },
];
/**
* NotificationsPanel — global subcontractor notifications.
*
* Renders a SpotlightCard with tabbed filtering and a list of notification rows.
* Each row navigates to its referenced task (if any) when clicked.
*/
export const NotificationsPanel = ({ notifications, onMarkAllRead, onNotificationClick }) => {
const navigate = useNavigate();
const [tab, setTab] = useState('all');
const allowed = useMemo(
() => notifications.filter(n => ALLOWED_TYPES.includes(n.type)),
[notifications],
);
const filtered = useMemo(() => {
if (tab === 'all') return allowed;
return allowed.filter(n => n.type === tab);
}, [allowed, tab]);
const unreadCount = allowed.filter(n => !n.isRead).length;
const handleClick = (n) => {
if (onNotificationClick) onNotificationClick(n);
if (n.taskId) navigate(`/subcontractor/tasks/${n.taskId}`);
};
return (
<SpotlightCard className="p-5 sm:p-6">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2.5 min-w-0">
<div className="p-1.5 rounded-lg bg-blue-500/10 text-blue-500 shrink-0">
<Bell size={14} />
</div>
<h3 className="text-sm sm:text-base font-bold text-zinc-900 dark:text-white tracking-wide">
Notifications
</h3>
{unreadCount > 0 && (
<span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 font-mono shrink-0">
{unreadCount} new
</span>
)}
</div>
<button
type="button"
onClick={onMarkAllRead}
disabled={unreadCount === 0}
className="text-[11px] font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 hover:underline disabled:text-zinc-400 disabled:no-underline transition-colors shrink-0"
>
Mark all read
</button>
</div>
{/* Tab strip — scrollable on narrow screens */}
<div className="mt-4 -mx-1 px-1 overflow-x-auto custom-scrollbar">
<div className="inline-flex rounded-xl bg-zinc-100 dark:bg-white/5 border border-zinc-200 dark:border-white/10 p-1 min-w-full">
{TABS.map(t => {
const count = t.key === 'all' ? allowed.length : allowed.filter(n => n.type === t.key).length;
return (
<TabPill
key={t.key}
active={tab === t.key}
onClick={() => setTab(t.key)}
label={t.label}
count={count}
/>
);
})}
</div>
</div>
<div className="mt-4 space-y-2 max-h-[36rem] overflow-y-auto pr-1 custom-scrollbar">
{filtered.length === 0 ? (
<div className="text-center py-10 text-zinc-500">
<Bell size={20} className="mx-auto mb-2 opacity-50" />
<p className="text-xs">You&apos;re all caught up.</p>
</div>
) : filtered.map(n => (
<NotificationRow key={n.id} notification={n} onClick={() => handleClick(n)} />
))}
</div>
<div className="mt-4 pt-3 border-t border-zinc-200 dark:border-white/10">
<p className="text-[10px] text-zinc-500 flex items-center gap-1.5">
<AlertCircle size={10} /> In-app only · No SMS or email unless specified.
</p>
</div>
</SpotlightCard>
);
};
const TabPill = ({ active, onClick, label, count }) => (
<button
type="button"
onClick={onClick}
className={`flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-bold whitespace-nowrap transition-colors
${active
? 'bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white shadow-sm'
: 'text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
}`}
>
{label}
{typeof count === 'number' && (
<span className={`text-[10px] font-mono px-1.5 rounded-full ${active ? 'bg-blue-100 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400' : 'bg-zinc-200 dark:bg-white/10 text-zinc-500'}`}>
{count}
</span>
)}
</button>
);
const NotificationRow = ({ notification, onClick }) => {
const cfg = NOTIF_CONFIG[notification.type];
if (!cfg) return null;
const Icon = cfg.icon;
return (
<button
type="button"
onClick={onClick}
className={`w-full flex items-start gap-3 p-3 rounded-xl text-left border-l-2 ${cfg.side}
${notification.isRead
? 'bg-zinc-50 dark:bg-white/[0.02] border-y border-r border-zinc-100 dark:border-white/5'
: 'bg-white dark:bg-white/5 border-y border-r border-zinc-200 dark:border-white/10 shadow-sm'
}
hover:bg-zinc-100 dark:hover:bg-white/10 transition-colors`}
>
<div className={`p-1.5 rounded-lg shrink-0 ${cfg.tone}`}>
<Icon size={14} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-xs font-bold text-zinc-900 dark:text-white">{cfg.label}</span>
{!notification.isRead && <span className="w-1.5 h-1.5 rounded-full bg-blue-500" />}
</div>
<p className="text-[11px] text-zinc-600 dark:text-zinc-400 mt-0.5 line-clamp-2">{notification.message}</p>
<p className="text-[10px] text-zinc-500 font-mono mt-1">{formatDateTime(notification.createdAt)}</p>
</div>
</button>
);
};
export default NotificationsPanel;
@@ -0,0 +1,89 @@
import React, { useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { X, Repeat, User, Loader2 } from 'lucide-react';
import { useMockStore } from '../../data/mockStore';
const inputBase = "w-full bg-white dark:bg-[#18181b] border border-zinc-200 dark:border-white/10 rounded-xl px-4 py-2.5 text-sm text-zinc-900 dark:text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition-all";
const ReassignTaskModal = ({ isOpen, onClose, task }) => {
const { subcontractors, reassignSubcontractorTask } = useMockStore();
const [selected, setSelected] = useState('');
const [submitting, setSubmitting] = useState(false);
const activeSubs = useMemo(
() => subcontractors.filter(s => s.status === 'active' && s.id !== task?.subcontractorId),
[subcontractors, task],
);
useEffect(() => {
if (isOpen) {
setSelected('');
setSubmitting(false);
}
}, [isOpen]);
useEffect(() => {
const handler = (e) => { if (e.key === 'Escape') onClose(); };
if (isOpen) window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [isOpen, onClose]);
if (!isOpen || !task) return null;
const handleConfirm = async () => {
if (!selected) return;
setSubmitting(true);
await new Promise(r => setTimeout(r, 300));
reassignSubcontractorTask(task.id, selected);
setSubmitting(false);
onClose();
};
return createPortal(
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={submitting ? undefined : onClose} />
<div className="relative w-full max-w-md bg-white dark:bg-[#121214] rounded-2xl shadow-2xl border border-zinc-200 dark:border-white/10 overflow-hidden animate-in zoom-in-95 duration-200">
<div className="px-5 py-4 border-b border-zinc-200 dark:border-white/10 flex items-center justify-between bg-zinc-50/50 dark:bg-white/5">
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-purple-500/10 text-purple-500"><Repeat size={18} /></div>
<h2 className="text-base font-bold text-zinc-900 dark:text-white uppercase tracking-wider">Reassign Task</h2>
</div>
<button onClick={onClose} disabled={submitting} className="p-2 rounded-lg bg-zinc-100 dark:bg-white/10 text-zinc-500 hover:text-red-500 transition-colors disabled:opacity-50">
<X size={18} />
</button>
</div>
<div className="p-5 space-y-4">
<div className="text-sm text-zinc-600 dark:text-zinc-400">
Reassign <span className="font-bold text-zinc-900 dark:text-white">{task.title}</span> currently assigned to <span className="font-bold text-zinc-900 dark:text-white">{task.subcontractorName}</span>.
</div>
<div className="space-y-1.5">
<label htmlFor="reassign-sub" className="text-xs font-bold uppercase tracking-wider text-zinc-600 dark:text-zinc-400 flex items-center gap-1.5">
<User size={12} /> New Subcontractor
</label>
<select id="reassign-sub" value={selected} onChange={(e) => setSelected(e.target.value)} className={inputBase}>
<option value="" disabled>Select a subcontractor</option>
{activeSubs.map(s => (
<option key={s.id} value={s.id}>{s.name} {s.tradeType}</option>
))}
</select>
{activeSubs.length === 0 && (
<p className="text-xs text-zinc-500 mt-1">No other active subcontractors available.</p>
)}
</div>
</div>
<div className="px-5 py-4 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5 flex justify-end gap-2">
<button type="button" onClick={onClose} disabled={submitting} className="px-4 py-2 text-sm font-bold rounded-xl border border-zinc-200 dark:border-white/10 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-white/5 transition-colors disabled:opacity-50">
Cancel
</button>
<button type="button" onClick={handleConfirm} disabled={!selected || submitting} className="inline-flex items-center gap-2 px-5 py-2 text-sm font-bold rounded-xl bg-purple-600 hover:bg-purple-500 text-white shadow-lg shadow-purple-500/20 transition-all disabled:opacity-50">
{submitting && <Loader2 size={14} className="animate-spin" />}
Reassign
</button>
</div>
</div>
</div>,
document.body,
);
};
export default ReassignTaskModal;
@@ -0,0 +1,132 @@
import React, { useEffect } from 'react';
import { createPortal } from 'react-dom';
import { X, ClipboardList, MapPin, Calendar, User, Building2, Camera } from 'lucide-react';
const PRIORITY_STYLES = {
low: { label: 'Low', cls: 'bg-zinc-200 text-zinc-700 dark:bg-zinc-700 dark:text-zinc-300' },
medium: { label: 'Medium', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400' },
high: { label: 'High', cls: 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400' },
};
const STATUS_STYLES = {
Assigned: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400',
'In Progress': 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400',
Completed: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400',
Cancelled: 'bg-zinc-200 text-zinc-600 dark:bg-zinc-700 dark:text-zinc-300',
};
const formatDate = (iso) => {
if (!iso) return '—';
try { return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); }
catch { return iso; }
};
const TaskViewModal = ({ isOpen, onClose, task }) => {
useEffect(() => {
const handler = (e) => { if (e.key === 'Escape') onClose(); };
if (isOpen) window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [isOpen, onClose]);
if (!isOpen || !task) return null;
const priority = PRIORITY_STYLES[task.priority] || PRIORITY_STYLES.medium;
return createPortal(
<div className="fixed inset-0 z-[9999] flex items-end sm:items-center justify-center sm:p-6" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
<div className="relative w-full sm:max-w-2xl h-[90dvh] sm:h-auto sm:max-h-[88vh] bg-white dark:bg-[#121214] rounded-t-2xl sm:rounded-2xl shadow-2xl border border-zinc-200 dark:border-white/10 overflow-hidden flex flex-col animate-in slide-in-from-bottom-10 duration-200">
<div className="px-5 sm:px-6 py-4 sm:py-5 border-b border-zinc-200 dark:border-white/10 flex items-center justify-between bg-zinc-50/50 dark:bg-white/5">
<div className="flex items-center gap-3 min-w-0">
<div className="p-2 rounded-xl bg-blue-500/10 text-blue-500 shrink-0">
<ClipboardList size={20} />
</div>
<div className="min-w-0">
<h2 className="text-base sm:text-lg font-bold text-zinc-900 dark:text-white uppercase tracking-wider truncate">Task Details</h2>
<p className="text-[11px] text-zinc-500 font-mono mt-0.5 truncate">{task.id}</p>
</div>
</div>
<button onClick={onClose} className="p-2 rounded-lg bg-zinc-100 dark:bg-white/10 text-zinc-500 hover:text-red-500 transition-colors">
<X size={18} />
</button>
</div>
<div className="flex-1 overflow-y-auto px-5 sm:px-6 py-5 space-y-5 custom-scrollbar">
{/* Title + badges */}
<div>
<h3 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-white">{task.title}</h3>
<div className="flex flex-wrap items-center gap-2 mt-2">
<span className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide ${STATUS_STYLES[task.status] || STATUS_STYLES.Assigned}`}>
{task.status}
</span>
<span className={`px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide ${priority.cls}`}>
{priority.label} priority
</span>
</div>
</div>
{/* Meta grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<Meta icon={User} label="Subcontractor" value={task.subcontractorName} />
<Meta icon={Building2} label="Assigned By" value={`${task.assignedByName} · ${task.companyName}`} />
<Meta icon={MapPin} label="Location" value={task.location} />
<Meta icon={Calendar} label="Due Date" value={formatDate(task.dueDate)} />
<Meta icon={Calendar} label="Created" value={formatDate(task.createdAt)} />
<Meta icon={Calendar} label="Last Updated" value={formatDate(task.updatedAt)} />
</div>
{/* Description */}
{task.description && (
<div className="p-4 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/10">
<h4 className="text-xs font-bold uppercase tracking-wider text-zinc-500 mb-2">Description</h4>
<p className="text-sm text-zinc-700 dark:text-zinc-300 whitespace-pre-line">{task.description}</p>
</div>
)}
{/* Photos */}
<div>
<h4 className="text-xs font-bold uppercase tracking-wider text-zinc-500 mb-2 flex items-center gap-1.5">
<Camera size={12} /> Photos ({task.photos?.length || 0})
</h4>
{(!task.photos || task.photos.length === 0) ? (
<p className="text-xs text-zinc-500 italic">No photos attached.</p>
) : (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{task.photos.map((p) => (
<div key={p.id} className="rounded-xl overflow-hidden border border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5">
<div className="aspect-square bg-zinc-200 dark:bg-zinc-800">
<img src={p.url} alt={p.name || 'Task photo'} className="w-full h-full object-cover" />
</div>
{p.annotation && (
<div className="p-2 text-[11px] font-semibold text-zinc-700 dark:text-zinc-300">
{p.annotation}
</div>
)}
</div>
))}
</div>
)}
</div>
</div>
<div className="px-5 sm:px-6 py-4 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5 flex justify-end">
<button onClick={onClose} className="px-5 py-2 text-sm font-bold rounded-xl border border-zinc-200 dark:border-white/10 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-white/5 transition-colors">
Close
</button>
</div>
</div>
</div>,
document.body,
);
};
const Meta = ({ icon: MetaIcon, label, value }) => (
<div className="p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/10">
<div className="text-[10px] font-bold uppercase tracking-wider text-zinc-500 flex items-center gap-1.5 mb-1">
<MetaIcon size={12} /> {label}
</div>
<div className="text-sm font-semibold text-zinc-900 dark:text-white">{value || '—'}</div>
</div>
);
export default TaskViewModal;
+1295 -46
View File
File diff suppressed because it is too large Load Diff
+322 -147
View File
@@ -1,4 +1,4 @@
import React, { useState, useMemo, useRef } from 'react'; import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext'; import { useAuth } from '../../context/AuthContext';
import { useMockStore } from '../../data/mockStore'; import { useMockStore } from '../../data/mockStore';
@@ -12,7 +12,7 @@ import {
ArrowLeft, CheckCircle, Clock, AlertTriangle, PauseCircle, ShieldAlert, ArrowLeft, CheckCircle, Clock, AlertTriangle, PauseCircle, ShieldAlert,
FileText, DollarSign, GitPullRequest, AlertCircle, Activity, Milestone, FileText, DollarSign, GitPullRequest, AlertCircle, Activity, Milestone,
Shield, ChevronRight, Phone, MessageSquare, Mail, AlertOctagon, TrendingUp, Key, Zap, Camera, Plus, Map, User, Crosshair, Image as ImageIcon, MapPin, Shield, ChevronRight, Phone, MessageSquare, Mail, AlertOctagon, TrendingUp, Key, Zap, Camera, Plus, Map, User, Crosshair, Image as ImageIcon, MapPin,
Upload, Trash2, Eye, Pencil, X as XIcon, FolderOpen, Download, File, StickyNote, Banknote, ChevronLeft, ChevronDown as ChevronDownIcon, Info, Settings, Building2, User as UserIcon, Briefcase, Users Upload, Trash2, Eye, Pencil, X as XIcon, FolderOpen, Download, File, StickyNote, Banknote, ChevronLeft, ChevronDown as ChevronDownIcon, Info, Settings, Building2, User as UserIcon, Briefcase, Users, HardHat, Wrench, UserCheck, Wallet
} from 'lucide-react'; } from 'lucide-react';
import ChangeOrderDrawer from '../../components/owner/ChangeOrderDrawer'; import ChangeOrderDrawer from '../../components/owner/ChangeOrderDrawer';
import InvoiceDetailModal from '../../components/owner/InvoiceDetailModal'; import InvoiceDetailModal from '../../components/owner/InvoiceDetailModal';
@@ -125,6 +125,51 @@ function seedPaymentsMock(projectId) {
const PAYMENTS_PER_PAGE = 5; const PAYMENTS_PER_PAGE = 5;
// ── Expense type taxonomy ──────────────────────────────────────────────
const EXPENSE_TYPE_CONFIG = {
material: { label: 'Material', icon: Wrench, color: 'text-sky-600 dark:text-[#00f0ff]', bg: 'bg-sky-50 dark:bg-blue-500/10', border: 'border-sky-200 dark:border-blue-500/20' },
labor: { label: 'Labor', icon: HardHat, color: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-500/10', border: 'border-emerald-200 dark:border-emerald-500/20' },
team: { label: 'Team Commission', icon: UserCheck, color: 'text-purple-600 dark:text-purple-400', bg: 'bg-purple-50 dark:bg-purple-500/10', border: 'border-purple-200 dark:border-purple-500/20' },
subcontractor: { label: 'Subcontractor', icon: HardHat, color: 'text-amber-600 dark:text-[#fda913]', bg: 'bg-amber-50 dark:bg-[#fda913]/10', border: 'border-amber-200 dark:border-[#fda913]/20' },
other: { label: 'Other', icon: DollarSign, color: 'text-zinc-600 dark:text-zinc-400', bg: 'bg-zinc-100 dark:bg-white/5', border: 'border-zinc-200 dark:border-white/10' },
};
const SUBCONTRACTOR_WORK_TYPES = ['Plumbing', 'Electrical', 'Painting', 'Roofing', 'Civil work', 'HVAC', 'Carpentry', 'Other'];
const inferExpenseType = (category = '') => {
const c = (category || '').toLowerCase();
if (c.includes('material')) return 'material';
if (c.includes('labor')) return 'labor';
if (c.includes('commission') || c.includes('sales rep')) return 'team';
if (SUBCONTRACTOR_WORK_TYPES.some(w => c.includes(w.toLowerCase()))) return 'subcontractor';
return 'other';
};
function seedExpenseRowsMock(project) {
const baseRows = (project?.budgetBreakdown || []).map((b, i) => ({
id: `exp_base_${i}`,
type: inferExpenseType(b.category),
name: b.name || '—',
category: b.category || '',
allocated: Number(b.allocated) || 0,
actual: Number(b.actual) || 0,
paid: Number(b.actual) > 0 && Number(b.actual) >= Number(b.allocated) * 0.9,
}));
const seed = (project?.id || '').charCodeAt((project?.id || 'x').length - 1) % 3;
const teamRows = [
{ id: 'exp_team_1', type: 'team', name: 'Jesus Gonzales', category: 'Sales Rep', allocated: 4200, actual: 4200, paid: true },
{ id: 'exp_team_2', type: 'team', name: 'Frank Agent', category: 'Canvasser', allocated: 1500, actual: 1500, paid: false },
{ id: 'exp_team_3', type: 'team', name: 'Sarah Sales', category: 'Estimator', allocated: 1200, actual: 0, paid: false },
].slice(0, 2 + seed);
const subRows = [
{ id: 'exp_sub_1', type: 'subcontractor', name: 'PlumbPro Services', category: 'Plumbing', allocated: 1800, actual: 1800, paid: true },
{ id: 'exp_sub_2', type: 'subcontractor', name: 'Bright Electric LLC', category: 'Electrical', allocated: 2400, actual: 2150, paid: false },
{ id: 'exp_sub_3', type: 'subcontractor', name: 'Premium Painters', category: 'Painting', allocated: 950, actual: 950, paid: true },
{ id: 'exp_sub_4', type: 'subcontractor', name: 'Solid Civil Works', category: 'Civil work', allocated: 3200, actual: 0, paid: false },
].slice(0, 3 + seed);
return [...baseRows, ...teamRows, ...subRows];
}
const COMMISSION_TYPES = [ const COMMISSION_TYPES = [
{ value: 'flat', label: 'Flat Amount', hint: 'Fixed dollar amount' }, { value: 'flat', label: 'Flat Amount', hint: 'Fixed dollar amount' },
{ value: 'percent_gross', label: '% of Gross', hint: 'Percentage of Total Received' }, { value: 'percent_gross', label: '% of Gross', hint: 'Percentage of Total Received' },
@@ -158,6 +203,10 @@ const OwnerProjectDetail = () => {
const [paymentSort, setPaymentSort] = useState({ field: 'date', dir: 'desc' }); const [paymentSort, setPaymentSort] = useState({ field: 'date', dir: 'desc' });
const [paymentPage, setPaymentPage] = useState(0); const [paymentPage, setPaymentPage] = useState(0);
// ── Expense rows state (unified cost breakdown) ───────────────────────────
const [expenseRows, setExpenseRows] = useState([]);
const [expensesSeeded, setExpensesSeeded] = useState(false);
const [openTooltip, setOpenTooltip] = useState(null); const [openTooltip, setOpenTooltip] = useState(null);
// ── Commission config state ───────────────────────────────────────────── // ── Commission config state ─────────────────────────────────────────────
@@ -248,6 +297,31 @@ const OwnerProjectDetail = () => {
projects.find(p => p.id === projectId && p.ownerId === user?.id) projects.find(p => p.id === projectId && p.ownerId === user?.id)
, [projects, projectId, user]); , [projects, projectId, user]);
useEffect(() => {
if (project && !expensesSeeded) {
setExpenseRows(seedExpenseRowsMock(project));
setExpensesSeeded(true);
}
}, [project, expensesSeeded]);
const togglePaid = (id) => {
setExpenseRows(prev => prev.map(r => r.id === id ? { ...r, paid: !r.paid } : r));
};
const handleAddExpense = (data, type) => {
const amt = parseFloat(data.amount) || 0;
const newRow = {
id: `exp_${Date.now()}`,
type: type || data.type || 'other',
name: data.name || '',
category: data.category || '',
allocated: amt,
actual: amt,
paid: false,
};
setExpenseRows(prev => [newRow, ...prev]);
};
const teamFinancials = useMemo(() => { const teamFinancials = useMemo(() => {
if (!project) return { totalReceived: 0, grossProfit: 0 }; if (!project) return { totalReceived: 0, grossProfit: 0 };
const paid = (project.paymentSchedule || []) const paid = (project.paymentSchedule || [])
@@ -283,9 +357,16 @@ const OwnerProjectDetail = () => {
const activeCommissionConfig = resolvedCommission; const activeCommissionConfig = resolvedCommission;
const expenseTotals = useMemo(() => {
const total = expenseRows.reduce((s, r) => s + (Number(r.actual) || Number(r.allocated) || 0), 0);
const paid = expenseRows.reduce((s, r) => s + (r.paid ? (Number(r.actual) || Number(r.allocated) || 0) : 0), 0);
const outstanding = Math.max(0, total - paid);
return { total, paid, outstanding };
}, [expenseRows]);
const profitMetrics = useMemo(() => { const profitMetrics = useMemo(() => {
if (!project) return { totalCosts: 0, commission: 0, commissionFormula: '', grossProfit: 0, netProfit: 0, grossMargin: 0, netMargin: 0 }; if (!project) return { totalCosts: 0, totalExpenses: 0, paidExpenses: 0, outstandingExpenses: 0, totalBudget: 0, commission: 0, commissionFormula: '', grossProfit: 0, netProfit: 0, grossMargin: 0, netMargin: 0 };
const totalCosts = Number(project.actualCost ?? project.spent) || 0; const totalCosts = expenseTotals.total || Number(project.actualCost ?? project.spent) || 0;
const gross = totalReceived - totalCosts; const gross = totalReceived - totalCosts;
const { type, rate } = activeCommissionConfig; const { type, rate } = activeCommissionConfig;
@@ -315,11 +396,25 @@ const OwnerProjectDetail = () => {
} }
commission = Number.isFinite(commission) ? commission : 0; commission = Number.isFinite(commission) ? commission : 0;
const net = gross - commission; // Net Profit = Total Payments Received Total Expenses (expense table already includes team commission + subcontractors)
const net = totalReceived - expenseTotals.total;
const grossMargin = totalReceived > 0 ? (gross / totalReceived) * 100 : 0; const grossMargin = totalReceived > 0 ? (gross / totalReceived) * 100 : 0;
const netMargin = totalReceived > 0 ? (net / totalReceived) * 100 : 0; const netMargin = totalReceived > 0 ? (net / totalReceived) * 100 : 0;
return { totalCosts, commission, commissionFormula, grossProfit: gross, netProfit: net, grossMargin, netMargin }; const totalBudget = Number(project.approvedBudget ?? project.budget) || 0;
}, [project, totalReceived, activeCommissionConfig]); return {
totalCosts,
totalExpenses: expenseTotals.total,
paidExpenses: expenseTotals.paid,
outstandingExpenses: expenseTotals.outstanding,
totalBudget,
commission,
commissionFormula,
grossProfit: gross,
netProfit: net,
grossMargin,
netMargin,
};
}, [project, totalReceived, activeCommissionConfig, expenseTotals]);
if (!project) { if (!project) {
return ( return (
@@ -691,97 +786,200 @@ const OwnerProjectDetail = () => {
{/* BUDGET TAB */} {/* BUDGET TAB */}
{activeTab === 'budget' && ( {activeTab === 'budget' && (
<div className="space-y-6 max-w-7xl mx-auto"> <div className="space-y-6 max-w-7xl mx-auto">
{budgetChartData.length > 0 ? ( {/* Budget & Costs Summary Cards */}
<> <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">
<NeoCard spotlightColor="rgba(0, 240, 255, 0.1)"> {[
<div className="flex items-center justify-between mb-1"> { label: 'Total Budget', value: profitMetrics.totalBudget, icon: Wallet, color: 'text-sky-600 dark:text-[#00f0ff]', spotlight: 'rgba(0, 240, 255, 0.12)' },
<div className="flex items-center gap-3"> { label: 'Total Expenses', value: profitMetrics.totalExpenses, icon: Wrench, color: 'text-amber-600 dark:text-[#fda913]', spotlight: 'rgba(253, 169, 19, 0.12)' },
<DollarSign className={NEON_BLUE} size={20} /> { label: 'Payments Received', value: totalReceived, icon: Banknote, color: 'text-emerald-600 dark:text-[#39ff14]', spotlight: 'rgba(57, 255, 20, 0.12)' },
<h3 className="text-lg font-bold text-zinc-900 dark:text-white tracking-widest uppercase">Budget Breakdown</h3> { label: 'Outstanding Expenses', value: profitMetrics.outstandingExpenses, icon: AlertCircle, color: 'text-orange-600 dark:text-[#ff4500]', spotlight: 'rgba(255, 69, 0, 0.12)' },
{
label: 'Net Profit',
value: profitMetrics.netProfit,
icon: TrendingUp,
color: profitMetrics.netProfit >= 0 ? 'text-emerald-600 dark:text-[#39ff14]' : 'text-red-600 dark:text-[#ff003c]',
spotlight: profitMetrics.netProfit >= 0 ? 'rgba(57, 255, 20, 0.12)' : 'rgba(255, 0, 60, 0.12)',
emphasis: true,
},
].map((c, i) => {
const CardIcon = c.icon;
return (
<NeoCard key={i} spotlightColor={c.spotlight} innerClassName="!p-4">
<div className="flex items-center gap-2 mb-2">
<CardIcon size={14} className={c.color} />
<h4 className="text-[10px] font-mono font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-widest truncate">{c.label}</h4>
</div> </div>
<button <div className={`font-mono font-black tracking-tight ${c.emphasis ? 'text-2xl sm:text-3xl' : 'text-lg sm:text-xl'} ${c.color}`}>
onClick={() => setCreateModalConfig({ {c.value >= 0 ? '' : '-'}{formatCurrency(Math.abs(c.value))}
title: 'Add Budget Cost', icon: DollarSign, iconColor: 'text-[#39ff14]', iconBg: 'bg-[#39ff14]/10', </div>
submitLabel: 'Save Cost', submitColor: 'bg-[#39ff14]/20 text-[#39ff14] border-[#39ff14]/30', {c.label === 'Net Profit' && (
fields: [ <p className="mt-1 text-[10px] font-mono text-zinc-500 dark:text-zinc-500 truncate">
{ name: 'category', label: 'Category', type: 'text', required: true }, Received Expenses
{ name: 'allocated', label: 'Allocated Amount', type: 'number', required: true }, </p>
{ name: 'spent', label: 'Actual Spent', type: 'number' } )}
], {c.label === 'Outstanding Expenses' && (
onSubmit: handleCreateSubmit <p className="mt-1 text-[10px] font-mono text-zinc-500 dark:text-zinc-500 truncate">
})} Paid: {formatCurrency(profitMetrics.paidExpenses)}
className="bg-blue-500/10 hover:bg-blue-500/20 text-[#00f0ff] border border-blue-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2" </p>
> )}
<Plus size={14} /> Add Cost </NeoCard>
</button> );
})}
</div>
{budgetChartData.length > 0 && (
<NeoCard spotlightColor="rgba(0, 240, 255, 0.1)">
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-3">
<DollarSign className={NEON_BLUE} size={20} />
<h3 className="text-lg font-bold text-zinc-900 dark:text-white tracking-widest uppercase">Budget Breakdown</h3>
</div> </div>
<p className="text-xs text-zinc-400 mb-6 font-mono">Allocated vs Actual ($k)</p> </div>
<div className="h-64 bg-zinc-50 dark:bg-black/20 rounded-xl p-4 border border-zinc-200 dark:border-white/5"> <p className="text-xs text-zinc-400 mb-6 font-mono">Allocated vs Actual ($k)</p>
<ResponsiveContainer width="99%" height={256} minWidth={1} minHeight={1}> <div className="h-64 bg-zinc-50 dark:bg-black/20 rounded-xl p-4 border border-zinc-200 dark:border-white/5">
<BarChart data={budgetChartData} barGap={2}> <ResponsiveContainer width="99%" height={256} minWidth={1} minHeight={1}>
<XAxis dataKey="name" tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} /> <BarChart data={budgetChartData} barGap={2}>
<YAxis tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} /> <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
<Tooltip content={<CustomTooltip />} /> <YAxis tick={{ fontSize: 11, fill: '#a1a1aa' }} axisLine={false} tickLine={false} />
<Bar dataKey="allocated" name="Allocated" fill="#3b82f6" radius={[4, 4, 0, 0]} /> <Tooltip content={<CustomTooltip />} />
<Bar dataKey="actual" name="Actual" fill="#22c55e" radius={[4, 4, 0, 0]} /> <Bar dataKey="allocated" name="Allocated" fill="#3b82f6" radius={[4, 4, 0, 0]} />
</BarChart> <Bar dataKey="actual" name="Actual" fill="#22c55e" radius={[4, 4, 0, 0]} />
</ResponsiveContainer> </BarChart>
</ResponsiveContainer>
</div>
</NeoCard>
)}
<NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="p-0 lg:p-0">
<div className="p-5 border-b border-zinc-200 dark:border-white/5 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div className="flex items-center gap-3">
<DollarSign className={NEON_GOLD} size={20} />
<h3 className="text-lg font-bold text-zinc-900 dark:text-white tracking-widest uppercase">Cost Breakdown / Expenses</h3>
<span className="text-xs font-bold bg-zinc-100 dark:bg-white/5 border border-zinc-200 dark:border-white/5 px-2 py-0.5 rounded-full text-zinc-500 dark:text-zinc-400">
{expenseRows.length}
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<button
onClick={() => setCreateModalConfig({
title: 'Add Team Commission Cost', icon: UserCheck, iconColor: 'text-purple-500 dark:text-purple-400', iconBg: 'bg-purple-500/10',
submitLabel: 'Save Team Cost', submitColor: 'bg-purple-500/20 text-purple-500 dark:text-purple-400 border-purple-500/30',
fields: [
{ name: 'name', label: 'Team Member Name', type: 'text', required: true, placeholder: 'e.g. Jesus Gonzales' },
{ name: 'category', label: 'Role / Category', type: 'text', required: true, placeholder: 'e.g. Sales Rep' },
{ name: 'amount', label: 'Commission Amount ($)', type: 'number', required: true },
],
onSubmit: (d) => handleAddExpense(d, 'team'),
})}
className="bg-purple-500/10 hover:bg-purple-500/20 text-purple-600 dark:text-purple-400 border border-purple-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
>
<UserCheck size={14} /> Add Team Cost
</button>
<button
onClick={() => setCreateModalConfig({
title: 'Add Subcontractor Cost', icon: HardHat, iconColor: 'text-amber-500 dark:text-[#fda913]', iconBg: 'bg-amber-500/10',
submitLabel: 'Save Subcontractor Cost', submitColor: 'bg-amber-500/20 text-amber-500 dark:text-[#fda913] border-amber-500/30',
fields: [
{ name: 'name', label: 'Subcontractor Name', type: 'text', required: true, placeholder: 'e.g. PlumbPro Services' },
{ name: 'category', label: 'Category / Work Type', type: 'select', required: true, options: SUBCONTRACTOR_WORK_TYPES.map(w => ({ label: w, value: w })) },
{ name: 'amount', label: 'Amount ($)', type: 'number', required: true },
],
onSubmit: (d) => handleAddExpense(d, 'subcontractor'),
})}
className="bg-amber-500/10 hover:bg-amber-500/20 text-amber-600 dark:text-[#fda913] border border-amber-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
>
<HardHat size={14} /> Add Subcontractor
</button>
<button
onClick={() => setCreateModalConfig({
title: 'Add Cost', icon: DollarSign, iconColor: 'text-[#39ff14]', iconBg: 'bg-[#39ff14]/10',
submitLabel: 'Save Cost', submitColor: 'bg-[#39ff14]/20 text-[#39ff14] border-[#39ff14]/30',
fields: [
{ name: 'name', label: 'Vendor / Source Name', type: 'text', required: true },
{ name: 'category', label: 'Category', type: 'text', required: true, placeholder: 'e.g. Materials - Shingles' },
{ name: 'amount', label: 'Amount ($)', type: 'number', required: true },
],
onSubmit: (d) => handleAddExpense(d, inferExpenseType(d.category)),
})}
className="bg-blue-500/10 hover:bg-blue-500/20 text-[#00f0ff] border border-blue-500/30 px-3 py-1.5 rounded-lg text-xs font-bold transition flex items-center gap-2"
>
<Plus size={14} /> Add Cost
</button>
</div>
</div> </div>
</NeoCard>
<NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="p-0 lg:p-0">
<div className="overflow-x-auto w-full rounded-2xl"> <div className="overflow-x-auto w-full rounded-2xl">
<table className="w-full text-left border-collapse min-w-[600px]"> <table className="w-full text-left border-collapse min-w-[860px]">
<thead className="bg-zinc-100 dark:bg-[#18181b]/80 border-b border-zinc-200 dark:border-white/10"> <thead className="bg-zinc-100 dark:bg-[#18181b]/80 border-b border-zinc-200 dark:border-white/10">
<tr> <tr>
{['Name', 'Category', 'Allocated', 'Actual', 'Variance'].map(h => ( <th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Type</th>
<th key={h} className={`px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-400 ${h !== 'Name' && h !== 'Category' ? 'text-right' : ''}`}>{h}</th> <th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Name</th>
))} <th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400">Category / Role</th>
<th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 text-right">Allocated</th>
<th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 text-right">Actual</th>
<th className="px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 dark:text-zinc-400 text-center">Paid</th>
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-zinc-100 dark:divide-white/5"> <tbody className="divide-y divide-zinc-100 dark:divide-white/5">
{(project.budgetBreakdown || []).map((b, i) => { {expenseRows.map((row) => {
const variance = b.actual - b.allocated; const cfg = EXPENSE_TYPE_CONFIG[row.type] || EXPENSE_TYPE_CONFIG.other;
const TypeIcon = cfg.icon;
return ( return (
<tr key={i} className="hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors"> <tr key={row.id} className="hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors">
<td className="px-5 py-4 text-sm text-zinc-500 dark:text-zinc-400">{b.name || '—'}</td> <td className="px-5 py-4">
<td className="px-5 py-4 font-bold text-sm text-zinc-900 dark:text-white">{b.category}</td> <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-widest border ${cfg.color} ${cfg.bg} ${cfg.border}`}>
<td className="px-5 py-4 text-right font-mono text-sm text-zinc-600 dark:text-zinc-300">{formatCurrency(b.allocated)}</td> <TypeIcon size={11} />
<td className="px-5 py-4 text-right font-mono text-sm text-[#00f0ff]">{formatCurrency(b.actual)}</td> {cfg.label}
<td className={`px-5 py-4 text-right font-mono text-sm font-bold ${variance > 0 ? 'text-[#ff4500]' : 'text-[#39ff14]'}`}> </span>
{variance > 0 ? '+' : ''}{formatCurrency(variance)} </td>
<td className="px-5 py-4 font-bold text-sm text-zinc-900 dark:text-white">{row.name || '—'}</td>
<td className="px-5 py-4 text-sm text-zinc-500 dark:text-zinc-400">{row.category || '—'}</td>
<td className="px-5 py-4 text-right font-mono text-sm text-zinc-600 dark:text-zinc-300">{formatCurrency(row.allocated)}</td>
<td className="px-5 py-4 text-right font-mono text-sm text-[#00f0ff]">{formatCurrency(row.actual)}</td>
<td className="px-5 py-4 text-center">
<label className="inline-flex items-center justify-center cursor-pointer">
<input
type="checkbox"
checked={!!row.paid}
onChange={() => togglePaid(row.id)}
className="sr-only peer"
aria-label={`Mark ${row.name || 'expense'} paid`}
/>
<span className={`w-5 h-5 rounded-md border flex items-center justify-center transition-colors ${row.paid
? 'bg-emerald-500 border-emerald-500 dark:bg-[#39ff14] dark:border-[#39ff14]'
: 'bg-white dark:bg-[#18181b] border-zinc-300 dark:border-white/20 hover:border-emerald-400'}`}>
{row.paid && <CheckCircle size={12} className="text-white dark:text-black" strokeWidth={3} />}
</span>
</label>
</td> </td>
</tr> </tr>
); );
})} })}
{expenseRows.length === 0 && (
<tr>
<td colSpan={6} className="px-5 py-10 text-center text-sm text-zinc-500 dark:text-zinc-400">
No expenses recorded yet.
</td>
</tr>
)}
</tbody> </tbody>
<tfoot className="border-t-2 border-zinc-300 dark:border-white/10"> <tfoot className="border-t-2 border-zinc-300 dark:border-white/10">
<tr className="bg-zinc-50 dark:bg-white/[0.03]"> <tr className="bg-zinc-50 dark:bg-white/[0.03]">
<td className="px-5 py-4" colSpan={2}> <td className="px-5 py-4" colSpan={3}>
<span className="text-xs font-bold uppercase tracking-widest text-zinc-500 dark:text-zinc-400">Totals</span> <span className="text-xs font-bold uppercase tracking-widest text-zinc-500 dark:text-zinc-400">Totals</span>
</td> </td>
<td className="px-5 py-4 text-right font-mono text-sm font-bold text-green-600 dark:text-[#39ff14]">{formatCurrency(totalReceived)}</td> <td className="px-5 py-4 text-right font-mono text-sm font-bold text-zinc-600 dark:text-zinc-300">
<td className="px-5 py-4 text-right font-mono text-sm font-bold text-[#00f0ff]">{formatCurrency(profitMetrics.totalCosts)}</td> {formatCurrency(expenseRows.reduce((s, r) => s + (Number(r.allocated) || 0), 0))}
{(() => { </td>
const totalVariance = profitMetrics.totalCosts - totalReceived; <td className="px-5 py-4 text-right font-mono text-sm font-bold text-[#00f0ff]">
return ( {formatCurrency(profitMetrics.totalExpenses)}
<td className={`px-5 py-4 text-right font-mono text-sm font-bold ${totalVariance > 0 ? 'text-[#ff4500]' : 'text-[#39ff14]'}`}> </td>
{totalVariance > 0 ? '+' : ''}{formatCurrency(totalVariance)} <td className="px-5 py-4 text-center text-[10px] font-mono font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-widest">
</td> {expenseRows.filter(r => r.paid).length}/{expenseRows.length}
); </td>
})()}
</tr> </tr>
</tfoot> </tfoot>
</table> </table>
</div> </div>
</NeoCard> </NeoCard>
</>
) : (
<NeoCard className="p-12 text-center text-zinc-500">
<DollarSign size={48} className="mx-auto mb-4 text-zinc-600" />
<p className="font-bold text-lg text-zinc-900 dark:text-white">No detailed budget breakdown available.</p>
<p className="text-sm mt-2 text-zinc-400 font-mono">Budget: {formatCurrency(project.approvedBudget || project.budget)} &nbsp;&middot;&nbsp; Spent: {formatCurrency(project.actualCost || project.spent)}</p>
</NeoCard>
)}
{/* Commission Configuration Card */} {/* Commission Configuration Card */}
<NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="!p-5"> <NeoCard spotlightColor="rgba(253, 169, 19, 0.1)" innerClassName="!p-5">
@@ -888,84 +1086,61 @@ const OwnerProjectDetail = () => {
</div> </div>
</NeoCard> </NeoCard>
{/* Profit Summary Cards */} {/* Net Profit Breakdown */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4"> <NeoCard
<NeoCard spotlightColor={profitMetrics.netProfit >= 0 ? "rgba(57, 255, 20, 0.12)" : "rgba(255, 0, 60, 0.12)"}
spotlightColor={profitMetrics.grossProfit >= 0 ? "rgba(57, 255, 20, 0.12)" : "rgba(255, 0, 60, 0.12)"} innerClassName="!p-5"
innerClassName="!p-5" >
> <div className="flex items-start justify-between mb-4">
<div className="flex items-start justify-between mb-3"> <div className="flex items-center gap-2">
<div className="flex items-center gap-2"> <TrendingUp size={18} className={profitMetrics.netProfit >= 0 ? NEON_GREEN : NEON_RED} />
<TrendingUp size={18} className={profitMetrics.grossProfit >= 0 ? NEON_GREEN : NEON_RED} /> <h4 className="text-sm font-mono font-bold text-zinc-900 dark:text-white uppercase tracking-widest">Net Profit Breakdown</h4>
<h4 className="text-xs font-mono font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-widest">Gross Profit</h4> </div>
</div> <div className="relative">
<div className="relative"> <button type="button" onClick={(e) => { e.stopPropagation(); setOpenTooltip(prev => prev === 'net' ? null : 'net'); }} className="p-1 rounded-lg hover:bg-zinc-100 dark:hover:bg-white/10 transition-colors">
<button type="button" onClick={(e) => { e.stopPropagation(); setOpenTooltip(prev => prev === 'gross' ? null : 'gross'); }} className="p-1 rounded-lg hover:bg-zinc-100 dark:hover:bg-white/10 transition-colors"> <Info size={14} className="text-zinc-400 dark:text-zinc-500" />
<Info size={14} className="text-zinc-400 dark:text-zinc-500" /> </button>
</button> {openTooltip === 'net' && (
{openTooltip === 'gross' && ( <div className="absolute right-0 top-2 z-30 w-72 p-3 rounded-xl bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-white/10 shadow-xl text-xs text-zinc-600 dark:text-zinc-300">
<div className="absolute right-0 top-2 z-30 w-64 p-3 rounded-xl bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-white/10 shadow-xl text-xs text-zinc-600 dark:text-zinc-300"> <p className="font-bold text-zinc-900 dark:text-white mb-1">Net Profit Formula</p>
<p className="font-bold text-zinc-900 dark:text-white mb-1">Gross Profit Formula</p> <p className="font-mono text-[11px]">Total Payments Received Total Expenses</p>
<p className="font-mono text-[11px]">Total Received Total Actual Costs</p> <div className="mt-2 pt-2 border-t border-zinc-100 dark:border-white/5 space-y-1">
<div className="mt-2 pt-2 border-t border-zinc-100 dark:border-white/5 space-y-1"> <p>{formatCurrency(totalReceived)} {formatCurrency(profitMetrics.totalExpenses)} = {formatCurrency(profitMetrics.netProfit)}</p>
<p>{formatCurrency(totalReceived)} {formatCurrency(profitMetrics.totalCosts)} = {formatCurrency(profitMetrics.grossProfit)}</p>
</div>
</div> </div>
)} <p className="mt-2 text-[10px] text-zinc-500">Total expenses include materials, labor, team commission, and subcontractor costs.</p>
</div> </div>
)}
</div> </div>
<div className={`text-3xl sm:text-4xl font-black font-mono tracking-tight ${profitMetrics.grossProfit >= 0 ? NEON_GREEN : NEON_RED}`}> </div>
{profitMetrics.grossProfit >= 0 ? '+' : ''}{formatCurrency(profitMetrics.grossProfit)} <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4">
<div className="bg-zinc-50 dark:bg-black/30 rounded-xl px-4 py-3 border border-zinc-100 dark:border-white/5">
<p className="text-[10px] font-mono font-bold text-zinc-500 dark:text-zinc-500 uppercase tracking-widest mb-1">Payments Received</p>
<p className="font-mono text-lg font-black text-emerald-600 dark:text-[#39ff14]">{formatCurrency(totalReceived)}</p>
</div> </div>
<div className="flex items-center gap-2 mt-2"> <div className="bg-zinc-50 dark:bg-black/30 rounded-xl px-4 py-3 border border-zinc-100 dark:border-white/5">
<span className={`text-xs font-bold px-2 py-0.5 rounded-full ${ <p className="text-[10px] font-mono font-bold text-zinc-500 dark:text-zinc-500 uppercase tracking-widest mb-1"> Total Expenses</p>
profitMetrics.grossMargin >= 0 <p className="font-mono text-lg font-black text-amber-600 dark:text-[#fda913]">{formatCurrency(profitMetrics.totalExpenses)}</p>
? 'text-green-600 dark:text-[#39ff14] bg-green-50 dark:bg-[#39ff14]/10 border border-green-200 dark:border-[#39ff14]/20'
: 'text-red-600 dark:text-[#ff003c] bg-red-50 dark:bg-[#ff003c]/10 border border-red-200 dark:border-[#ff003c]/20'
}`}>
{profitMetrics.grossMargin >= 0 ? '+' : ''}{profitMetrics.grossMargin.toFixed(1)}% margin
</span>
</div> </div>
</NeoCard> <div className={`rounded-xl px-4 py-3 border ${profitMetrics.netProfit >= 0 ? 'bg-emerald-50/60 dark:bg-[#39ff14]/5 border-emerald-200 dark:border-[#39ff14]/20' : 'bg-red-50/60 dark:bg-[#ff003c]/5 border-red-200 dark:border-[#ff003c]/20'}`}>
<p className="text-[10px] font-mono font-bold text-zinc-500 dark:text-zinc-500 uppercase tracking-widest mb-1">= Net Profit</p>
<NeoCard <p className={`font-mono text-lg font-black ${profitMetrics.netProfit >= 0 ? NEON_GREEN : NEON_RED}`}>
spotlightColor={profitMetrics.netProfit >= 0 ? "rgba(57, 255, 20, 0.12)" : "rgba(255, 0, 60, 0.12)"} {profitMetrics.netProfit >= 0 ? '+' : ''}{formatCurrency(profitMetrics.netProfit)}
innerClassName="!p-5" </p>
>
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2">
<DollarSign size={18} className={profitMetrics.netProfit >= 0 ? NEON_GREEN : NEON_RED} />
<h4 className="text-xs font-mono font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-widest">Net Profit</h4>
</div>
<div className="relative">
<button type="button" onClick={(e) => { e.stopPropagation(); setOpenTooltip(prev => prev === 'net' ? null : 'net'); }} className="p-1 rounded-lg hover:bg-zinc-100 dark:hover:bg-white/10 transition-colors">
<Info size={14} className="text-zinc-400 dark:text-zinc-500" />
</button>
{openTooltip === 'net' && (
<div className="absolute right-0 top-2 z-30 w-72 p-3 rounded-xl bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-white/10 shadow-xl text-xs text-zinc-600 dark:text-zinc-300">
<p className="font-bold text-zinc-900 dark:text-white mb-1">Net Profit Formula</p>
<p className="font-mono text-[11px]">Gross Profit Commission</p>
<div className="mt-2 pt-2 border-t border-zinc-100 dark:border-white/5 space-y-1">
<p>{formatCurrency(profitMetrics.grossProfit)} {formatCurrency(profitMetrics.commission)} = {formatCurrency(profitMetrics.netProfit)}</p>
</div>
</div>
)}
</div>
</div> </div>
<div className={`text-3xl sm:text-4xl font-black font-mono tracking-tight ${profitMetrics.netProfit >= 0 ? NEON_GREEN : NEON_RED}`}> </div>
{profitMetrics.netProfit >= 0 ? '+' : ''}{formatCurrency(profitMetrics.netProfit)} <div className="flex items-center gap-2">
</div> <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${
<div className="flex items-center gap-2 mt-2"> profitMetrics.netMargin >= 0
<span className={`text-xs font-bold px-2 py-0.5 rounded-full ${ ? 'text-green-600 dark:text-[#39ff14] bg-green-50 dark:bg-[#39ff14]/10 border border-green-200 dark:border-[#39ff14]/20'
profitMetrics.netMargin >= 0 : 'text-red-600 dark:text-[#ff003c] bg-red-50 dark:bg-[#ff003c]/10 border border-red-200 dark:border-[#ff003c]/20'
? 'text-green-600 dark:text-[#39ff14] bg-green-50 dark:bg-[#39ff14]/10 border border-green-200 dark:border-[#39ff14]/20' }`}>
: 'text-red-600 dark:text-[#ff003c] bg-red-50 dark:bg-[#ff003c]/10 border border-red-200 dark:border-[#ff003c]/20' {profitMetrics.netMargin >= 0 ? '+' : ''}{profitMetrics.netMargin.toFixed(1)}% margin
}`}> </span>
{profitMetrics.netMargin >= 0 ? '+' : ''}{profitMetrics.netMargin.toFixed(1)}% margin <span className="text-[10px] font-mono text-zinc-500 dark:text-zinc-500">
</span> Outstanding: {formatCurrency(profitMetrics.outstandingExpenses)}
</div> </span>
</NeoCard> </div>
</div> </NeoCard>
{/* Payments Received Table */} {/* Payments Received Table */}
<NeoCard spotlightColor="rgba(57, 255, 20, 0.1)" innerClassName="p-0 lg:p-0"> <NeoCard spotlightColor="rgba(57, 255, 20, 0.1)" innerClassName="p-0 lg:p-0">
+19
View File
@@ -8,6 +8,7 @@ import FinancialDetailsModal from '../../components/owner/FinancialDetailsModal'
import ActionCenterModal from '../../components/owner/ActionCenterModal'; import ActionCenterModal from '../../components/owner/ActionCenterModal';
import TeamManagementPanel from '../../components/owner/TeamManagementPanel'; import TeamManagementPanel from '../../components/owner/TeamManagementPanel';
import CommissionDistributionPanel from '../../components/owner/CommissionDistributionPanel'; import CommissionDistributionPanel from '../../components/owner/CommissionDistributionPanel';
import SubcontractorPaymentsPanel from '../../components/owner/SubcontractorPaymentsPanel';
import { SpotlightCard } from '../../components/SpotlightCard'; import { SpotlightCard } from '../../components/SpotlightCard';
import { import {
BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend
@@ -24,6 +25,7 @@ const OwnerSnapshot = () => {
orgCommissionDefaults, userCommissionOverrides, orgCommissionDefaults, userCommissionOverrides,
roleCommissionOverrides, orgMembers, roleCommissionOverrides, orgMembers,
addJobTeamMember, removeJobTeamMember, updateJobTeamMember, addJobTeamMember, removeJobTeamMember, updateJobTeamMember,
subcontractorTasks, subcontractors,
} = useMockStore(); } = useMockStore();
// Find the current owner profile // Find the current owner profile
@@ -404,6 +406,23 @@ const OwnerSnapshot = () => {
</SpotlightCard> </SpotlightCard>
</section> </section>
)} )}
{/* ── Owner's Box — Subcontractor Payments ── */}
{subcontractorTasks?.length > 0 && (
<section>
<h2 className="text-xl font-bold text-zinc-900 dark:text-white/90 mb-4 flex items-center">
<span className="w-2 h-8 bg-amber-500 rounded-full mr-3"></span>
Subcontractor Payments
</h2>
<SpotlightCard className="p-5 lg:p-6" spotlightColor="rgba(245, 158, 11, 0.06)">
<SubcontractorPaymentsPanel
subcontractorTasks={subcontractorTasks}
subcontractors={subcontractors}
projects={projects}
/>
</SpotlightCard>
</section>
)}
</div> </div>
{/* Interactive Modals */} {/* Interactive Modals */}
+658
View File
@@ -0,0 +1,658 @@
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useMockStore } from '../../data/mockStore';
import { usePermissions } from '../../hooks/usePermissions';
import { SpotlightCard } from '../../components/SpotlightCard';
import AssignTaskModal from '../../components/subcontractor/AssignTaskModal';
import TaskViewModal from '../../components/subcontractor/TaskViewModal';
import ReassignTaskModal from '../../components/subcontractor/ReassignTaskModal';
import {
Plus, Search, Filter, ClipboardList, MoreVertical, Eye, Pencil,
XCircle, Repeat, ChevronLeft, ChevronRight, Lock, Users, MapPin,
Calendar, AlertCircle, Clock, CheckCircle, PauseCircle, ChevronDown, Check,
} from 'lucide-react';
// Dark-mode-aware dropdown — replaces native <select>. The menu is portaled
// to <body> so it escapes the parent card's `overflow-hidden` clipping and any
// new stacking contexts created by table rows below.
function FilterPopover({ id, value, onChange, options, ariaLabel }) {
const [open, setOpen] = useState(false);
const [menuRect, setMenuRect] = useState(null);
const triggerRef = useRef(null);
const menuRef = useRef(null);
const updatePosition = () => {
if (!triggerRef.current) return;
const r = triggerRef.current.getBoundingClientRect();
setMenuRect({ top: r.bottom + 4, left: r.left, width: r.width });
};
useLayoutEffect(() => {
if (open) updatePosition();
}, [open]);
useEffect(() => {
if (!open) return;
const onClick = (e) => {
if (triggerRef.current?.contains(e.target)) return;
if (menuRef.current?.contains(e.target)) return;
setOpen(false);
};
const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
const onReflow = () => updatePosition();
document.addEventListener('mousedown', onClick);
document.addEventListener('keydown', onKey);
window.addEventListener('resize', onReflow);
window.addEventListener('scroll', onReflow, true);
return () => {
document.removeEventListener('mousedown', onClick);
document.removeEventListener('keydown', onKey);
window.removeEventListener('resize', onReflow);
window.removeEventListener('scroll', onReflow, true);
};
}, [open]);
const current = options.find(o => o.value === value) || options[0];
return (
<div className="relative w-full">
<button
id={id}
ref={triggerRef}
type="button"
aria-haspopup="listbox"
aria-expanded={open}
aria-label={ariaLabel}
onClick={() => setOpen(o => !o)}
className="w-full flex items-center justify-between gap-2 pl-3 pr-2 py-2 text-sm rounded-xl bg-zinc-100 dark:bg-white/5 border border-zinc-200 dark:border-white/10 text-zinc-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500/40 transition-colors"
>
<span className="truncate text-left">{current?.label ?? '—'}</span>
<ChevronDown size={14} className={`shrink-0 text-zinc-400 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && menuRect && createPortal(
<div
ref={menuRef}
role="listbox"
style={{
position: 'fixed',
top: menuRect.top,
left: menuRect.left,
width: menuRect.width,
}}
className="z-[10000] rounded-xl bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-white/10 shadow-xl shadow-black/10 dark:shadow-black/50 overflow-hidden"
>
<div className="max-h-56 overflow-y-auto custom-scrollbar py-1">
{options.map(opt => {
const isSelected = opt.value === value;
return (
<button
key={opt.value}
type="button"
role="option"
aria-selected={isSelected}
onClick={() => { onChange(opt.value); setOpen(false); }}
className={`w-full flex items-center justify-between px-3 py-2 text-sm text-left transition-colors ${
isSelected
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-500/10'
: 'text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/5'
}`}
>
<span className="truncate">{opt.label}</span>
{isSelected && <Check size={12} strokeWidth={2.5} className="shrink-0 opacity-70" />}
</button>
);
})}
</div>
</div>,
document.body,
)}
</div>
);
}
const PRIORITY_STYLES = {
low: { label: 'Low', cls: 'bg-zinc-200 text-zinc-700 dark:bg-zinc-700 dark:text-zinc-300', dot: 'bg-zinc-400' },
medium: { label: 'Medium', cls: 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400', dot: 'bg-blue-500' },
high: { label: 'High', cls: 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400', dot: 'bg-red-500' },
};
const STATUS_CONFIG = {
Assigned: { cls: 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400', icon: Clock },
'In Progress': { cls: 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400', icon: PauseCircle },
Completed: { cls: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400', icon: CheckCircle },
Cancelled: { cls: 'bg-zinc-200 text-zinc-600 dark:bg-zinc-700 dark:text-zinc-300', icon: XCircle },
};
const PAGE_SIZE = 8;
const formatDate = (iso) => {
if (!iso) return '—';
try { return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }); }
catch { return iso; }
};
const todayIso = () => new Date().toISOString().slice(0, 10);
const SubcontractorTasksPage = () => {
const { subcontractorTasks, subcontractors, taskStatuses, cancelSubcontractorTask } = useMockStore();
const { can } = usePermissions();
const canAssign = can('subcontractor_tasks', 'assign');
const [search, setSearch] = useState('');
const [statusFilter, setStatusFilter] = useState('all');
const [subFilter, setSubFilter] = useState('all');
const [dueFilter, setDueFilter] = useState('all'); // all | overdue | today | week | month
const [page, setPage] = useState(1);
// Modal state
const [createOpen, setCreateOpen] = useState(false);
const [editTask, setEditTask] = useState(null);
const [viewTask, setViewTask] = useState(null);
const [reassignTask, setReassignTask] = useState(null);
const [confirmCancel, setConfirmCancel] = useState(null);
const [openMenuId, setOpenMenuId] = useState(null);
// Derived
const filtered = useMemo(() => {
const q = search.trim().toLowerCase();
const today = todayIso();
const inDays = (n) => {
const d = new Date();
d.setDate(d.getDate() + n);
return d.toISOString().slice(0, 10);
};
const weekFromNow = inDays(7);
const monthFromNow = inDays(30);
return subcontractorTasks.filter(t => {
// Search
if (q) {
const blob = `${t.title} ${t.subcontractorName} ${t.location} ${t.companyName}`.toLowerCase();
if (!blob.includes(q)) return false;
}
// Status
if (statusFilter !== 'all' && t.status !== statusFilter) return false;
// Subcontractor
if (subFilter !== 'all' && t.subcontractorId !== subFilter) return false;
// Due date
if (dueFilter !== 'all' && t.dueDate) {
if (dueFilter === 'overdue' && !(t.dueDate < today && t.status !== 'Completed' && t.status !== 'Cancelled')) return false;
if (dueFilter === 'today' && t.dueDate !== today) return false;
if (dueFilter === 'week' && !(t.dueDate >= today && t.dueDate <= weekFromNow)) return false;
if (dueFilter === 'month' && !(t.dueDate >= today && t.dueDate <= monthFromNow)) return false;
}
return true;
});
}, [subcontractorTasks, search, statusFilter, subFilter, dueFilter]);
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
const safePage = Math.min(page, totalPages);
const pageStart = (safePage - 1) * PAGE_SIZE;
const paginated = filtered.slice(pageStart, pageStart + PAGE_SIZE);
// Reset to page 1 when filters change
React.useEffect(() => { setPage(1); }, [search, statusFilter, subFilter, dueFilter]);
// Close action menus on outside click
React.useEffect(() => {
const handler = () => setOpenMenuId(null);
if (openMenuId) document.addEventListener('click', handler);
return () => document.removeEventListener('click', handler);
}, [openMenuId]);
const stats = useMemo(() => ({
total: subcontractorTasks.length,
assigned: subcontractorTasks.filter(t => t.status === 'Assigned').length,
inProgress: subcontractorTasks.filter(t => t.status === 'In Progress').length,
completed: subcontractorTasks.filter(t => t.status === 'Completed').length,
}), [subcontractorTasks]);
return (
<div className="min-h-full bg-zinc-50 dark:bg-[#09090b] text-zinc-900 dark:text-white transition-colors duration-300 relative">
{/* Ambient bg */}
<div className="fixed top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
<div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-blue-500/5 dark:bg-blue-900/10 rounded-full blur-[120px]" />
<div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-purple-500/5 dark:bg-purple-900/10 rounded-full blur-[120px]" />
</div>
<div className="relative z-10 p-4 sm:p-8 max-w-7xl mx-auto space-y-6 pb-20">
{/* Header */}
<header className="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 border-b border-zinc-200 dark:border-white/5 pb-6">
<div>
<h1 className="text-3xl sm:text-4xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-zinc-900 to-zinc-600 dark:from-white dark:to-white/60 tracking-tight">
Subcontractor Tasks
</h1>
<p className="text-zinc-500 dark:text-zinc-400 mt-1 text-sm">
{stats.total} total · {stats.assigned} assigned · {stats.inProgress} in progress · {stats.completed} completed
</p>
</div>
{canAssign ? (
<button
type="button"
onClick={() => setCreateOpen(true)}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm uppercase tracking-widest text-white bg-blue-600 hover:bg-blue-500 shadow-lg shadow-blue-500/20 transition-all active:scale-[0.97]"
>
<Plus size={14} />
Assign Task
</button>
) : (
<div className="flex items-center gap-2 px-4 py-2.5 rounded-xl font-bold text-sm uppercase tracking-widest text-zinc-400 bg-zinc-200 dark:bg-zinc-800 cursor-not-allowed" title="You don't have permission to assign tasks">
<Lock size={14} />
Assign Task
</div>
)}
</header>
{/* Filters */}
<SpotlightCard className="p-4">
<div className="grid grid-cols-1 md:grid-cols-12 gap-3">
{/* Search */}
<div className="relative md:col-span-5">
<label htmlFor="search-tasks" className="sr-only">Search tasks</label>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400" size={16} />
<input
id="search-tasks"
type="text"
placeholder="Search title, subcontractor, location…"
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full bg-zinc-100 dark:bg-black/40 border border-zinc-200 dark:border-white/10 rounded-xl py-2 pl-10 pr-4 text-sm text-zinc-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500/20"
/>
</div>
{/* Subcontractor */}
<div className="md:col-span-3">
<FilterPopover
id="filter-sub"
ariaLabel="Filter by subcontractor"
value={subFilter}
onChange={setSubFilter}
options={[
{ value: 'all', label: 'All subcontractors' },
...subcontractors.map(s => ({ value: s.id, label: s.name })),
]}
/>
</div>
{/* Status */}
<div className="md:col-span-2">
<FilterPopover
id="filter-status"
ariaLabel="Filter by status"
value={statusFilter}
onChange={setStatusFilter}
options={[
{ value: 'all', label: 'All statuses' },
...taskStatuses.map(s => ({ value: s, label: s })),
]}
/>
</div>
{/* Due */}
<div className="md:col-span-2">
<FilterPopover
id="filter-due"
ariaLabel="Filter by due date"
value={dueFilter}
onChange={setDueFilter}
options={[
{ value: 'all', label: 'Any due date' },
{ value: 'overdue', label: 'Overdue' },
{ value: 'today', label: 'Due today' },
{ value: 'week', label: 'Next 7 days' },
{ value: 'month', label: 'Next 30 days' },
]}
/>
</div>
</div>
{(search || statusFilter !== 'all' || subFilter !== 'all' || dueFilter !== 'all') && (
<div className="mt-3 flex items-center justify-between text-xs text-zinc-500 dark:text-zinc-400">
<span className="flex items-center gap-1.5">
<Filter size={12} />
{filtered.length} match{filtered.length === 1 ? '' : 'es'}
</span>
<button
type="button"
onClick={() => { setSearch(''); setStatusFilter('all'); setSubFilter('all'); setDueFilter('all'); }}
className="font-bold uppercase tracking-wider text-blue-600 dark:text-blue-400 hover:underline"
>
Clear filters
</button>
</div>
)}
</SpotlightCard>
{/* Table */}
<SpotlightCard className="overflow-hidden">
{/* Desktop */}
<div className="hidden lg:block overflow-x-auto">
<table className="w-full text-left border-collapse">
<thead className="bg-zinc-50 dark:bg-[#18181b] border-b border-zinc-200 dark:border-white/10">
<tr>
<Th>Task</Th>
<Th>Subcontractor</Th>
<Th>Location</Th>
<Th>Due</Th>
<Th>Priority</Th>
<Th>Status</Th>
<Th>Created</Th>
<Th align="right">Actions</Th>
</tr>
</thead>
<tbody className="divide-y divide-zinc-100 dark:divide-white/5">
{paginated.length === 0 ? (
<tr>
<td colSpan={8}>
<EmptyState />
</td>
</tr>
) : paginated.map(task => (
<TaskRow
key={task.id}
task={task}
onView={() => setViewTask(task)}
onEdit={() => setEditTask(task)}
onCancel={() => setConfirmCancel(task)}
onReassign={() => setReassignTask(task)}
openMenu={openMenuId === task.id}
setOpenMenu={(open) => setOpenMenuId(open ? task.id : null)}
canAssign={canAssign}
/>
))}
</tbody>
</table>
</div>
{/* Mobile / tablet cards */}
<div className="lg:hidden divide-y divide-zinc-100 dark:divide-white/5">
{paginated.length === 0 ? (
<EmptyState />
) : paginated.map(task => (
<TaskCard
key={task.id}
task={task}
onView={() => setViewTask(task)}
onEdit={() => setEditTask(task)}
onCancel={() => setConfirmCancel(task)}
onReassign={() => setReassignTask(task)}
canAssign={canAssign}
/>
))}
</div>
{/* Pagination footer */}
<div className="px-5 py-3 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5 flex flex-col sm:flex-row justify-between items-center gap-3 text-xs">
<span className="text-zinc-500">
Showing {filtered.length === 0 ? 0 : pageStart + 1}{Math.min(pageStart + PAGE_SIZE, filtered.length)} of {filtered.length}
</span>
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={() => setPage(p => Math.max(1, p - 1))}
disabled={safePage === 1}
className="p-1.5 rounded-lg bg-white dark:bg-white/5 border border-zinc-200 dark:border-white/10 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-white/10 disabled:opacity-40 disabled:pointer-events-none transition-colors"
aria-label="Previous page"
>
<ChevronLeft size={14} />
</button>
<span className="px-3 py-1.5 rounded-lg bg-white dark:bg-white/5 border border-zinc-200 dark:border-white/10 font-mono font-bold text-zinc-900 dark:text-white">
{safePage} / {totalPages}
</span>
<button
type="button"
onClick={() => setPage(p => Math.min(totalPages, p + 1))}
disabled={safePage === totalPages}
className="p-1.5 rounded-lg bg-white dark:bg-white/5 border border-zinc-200 dark:border-white/10 text-zinc-500 hover:bg-zinc-100 dark:hover:bg-white/10 disabled:opacity-40 disabled:pointer-events-none transition-colors"
aria-label="Next page"
>
<ChevronRight size={14} />
</button>
</div>
</div>
</SpotlightCard>
</div>
{/* Modals */}
<AssignTaskModal isOpen={createOpen} onClose={() => setCreateOpen(false)} />
<AssignTaskModal isOpen={Boolean(editTask)} task={editTask} onClose={() => setEditTask(null)} />
<TaskViewModal isOpen={Boolean(viewTask)} task={viewTask} onClose={() => setViewTask(null)} />
<ReassignTaskModal isOpen={Boolean(reassignTask)} task={reassignTask} onClose={() => setReassignTask(null)} />
{/* Cancel confirmation */}
{confirmCancel && (
<ConfirmDialog
title="Cancel task assignment?"
body={
<>
This will set <span className="font-bold text-zinc-900 dark:text-white">{confirmCancel.title}</span> assigned to <span className="font-bold text-zinc-900 dark:text-white">{confirmCancel.subcontractorName}</span> to <span className="font-bold">Cancelled</span>. It will remain in the list for history.
</>
}
confirmLabel="Cancel Task"
confirmColor="bg-red-600 hover:bg-red-500"
onConfirm={() => { cancelSubcontractorTask(confirmCancel.id); setConfirmCancel(null); }}
onClose={() => setConfirmCancel(null)}
/>
)}
</div>
);
};
const Th = ({ children, align }) => (
<th className={`px-5 py-4 text-xs font-bold uppercase tracking-wider text-zinc-500 ${align === 'right' ? 'text-right' : ''}`}>
{children}
</th>
);
const StatusBadge = ({ status }) => {
const cfg = STATUS_CONFIG[status] || STATUS_CONFIG.Assigned;
const Icon = cfg.icon;
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wide ${cfg.cls}`}>
<Icon size={11} />
{status}
</span>
);
};
const PriorityBadge = ({ priority }) => {
const cfg = PRIORITY_STYLES[priority] || PRIORITY_STYLES.medium;
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide ${cfg.cls}`}>
<span className={`w-1.5 h-1.5 rounded-full ${cfg.dot}`} />
{cfg.label}
</span>
);
};
const isOverdue = (task) => task.dueDate && task.dueDate < todayIso() && task.status !== 'Completed' && task.status !== 'Cancelled';
const TaskRow = ({ task, onView, onEdit, onCancel, onReassign, openMenu, setOpenMenu, canAssign }) => {
const overdue = isOverdue(task);
const isClosed = task.status === 'Completed' || task.status === 'Cancelled';
return (
<tr className="hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors group">
<td className="px-5 py-4 max-w-xs">
<button type="button" onClick={onView} className="text-left">
<div className="font-semibold text-zinc-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors truncate">
{task.title}
</div>
<div className="text-[11px] text-zinc-500 font-mono mt-0.5">{task.id}</div>
</button>
</td>
<td className="px-5 py-4">
<div className="flex items-center gap-2">
<div className="w-7 h-7 rounded-full bg-blue-500/10 text-blue-500 flex items-center justify-center text-xs font-bold shrink-0">
{task.subcontractorName?.charAt(0)}
</div>
<span className="text-sm font-medium text-zinc-900 dark:text-white truncate">{task.subcontractorName}</span>
</div>
</td>
<td className="px-5 py-4">
<div className="flex items-center gap-1.5 text-sm text-zinc-600 dark:text-zinc-400 max-w-[220px]">
<MapPin size={12} className="text-zinc-400 shrink-0" />
<span className="truncate">{task.location}</span>
</div>
</td>
<td className="px-5 py-4 whitespace-nowrap">
<div className={`text-sm font-mono ${overdue ? 'text-red-500 font-bold' : 'text-zinc-700 dark:text-zinc-300'}`}>
{formatDate(task.dueDate)}
</div>
{overdue && (
<div className="text-[10px] font-bold uppercase text-red-500 flex items-center gap-1 mt-0.5">
<AlertCircle size={9} /> Overdue
</div>
)}
</td>
<td className="px-5 py-4"><PriorityBadge priority={task.priority} /></td>
<td className="px-5 py-4"><StatusBadge status={task.status} /></td>
<td className="px-5 py-4 whitespace-nowrap text-sm text-zinc-500">{formatDate(task.createdAt)}</td>
<td className="px-5 py-4 text-right relative">
<div className="inline-flex items-center gap-1">
<button
type="button"
onClick={onView}
className="p-1.5 rounded-lg text-zinc-500 hover:text-blue-600 hover:bg-blue-500/10 transition-colors"
aria-label="View task"
title="View"
>
<Eye size={14} />
</button>
<button
type="button"
onClick={(e) => { e.stopPropagation(); setOpenMenu(!openMenu); }}
className="p-1.5 rounded-lg text-zinc-500 hover:text-zinc-900 dark:hover:text-white hover:bg-zinc-200 dark:hover:bg-white/10 transition-colors"
aria-label="More actions"
aria-expanded={openMenu}
>
<MoreVertical size={14} />
</button>
</div>
{openMenu && (
<div
onClick={(e) => e.stopPropagation()}
className="absolute right-5 top-full mt-1 w-44 bg-white dark:bg-[#18181b] border border-zinc-200 dark:border-white/10 rounded-xl shadow-xl z-20 overflow-hidden text-left"
>
<MenuItem onClick={() => { setOpenMenu(false); onEdit(); }} icon={Pencil} disabled={!canAssign || isClosed}>
Edit
</MenuItem>
<MenuItem onClick={() => { setOpenMenu(false); onReassign(); }} icon={Repeat} disabled={!canAssign || isClosed}>
Reassign
</MenuItem>
<MenuItem onClick={() => { setOpenMenu(false); onCancel(); }} icon={XCircle} disabled={!canAssign || isClosed} variant="danger">
Cancel
</MenuItem>
</div>
)}
</td>
</tr>
);
};
const MenuItem = ({ icon: MenuIcon, children, onClick, disabled, variant }) => (
<button
type="button"
onClick={onClick}
disabled={disabled}
className={`w-full flex items-center gap-2 px-3 py-2 text-xs font-semibold transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${
variant === 'danger'
? 'text-red-600 dark:text-red-400 hover:bg-red-500/10'
: 'text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-white/5'
}`}
>
<MenuIcon size={13} />
{children}
</button>
);
const TaskCard = ({ task, onView, onEdit, onCancel, onReassign, canAssign }) => {
const overdue = isOverdue(task);
const isClosed = task.status === 'Completed' || task.status === 'Cancelled';
return (
<div className="p-4 active:bg-zinc-50 dark:active:bg-white/5 transition-colors">
<button type="button" onClick={onView} className="w-full text-left">
<div className="flex justify-between items-start gap-3 mb-2">
<div className="min-w-0 flex-1">
<h4 className="font-semibold text-zinc-900 dark:text-white truncate">{task.title}</h4>
<p className="text-[11px] text-zinc-500 font-mono mt-0.5">{task.id}</p>
</div>
<StatusBadge status={task.status} />
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-zinc-500 mb-2">
<span className="flex items-center gap-1"><Users size={11} />{task.subcontractorName}</span>
<span className="flex items-center gap-1"><MapPin size={11} /><span className="truncate max-w-[160px]">{task.location}</span></span>
</div>
<div className="flex flex-wrap items-center gap-2">
<PriorityBadge priority={task.priority} />
<span className={`flex items-center gap-1 text-[11px] font-mono ${overdue ? 'text-red-500 font-bold' : 'text-zinc-500'}`}>
<Calendar size={11} /> Due {formatDate(task.dueDate)}{overdue ? ' · OVERDUE' : ''}
</span>
</div>
</button>
<div className="mt-3 flex flex-wrap gap-2 pt-2 border-t border-zinc-100 dark:border-white/5">
<CardActionButton onClick={onView} icon={Eye}>View</CardActionButton>
<CardActionButton onClick={onEdit} icon={Pencil} disabled={!canAssign || isClosed}>Edit</CardActionButton>
<CardActionButton onClick={onReassign} icon={Repeat} disabled={!canAssign || isClosed}>Reassign</CardActionButton>
<CardActionButton onClick={onCancel} icon={XCircle} disabled={!canAssign || isClosed} variant="danger">Cancel</CardActionButton>
</div>
</div>
);
};
const CardActionButton = ({ icon: ActionIcon, children, onClick, disabled, variant }) => (
<button
type="button"
onClick={onClick}
disabled={disabled}
className={`flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${
variant === 'danger'
? 'text-red-600 dark:text-red-400 border-red-500/20 hover:bg-red-500/10'
: 'text-zinc-700 dark:text-zinc-300 border-zinc-200 dark:border-white/10 hover:bg-zinc-100 dark:hover:bg-white/5'
}`}
>
<ActionIcon size={12} />
{children}
</button>
);
const EmptyState = () => (
<div className="py-16 text-center text-zinc-500">
<ClipboardList size={32} className="mx-auto mb-3 text-zinc-400" />
<p className="font-semibold">No tasks match your filters.</p>
<p className="text-sm mt-1">Try clearing filters or assigning a new task.</p>
</div>
);
const ConfirmDialog = ({ title, body, confirmLabel, confirmColor, onConfirm, onClose }) => {
React.useEffect(() => {
const handler = (e) => { if (e.key === 'Escape') onClose(); };
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [onClose]);
return (
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
<div className="relative w-full max-w-sm bg-white dark:bg-[#121214] rounded-2xl shadow-2xl border border-zinc-200 dark:border-white/10 overflow-hidden animate-in zoom-in-95 duration-200">
<div className="p-5 space-y-3">
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-red-500/10 text-red-500"><AlertCircle size={20} /></div>
<h2 className="text-base font-bold text-zinc-900 dark:text-white">{title}</h2>
</div>
<div className="text-sm text-zinc-600 dark:text-zinc-400">{body}</div>
</div>
<div className="px-5 py-3 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5 flex justify-end gap-2">
<button type="button" onClick={onClose} className="px-4 py-2 text-xs font-bold uppercase tracking-wider rounded-lg border border-zinc-200 dark:border-white/10 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-white/5 transition-colors">
Keep Task
</button>
<button type="button" onClick={onConfirm} className={`px-4 py-2 text-xs font-bold uppercase tracking-wider rounded-lg text-white shadow-lg shadow-red-500/20 transition-colors ${confirmColor}`}>
{confirmLabel}
</button>
</div>
</div>
</div>
);
};
export default SubcontractorTasksPage;
@@ -1,12 +1,14 @@
import React, { useState, useMemo } from 'react'; import React, { useState, useMemo } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../context/AuthContext'; import { useAuth } from '../../context/AuthContext';
import { useMockStore } from '../../data/mockStore'; import { useMockStore } from '../../data/mockStore';
import { StatCard } from '../../components/StatCard'; import { StatCard } from '../../components/StatCard';
import { SpotlightCard } from '../../components/SpotlightCard'; import { SpotlightCard } from '../../components/SpotlightCard';
import { CheckSquare, Clock, Wallet, MapPin, Camera, X, Calendar, DollarSign, ChevronRight } from 'lucide-react'; import { CheckSquare, Clock, Wallet, MapPin, Camera, X, Calendar, DollarSign, ChevronRight, AlertCircle, ArrowDown, ArrowUp, FileText, Receipt } from 'lucide-react';
import TaskDetailsModal from '../../components/contractor/TaskDetailsModal'; import TaskDetailsModal from '../../components/contractor/TaskDetailsModal';
import FinancialSummaryModal from '../../components/contractor/FinancialSummaryModal'; import FinancialSummaryModal from '../../components/contractor/FinancialSummaryModal';
import { NotificationsPanel } from '../../components/subcontractor/NotificationsPanel';
// --- Reusable list modal for filtered tasks / clock-in / payment history --- // --- Reusable list modal for filtered tasks / clock-in / payment history ---
const SubDetailModal = ({ isOpen, onClose, title, type, tasks, invoices, clockIns, onTaskClick }) => { const SubDetailModal = ({ isOpen, onClose, title, type, tasks, invoices, clockIns, onTaskClick }) => {
@@ -194,11 +196,18 @@ const SubDetailModal = ({ isOpen, onClose, title, type, tasks, invoices, clockIn
const SubContractorDashboard = () => { const SubContractorDashboard = () => {
const { user } = useAuth(); const { user } = useAuth();
const { projects } = useMockStore(); const { projects, subcontractorTasks, notifications, markNotificationRead } = useMockStore();
const navigate = useNavigate();
const subId = user?.id || 'sub_001'; const subId = user?.id || 'sub_001';
// Aggregate Tasks // Notifications for the current subcontractor (across all tasks).
const myNotifications = useMemo(
() => notifications.filter(n => n.recipientUserId === subId),
[notifications, subId],
);
// Aggregate Tasks (legacy milestone-based for stat parity below)
const myTasks = projects.flatMap(p => const myTasks = projects.flatMap(p =>
p.milestones.filter(m => m.assignedTo === subId) p.milestones.filter(m => m.assignedTo === subId)
.map(m => ({ ...m, projectAddress: p.address, projectId: p.id, projectStatus: p.status })) .map(m => ({ ...m, projectAddress: p.address, projectId: p.id, projectStatus: p.status }))
@@ -208,6 +217,12 @@ const SubContractorDashboard = () => {
const pendingTasks = myTasks.filter(t => t.status === 'pending'); const pendingTasks = myTasks.filter(t => t.status === 'pending');
const completedTasks = myTasks.filter(t => t.status === 'completed'); const completedTasks = myTasks.filter(t => t.status === 'completed');
// CRM-assigned tasks (the real "My Assignments")
const myAssignments = useMemo(
() => subcontractorTasks.filter(t => t.subcontractorId === subId),
[subcontractorTasks, subId],
);
// Financials // Financials
const myInvoices = projects.flatMap(p => const myInvoices = projects.flatMap(p =>
(p.invoices || []).filter(i => i.submittedBy === subId) (p.invoices || []).filter(i => i.submittedBy === subId)
@@ -224,6 +239,59 @@ const SubContractorDashboard = () => {
{ date: '2026-02-14', project: '2612 Dunwick Dr — Interior Renovation', clockIn: '7:30 AM', clockOut: '5:00 PM', hours: '9.5' }, { date: '2026-02-14', project: '2612 Dunwick Dr — Interior Renovation', clockIn: '7:30 AM', clockOut: '5:00 PM', hours: '9.5' },
], []); ], []);
// Project history & payment tracking
const [historyFilter, setHistoryFilter] = useState('all'); // all | Paid | Requested | Pending
const [historySort, setHistorySort] = useState('desc'); // desc = newest first
const [noteModal, setNoteModal] = useState(null); // { title, body, project, requestedAt, receivedAt, status }
const projectById = useMemo(() => {
const m = new Map();
for (const p of projects) m.set(p.id, p);
return m;
}, [projects]);
const paymentHistoryRows = useMemo(() => {
const items = myAssignments.map(t => {
const project = t.projectId ? projectById.get(t.projectId) : null;
const requestedAt = t.paymentRequestedAt || null;
const receivedAt = t.paidAt || null;
const status = t.paymentStatus === 'Paid'
? 'Paid'
: (requestedAt ? 'Requested' : 'Pending');
const expenses = (t.expenses || []).reduce((s, e) => s + (Number(e.amount) || 0), 0);
const fees = (t.fees || []).reduce((s, f) => s + (Number(f.amount) || 0), 0);
return {
id: t.id,
projectId: t.projectId || null,
projectName: project ? (project.projectType || project.address) : 'Standalone Task',
projectAddress: project?.address || t.location || '',
requestedAt,
receivedAt,
amount: expenses + fees,
note: t.title || '',
description: t.description || '',
status,
};
});
const filtered = historyFilter === 'all' ? items : items.filter(r => r.status === historyFilter);
const sorted = [...filtered].sort((a, b) => {
const av = a.requestedAt || '';
const bv = b.requestedAt || '';
if (av === bv) return 0;
if (!av) return 1; // missing requested dates sink to bottom
if (!bv) return -1;
return historySort === 'desc' ? (bv > av ? 1 : -1) : (av > bv ? 1 : -1);
});
return sorted;
}, [myAssignments, projectById, historyFilter, historySort]);
const historyCounts = useMemo(() => ({
all: myAssignments.length,
Paid: myAssignments.filter(t => t.paymentStatus === 'Paid').length,
Requested: myAssignments.filter(t => t.paymentStatus !== 'Paid' && t.paymentRequestedAt).length,
Pending: myAssignments.filter(t => !t.paymentRequestedAt).length,
}), [myAssignments]);
// Modal states // Modal states
const [detailModal, setDetailModal] = useState({ isOpen: false, type: null, title: '' }); const [detailModal, setDetailModal] = useState({ isOpen: false, type: null, title: '' });
const [selectedTask, setSelectedTask] = useState(null); const [selectedTask, setSelectedTask] = useState(null);
@@ -308,58 +376,221 @@ const SubContractorDashboard = () => {
</div> </div>
{/* Main Task List */} {/* Main Task List */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
<div className="lg:col-span-2"> <div className="lg:col-span-2 space-y-6">
<SpotlightCard className="p-6 h-full"> <SpotlightCard className="p-6">
<div className="flex justify-between items-center mb-6"> <div className="flex justify-between items-center mb-6">
<h2 className="text-lg font-bold text-zinc-900 dark:text-white">My Assignments</h2> <h2 className="text-lg font-bold text-zinc-900 dark:text-white">My Assignments</h2>
<span className="text-[11px] font-bold uppercase tracking-wider text-zinc-500">{myAssignments.length} task{myAssignments.length === 1 ? '' : 's'}</span>
</div> </div>
<div className="space-y-4"> <div className="space-y-4">
{myTasks.length > 0 ? myTasks.map((task, idx) => ( {myAssignments.length > 0 ? myAssignments.map(task => {
<div key={idx} className="group p-4 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-100 dark:border-white/5 hover:border-blue-500/30 transition-all cursor-pointer" onClick={() => handleTaskClick(task)}> const overdue = task.dueDate && task.dueDate < new Date().toISOString().slice(0, 10)
&& task.status !== 'Completed' && task.status !== 'Cancelled';
const statusTone = {
Completed: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400',
'In Progress': 'bg-blue-100 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400',
'On Hold': 'bg-amber-100 text-amber-600 dark:bg-amber-500/20 dark:text-amber-400',
Assigned: 'bg-zinc-100 text-zinc-600 dark:bg-white/10 dark:text-zinc-400',
Cancelled: 'bg-zinc-100 text-zinc-500 dark:bg-white/10 dark:text-zinc-500',
}[task.status] || 'bg-zinc-100 text-zinc-600 dark:bg-white/10 dark:text-zinc-400';
return (
<div
key={task.id}
role="button"
tabIndex={0}
onClick={() => navigate(`/subcontractor/tasks/${task.id}`)}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') navigate(`/subcontractor/tasks/${task.id}`); }}
className="group p-4 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-100 dark:border-white/5 hover:border-blue-500/30 transition-all cursor-pointer"
>
<div className="flex flex-col md:flex-row justify-between md:items-center gap-4"> <div className="flex flex-col md:flex-row justify-between md:items-center gap-4">
<div className="flex items-start gap-4"> <div className="flex items-start gap-4 min-w-0">
<div className={`p-3 rounded-lg ${task.status === 'completed' ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400' : <div className={`p-3 rounded-lg shrink-0 ${statusTone}`}>
task.status === 'in_progress' ? 'bg-blue-100 text-blue-600 dark:bg-blue-500/20 dark:text-blue-400' :
'bg-zinc-100 text-zinc-600 dark:bg-white/10 dark:text-zinc-400'
}`}>
<CheckSquare size={20} /> <CheckSquare size={20} />
</div> </div>
<div> <div className="min-w-0">
<h4 className="font-bold text-zinc-900 dark:text-white">{task.name}</h4> <h4 className="font-bold text-zinc-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors truncate">{task.title}</h4>
<div className="flex items-center text-xs text-zinc-500 dark:text-zinc-400 mt-1"> <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-zinc-500 dark:text-zinc-400 mt-1">
<MapPin size={12} className="mr-1" /> <span className="flex items-center gap-1"><MapPin size={12} />{task.location}</span>
{task.projectAddress} <span className="font-mono">{task.id}</span>
</div> </div>
</div> </div>
</div> </div>
<div className="flex items-center gap-4"> <div className="flex items-center gap-3 md:gap-4 shrink-0">
<div className="text-right"> <div className="text-right">
<p className="text-xs font-mono font-medium text-zinc-500 mb-1">Due: {task.dueDate}</p> <p className={`text-xs font-mono font-medium mb-1 flex items-center justify-end gap-1 ${overdue ? 'text-red-500 font-bold' : 'text-zinc-500'}`}>
<span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${task.status === 'completed' ? 'bg-emerald-100 text-emerald-600' : {overdue && <AlertCircle size={11} />}
task.status === 'in_progress' ? 'bg-blue-100 text-blue-600' : 'bg-amber-100 text-amber-600' Due: {task.dueDate}
}`}> </p>
{task.status.replace('_', ' ')} <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${statusTone}`}>
{task.status}
</span> </span>
</div> </div>
{task.status !== 'completed' && ( <ChevronRight size={16} className="text-zinc-400 group-hover:text-blue-500 transition-colors" />
<button className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-xs font-bold transition-colors"
onClick={(e) => { e.stopPropagation(); handleTaskClick(task); }}>
Update
</button>
)}
</div> </div>
</div> </div>
</div> </div>
)) : ( );
<div className="text-center py-10 text-zinc-500"><p>No tasks assigned.</p></div> }) : (
<div className="text-center py-10 text-zinc-500"><p>No tasks assigned yet.</p></div>
)} )}
</div> </div>
</SpotlightCard> </SpotlightCard>
{/* Project History & Payment Tracking */}
<SpotlightCard className="p-6">
<div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
<div>
<h2 className="text-lg font-bold text-zinc-900 dark:text-white flex items-center gap-2">
<Receipt size={18} className="text-amber-500 dark:text-amber-400" />
Project History & Payments
</h2>
<p className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">
Track payment requests and receipts across every project you've worked on.
</p>
</div>
<div className="flex items-center gap-2 flex-wrap">
{[
{ key: 'all', label: 'All', tone: 'bg-zinc-100 dark:bg-white/10 text-zinc-700 dark:text-zinc-200' },
{ key: 'Paid', label: 'Paid', tone: 'bg-emerald-100 dark:bg-emerald-500/15 text-emerald-700 dark:text-emerald-400' },
{ key: 'Requested', label: 'Requested', tone: 'bg-blue-100 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400' },
{ key: 'Pending', label: 'Pending', tone: 'bg-amber-100 dark:bg-amber-500/15 text-amber-700 dark:text-amber-400' },
].map(p => {
const active = historyFilter === p.key;
return (
<button
key={p.key}
type="button"
onClick={() => setHistoryFilter(p.key)}
className={`px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider transition-colors border ${active ? `${p.tone} border-transparent shadow-sm` : 'bg-transparent border-zinc-200 dark:border-white/10 text-zinc-500 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-white/5'}`}
>
{p.label}
<span className="ml-1.5 opacity-70">{historyCounts[p.key] ?? 0}</span>
</button>
);
})}
<button
type="button"
onClick={() => setHistorySort(d => d === 'desc' ? 'asc' : 'desc')}
className="px-3 py-1.5 rounded-lg text-[11px] font-bold uppercase tracking-wider border border-zinc-200 dark:border-white/10 text-zinc-600 dark:text-zinc-300 hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors flex items-center gap-1.5"
aria-label={`Sort by requested date ${historySort === 'desc' ? 'descending' : 'ascending'}`}
>
{historySort === 'desc' ? <ArrowDown size={12} /> : <ArrowUp size={12} />}
{historySort === 'desc' ? 'Newest' : 'Oldest'}
</button>
</div>
</div>
{paymentHistoryRows.length === 0 ? (
<div className="py-10 text-center">
<FileText size={28} className="mx-auto mb-3 text-zinc-400" />
<p className="text-sm text-zinc-500">No project history yet.</p>
<p className="text-xs text-zinc-400 mt-1">
{historyFilter === 'all' ? 'Tasks assigned to you will appear here.' : `No projects with status "${historyFilter}".`}
</p>
</div>
) : (
<div className="overflow-x-auto rounded-xl border border-zinc-200 dark:border-white/5">
<table className="w-full text-left min-w-[940px]">
<thead>
<tr className="border-b border-zinc-200 dark:border-white/5 bg-zinc-50 dark:bg-white/[0.02]">
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Project ID</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Project Name</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">
<button
type="button"
onClick={() => setHistorySort(d => d === 'desc' ? 'asc' : 'desc')}
className="inline-flex items-center gap-1 hover:text-zinc-900 dark:hover:text-white transition-colors"
title="Sort by requested date"
>
Requested
{historySort === 'desc' ? <ArrowDown size={10} /> : <ArrowUp size={10} />}
</button>
</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Received</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest text-right">Amount</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Note</th>
<th className="px-4 py-2.5 text-[10px] font-mono font-bold text-zinc-500 uppercase tracking-widest">Status</th>
</tr>
</thead>
<tbody>
{paymentHistoryRows.map(row => {
const unpaid = row.status !== 'Paid';
const statusTone = {
Paid: 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-500/15 dark:text-emerald-400 dark:border-emerald-500/20',
Requested: 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-500/15 dark:text-blue-400 dark:border-blue-500/20',
Pending: 'bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-500/15 dark:text-amber-400 dark:border-amber-500/20',
}[row.status] || 'bg-zinc-100 text-zinc-600 border-zinc-200 dark:bg-white/5 dark:text-zinc-400 dark:border-white/10';
return (
<tr
key={row.id}
role="button"
tabIndex={0}
onClick={() => navigate(`/subcontractor/tasks/${row.id}`)}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') navigate(`/subcontractor/tasks/${row.id}`); }}
className={`border-b border-zinc-100 dark:border-white/[0.03] hover:bg-zinc-50 dark:hover:bg-white/[0.02] transition-colors cursor-pointer group ${unpaid ? 'border-l-2 border-l-amber-400/60 dark:border-l-amber-500/40' : ''}`}
>
<td className="px-4 py-3">
<span className="text-[11px] font-mono text-zinc-500 dark:text-zinc-400">
{row.projectId || ''}
</span>
</td>
<td className="px-4 py-3">
<div className="min-w-0">
<div className="text-xs font-semibold text-zinc-900 dark:text-white group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors truncate max-w-[220px]" title={row.projectName}>
{row.projectName}
</div>
{row.projectAddress && (
<div className="text-[10px] text-zinc-500 dark:text-zinc-400 truncate max-w-[220px]" title={row.projectAddress}>
{row.projectAddress}
</div>
)}
</div>
</td>
<td className="px-4 py-3">
<span className="text-[11px] font-mono text-zinc-600 dark:text-zinc-300 whitespace-nowrap">
{row.requestedAt ? new Date(row.requestedAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : ''}
</span>
</td>
<td className="px-4 py-3">
<span className={`text-[11px] font-mono whitespace-nowrap ${row.receivedAt ? 'text-emerald-600 dark:text-emerald-400 font-semibold' : 'text-amber-600 dark:text-amber-400/80'}`}>
{row.receivedAt ? new Date(row.receivedAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'Not received'}
</span>
</td>
<td className="px-4 py-3 text-right">
<span className={`font-mono text-xs font-bold whitespace-nowrap ${row.amount > 0 ? (row.status === 'Paid' ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400') : 'text-zinc-400 dark:text-zinc-500'}`}>
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(row.amount)}
</span>
</td>
<td className="px-4 py-3">
<button
type="button"
onClick={(e) => { e.stopPropagation(); setNoteModal(row); }}
className="inline-flex items-center gap-1.5 text-[11px] text-zinc-600 dark:text-zinc-300 hover:text-blue-600 dark:hover:text-blue-400 max-w-[220px] truncate"
title={row.note}
>
<FileText size={11} className="shrink-0" />
<span className="truncate">{row.note || 'View note'}</span>
</button>
</td>
<td className="px-4 py-3">
<span className={`text-[11px] font-bold rounded-md px-1.5 py-0.5 border whitespace-nowrap ${statusTone}`}>
{row.status}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</SpotlightCard>
</div> </div>
{/* Earnings Widget */} {/* Right column: Earnings + Notifications */}
<div> <div className="space-y-6">
<SpotlightCard className="p-6"> <SpotlightCard className="p-6">
<h2 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Earnings Tracker</h2> <h2 className="text-lg font-bold text-zinc-900 dark:text-white mb-4">Earnings Tracker</h2>
<div className="relative pt-4 pb-8"> <div className="relative pt-4 pb-8">
@@ -385,9 +616,79 @@ const SubContractorDashboard = () => {
</button> </button>
</div> </div>
</SpotlightCard> </SpotlightCard>
<NotificationsPanel
notifications={myNotifications}
onMarkAllRead={() => myNotifications.forEach(n => !n.isRead && markNotificationRead(n.id))}
onNotificationClick={(n) => { if (!n.isRead) markNotificationRead(n.id); }}
/>
</div> </div>
</div> </div>
{/* Note detail modal */}
{noteModal && createPortal(
<div className="fixed inset-0 z-[9999] flex items-center justify-center p-4" role="dialog" aria-modal="true">
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setNoteModal(null)} />
<div className="relative w-full max-w-lg bg-white dark:bg-[#121214] rounded-2xl shadow-2xl border border-zinc-200 dark:border-white/10 overflow-hidden animate-in zoom-in-95 duration-200">
<div className="px-6 py-5 border-b border-zinc-200 dark:border-white/10 flex justify-between items-center bg-zinc-50/50 dark:bg-white/5">
<h2 className="text-lg font-bold text-zinc-900 dark:text-white">Note Detail</h2>
<button onClick={() => setNoteModal(null)} className="p-2 rounded-lg bg-zinc-100 dark:bg-white/10 text-zinc-500 hover:text-red-500 transition-colors"><X size={18} /></button>
</div>
<div className="p-6 space-y-4">
<div>
<div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mb-1">Project</div>
<div className="font-semibold text-zinc-900 dark:text-white">{noteModal.projectName}</div>
{noteModal.projectAddress && (
<div className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">{noteModal.projectAddress}</div>
)}
</div>
<div className="grid grid-cols-3 gap-3 text-sm">
<div className="p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/5">
<div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mb-1">Requested</div>
<div className="font-mono text-zinc-900 dark:text-white">
{noteModal.requestedAt ? new Date(noteModal.requestedAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : ''}
</div>
</div>
<div className="p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/5">
<div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mb-1">Received</div>
<div className={`font-mono ${noteModal.receivedAt ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400'}`}>
{noteModal.receivedAt ? new Date(noteModal.receivedAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'Not received'}
</div>
</div>
<div className="p-3 rounded-xl bg-zinc-50 dark:bg-white/5 border border-zinc-200 dark:border-white/5">
<div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mb-1">Amount</div>
<div className={`font-mono font-bold ${noteModal.amount > 0 ? (noteModal.status === 'Paid' ? 'text-emerald-600 dark:text-emerald-400' : 'text-amber-600 dark:text-amber-400') : 'text-zinc-400'}`}>
{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(noteModal.amount || 0)}
</div>
</div>
</div>
<div>
<div className="text-[10px] uppercase font-bold tracking-wider text-zinc-500 mb-1">Note</div>
<div className="text-sm text-zinc-900 dark:text-white font-semibold">{noteModal.note || ''}</div>
{noteModal.description && (
<p className="text-sm text-zinc-600 dark:text-zinc-300 mt-2 leading-relaxed whitespace-pre-line">{noteModal.description}</p>
)}
</div>
</div>
<div className="px-6 py-4 border-t border-zinc-200 dark:border-white/10 bg-zinc-50 dark:bg-white/5 flex justify-end gap-2">
<button
onClick={() => setNoteModal(null)}
className="px-4 py-2 text-sm font-bold rounded-xl border border-zinc-200 dark:border-white/10 hover:bg-zinc-100 dark:hover:bg-white/5 transition-colors"
>
Close
</button>
<button
onClick={() => { const id = noteModal.id; setNoteModal(null); navigate(`/subcontractor/tasks/${id}`); }}
className="px-4 py-2 text-sm font-bold rounded-xl bg-blue-600 hover:bg-blue-500 text-white transition-colors"
>
Open Task
</button>
</div>
</div>
</div>,
document.body
)}
{/* Modals */} {/* Modals */}
<TaskDetailsModal isOpen={isTaskModalOpen} onClose={() => setIsTaskModalOpen(false)} task={selectedTask} onUpdate={handleTaskUpdate} /> <TaskDetailsModal isOpen={isTaskModalOpen} onClose={() => setIsTaskModalOpen(false)} task={selectedTask} onUpdate={handleTaskUpdate} />
<FinancialSummaryModal isOpen={isFinancialModalOpen} onClose={() => setIsFinancialModalOpen(false)} role="SUBCONTRACTOR" data={financialData} /> <FinancialSummaryModal isOpen={isFinancialModalOpen} onClose={() => setIsFinancialModalOpen(false)} role="SUBCONTRACTOR" data={financialData} />
File diff suppressed because it is too large Load Diff