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
+5 -2
View File
@@ -5,7 +5,8 @@ import { useTheme } from '../context/ThemeContext';
import {
LayoutDashboard, Map, Calendar, LogOut, User, Home, MessageSquare,
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';
import PageTransition from './PageTransition';
@@ -150,6 +151,7 @@ const Layout = () => {
{ to: "/owner/estimates", icon: Calculator, label: "Estimates" },
{ to: "/admin/schedule", icon: Calendar, label: "Team Schedule" },
{ to: "/admin/leaderboard", icon: Trophy, label: "Leaderboard" },
{ to: "/owner/subcontractor-tasks", icon: HardHat, label: "Subcontractor Tasks" },
{ to: "/owner/settings", icon: Settings, label: "Org Settings" },
...commonItems,
];
@@ -169,7 +171,8 @@ const Layout = () => {
label: <span><span className="text-[#fda913]">Pro</span>Canvas</span>
},
{ 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,
];
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;