79beb7a7
3,200 lines · 154 KB xml
Raw
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timesheets Pro | Freelance & Project Admin Portal</title>
<!-- Tailwind CSS via CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
brand: {
50: '#eef2ff',
100: '#e0e7ff',
200: '#c7d2fe',
500: '#6366f1',
600: '#4f46e5',
700: '#4338ca',
800: '#3730a3',
900: '#312e81',
}
}
}
}
}
</script>
<style>
[x-cloak] { display: none !important; }
/* Custom scrollbar for modern look */
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: #f1f5f9; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
</style>
</head>
<body class="bg-slate-50 text-slate-800 min-h-screen flex flex-col font-sans antialiased">
<!-- Toast Notification Container -->
<div id="toast-container" class="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm pointer-events-none"></div>
<!-- Top Navigation Bar & Persona Switcher -->
<header class="bg-white border-b border-slate-200 sticky top-0 z-30 shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between h-16">
<!-- Brand Title & Icon -->
<div class="flex items-center space-x-3">
<div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-indigo-600 to-violet-500 flex items-center justify-center text-white shadow-md shadow-indigo-200">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div>
<div class="font-bold text-lg leading-tight text-slate-900 tracking-tight flex items-center gap-2">
Timesheets Pro
<span class="text-xs px-2 py-0.5 rounded-full font-medium bg-indigo-100 text-indigo-700">v1.0</span>
</div>
<p class="text-xs text-slate-500">Freelance & Project Admin Portal</p>
</div>
</div>
<!-- Header Actions: Role Switcher & User Profile / Auth -->
<div class="flex items-center space-x-3">
<!-- Role Switch Pills (Visible to Admin to toggle between admin & freelancer test views) -->
<div id="role-switch-container" class="bg-slate-100 p-1 rounded-xl flex items-center border border-slate-200">
<button id="role-btn-freelancer" onclick="switchRole('freelancer')"
class="px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 shadow-sm bg-white text-indigo-700">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<span>Freelancer View</span>
</button>
<button id="role-btn-admin" onclick="switchRole('admin')"
class="px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 text-slate-600 hover:text-slate-900">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
<span>Project Admin View</span>
</button>
</div>
<!-- Demo Accounts Quick Button & Dropdown -->
<div class="relative inline-block text-left" id="demo-dropdown-wrapper">
<button id="demo-dropdown-btn" type="button" onclick="toggleDemoDropdown(event)"
class="px-2.5 py-1.5 bg-amber-50 hover:bg-amber-100 text-amber-800 border border-amber-200 rounded-xl text-xs font-semibold flex items-center gap-1.5 transition shadow-sm"
title="Quickly switch between pre-configured demo accounts">
<svg class="w-3.5 h-3.5 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<span class="hidden sm:inline">Demo Accounts</span>
<span class="sm:hidden">Demo</span>
<svg class="w-3 h-3 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<div id="demo-dropdown-menu" class="hidden absolute right-0 mt-2 w-72 bg-white rounded-2xl shadow-2xl border border-slate-200 p-2 z-50">
<div class="text-[10px] uppercase font-bold text-slate-400 px-3 py-1.5 tracking-wider">Quick Demo Login</div>
<button type="button" onclick="loginDemo('admin')"
class="w-full text-left p-2.5 hover:bg-purple-50 rounded-xl transition flex items-center gap-3 group">
<div class="w-8 h-8 rounded-full bg-purple-100 text-purple-700 font-bold text-xs flex items-center justify-center flex-shrink-0 group-hover:bg-purple-600 group-hover:text-white transition">SJ</div>
<div class="flex-1 min-w-0">
<div class="flex items-center justify-between">
<p class="text-xs font-bold text-slate-800 truncate">Sarah Jenkins</p>
<span class="text-[9px] font-bold px-1.5 py-0.5 rounded bg-purple-100 text-purple-700 uppercase">Admin</span>
</div>
<p class="text-[10px] text-slate-500 truncate">sarah.jenkins@example.com</p>
</div>
</button>
<button type="button" onclick="loginDemo('freelancer')"
class="w-full text-left p-2.5 hover:bg-emerald-50 rounded-xl transition flex items-center gap-3 mt-1 group">
<div class="w-8 h-8 rounded-full bg-emerald-100 text-emerald-700 font-bold text-xs flex items-center justify-center flex-shrink-0 group-hover:bg-emerald-600 group-hover:text-white transition">CD</div>
<div class="flex-1 min-w-0">
<div class="flex items-center justify-between">
<p class="text-xs font-bold text-slate-800 truncate">Charlie Dupont</p>
<span class="text-[9px] font-bold px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-700 uppercase">Freelancer</span>
</div>
<p class="text-[10px] text-slate-500 truncate">charlie.dupont@example.com</p>
</div>
</button>
</div>
</div>
<!-- Real User Profile Widget (When Logged In) -->
<div id="header-user-profile" class="flex items-center space-x-2.5 pl-2 border-l border-slate-200">
<div class="w-8 h-8 rounded-full bg-gradient-to-tr from-indigo-600 to-purple-600 text-white flex items-center justify-center font-bold text-xs shadow-sm" id="user-profile-avatar">
--
</div>
<div class="hidden sm:block text-left">
<div class="flex items-center gap-1.5">
<span class="text-xs font-bold text-slate-800 leading-none truncate max-w-[130px]" id="user-profile-name">User</span>
<span class="text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider" id="user-profile-role-badge">Role</span>
</div>
<p class="text-[10px] text-slate-400 truncate max-w-[160px] leading-tight mt-0.5" id="user-profile-email">email</p>
</div>
<button onclick="logout()" title="Log Out" class="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-rose-50 rounded-lg transition" aria-label="Log out">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
</svg>
</button>
</div>
<!-- Logged Out Actions (When Not Logged In) -->
<div id="header-auth-buttons" class="hidden items-center space-x-2 pl-2 border-l border-slate-200">
<button onclick="openAuthModal('login')" class="px-3 py-1.5 text-xs font-semibold text-slate-700 hover:text-indigo-600 bg-slate-100 hover:bg-slate-200 rounded-xl transition">
Log In
</button>
<button onclick="openAuthModal('register')" class="px-3 py-1.5 text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-700 rounded-xl shadow-sm transition">
Sign Up
</button>
</div>
</div>
</div>
</div>
</header>
<!-- Admin Testing Notice Banner -->
<div id="admin-testing-notice" class="hidden bg-indigo-50 border-b border-indigo-200 text-indigo-800 text-xs py-2 px-4 text-center font-medium">
⚡ <strong>Admin Preview Mode:</strong> You are previewing the Freelancer View as an Administrator. Toggle back to <button onclick="switchRole('admin')" class="underline font-bold text-indigo-950 hover:text-indigo-700 ml-1">Project Admin View</button> anytime.
</div>
<!-- Guest / Signed-out Alert Banner -->
<div id="signed-out-banner" class="hidden bg-amber-50 border-b border-amber-200 text-amber-900 text-xs py-2.5 px-4 text-center font-medium">
🔒 You are currently in guest mode. <button onclick="openAuthModal('login')" class="underline font-bold text-amber-950">Log In</button> or select a <button onclick="loginDemo('admin')" class="underline font-bold text-amber-950">Demo Account</button> to save and submit timesheets.
</div>
<!-- Subheader Navigation (Role specific) -->
<div class="bg-white border-b border-slate-200 shadow-sm">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- Freelancer Subnav -->
<nav id="freelancer-subnav" class="flex space-x-6">
<button onclick="setFreelancerTab('entry')" id="f-tab-entry"
class="border-b-2 border-indigo-600 text-indigo-600 py-3.5 text-sm font-semibold flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
Timesheet Entry
</button>
<button onclick="setFreelancerTab('projects')" id="f-tab-projects"
class="border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-3.5 text-sm font-semibold flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
My Projects
<span id="badge-my-projects-count" class="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded-full font-medium">0</span>
</button>
<button onclick="setFreelancerTab('history')" id="f-tab-history"
class="border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-3.5 text-sm font-semibold flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Submitted Months
<span id="badge-history-count" class="text-xs bg-indigo-50 text-indigo-600 px-1.5 py-0.5 rounded-full font-medium">0</span>
</button>
</nav>
<!-- Admin Subnav -->
<nav id="admin-subnav" class="hidden flex space-x-6">
<button onclick="setAdminTab('validation')" id="a-tab-validation"
class="border-b-2 border-indigo-600 text-indigo-600 py-3.5 text-sm font-semibold flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
Timesheet Validation Queue
<span id="badge-admin-queue-count" class="text-xs bg-amber-100 text-amber-800 px-2 py-0.5 rounded-full font-bold">0</span>
</button>
<button onclick="setAdminTab('projects')" id="a-tab-projects"
class="border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-3.5 text-sm font-semibold flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
Projects & Assignments
<span id="badge-admin-projects-count" class="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded-full font-medium">0</span>
</button>
</nav>
</div>
</div>
<!-- Main Container -->
<main class="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- ================================================================= -->
<!-- FREELANCER SECTIONS -->
<!-- ================================================================= -->
<div id="freelancer-view-container">
<!-- 1. Timesheet Entry Tab -->
<div id="f-view-entry" class="space-y-6">
<!-- Controls & Status Bar -->
<div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200">
<div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
<div class="flex flex-wrap items-center gap-4">
<!-- Project Selector -->
<div>
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Project</label>
<select id="ts-project-select" onchange="onTimesheetContextChange()"
class="bg-slate-50 border border-slate-300 text-slate-900 text-sm rounded-xl focus:ring-indigo-500 focus:border-indigo-500 block p-2.5 font-medium min-w-[240px]">
<!-- Options filled via JS -->
</select>
</div>
<!-- Month Selector -->
<div>
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1.5">Target Month</label>
<input type="month" id="ts-month-input" onchange="onTimesheetContextChange()"
class="bg-slate-50 border border-slate-300 text-slate-900 text-sm rounded-xl focus:ring-indigo-500 focus:border-indigo-500 block p-2 font-medium">
</div>
<!-- Contract Range Info Pill -->
<div id="ts-contract-info" class="pt-5 flex items-center gap-2 text-xs text-slate-600">
<!-- Filled dynamically -->
</div>
</div>
<!-- Current Month Status Banner -->
<div class="flex items-center gap-3">
<div id="ts-status-badge-container">
<!-- Badge rendered here -->
</div>
</div>
</div>
<!-- Rejection Alert Banner (shown if refused) -->
<div id="ts-refused-alert" class="hidden mt-6 p-4 rounded-xl bg-rose-50 border border-rose-200 text-rose-900 flex items-start justify-between gap-4">
<div class="flex items-start gap-3">
<div class="p-1.5 rounded-lg bg-rose-100 text-rose-600 mt-0.5">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
</div>
<div>
<h4 class="font-bold text-sm text-rose-900">Admin Rejection Feedback</h4>
<p id="ts-refused-feedback-text" class="text-sm text-rose-800 mt-0.5"></p>
<p class="text-xs text-rose-600 mt-1">Please update your logged days, tasks or attach an adjusted invoice, then resubmit.</p>
</div>
</div>
<button onclick="unlockForResubmission()"
class="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white rounded-xl text-xs font-semibold shadow transition-all whitespace-nowrap">
Edit & Resubmit
</button>
</div>
<!-- Locked Notice Banner (shown if submitted / validated) -->
<div id="ts-locked-alert" class="hidden mt-6 p-4 rounded-xl bg-slate-50 border border-slate-200 text-slate-700 flex items-center gap-3">
<svg class="w-5 h-5 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
<span id="ts-locked-message" class="text-sm font-medium">This timesheet is locked against further edits.</span>
</div>
</div>
<!-- Metrics Summary Cards -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Total Days Worked</p>
<h3 id="stat-days-worked" class="text-2xl font-black text-slate-800">0 days</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-xl bg-violet-50 text-violet-600 flex items-center justify-center font-bold">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Meeting Hours</p>
<h3 id="stat-meeting-hours" class="text-2xl font-black text-slate-800">0.0 hrs</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
<div class="w-12 h-12 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Estimated Billing</p>
<h3 id="stat-estimated-billing" class="text-2xl font-black text-slate-800">€0</h3>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4">
<div id="stat-invoice-icon" class="w-12 h-12 rounded-xl bg-slate-100 text-slate-400 flex items-center justify-center font-bold">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Invoice Status</p>
<h3 id="stat-invoice-status" class="text-sm font-bold text-slate-700">Missing (Mandatory)</h3>
</div>
</div>
</div>
<!-- Day-by-Day Interactive Calendar Table -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div class="p-5 border-b border-slate-200 flex items-center justify-between">
<div>
<h3 class="text-base font-bold text-slate-900">Daily Log & Activities</h3>
<p class="text-xs text-slate-500">Toggle worked days, add details of completed tasks, and log meeting minutes.</p>
</div>
<div class="flex items-center gap-2">
<button type="button" onclick="quickFillWorkdays()" id="btn-quick-fill"
class="text-xs font-semibold px-3 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 transition">
Auto-check Mon-Fri
</button>
<button type="button" onclick="clearAllDays()" id="btn-clear-days"
class="text-xs font-semibold px-3 py-1.5 rounded-lg border border-slate-200 bg-slate-50 hover:bg-slate-100 text-slate-700 transition">
Clear All
</button>
</div>
</div>
<div class="overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="bg-slate-50 text-slate-500 text-xs uppercase font-semibold tracking-wider border-b border-slate-200">
<tr>
<th class="py-3 px-4 w-36">Date</th>
<th class="py-3 px-4 w-28 text-center">Worked</th>
<th class="py-3 px-4">Daily Tasks & Details</th>
<th class="py-3 px-4 w-44">Meeting (min)</th>
</tr>
</thead>
<tbody id="ts-days-tbody" class="divide-y divide-slate-100">
<!-- Dynamically generated rows -->
</tbody>
</table>
</div>
</div>
<!-- Mandatory Invoice Attachment & Submission Panel -->
<div class="bg-white rounded-2xl p-6 shadow-sm border border-slate-200 space-y-6">
<div class="border-b border-slate-200 pb-4">
<h3 class="text-base font-bold text-slate-900 flex items-center gap-2">
<svg class="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
</svg>
Mandatory Invoice Attachment
<span class="text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-200 px-2 py-0.5 rounded-full">Required to submit</span>
</h3>
<p class="text-xs text-slate-500 mt-1">Upload your freelance invoice in PDF or image format (PNG, JPG). Stored securely with your submission.</p>
</div>
<!-- File Upload Zone -->
<div class="flex flex-col md:flex-row items-center gap-6">
<div id="invoice-upload-box" class="flex-1 w-full border-2 border-dashed border-slate-300 hover:border-indigo-400 rounded-2xl p-6 text-center bg-slate-50/50 transition">
<input type="file" id="invoice-file-input" accept=".pdf,image/png,image/jpeg,image/webp" class="hidden" onchange="handleInvoiceFileUpload(event)">
<div id="invoice-empty-state">
<div class="w-12 h-12 mx-auto rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center mb-3">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
</svg>
</div>
<p class="text-sm font-semibold text-slate-700">Click to upload your invoice file</p>
<p class="text-xs text-slate-400 mt-0.5">PDF, PNG, JPG up to 10MB</p>
<div class="mt-4 flex flex-wrap items-center justify-center gap-2">
<button type="button" onclick="document.getElementById('invoice-file-input').click()" id="btn-browse-invoice"
class="px-4 py-2 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 rounded-xl text-xs font-semibold shadow-sm transition">
Browse File
</button>
<button type="button" onclick="generateSampleInvoicePDF()" id="btn-sample-invoice"
class="px-4 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl text-xs font-semibold transition flex items-center gap-1">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
Generate Sample PDF
</button>
</div>
</div>
<!-- Attached file indicator -->
<div id="invoice-attached-state" class="hidden flex items-center justify-between p-3 bg-white rounded-xl border border-indigo-100 shadow-sm">
<div class="flex items-center space-x-3 text-left">
<div class="w-10 h-10 rounded-lg bg-indigo-50 text-indigo-600 flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<div>
<p id="attached-filename" class="text-sm font-semibold text-slate-800 truncate max-w-xs"></p>
<p id="attached-filesize" class="text-xs text-slate-400"></p>
</div>
</div>
<div class="flex items-center gap-2">
<button type="button" onclick="previewCurrentInvoice()"
class="px-3 py-1.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-semibold rounded-lg transition">
Preview
</button>
<button type="button" onclick="removeAttachedInvoice()" id="btn-remove-invoice"
class="p-1.5 text-slate-400 hover:text-rose-600 rounded-lg hover:bg-rose-50 transition">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</button>
</div>
</div>
</div>
</div>
<!-- Bottom Action Buttons -->
<div class="pt-4 border-t border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-4">
<p class="text-xs text-slate-500">
<span class="font-semibold text-slate-700">Notice:</span> Submitting locks this month from further edits until an admin reviews it.
</p>
<div class="flex items-center gap-3 w-full sm:w-auto justify-end">
<button type="button" onclick="saveTimesheetDraft()" id="btn-save-draft"
class="px-5 py-2.5 rounded-xl border border-slate-300 bg-white hover:bg-slate-50 text-slate-700 text-sm font-semibold shadow-sm transition">
Save Draft
</button>
<button type="button" onclick="submitTimesheet()" id="btn-submit-timesheet"
class="px-6 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold shadow-md shadow-indigo-200 transition flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
Submit Timesheet
</button>
</div>
</div>
</div>
</div>
<!-- 2. My Projects Tab -->
<div id="f-view-projects" class="hidden space-y-6">
<div class="flex items-center justify-between">
<div>
<h2 class="text-xl font-bold text-slate-900">My Assigned Projects</h2>
<p class="text-xs text-slate-500 mt-1">Review active contracts, assignment dates, and client managers.</p>
</div>
</div>
<div id="f-projects-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Populated via JS -->
</div>
</div>
<!-- 3. Submitted Months History Tab -->
<div id="f-view-history" class="hidden space-y-6">
<div class="flex items-center justify-between">
<div>
<h2 class="text-xl font-bold text-slate-900">Timesheet History</h2>
<p class="text-xs text-slate-500 mt-1">All months logged and submitted for review across your assigned projects.</p>
</div>
</div>
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="bg-slate-50 text-slate-500 text-xs uppercase font-semibold tracking-wider border-b border-slate-200">
<tr>
<th class="py-3 px-4">Project</th>
<th class="py-3 px-4">Month</th>
<th class="py-3 px-4">Days Worked</th>
<th class="py-3 px-4">Meeting Hours</th>
<th class="py-3 px-4">Invoice</th>
<th class="py-3 px-4">Status</th>
<th class="py-3 px-4">Admin Notes</th>
<th class="py-3 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody id="f-history-tbody" class="divide-y divide-slate-100">
<!-- Dynamically populated -->
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- ================================================================= -->
<!-- PROJECT ADMIN SECTIONS -->
<!-- ================================================================= -->
<div id="admin-view-container" class="hidden space-y-6">
<!-- 1. Timesheet Validation Queue Tab -->
<div id="a-view-validation" class="space-y-6">
<!-- Metric Cards -->
<div class="grid grid-cols-1 sm:grid-cols-4 gap-4">
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center justify-between">
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Pending Review</p>
<h3 id="stat-admin-pending" class="text-2xl font-black text-amber-600">0</h3>
</div>
<div class="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center justify-between">
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Validated</p>
<h3 id="stat-admin-validated" class="text-2xl font-black text-emerald-600">0</h3>
</div>
<div class="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center justify-between">
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Refused / Revision</p>
<h3 id="stat-admin-refused" class="text-2xl font-black text-rose-600">0</h3>
</div>
<div class="w-10 h-10 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
</div>
<div class="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center justify-between">
<div>
<p class="text-xs text-slate-500 uppercase font-semibold">Total Submissions</p>
<h3 id="stat-admin-total" class="text-2xl font-black text-slate-800">0</h3>
</div>
<div class="w-10 h-10 rounded-xl bg-slate-100 text-slate-600 flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
</div>
</div>
<!-- Filters & Search -->
<div class="bg-white rounded-2xl p-4 shadow-sm border border-slate-200 flex flex-col sm:flex-row items-center justify-between gap-4">
<!-- Status Filter Tabs -->
<div class="flex items-center gap-1.5 p-1 bg-slate-100 rounded-xl border border-slate-200 w-full sm:w-auto">
<button onclick="filterAdminQueue('all')" id="btn-filter-all"
class="px-3 py-1.5 rounded-lg text-xs font-semibold bg-white text-slate-800 shadow-sm transition">
All
</button>
<button onclick="filterAdminQueue('submitted')" id="btn-filter-submitted"
class="px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition flex items-center gap-1">
<span>Pending Review</span>
<span id="badge-filter-pending-count" class="w-2 h-2 rounded-full bg-amber-500"></span>
</button>
<button onclick="filterAdminQueue('validated')" id="btn-filter-validated"
class="px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition">
Validated
</button>
<button onclick="filterAdminQueue('refused')" id="btn-filter-refused"
class="px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition">
Refused
</button>
</div>
<!-- Project Filter & Search -->
<div class="flex items-center gap-3 w-full sm:w-auto">
<select id="admin-project-filter" onchange="filterAdminQueue(currentAdminQueueFilter)"
class="bg-slate-50 border border-slate-300 text-slate-700 text-xs rounded-xl p-2 font-medium focus:ring-indigo-500">
<option value="">All Projects</option>
<!-- Filled via JS -->
</select>
<input type="text" id="admin-search-input" oninput="filterAdminQueue(currentAdminQueueFilter)" placeholder="Search freelancer..."
class="bg-slate-50 border border-slate-300 text-slate-700 text-xs rounded-xl p-2 font-medium focus:ring-indigo-500 w-44">
</div>
</div>
<!-- Validation Queue Table -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left text-sm">
<thead class="bg-slate-50 text-slate-500 text-xs uppercase font-semibold tracking-wider border-b border-slate-200">
<tr>
<th class="py-3 px-4">Freelancer</th>
<th class="py-3 px-4">Project</th>
<th class="py-3 px-4">Month</th>
<th class="py-3 px-4 text-center">Days Worked</th>
<th class="py-3 px-4 text-center">Meeting Hours</th>
<th class="py-3 px-4">Invoice</th>
<th class="py-3 px-4">Status</th>
<th class="py-3 px-4 text-right">Review Action</th>
</tr>
</thead>
<tbody id="admin-queue-tbody" class="divide-y divide-slate-100">
<!-- Dynamically populated -->
</tbody>
</table>
</div>
</div>
</div>
<!-- 2. Projects & Assignments Tab -->
<div id="a-view-projects" class="hidden space-y-6">
<div class="flex items-center justify-between">
<div>
<h2 class="text-xl font-bold text-slate-900">Projects & Freelancer Assignments</h2>
<p class="text-xs text-slate-500 mt-1">Manage project details, assign freelancers, configure start/end contract dates.</p>
</div>
<button onclick="openNewProjectModal()"
class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-semibold shadow-sm transition flex items-center gap-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
Create New Project
</button>
</div>
<div id="admin-projects-list" class="space-y-6">
<!-- Populated via JS -->
</div>
</div>
</div>
</main>
<!-- ================================================================= -->
<!-- MODALS -->
<!-- ================================================================= -->
<!-- 1. Detailed Timesheet Inspection Modal (Admin View) -->
<div id="modal-inspect-timesheet" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-4xl w-full shadow-2xl border border-slate-100 overflow-hidden flex flex-col max-h-[90vh]">
<!-- Modal Header -->
<div class="p-6 border-b border-slate-200 bg-slate-50 flex items-center justify-between">
<div>
<div class="flex items-center gap-3">
<h3 id="inspect-title" class="text-lg font-bold text-slate-900">Inspect Timesheet</h3>
<span id="inspect-status-badge"></span>
</div>
<p id="inspect-subtitle" class="text-xs text-slate-500 mt-1"></p>
</div>
<button onclick="closeInspectModal()" class="p-2 text-slate-400 hover:text-slate-600 rounded-xl hover:bg-slate-200 transition">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- Modal Body (Scrollable) -->
<div class="p-6 overflow-y-auto space-y-6 flex-1">
<!-- Summary stats -->
<div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
<div class="p-4 rounded-xl bg-slate-50 border border-slate-200">
<p class="text-xs font-semibold text-slate-500 uppercase">Days Worked</p>
<p id="inspect-days-worked" class="text-xl font-black text-slate-800 mt-1">0</p>
</div>
<div class="p-4 rounded-xl bg-slate-50 border border-slate-200">
<p class="text-xs font-semibold text-slate-500 uppercase">Meeting Hours</p>
<p id="inspect-meeting-hours" class="text-xl font-black text-slate-800 mt-1">0 hrs</p>
</div>
<div class="p-4 rounded-xl bg-slate-50 border border-slate-200">
<p class="text-xs font-semibold text-slate-500 uppercase">Daily Rate</p>
<p id="inspect-daily-rate" class="text-xl font-black text-slate-800 mt-1">€0</p>
</div>
<div class="p-4 rounded-xl bg-slate-50 border border-slate-200">
<p class="text-xs font-semibold text-slate-500 uppercase">Total Invoice Amount</p>
<p id="inspect-total-amount" class="text-xl font-black text-indigo-600 mt-1">€0</p>
</div>
</div>
<!-- Attached Invoice Section -->
<div class="p-4 rounded-2xl bg-indigo-50/50 border border-indigo-100 flex items-center justify-between">
<div class="flex items-center space-x-3">
<div class="w-10 h-10 rounded-xl bg-indigo-600 text-white flex items-center justify-center">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<div>
<p class="text-xs font-semibold text-slate-500 uppercase">Attached Invoice</p>
<p id="inspect-invoice-name" class="text-sm font-bold text-slate-900">No invoice attached</p>
</div>
</div>
<div class="flex items-center gap-2">
<button type="button" id="btn-inspect-invoice-view" onclick="viewModalInvoice()"
class="px-4 py-2 bg-white hover:bg-slate-50 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold shadow-sm transition">
View / Download Invoice
</button>
</div>
</div>
<!-- Previous Refusal Feedback if any -->
<div id="inspect-feedback-box" class="hidden p-4 rounded-xl bg-rose-50 border border-rose-200">
<p class="text-xs font-bold uppercase text-rose-700">Current Refusal Feedback:</p>
<p id="inspect-feedback-text" class="text-sm text-rose-900 mt-0.5"></p>
</div>
<!-- Detailed Days Worked Table -->
<div>
<h4 class="text-sm font-bold text-slate-800 mb-2">Detailed Days Breakdown</h4>
<div class="border border-slate-200 rounded-xl overflow-hidden">
<table class="w-full text-left text-xs">
<thead class="bg-slate-50 text-slate-500 font-semibold border-b border-slate-200 uppercase">
<tr>
<th class="py-2.5 px-4 w-32">Date</th>
<th class="py-2.5 px-4 w-20 text-center">Status</th>
<th class="py-2.5 px-4">Task Details</th>
<th class="py-2.5 px-4 w-32 text-right">Meeting Time</th>
</tr>
</thead>
<tbody id="inspect-days-tbody" class="divide-y divide-slate-100">
<!-- Days populated here -->
</tbody>
</table>
</div>
</div>
</div>
<!-- Modal Footer / Actions -->
<div class="p-6 border-t border-slate-200 bg-slate-50 flex flex-col sm:flex-row items-center justify-between gap-4">
<button onclick="closeInspectModal()" class="w-full sm:w-auto px-4 py-2 text-slate-600 text-xs font-semibold hover:text-slate-900">
Close
</button>
<div class="flex items-center gap-3 w-full sm:w-auto justify-end">
<button type="button" onclick="openRefusePrompt()"
class="w-full sm:w-auto px-5 py-2.5 bg-white hover:bg-rose-50 text-rose-600 border border-rose-200 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1.5">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
Refuse Month
</button>
<button type="button" onclick="validateCurrentMonth()"
class="w-full sm:w-auto px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold shadow-md shadow-emerald-200 transition flex items-center justify-center gap-1.5">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
Validate & Approve
</button>
</div>
</div>
</div>
</div>
<!-- 2. Refuse Feedback Prompt Modal -->
<div id="modal-refuse-prompt" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-lg w-full shadow-2xl border border-slate-100 overflow-hidden">
<div class="p-6 border-b border-slate-200">
<h3 class="text-base font-bold text-slate-900">Refuse Timesheet</h3>
<p class="text-xs text-slate-500 mt-1">Enter clear feedback so the freelancer can rectify the days, tasks, or invoice before resubmitting.</p>
</div>
<div class="p-6 space-y-4">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1.5">Rejection Feedback / Notes *</label>
<textarea id="refusal-feedback-input" rows="4" placeholder="e.g., The invoice amount does not match the 2 logged days. Please review and re-attach."
class="w-full text-sm p-3 rounded-xl border border-slate-300 focus:ring-rose-500 focus:border-rose-500"></textarea>
</div>
</div>
<div class="p-4 bg-slate-50 border-t border-slate-200 flex items-center justify-end gap-3">
<button onclick="closeRefusePrompt()" class="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-900">Cancel</button>
<button onclick="confirmRefuseTimesheet()" class="px-5 py-2.5 bg-rose-600 hover:bg-rose-700 text-white text-xs font-bold rounded-xl shadow-md transition">
Confirm Refusal
</button>
</div>
</div>
</div>
<!-- 3. Add Freelancer Assignment Modal -->
<div id="modal-add-assignment" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-lg w-full shadow-2xl border border-slate-100 overflow-hidden">
<div class="p-6 border-b border-slate-200">
<h3 class="text-base font-bold text-slate-900">Assign Freelancer to Project</h3>
<p id="modal-assign-project-name" class="text-xs text-indigo-600 font-semibold mt-0.5"></p>
</div>
<form id="form-add-assignment" onsubmit="handleSaveAssignment(event)" class="p-6 space-y-4">
<input type="hidden" id="assign-project-id">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Freelancer Name *</label>
<input type="text" id="assign-freelance-name" required placeholder="e.g., Alex Dupont"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Freelancer Email *</label>
<input type="email" id="assign-freelance-email" required placeholder="e.g., alex.dupont@example.com"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Start Date *</label>
<input type="date" id="assign-start-date" required
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">End Date *</label>
<input type="date" id="assign-end-date" required
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Daily Rate (€)</label>
<input type="number" id="assign-daily-rate" min="0" placeholder="500"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div class="pt-4 border-t border-slate-200 flex items-center justify-end gap-3">
<button type="button" onclick="closeAddAssignmentModal()" class="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-900">Cancel</button>
<button type="submit" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md transition">
Save Assignment
</button>
</div>
</form>
</div>
</div>
<!-- 4. Edit Assignment Dates Modal -->
<div id="modal-edit-assignment" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 overflow-hidden">
<div class="p-6 border-b border-slate-200">
<h3 class="text-base font-bold text-slate-900">Edit Freelance Contract Dates</h3>
<p id="modal-edit-assign-title" class="text-xs text-indigo-600 font-semibold mt-0.5"></p>
</div>
<form id="form-edit-assignment" onsubmit="handleUpdateAssignmentDates(event)" class="p-6 space-y-4">
<input type="hidden" id="edit-assignment-id">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Start Date *</label>
<input type="date" id="edit-assign-start-date" required
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">End Date *</label>
<input type="date" id="edit-assign-end-date" required
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Daily Rate (€)</label>
<input type="number" id="edit-assign-daily-rate" min="0"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div class="pt-4 border-t border-slate-200 flex items-center justify-end gap-3">
<button type="button" onclick="closeEditAssignmentModal()" class="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-900">Cancel</button>
<button type="submit" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md transition">
Update Contract
</button>
</div>
</form>
</div>
</div>
<!-- 5. Create New Project Modal -->
<div id="modal-create-project" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-lg w-full shadow-2xl border border-slate-100 overflow-hidden">
<div class="p-6 border-b border-slate-200">
<h3 class="text-base font-bold text-slate-900">Create New Project</h3>
<p class="text-xs text-slate-500 mt-0.5">Define project scope and client administrator.</p>
</div>
<form id="form-create-project" onsubmit="handleCreateProject(event)" class="p-6 space-y-4">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Project Name *</label>
<input type="text" id="new-project-name" required placeholder="e.g. AI Search Integration"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Description</label>
<textarea id="new-project-desc" rows="2" placeholder="Brief project overview..."
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500"></textarea>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Admin Name</label>
<input type="text" id="new-project-admin-name" placeholder="Sarah Jenkins"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Admin Email</label>
<input type="email" id="new-project-admin-email" placeholder="sarah.jenkins@example.com"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500">
</div>
</div>
<div class="pt-4 border-t border-slate-200 flex items-center justify-end gap-3">
<button type="button" onclick="closeNewProjectModal()" class="px-4 py-2 text-xs font-semibold text-slate-600 hover:text-slate-900">Cancel</button>
<button type="submit" class="px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md transition">
Create Project
</button>
</div>
</form>
</div>
</div>
<!-- 6. Invoice Preview Modal -->
<div id="modal-invoice-preview" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4">
<div class="bg-white rounded-3xl max-w-4xl w-full shadow-2xl border border-slate-100 overflow-hidden flex flex-col h-[85vh]">
<div class="p-4 border-b border-slate-200 flex items-center justify-between bg-slate-50">
<div class="flex items-center space-x-2">
<svg class="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<h3 id="preview-invoice-title" class="text-sm font-bold text-slate-800">Invoice Preview</h3>
</div>
<div class="flex items-center gap-2">
<a id="preview-invoice-download-btn" download="invoice.pdf" href="#"
class="px-3.5 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-semibold rounded-xl shadow-sm transition flex items-center gap-1.5">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
Download
</a>
<button onclick="closeInvoicePreviewModal()" class="p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-200">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div class="flex-1 bg-slate-100 flex items-center justify-center p-2 overflow-hidden">
<iframe id="preview-invoice-frame" class="w-full h-full rounded-xl border border-slate-300 bg-white" src="about:blank"></iframe>
<img id="preview-invoice-img" class="hidden max-h-full max-w-full object-contain rounded-xl shadow-md" src="" alt="Invoice">
</div>
</div>
</div>
<!-- 7. Authentication Modal (Login & Register) -->
<div id="modal-auth" class="hidden fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-sm flex items-center justify-center p-4" role="dialog" aria-modal="true" aria-labelledby="auth-modal-title">
<div class="bg-white rounded-3xl max-w-md w-full shadow-2xl border border-slate-100 overflow-hidden transform transition-all">
<!-- Modal Header -->
<div class="p-6 border-b border-slate-100 flex items-start justify-between bg-gradient-to-r from-slate-50 to-indigo-50/40">
<div>
<div class="w-9 h-9 rounded-xl bg-indigo-600 flex items-center justify-center text-white mb-2 shadow-md shadow-indigo-100">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
</svg>
</div>
<h3 class="text-lg font-bold text-slate-900" id="auth-modal-title">Sign In to Timesheets Pro</h3>
<p class="text-xs text-slate-500 mt-0.5" id="auth-modal-desc">Access your timesheet portal and project dashboard.</p>
</div>
<button type="button" onclick="closeAuthModal()" class="p-1.5 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-200 transition" aria-label="Close modal">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- Quick 1-Click Demo Section -->
<div class="p-5 bg-indigo-50/50 border-b border-indigo-100">
<div class="flex items-center justify-between mb-2">
<span class="text-[11px] font-bold uppercase tracking-wider text-indigo-900 flex items-center gap-1.5">
<svg class="w-3.5 h-3.5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
1-Click Demo Login
</span>
<span class="text-[10px] text-indigo-600 font-medium">Real auth & token session</span>
</div>
<div class="grid grid-cols-2 gap-2.5">
<button type="button" onclick="loginDemo('admin')"
class="p-2.5 bg-white hover:bg-purple-50 text-purple-900 border border-purple-200 hover:border-purple-300 rounded-xl text-left transition shadow-sm group">
<div class="flex items-center justify-between">
<span class="text-xs font-bold truncate">Sarah Jenkins</span>
<span class="text-[9px] font-bold px-1.5 py-0.5 rounded bg-purple-100 text-purple-700 uppercase">Admin</span>
</div>
<p class="text-[10px] text-slate-500 truncate mt-0.5 group-hover:text-purple-700">sarah.jenkins@example.com</p>
</button>
<button type="button" onclick="loginDemo('freelancer')"
class="p-2.5 bg-white hover:bg-emerald-50 text-emerald-900 border border-emerald-200 hover:border-emerald-300 rounded-xl text-left transition shadow-sm group">
<div class="flex items-center justify-between">
<span class="text-xs font-bold truncate">Charlie Dupont</span>
<span class="text-[9px] font-bold px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-700 uppercase">Freelancer</span>
</div>
<p class="text-[10px] text-slate-500 truncate mt-0.5 group-hover:text-emerald-700">charlie.dupont@example.com</p>
</button>
</div>
</div>
<!-- Mode Selector Tabs -->
<div class="px-6 pt-4 pb-1">
<div class="grid grid-cols-2 bg-slate-100 p-1 rounded-xl">
<button type="button" id="tab-auth-login" onclick="setAuthModalMode('login')"
class="py-1.5 text-xs font-bold rounded-lg text-indigo-700 bg-white shadow-sm transition">
Sign In
</button>
<button type="button" id="tab-auth-register" onclick="setAuthModalMode('register')"
class="py-1.5 text-xs font-bold rounded-lg text-slate-600 hover:text-slate-900 transition">
Create Account
</button>
</div>
</div>
<!-- Auth Error Notification Alert -->
<div id="auth-error-alert" class="hidden mx-6 mt-3 p-3 bg-rose-50 border border-rose-200 text-rose-800 text-xs rounded-xl flex items-center gap-2">
<svg class="w-4 h-4 text-rose-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span id="auth-error-msg" class="flex-1 font-medium"></span>
</div>
<!-- Sign In Form -->
<form id="form-auth-login" onsubmit="handleAuthLoginSubmit(event)" class="p-6 space-y-4">
<div>
<label for="auth-login-email" class="block text-xs font-semibold text-slate-700 uppercase mb-1">Email Address *</label>
<input type="email" id="auth-login-email" required placeholder="name@example.com" autocomplete="email"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
</div>
<div>
<label for="auth-login-password" class="block text-xs font-semibold text-slate-700 uppercase mb-1">Password *</label>
<input type="password" id="auth-login-password" required placeholder="••••••••" autocomplete="current-password"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
</div>
<button type="submit" id="auth-login-submit-btn"
class="w-full py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md transition flex items-center justify-center gap-2">
<span>Sign In</span>
</button>
<p class="text-center text-xs text-slate-500 pt-1">
Don't have an account?
<button type="button" onclick="setAuthModalMode('register')" class="text-indigo-600 hover:underline font-semibold">Sign up now</button>
</p>
</form>
<!-- Register Form -->
<form id="form-auth-register" onsubmit="handleAuthRegisterSubmit(event)" class="hidden p-6 space-y-4">
<div>
<label for="auth-reg-name" class="block text-xs font-semibold text-slate-700 uppercase mb-1">Full Name *</label>
<input type="text" id="auth-reg-name" required placeholder="e.g. Alex Dupont" autocomplete="name"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
</div>
<div>
<label for="auth-reg-email" class="block text-xs font-semibold text-slate-700 uppercase mb-1">Email Address *</label>
<input type="email" id="auth-reg-email" required placeholder="name@example.com" autocomplete="email"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
</div>
<div>
<label for="auth-reg-password" class="block text-xs font-semibold text-slate-700 uppercase mb-1">Password *</label>
<input type="password" id="auth-reg-password" required minlength="6" placeholder="At least 6 characters" autocomplete="new-password"
class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none">
</div>
<div>
<label class="block text-xs font-semibold text-slate-700 uppercase mb-1.5">Account Role *</label>
<div class="grid grid-cols-2 gap-3">
<label class="cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-indigo-500 bg-indigo-50/50" id="role-card-freelancer">
<input type="radio" name="auth-role" value="freelancer" checked onchange="updateRoleCardSelection()" class="sr-only">
<svg class="w-5 h-5 text-indigo-600 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<span class="text-xs font-bold text-slate-800">Freelancer</span>
<span class="text-[10px] text-slate-500 mt-0.5">Log hours, submit timesheets</span>
</label>
<label class="cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-slate-200 hover:border-slate-300" id="role-card-admin">
<input type="radio" name="auth-role" value="admin" onchange="updateRoleCardSelection()" class="sr-only">
<svg class="w-5 h-5 text-slate-500 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
<span class="text-xs font-bold text-slate-800">Project Admin</span>
<span class="text-[10px] text-slate-500 mt-0.5">Validate queue, manage projects</span>
</label>
</div>
</div>
<button type="submit" id="auth-reg-submit-btn"
class="w-full py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold rounded-xl shadow-md transition flex items-center justify-center gap-2">
<span>Create Account</span>
</button>
<p class="text-center text-xs text-slate-500 pt-1">
Already have an account?
<button type="button" onclick="setAuthModalMode('login')" class="text-indigo-600 hover:underline font-semibold">Sign in</button>
</p>
</form>
</div>
</div>
<!-- ================================================================= -->
<!-- APPLICATION LOGIC & STORE -->
<!-- ================================================================= -->
<script>
// -------------------------------------------------------------
// Initial Seed Data (matching Kallax database schema and initial rows)
// -------------------------------------------------------------
const SAMPLE_PDF_BASE64 = "data:application/pdf;base64,JVBERi0xLjQKJcfsj6IKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZwovUGFnZXMgMiAwIFIKPj4KZW5kb2JqCjIgMCBvYmoKPDwKL1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDEKPj4KZW5kb2JqCjMgMCBvYmoKPDwKL1R5cGUgL1BhZ2UKL1BhcmVudCAyIDAgUgovTWVkaWFCb3ggWzAgMCA2MTIgNzkyXQovQ29udGVudHMgNCAwIFIKL1Jlc291cmNlcyA8PAovRm9udCA8PAovRjEgNSAwIFIKPj4KPj4KPj4KZW5kb2JqCjQgMCBvYmoKPDwKL0xlbmd0aCA4NQo+PgpzdHJlYW0KQlQKL0YxIDI0IFRmCjEwMCA3MDAgVGROCihJbnZvaWNlIC0gQ2hhcmxpZSBEdXBvbnQgLSBNYXkgMjAyNSkgVGoKMCAtNTAgVGROCigyIERheXMgV29ya2VkIC0gVG90YWw6IDExMDAgRVVSKSBUagpFVAplbmRzdHJlYW0KZW5kb2JqCjUgMCBvYmoKPDwKL1R5cGUgL0ZvbnQKL1N1YnR5cGUgL1R5cGUxCi9CYXNlRm9udCAvSGVsdmV0aWNhCj4+CmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMTUgMDAwMDAgbiAKMDAwMDAwMDA2OCAwMDAwMCBuIAowMDAwMDAwMTI1IDAwMDAwIG4gCjAwMDAwMDAyNjAgMDAwMDAgbiAKMDAwMDAwMDM5NSAwMDAwMCBuIAp0cmFpbGVyCjw8Ci9TaXplIDYKL1Jvb3QgMSAwIFIKPj4Kc3RhcnR4cmVmCjQ3NgolJUVPRg==";
const INITIAL_DATA = {
projects: [
{
_id: "6a9c60978176c20c82591910",
name: "E-Commerce Platform",
description: "Full-stack redesign and revamp of online store",
adminName: "Alice Martin",
adminEmail: "alice.martin@example.com",
status: "active"
},
{
_id: "6a9c60998176c20c82591912",
name: "Mobile Banking App",
description: "Native iOS and Android secure banking application",
adminName: "Bob Vance",
adminEmail: "bob.vance@example.com",
status: "active"
}
],
assignments: [
{
_id: "6a9c609d8176c20c82591914",
projectId: "6a9c60978176c20c82591910",
projectName: "E-Commerce Platform",
freelanceName: "Charlie Dupont",
freelanceEmail: "charlie.dupont@example.com",
startDate: "2025-01-01",
endDate: "2025-12-31",
dailyRate: 550
},
{
_id: "6a9c60a08176c20c82591916",
projectId: "6a9c60998176c20c82591912",
projectName: "Mobile Banking App",
freelanceName: "Dana Lee",
freelanceEmail: "dana.lee@example.com",
startDate: "2025-02-01",
endDate: "2025-11-30",
dailyRate: 650
}
],
timesheets: [
{
_id: "6a9c60a38176c20c82591918",
projectId: "6a9c60978176c20c82591910",
projectName: "E-Commerce Platform",
freelanceName: "Charlie Dupont",
freelanceEmail: "charlie.dupont@example.com",
month: "2025-05",
status: "submitted",
invoiceFileName: "facture_mai_2025.pdf",
invoiceFileData: SAMPLE_PDF_BASE64,
adminFeedback: "",
totalDaysWorked: 2,
totalMeetingHours: 1.5,
submittedAt: "2025-05-31T18:00:00.000Z"
}
],
timesheet_days: [
{
_id: "6a9c60a68176c20c8259191a",
timesheetId: "6a9c60a38176c20c82591918",
date: "2025-05-02",
worked: true,
details: "Sprint planning and initial setup of checkout module",
meetingDurationMinutes: 60
},
{
_id: "6a9c60a98176c20c8259191c",
timesheetId: "6a9c60a38176c20c82591918",
date: "2025-05-05",
worked: true,
details: "Implemented Stripe payment webhook handling",
meetingDurationMinutes: 30
}
]
};
// -------------------------------------------------------------
// Store & State Management
// -------------------------------------------------------------
// Store & State Management
// -------------------------------------------------------------
const STORAGE_KEY = "TIMESHEETS_APP_STORE_V1";
let state = {
projects: [],
assignments: [],
timesheets: [],
timesheet_days: []
};
// Pre-configured Demo Accounts
const DEMO_ACCOUNTS = {
admin: {
name: "Sarah Jenkins",
email: "sarah.jenkins@example.com",
role: "admin",
password: "Password123!"
},
freelancer: {
name: "Charlie Dupont",
email: "charlie.dupont@example.com",
role: "freelancer",
password: "Password123!"
}
};
// Compatibility persona arrays
const FREELANCER_PERSONAS = [
{ name: "Charlie Dupont", email: "charlie.dupont@example.com" },
{ name: "Dana Lee", email: "dana.lee@example.com" },
{ name: "Alice Martin", email: "alice.martin@example.com" },
{ name: "Alex Dupont", email: "alex.dupont@example.com" }
];
const ADMIN_PERSONAS = [
{ name: "Sarah Jenkins", email: "sarah.jenkins@example.com" },
{ name: "Bob Vance", email: "bob.vance@example.com" },
{ name: "Alice Martin", email: "alice.martin@example.com" }
];
// Auth Session State
const AUTH_TOKEN_KEY = "TIMESHEETS_AUTH_TOKEN_V1";
const AUTH_USER_KEY = "TIMESHEETS_AUTH_USER_V1";
let authToken = localStorage.getItem(AUTH_TOKEN_KEY) || null;
let currentUser = null;
let currentRole = "freelancer"; // 'freelancer' | 'admin'
let currentFreelancer = FREELANCER_PERSONAS[0];
let currentAdmin = ADMIN_PERSONAS[0];
// Subnav tabs
let currentFreelancerTab = "entry"; // 'entry' | 'projects' | 'history'
let currentAdminTab = "validation"; // 'validation' | 'projects'
let currentAdminQueueFilter = "all";
// Active Timesheet Editor state
let activeEditorTimesheet = null;
let activeEditorDays = [];
let activeAttachedInvoice = null; // { name, data, size }
// Inspect Modal State
let inspectTimesheetId = null;
// Load store from localStorage or initial seed
function initStore() {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
state = JSON.parse(saved);
} else {
state = JSON.parse(JSON.stringify(INITIAL_DATA));
saveStore();
}
} catch (e) {
console.error("Failed to load store, using seed data", e);
state = JSON.parse(JSON.stringify(INITIAL_DATA));
}
tryKallaxSync();
}
function saveStore() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
} catch (e) {
console.error("Failed to save to localStorage", e);
}
}
// -------------------------------------------------------------
// Authenticated API Fetch Helper
// -------------------------------------------------------------
function getAuthHeaders(customHeaders = {}) {
const headers = { ...customHeaders };
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`;
}
return headers;
}
async function apiFetch(url, options = {}) {
const headers = getAuthHeaders(options.headers || {});
if (options.body && !(options.body instanceof FormData) && !headers['Content-Type']) {
headers['Content-Type'] = 'application/json';
}
return fetch(url, {
...options,
headers
});
}
// Kallax API Integration (Graceful Sync with fallback)
async function tryKallaxSync() {
try {
const [projRes, assignRes, tsRes, daysRes] = await Promise.allSettled([
apiFetch('/api/projects').then(r => r.ok ? r.json() : null),
apiFetch('/api/assignments').then(r => r.ok ? r.json() : null),
apiFetch('/api/timesheets').then(r => r.ok ? r.json() : null),
apiFetch('/api/timesheet_days').then(r => r.ok ? r.json() : null)
]);
let changed = false;
if (projRes.status === 'fulfilled' && projRes.value?.items?.length) {
state.projects = projRes.value.items;
changed = true;
}
if (assignRes.status === 'fulfilled' && assignRes.value?.items?.length) {
state.assignments = assignRes.value.items;
changed = true;
}
if (tsRes.status === 'fulfilled' && tsRes.value?.items?.length) {
state.timesheets = tsRes.value.items;
changed = true;
}
if (daysRes.status === 'fulfilled' && daysRes.value?.items?.length) {
state.timesheet_days = daysRes.value.items;
changed = true;
}
if (changed) saveStore();
} catch (err) {
console.log("Operating in offline/local storage mode:", err);
}
}
async function syncPostKallax(endpoint, data) {
try {
await apiFetch(`/api/${endpoint}`, {
method: 'POST',
body: JSON.stringify(data)
});
} catch (err) {
// Non-blocking fallback
}
}
// -------------------------------------------------------------
// Authentication & Session Management
// -------------------------------------------------------------
async function initAuth() {
const savedUser = localStorage.getItem(AUTH_USER_KEY);
if (savedUser) {
try {
currentUser = JSON.parse(savedUser);
} catch (e) {
currentUser = null;
}
}
if (authToken) {
try {
const res = await apiFetch('/api/auth/me');
if (res.ok) {
const data = await res.json();
currentUser = data.user || data;
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(currentUser));
} else if (res.status === 401) {
logout(false);
return;
}
} catch (err) {
console.warn('Backend auth unreachable, using local session state:', err);
}
}
if (currentUser) {
applyUserSession(currentUser);
} else {
updateHeaderAuthUI();
openAuthModal('login');
}
}
function applyUserSession(user) {
currentUser = user;
if (user.role === 'admin') {
currentRole = 'admin';
currentAdmin = { name: user.name || 'Sarah Jenkins', email: user.email };
currentFreelancer = DEMO_ACCOUNTS.freelancer;
} else {
currentRole = 'freelancer';
currentFreelancer = { name: user.name || 'Charlie Dupont', email: user.email };
}
updateHeaderAuthUI();
switchRole(currentRole);
}
function setAuthSession(token, user) {
authToken = token;
currentUser = user;
if (token) {
localStorage.setItem(AUTH_TOKEN_KEY, token);
} else {
localStorage.removeItem(AUTH_TOKEN_KEY);
}
if (user) {
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(user));
} else {
localStorage.removeItem(AUTH_USER_KEY);
}
applyUserSession(user);
tryKallaxSync();
}
function logout(notify = true) {
authToken = null;
currentUser = null;
localStorage.removeItem(AUTH_TOKEN_KEY);
localStorage.removeItem(AUTH_USER_KEY);
updateHeaderAuthUI();
if (notify) {
showToast('Signed Out', 'You have been successfully logged out.', 'info');
}
openAuthModal('login');
}
function updateHeaderAuthUI() {
const profileEl = document.getElementById('header-user-profile');
const authBtnsEl = document.getElementById('header-auth-buttons');
const roleSwitchContainer = document.getElementById('role-switch-container');
const signedOutBanner = document.getElementById('signed-out-banner');
if (currentUser) {
if (profileEl) profileEl.classList.remove('hidden');
if (authBtnsEl) {
authBtnsEl.classList.add('hidden');
authBtnsEl.classList.remove('flex');
}
if (signedOutBanner) signedOutBanner.classList.add('hidden');
// Avatar Initials
const initials = (currentUser.name || currentUser.email || 'U')
.split(' ')
.filter(Boolean)
.map(n => n[0])
.join('')
.substring(0, 2)
.toUpperCase();
const avatarEl = document.getElementById('user-profile-avatar');
if (avatarEl) {
avatarEl.textContent = initials || 'U';
if (currentUser.role === 'admin') {
avatarEl.className = "w-8 h-8 rounded-full bg-gradient-to-tr from-purple-600 to-indigo-600 text-white flex items-center justify-center font-bold text-xs shadow-sm";
} else {
avatarEl.className = "w-8 h-8 rounded-full bg-gradient-to-tr from-emerald-600 to-teal-600 text-white flex items-center justify-center font-bold text-xs shadow-sm";
}
}
const nameEl = document.getElementById('user-profile-name');
if (nameEl) nameEl.textContent = currentUser.name || currentUser.email.split('@')[0];
const emailEl = document.getElementById('user-profile-email');
if (emailEl) emailEl.textContent = currentUser.email;
const roleBadgeEl = document.getElementById('user-profile-role-badge');
if (roleBadgeEl) {
if (currentUser.role === 'admin') {
roleBadgeEl.textContent = 'Admin';
roleBadgeEl.className = "text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider bg-purple-100 text-purple-700 border border-purple-200";
} else {
roleBadgeEl.textContent = 'Freelancer';
roleBadgeEl.className = "text-[9px] font-bold px-1.5 py-0.5 rounded-full uppercase tracking-wider bg-emerald-100 text-emerald-700 border border-emerald-200";
}
}
// Only Admin users see role switcher pills (to test freelancer view)
if (roleSwitchContainer) {
if (currentUser.role === 'admin') {
roleSwitchContainer.classList.remove('hidden');
} else {
roleSwitchContainer.classList.add('hidden');
}
}
} else {
if (profileEl) profileEl.classList.add('hidden');
if (authBtnsEl) {
authBtnsEl.classList.remove('hidden');
authBtnsEl.classList.add('flex');
}
if (roleSwitchContainer) roleSwitchContainer.classList.add('hidden');
if (signedOutBanner) signedOutBanner.classList.remove('hidden');
}
}
async function loginDemo(roleType) {
const demo = DEMO_ACCOUNTS[roleType];
if (!demo) return;
hideDemoDropdown();
showToast('Authenticating...', `Logging in as Demo ${demo.role === 'admin' ? 'Admin' : 'Freelancer'} (${demo.name})`, 'info');
let token = null;
let user = null;
try {
let res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: demo.email, password: demo.password })
});
if (!res.ok && (res.status === 401 || res.status === 404 || res.status === 400)) {
const regRes = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: demo.email,
password: demo.password,
name: demo.name,
role: demo.role
})
});
if (regRes.ok) {
const regData = await regRes.json();
token = regData.token || regData.accessToken || regData.jwt;
user = regData.user || regData;
}
if (!token) {
res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: demo.email, password: demo.password })
});
}
}
if (res && res.ok) {
const data = await res.json();
token = data.token || data.accessToken || data.jwt;
user = data.user || data;
}
} catch (err) {
console.warn('Backend auth endpoint unreachable, falling back to local demo session:', err);
}
if (!token) {
token = `demo-token-${roleType}-${Date.now()}`;
}
if (!user) {
user = {
id: `demo_${roleType}`,
email: demo.email,
name: demo.name,
role: demo.role
};
}
if (!user.role) user.role = demo.role;
if (!user.name) user.name = demo.name;
if (!user.email) user.email = demo.email;
setAuthSession(token, user);
closeAuthModal();
showToast('Demo Login Active', `Signed in as ${user.name} (${user.role === 'admin' ? 'Admin' : 'Freelancer'})`, 'success');
}
async function handleAuthLoginSubmit(e) {
e.preventDefault();
clearAuthError();
const email = document.getElementById('auth-login-email').value.trim();
const password = document.getElementById('auth-login-password').value;
const submitBtn = document.getElementById('auth-login-submit-btn');
const origText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = `
<svg class="animate-spin w-4 h-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
</svg>
<span>Signing in...</span>
`;
try {
let token = null;
let user = null;
try {
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (res.ok) {
const data = await res.json();
token = data.token || data.accessToken || data.jwt;
user = data.user || data;
} else {
const isDemoAdmin = email.toLowerCase() === DEMO_ACCOUNTS.admin.email.toLowerCase();
const isDemoFreelancer = email.toLowerCase() === DEMO_ACCOUNTS.freelancer.email.toLowerCase();
if (isDemoAdmin || isDemoFreelancer) {
const demo = isDemoAdmin ? DEMO_ACCOUNTS.admin : DEMO_ACCOUNTS.freelancer;
const regRes = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: demo.email, password, name: demo.name, role: demo.role })
});
if (regRes.ok) {
const regData = await regRes.json();
token = regData.token || regData.accessToken || regData.jwt;
user = regData.user || { email: demo.email, name: demo.name, role: demo.role };
}
}
if (!user) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.message || 'Invalid email or password');
}
}
} catch (fetchErr) {
const isDemoAdmin = email.toLowerCase() === DEMO_ACCOUNTS.admin.email.toLowerCase();
const isDemoFreelancer = email.toLowerCase() === DEMO_ACCOUNTS.freelancer.email.toLowerCase();
if (isDemoAdmin || isDemoFreelancer) {
const demo = isDemoAdmin ? DEMO_ACCOUNTS.admin : DEMO_ACCOUNTS.freelancer;
token = `local-token-${Date.now()}`;
user = { id: 'local_' + Date.now(), email: demo.email, name: demo.name, role: demo.role };
} else if (fetchErr.message && fetchErr.message.includes('Invalid')) {
throw fetchErr;
} else {
token = `local-token-${Date.now()}`;
user = {
id: 'local_' + Date.now(),
email,
name: email.split('@')[0],
role: 'freelancer'
};
}
}
if (user) {
if (!user.email) user.email = email;
if (!user.name) user.name = email.split('@')[0];
if (!user.role) user.role = (email.toLowerCase().includes('admin') ? 'admin' : 'freelancer');
if (!token) token = `token_${Date.now()}`;
setAuthSession(token, user);
closeAuthModal();
showToast('Signed In', `Welcome back, ${user.name}!`, 'success');
}
} catch (err) {
showAuthError(err.message || 'Failed to sign in. Please verify your credentials.');
} finally {
submitBtn.disabled = false;
submitBtn.innerHTML = origText;
}
}
async function handleAuthRegisterSubmit(e) {
e.preventDefault();
clearAuthError();
const name = document.getElementById('auth-reg-name').value.trim();
const email = document.getElementById('auth-reg-email').value.trim();
const password = document.getElementById('auth-reg-password').value;
const role = document.querySelector('input[name="auth-role"]:checked')?.value || 'freelancer';
const submitBtn = document.getElementById('auth-reg-submit-btn');
const origText = submitBtn.innerHTML;
submitBtn.disabled = true;
submitBtn.innerHTML = `
<svg class="animate-spin w-4 h-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
</svg>
<span>Creating account...</span>
`;
try {
let token = null;
let user = null;
try {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, name, role })
});
if (res.ok) {
const data = await res.json();
token = data.token || data.accessToken || data.jwt;
user = data.user || data;
if (!token) {
const loginRes = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (loginRes.ok) {
const loginData = await loginRes.json();
token = loginData.token || loginData.accessToken || loginData.jwt;
user = loginData.user || user;
}
}
} else {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.message || 'Registration failed. User may already exist.');
}
} catch (fetchErr) {
if (fetchErr.message && !fetchErr.message.includes('fetch')) {
throw fetchErr;
}
console.warn('Register fallback to local storage:', fetchErr);
token = `local-token-${Date.now()}`;
user = { id: 'local_' + Date.now(), email, name, role };
}
if (user) {
if (!user.email) user.email = email;
if (!user.name) user.name = name;
if (!user.role) user.role = role;
if (!token) token = `token_${Date.now()}`;
setAuthSession(token, user);
closeAuthModal();
showToast('Account Created', `Welcome to Timesheets Pro, ${user.name}!`, 'success');
}
} catch (err) {
showAuthError(err.message || 'Failed to register account.');
} finally {
submitBtn.disabled = false;
submitBtn.innerHTML = origText;
}
}
function updateRoleCardSelection() {
const role = document.querySelector('input[name="auth-role"]:checked')?.value;
const fCard = document.getElementById('role-card-freelancer');
const aCard = document.getElementById('role-card-admin');
if (role === 'admin') {
aCard.className = "cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-purple-500 bg-purple-50/50";
fCard.className = "cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-slate-200 hover:border-slate-300";
} else {
fCard.className = "cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-indigo-500 bg-indigo-50/50";
aCard.className = "cursor-pointer border-2 rounded-2xl p-3 flex flex-col items-center text-center transition border-slate-200 hover:border-slate-300";
}
}
function setAuthModalMode(mode) {
clearAuthError();
const loginForm = document.getElementById('form-auth-login');
const regForm = document.getElementById('form-auth-register');
const loginTab = document.getElementById('tab-auth-login');
const regTab = document.getElementById('tab-auth-register');
const title = document.getElementById('auth-modal-title');
const desc = document.getElementById('auth-modal-desc');
if (mode === 'register') {
loginForm.classList.add('hidden');
regForm.classList.remove('hidden');
loginTab.className = "py-1.5 text-xs font-bold rounded-lg text-slate-600 hover:text-slate-900 transition";
regTab.className = "py-1.5 text-xs font-bold rounded-lg text-indigo-700 bg-white shadow-sm transition";
title.textContent = "Create an Account";
desc.textContent = "Join as a Freelancer or Project Administrator.";
} else {
regForm.classList.add('hidden');
loginForm.classList.remove('hidden');
loginTab.className = "py-1.5 text-xs font-bold rounded-lg text-indigo-700 bg-white shadow-sm transition";
regTab.className = "py-1.5 text-xs font-bold rounded-lg text-slate-600 hover:text-slate-900 transition";
title.textContent = "Sign In to Timesheets Pro";
desc.textContent = "Access your timesheet portal and project dashboard.";
}
}
function openAuthModal(mode = 'login') {
clearAuthError();
setAuthModalMode(mode);
const modal = document.getElementById('modal-auth');
if (modal) modal.classList.remove('hidden');
}
function closeAuthModal() {
const modal = document.getElementById('modal-auth');
if (modal) modal.classList.add('hidden');
}
function showAuthError(msg) {
const alert = document.getElementById('auth-error-alert');
const text = document.getElementById('auth-error-msg');
if (alert && text) {
text.textContent = msg;
alert.classList.remove('hidden');
}
}
function clearAuthError() {
const alert = document.getElementById('auth-error-alert');
if (alert) alert.classList.add('hidden');
}
function toggleDemoDropdown(event) {
if (event) event.stopPropagation();
const menu = document.getElementById('demo-dropdown-menu');
menu.classList.toggle('hidden');
}
function hideDemoDropdown() {
const menu = document.getElementById('demo-dropdown-menu');
if (menu) menu.classList.add('hidden');
}
document.addEventListener('click', (e) => {
const wrapper = document.getElementById('demo-dropdown-wrapper');
if (wrapper && !wrapper.contains(e.target)) {
hideDemoDropdown();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeAuthModal();
hideDemoDropdown();
}
});
// Compatibility shim for existing references
function populatePersonaDropdown() {
updateHeaderAuthUI();
}
function changePersona(val) {
renderAll();
}
// -------------------------------------------------------------
// Toast Notifications
// -------------------------------------------------------------
function showToast(title, message, type = 'success') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `p-4 rounded-2xl shadow-lg border text-sm flex items-start gap-3 pointer-events-auto transition-all duration-300 transform translate-y-2 opacity-0 ${
type === 'success' ? 'bg-emerald-50 border-emerald-200 text-emerald-900' :
type === 'error' ? 'bg-rose-50 border-rose-200 text-rose-900' :
'bg-indigo-50 border-indigo-200 text-indigo-900'
}`;
const icon = type === 'success' ?
`<svg class="w-5 h-5 text-emerald-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>` :
type === 'error' ?
`<svg class="w-5 h-5 text-rose-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>` :
`<svg class="w-5 h-5 text-indigo-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`;
toast.innerHTML = `
${icon}
<div class="flex-1">
<p class="font-bold">${title}</p>
<p class="text-xs opacity-90 mt-0.5">${message}</p>
</div>
`;
container.appendChild(toast);
requestAnimationFrame(() => {
toast.classList.remove('translate-y-2', 'opacity-0');
});
setTimeout(() => {
toast.classList.add('opacity-0', 'translate-y-2');
setTimeout(() => toast.remove(), 300);
}, 3500);
}
// -------------------------------------------------------------
// Role & View Switching (Role-Enforced)
// -------------------------------------------------------------
function switchRole(role) {
if (!currentUser) {
openAuthModal('login');
return;
}
// Enforce view permissions: freelancers cannot access Admin View
if (currentUser.role !== 'admin' && role === 'admin') {
showToast('Access Restricted', 'Freelancers do not have admin permissions.', 'error');
return;
}
currentRole = role;
const fBtn = document.getElementById('role-btn-freelancer');
const aBtn = document.getElementById('role-btn-admin');
const fContainer = document.getElementById('freelancer-view-container');
const aContainer = document.getElementById('admin-view-container');
const fSubnav = document.getElementById('freelancer-subnav');
const aSubnav = document.getElementById('admin-subnav');
const adminNotice = document.getElementById('admin-testing-notice');
if (role === 'freelancer') {
if (fBtn) fBtn.className = "px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 shadow-sm bg-white text-indigo-700";
if (aBtn) aBtn.className = "px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 text-slate-600 hover:text-slate-900";
if (fContainer) fContainer.classList.remove('hidden');
if (aContainer) aContainer.classList.add('hidden');
if (fSubnav) fSubnav.classList.remove('hidden');
if (aSubnav) aSubnav.classList.add('hidden');
if (adminNotice) {
if (currentUser.role === 'admin') {
adminNotice.classList.remove('hidden');
} else {
adminNotice.classList.add('hidden');
}
}
} else {
if (aBtn) aBtn.className = "px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 shadow-sm bg-white text-indigo-700";
if (fBtn) fBtn.className = "px-3.5 py-1.5 rounded-lg text-xs font-semibold transition-all flex items-center space-x-1.5 text-slate-600 hover:text-slate-900";
if (aContainer) aContainer.classList.remove('hidden');
if (fContainer) fContainer.classList.add('hidden');
if (aSubnav) aSubnav.classList.remove('hidden');
if (fSubnav) fSubnav.classList.add('hidden');
if (adminNotice) adminNotice.classList.add('hidden');
}
updateHeaderAuthUI();
renderAll();
}
// -------------------------------------------------------------
// Navigation Tabs
// -------------------------------------------------------------
function setFreelancerTab(tab) {
currentFreelancerTab = tab;
['entry', 'projects', 'history'].forEach(t => {
const btn = document.getElementById(`f-tab-${t}`);
const view = document.getElementById(`f-view-${t}`);
if (t === tab) {
btn.className = "border-b-2 border-indigo-600 text-indigo-600 py-3.5 text-sm font-semibold flex items-center gap-2";
view.classList.remove('hidden');
} else {
btn.className = "border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-3.5 text-sm font-semibold flex items-center gap-2";
view.classList.add('hidden');
}
});
if (tab === 'projects') renderFreelancerProjects();
if (tab === 'history') renderFreelancerHistory();
if (tab === 'entry') renderTimesheetEntryView();
}
function setAdminTab(tab) {
if (currentUser && currentUser.role !== 'admin') {
showToast('Access Denied', 'Only administrators have access to admin views.', 'error');
return;
}
currentAdminTab = tab;
['validation', 'projects'].forEach(t => {
const btn = document.getElementById(`a-tab-${t}`);
const view = document.getElementById(`a-view-${t}`);
if (t === tab) {
btn.className = "border-b-2 border-indigo-600 text-indigo-600 py-3.5 text-sm font-semibold flex items-center gap-2";
view.classList.remove('hidden');
} else {
btn.className = "border-b-2 border-transparent text-slate-500 hover:text-slate-700 py-3.5 text-sm font-semibold flex items-center gap-2";
view.classList.add('hidden');
}
});
if (tab === 'validation') renderAdminQueue();
if (tab === 'projects') renderAdminProjects();
}
// -------------------------------------------------------------
// Freelancer View: Timesheet Entry Logic
// -------------------------------------------------------------
function renderFreelancerProjectSelector() {
const select = document.getElementById('ts-project-select');
const assigned = state.assignments.filter(a => a.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase());
select.innerHTML = '';
if (assigned.length === 0) {
const opt = document.createElement('option');
opt.value = '';
opt.textContent = 'No projects currently assigned';
select.appendChild(opt);
select.disabled = true;
} else {
select.disabled = false;
assigned.forEach(a => {
const opt = document.createElement('option');
opt.value = a.projectId;
opt.textContent = `${a.projectName} (${a.startDate} to ${a.endDate})`;
select.appendChild(opt);
});
}
}
function onTimesheetContextChange() {
loadActiveTimesheet();
}
function loadActiveTimesheet(targetMonth = null, targetProjectId = null) {
const projectSelect = document.getElementById('ts-project-select');
const monthInput = document.getElementById('ts-month-input');
if (targetProjectId) projectSelect.value = targetProjectId;
if (targetMonth) monthInput.value = targetMonth;
const projectId = projectSelect.value;
const month = monthInput.value;
if (!projectId || !month) {
document.getElementById('ts-days-tbody').innerHTML = `
<tr><td colspan="4" class="py-12 text-center text-slate-400">Please select an assigned project and target month above.</td></tr>
`;
return;
}
// Check assignment info
const assignment = state.assignments.find(a =>
a.projectId === projectId && a.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase()
);
const contractInfoDiv = document.getElementById('ts-contract-info');
if (assignment) {
contractInfoDiv.innerHTML = `
<span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-slate-100 text-slate-700 font-medium">
<svg class="w-3.5 h-3.5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
Active Contract: ${assignment.startDate} &rarr; ${assignment.endDate}
</span>
<span class="inline-flex items-center px-2 py-1 rounded-lg bg-emerald-50 text-emerald-700 font-semibold">
€${assignment.dailyRate || 0}/day
</span>
`;
} else {
contractInfoDiv.innerHTML = `<span class="text-rose-600 font-semibold">Not assigned to this project</span>`;
}
// Find existing timesheet
const existingTs = state.timesheets.find(t =>
t.projectId === projectId &&
t.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase() &&
t.month === month
);
if (existingTs) {
activeEditorTimesheet = JSON.parse(JSON.stringify(existingTs));
// load existing days
const savedDays = state.timesheet_days.filter(d => d.timesheetId === existingTs._id);
buildMonthDays(month, assignment, savedDays);
if (existingTs.invoiceFileName) {
activeAttachedInvoice = {
name: existingTs.invoiceFileName,
data: existingTs.invoiceFileData,
size: "Attached"
};
} else {
activeAttachedInvoice = null;
}
} else {
// Draft / new timesheet
activeEditorTimesheet = {
_id: 'draft_' + Math.random().toString(36).substring(2, 9),
projectId: projectId,
projectName: assignment ? assignment.projectName : 'Project',
freelanceName: currentFreelancer.name,
freelanceEmail: currentFreelancer.email,
month: month,
status: 'draft',
invoiceFileName: '',
invoiceFileData: '',
adminFeedback: '',
totalDaysWorked: 0,
totalMeetingHours: 0,
submittedAt: null
};
activeAttachedInvoice = null;
buildMonthDays(month, assignment, []);
}
renderEditorUI(assignment);
}
function buildMonthDays(monthStr, assignment, existingDaysList) {
const [yearStr, mStr] = monthStr.split('-');
const year = parseInt(yearStr, 10);
const m = parseInt(mStr, 10) - 1; // 0-based
const daysInMonth = new Date(year, m + 1, 0).getDate();
const existingMap = {};
existingDaysList.forEach(d => { existingMap[d.date] = d; });
activeEditorDays = [];
for (let day = 1; day <= daysInMonth; day++) {
const dStr = `${yearStr}-${mStr.padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const dateObj = new Date(year, m, day);
const dayOfWeek = dateObj.getDay(); // 0 = Sun, 6 = Sat
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
let inRange = true;
if (assignment) {
if (assignment.startDate && dStr < assignment.startDate) inRange = false;
if (assignment.endDate && dStr > assignment.endDate) inRange = false;
}
const existing = existingMap[dStr];
activeEditorDays.push({
date: dStr,
dayOfWeek,
isWeekend,
inRange,
worked: existing ? !!existing.worked : false,
details: existing ? (existing.details || '') : '',
meetingDurationMinutes: existing ? (existing.meetingDurationMinutes || 0) : 0
});
}
}
function renderEditorUI(assignment) {
const isLocked = activeEditorTimesheet.status === 'submitted' || activeEditorTimesheet.status === 'validated';
const isRefused = activeEditorTimesheet.status === 'refused';
// Status Badge
const statusContainer = document.getElementById('ts-status-badge-container');
statusContainer.innerHTML = getStatusBadgeHTML(activeEditorTimesheet.status);
// Alert Banners
const lockedAlert = document.getElementById('ts-locked-alert');
const lockedMsg = document.getElementById('ts-locked-message');
const refusedAlert = document.getElementById('ts-refused-alert');
const refusedFeedbackText = document.getElementById('ts-refused-feedback-text');
if (isLocked) {
lockedAlert.classList.remove('hidden');
lockedMsg.textContent = activeEditorTimesheet.status === 'validated'
? "This timesheet has been approved and validated by the project administrator."
: "This timesheet is submitted and pending admin review. Edits are locked.";
} else {
lockedAlert.classList.add('hidden');
}
if (isRefused) {
refusedAlert.classList.remove('hidden');
refusedFeedbackText.textContent = activeEditorTimesheet.adminFeedback || "The administrator requested corrections before validation.";
} else {
refusedAlert.classList.add('hidden');
}
// Buttons
document.getElementById('btn-save-draft').disabled = isLocked;
document.getElementById('btn-submit-timesheet').disabled = isLocked;
document.getElementById('btn-quick-fill').disabled = isLocked;
document.getElementById('btn-clear-days').disabled = isLocked;
document.getElementById('btn-browse-invoice').disabled = isLocked;
document.getElementById('btn-sample-invoice').disabled = isLocked;
document.getElementById('btn-remove-invoice').disabled = isLocked;
if (isLocked) {
document.getElementById('btn-save-draft').classList.add('opacity-50', 'cursor-not-allowed');
document.getElementById('btn-submit-timesheet').classList.add('opacity-50', 'cursor-not-allowed');
} else {
document.getElementById('btn-save-draft').classList.remove('opacity-50', 'cursor-not-allowed');
document.getElementById('btn-submit-timesheet').classList.remove('opacity-50', 'cursor-not-allowed');
}
// Render Days Table
const tbody = document.getElementById('ts-days-tbody');
tbody.innerHTML = '';
activeEditorDays.forEach((item, idx) => {
const tr = document.createElement('tr');
const dateObj = new Date(item.date + 'T00:00:00');
const dayName = dateObj.toLocaleDateString('en-US', { weekday: 'short' });
const formattedDate = dateObj.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
const rowBg = !item.inRange ? 'bg-slate-100/60 opacity-60' : item.isWeekend ? 'bg-amber-50/40' : item.worked ? 'bg-indigo-50/30' : 'hover:bg-slate-50';
tr.className = `transition ${rowBg}`;
tr.innerHTML = `
<td class="py-3 px-4 font-medium text-slate-800 whitespace-nowrap">
<div class="flex items-center gap-1.5">
<span>${dayName}, ${formattedDate}</span>
${item.isWeekend ? '<span class="text-[10px] uppercase font-bold text-amber-600 bg-amber-100 px-1 rounded">W-E</span>' : ''}
${!item.inRange ? '<span class="text-[10px] uppercase font-semibold text-rose-600 bg-rose-50 px-1 rounded border border-rose-200">Out</span>' : ''}
</div>
</td>
<td class="py-3 px-4 text-center">
<input type="checkbox" ${item.worked ? 'checked' : ''} ${isLocked || !item.inRange ? 'disabled' : ''}
onchange="toggleWorkedDay(${idx}, this.checked)"
class="w-5 h-5 rounded text-indigo-600 focus:ring-indigo-500 border-slate-300 cursor-pointer disabled:cursor-not-allowed">
</td>
<td class="py-3 px-4">
<input type="text" value="${escapeHtml(item.details)}" placeholder="${item.worked ? 'What did you accomplish today?' : 'Mark worked to enter details'}"
${isLocked || !item.worked ? 'disabled' : ''}
oninput="updateDayDetails(${idx}, this.value)"
class="w-full text-xs p-2 rounded-lg border border-slate-200 bg-white focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 disabled:bg-slate-50 disabled:text-slate-400">
</td>
<td class="py-3 px-4">
<div class="flex items-center gap-1.5">
<input type="number" min="0" max="600" step="15" value="${item.meetingDurationMinutes || 0}"
${isLocked || !item.worked ? 'disabled' : ''}
oninput="updateDayMeeting(${idx}, this.value)"
class="w-20 text-xs p-2 rounded-lg border border-slate-200 bg-white focus:ring-1 focus:ring-indigo-500 text-right disabled:bg-slate-50 disabled:text-slate-400">
<span class="text-xs text-slate-400">min</span>
</div>
</td>
`;
tbody.appendChild(tr);
});
// Update Attached Invoice Display
updateInvoiceUI();
// Recalculate Live Metrics
recalculateMetrics(assignment);
}
function toggleWorkedDay(idx, checked) {
activeEditorDays[idx].worked = checked;
if (!checked) {
// clear minutes if not worked
activeEditorDays[idx].meetingDurationMinutes = 0;
}
renderEditorUI(getSelectedAssignment());
}
function updateDayDetails(idx, val) {
activeEditorDays[idx].details = val;
}
function updateDayMeeting(idx, val) {
activeEditorDays[idx].meetingDurationMinutes = Math.max(0, parseInt(val, 10) || 0);
recalculateMetrics(getSelectedAssignment());
}
function quickFillWorkdays() {
activeEditorDays.forEach(d => {
if (d.inRange && !d.isWeekend) {
d.worked = true;
if (!d.details) d.details = "Full-day development & tasks";
}
});
renderEditorUI(getSelectedAssignment());
showToast('Quick-fill Applied', 'Marked all working weekdays within contract range.', 'info');
}
function clearAllDays() {
activeEditorDays.forEach(d => {
d.worked = false;
d.details = '';
d.meetingDurationMinutes = 0;
});
renderEditorUI(getSelectedAssignment());
}
function getSelectedAssignment() {
const projectId = document.getElementById('ts-project-select').value;
return state.assignments.find(a =>
a.projectId === projectId && a.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase()
);
}
function recalculateMetrics(assignment) {
let daysCount = 0;
let meetingMins = 0;
activeEditorDays.forEach(d => {
if (d.worked) {
daysCount++;
meetingMins += (d.meetingDurationMinutes || 0);
}
});
const meetingHours = Math.round((meetingMins / 60) * 10) / 10;
const rate = assignment ? (assignment.dailyRate || 0) : 0;
const estTotal = daysCount * rate;
document.getElementById('stat-days-worked').textContent = `${daysCount} day${daysCount === 1 ? '' : 's'}`;
document.getElementById('stat-meeting-hours').textContent = `${meetingHours} hrs (${meetingMins}m)`;
document.getElementById('stat-estimated-billing').textContent = `€${estTotal.toLocaleString()}`;
// Update active timesheet totals
activeEditorTimesheet.totalDaysWorked = daysCount;
activeEditorTimesheet.totalMeetingHours = meetingHours;
// Invoice status card
const invoiceStatusEl = document.getElementById('stat-invoice-status');
const invoiceIconEl = document.getElementById('stat-invoice-icon');
if (activeAttachedInvoice && activeAttachedInvoice.data) {
invoiceStatusEl.textContent = "Attached & Ready";
invoiceStatusEl.className = "text-sm font-bold text-emerald-600";
invoiceIconEl.className = "w-12 h-12 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center font-bold";
} else {
invoiceStatusEl.textContent = "Missing (Mandatory)";
invoiceStatusEl.className = "text-sm font-bold text-rose-600";
invoiceIconEl.className = "w-12 h-12 rounded-xl bg-rose-50 text-rose-600 flex items-center justify-center font-bold";
}
}
// -------------------------------------------------------------
// Invoice Attachment Handling
// -------------------------------------------------------------
function handleInvoiceFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
activeAttachedInvoice = {
name: file.name,
data: e.target.result, // base64 data URL
size: `${Math.round(file.size / 1024)} KB`
};
activeEditorTimesheet.invoiceFileName = activeAttachedInvoice.name;
activeEditorTimesheet.invoiceFileData = activeAttachedInvoice.data;
updateInvoiceUI();
recalculateMetrics(getSelectedAssignment());
showToast('Invoice Attached', `${file.name} uploaded successfully.`, 'success');
};
reader.readAsDataURL(file);
}
function generateSampleInvoicePDF() {
const month = document.getElementById('ts-month-input').value;
const filename = `Invoice_${currentFreelancer.name.replace(/\s+/g, '_')}_${month}.pdf`;
activeAttachedInvoice = {
name: filename,
data: SAMPLE_PDF_BASE64,
size: "12 KB"
};
activeEditorTimesheet.invoiceFileName = filename;
activeEditorTimesheet.invoiceFileData = SAMPLE_PDF_BASE64;
updateInvoiceUI();
recalculateMetrics(getSelectedAssignment());
showToast('Sample PDF Generated', 'Official sample PDF invoice created and attached!', 'success');
}
function removeAttachedInvoice() {
activeAttachedInvoice = null;
activeEditorTimesheet.invoiceFileName = '';
activeEditorTimesheet.invoiceFileData = '';
document.getElementById('invoice-file-input').value = '';
updateInvoiceUI();
recalculateMetrics(getSelectedAssignment());
showToast('Invoice Removed', 'Attached invoice cleared.', 'info');
}
function updateInvoiceUI() {
const emptyState = document.getElementById('invoice-empty-state');
const attachedState = document.getElementById('invoice-attached-state');
const filenameEl = document.getElementById('attached-filename');
const filesizeEl = document.getElementById('attached-filesize');
if (activeAttachedInvoice && activeAttachedInvoice.data) {
emptyState.classList.add('hidden');
attachedState.classList.remove('hidden');
filenameEl.textContent = activeAttachedInvoice.name;
filesizeEl.textContent = activeAttachedInvoice.size || "Base64 Document";
} else {
emptyState.classList.remove('hidden');
attachedState.classList.add('hidden');
}
}
function previewCurrentInvoice() {
if (!activeAttachedInvoice || !activeAttachedInvoice.data) {
showToast('No Invoice', 'Please attach an invoice file first.', 'error');
return;
}
openInvoicePreviewModal(activeAttachedInvoice.name, activeAttachedInvoice.data);
}
function openInvoicePreviewModal(title, base64Data) {
const modal = document.getElementById('modal-invoice-preview');
const frame = document.getElementById('preview-invoice-frame');
const img = document.getElementById('preview-invoice-img');
const downloadBtn = document.getElementById('preview-invoice-download-btn');
const titleEl = document.getElementById('preview-invoice-title');
titleEl.textContent = title || "Invoice Preview";
downloadBtn.href = base64Data;
downloadBtn.download = title || "invoice.pdf";
if (base64Data.startsWith('data:image/')) {
img.src = base64Data;
img.classList.remove('hidden');
frame.classList.add('hidden');
} else {
frame.src = base64Data;
frame.classList.remove('hidden');
img.classList.add('hidden');
}
modal.classList.remove('hidden');
}
function closeInvoicePreviewModal() {
const modal = document.getElementById('modal-invoice-preview');
const frame = document.getElementById('preview-invoice-frame');
frame.src = 'about:blank';
modal.classList.add('hidden');
}
// -------------------------------------------------------------
// Save Draft & Submit Timesheet
// -------------------------------------------------------------
function saveTimesheetDraft() {
commitActiveTimesheet('draft');
showToast('Draft Saved', 'Timesheet draft saved locally.', 'success');
renderEditorUI(getSelectedAssignment());
}
function submitTimesheet() {
// 1. Validate days worked > 0
const workedDays = activeEditorDays.filter(d => d.worked);
if (workedDays.length === 0) {
showToast('Validation Error', 'Please log at least 1 day worked before submitting.', 'error');
return;
}
// 2. Mandatory Invoice Attachment Check
if (!activeAttachedInvoice || !activeAttachedInvoice.data) {
showToast('Mandatory Invoice Missing', 'Please attach an invoice PDF or image before submitting.', 'error');
return;
}
// Commit as 'submitted'
activeEditorTimesheet.submittedAt = new Date().toISOString();
commitActiveTimesheet('submitted');
showToast('Timesheet Submitted!', 'Locked for admin review. Total days: ' + workedDays.length, 'success');
renderEditorUI(getSelectedAssignment());
renderFreelancerHistory();
renderAdminQueue();
}
function unlockForResubmission() {
activeEditorTimesheet.status = 'draft';
// Save status change
commitActiveTimesheet('draft');
showToast('Unlocked for Editing', 'You can now update your days, tasks, and invoice, then re-submit.', 'info');
renderEditorUI(getSelectedAssignment());
}
function commitActiveTimesheet(newStatus) {
activeEditorTimesheet.status = newStatus;
if (activeAttachedInvoice) {
activeEditorTimesheet.invoiceFileName = activeAttachedInvoice.name;
activeEditorTimesheet.invoiceFileData = activeAttachedInvoice.data;
}
// Insert or update in state.timesheets
let existingIndex = state.timesheets.findIndex(t =>
t.projectId === activeEditorTimesheet.projectId &&
t.freelanceEmail.toLowerCase() === activeEditorTimesheet.freelanceEmail.toLowerCase() &&
t.month === activeEditorTimesheet.month
);
if (existingIndex >= 0) {
state.timesheets[existingIndex] = JSON.parse(JSON.stringify(activeEditorTimesheet));
} else {
state.timesheets.push(JSON.parse(JSON.stringify(activeEditorTimesheet)));
}
// Update days
const currentTsId = activeEditorTimesheet._id;
// Remove old days for this timesheet
state.timesheet_days = state.timesheet_days.filter(d => d.timesheetId !== currentTsId);
// Append active days that are worked or have details
activeEditorDays.forEach(d => {
if (d.worked || d.details || d.meetingDurationMinutes > 0) {
state.timesheet_days.push({
_id: 'day_' + Math.random().toString(36).substring(2, 10),
timesheetId: currentTsId,
date: d.date,
worked: !!d.worked,
details: d.details || '',
meetingDurationMinutes: d.meetingDurationMinutes || 0
});
}
});
saveStore();
syncPostKallax('timesheets', activeEditorTimesheet);
updateBadges();
}
// -------------------------------------------------------------
// Freelancer View: My Projects Tab
// -------------------------------------------------------------
function renderFreelancerProjects() {
const grid = document.getElementById('f-projects-grid');
const assignments = state.assignments.filter(a => a.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase());
grid.innerHTML = '';
if (assignments.length === 0) {
grid.innerHTML = `
<div class="col-span-full p-12 bg-white rounded-2xl border border-slate-200 text-center">
<p class="text-sm font-semibold text-slate-700">No active projects assigned</p>
<p class="text-xs text-slate-400 mt-1">Contact your project administrator to be assigned to active client engagements.</p>
</div>
`;
return;
}
assignments.forEach(a => {
const project = state.projects.find(p => p._id === a.projectId);
const card = document.createElement('div');
card.className = "bg-white rounded-2xl p-6 shadow-sm border border-slate-200 flex flex-col justify-between hover:shadow-md transition";
card.innerHTML = `
<div>
<div class="flex items-start justify-between">
<span class="text-[10px] uppercase font-bold tracking-wider px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-700">Active Contract</span>
<span class="text-xs font-bold text-emerald-600 bg-emerald-50 px-2 py-0.5 rounded-full">€${a.dailyRate || 0}/day</span>
</div>
<h3 class="text-lg font-bold text-slate-900 mt-3">${a.projectName}</h3>
<p class="text-xs text-slate-500 mt-1 line-clamp-2">${project ? project.description : 'Client Project'}</p>
<div class="mt-4 pt-4 border-t border-slate-100 space-y-2 text-xs text-slate-600">
<div class="flex items-center justify-between">
<span class="text-slate-400">Start Date:</span>
<span class="font-semibold text-slate-800">${a.startDate}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-slate-400">End Date:</span>
<span class="font-semibold text-slate-800">${a.endDate}</span>
</div>
<div class="flex items-center justify-between">
<span class="text-slate-400">Admin Contact:</span>
<span class="font-semibold text-slate-800">${project ? project.adminName : 'Project Lead'}</span>
</div>
</div>
</div>
<div class="mt-6 pt-4 border-t border-slate-100">
<button onclick="jumpToTimesheetEntry('${a.projectId}')"
class="w-full py-2.5 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl text-xs font-bold transition flex items-center justify-center gap-1.5">
<span>Log Timesheet</span>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
</button>
</div>
`;
grid.appendChild(card);
});
}
function jumpToTimesheetEntry(projectId) {
setFreelancerTab('entry');
const select = document.getElementById('ts-project-select');
select.value = projectId;
onTimesheetContextChange();
}
// -------------------------------------------------------------
// Freelancer View: History Page (Submitted Months)
// -------------------------------------------------------------
function renderFreelancerHistory() {
const tbody = document.getElementById('f-history-tbody');
const myTimesheets = state.timesheets.filter(t => t.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase());
tbody.innerHTML = '';
if (myTimesheets.length === 0) {
tbody.innerHTML = `<tr><td colspan="8" class="py-12 text-center text-slate-400">No timesheets logged or submitted yet.</td></tr>`;
return;
}
// Sort recent first
myTimesheets.sort((a, b) => (b.month || '').localeCompare(a.month || ''));
myTimesheets.forEach(ts => {
const tr = document.createElement('tr');
tr.className = "hover:bg-slate-50 transition";
const hasInvoice = !!ts.invoiceFileData;
const isRefused = ts.status === 'refused';
tr.innerHTML = `
<td class="py-3.5 px-4 font-semibold text-slate-900">${ts.projectName}</td>
<td class="py-3.5 px-4 font-mono font-medium text-slate-700">${ts.month}</td>
<td class="py-3.5 px-4 text-slate-800 font-bold">${ts.totalDaysWorked || 0} days</td>
<td class="py-3.5 px-4 text-slate-600">${ts.totalMeetingHours || 0} hrs</td>
<td class="py-3.5 px-4">
${hasInvoice ? `
<button onclick="openInvoicePreviewModal('${escapeHtml(ts.invoiceFileName)}', '${escapeHtml(ts.invoiceFileData)}')"
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-semibold bg-indigo-50 text-indigo-700 hover:bg-indigo-100 transition">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
<span>Invoice</span>
</button>
` : `<span class="text-xs text-slate-400">None</span>`}
</td>
<td class="py-3.5 px-4">
${getStatusBadgeHTML(ts.status)}
</td>
<td class="py-3.5 px-4 max-w-xs truncate text-xs text-slate-500">
${ts.adminFeedback ? `<span class="text-rose-600 font-medium" title="${escapeHtml(ts.adminFeedback)}">${escapeHtml(ts.adminFeedback)}</span>` : '<span class="text-slate-400">&mdash;</span>'}
</td>
<td class="py-3.5 px-4 text-right whitespace-nowrap">
${isRefused ? `
<button onclick="editAndResubmitFromHistory('${ts.projectId}', '${ts.month}')"
class="px-3 py-1.5 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-xs font-bold transition shadow-sm">
Edit & Resubmit
</button>
` : `
<button onclick="viewHistoryMonthDetails('${ts._id}')"
class="px-3 py-1.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg text-xs font-semibold transition">
View Log
</button>
`}
</td>
`;
tbody.appendChild(tr);
});
}
function editAndResubmitFromHistory(projectId, month) {
setFreelancerTab('entry');
const pSelect = document.getElementById('ts-project-select');
const mInput = document.getElementById('ts-month-input');
pSelect.value = projectId;
mInput.value = month;
loadActiveTimesheet(month, projectId);
unlockForResubmission();
}
function viewHistoryMonthDetails(timesheetId) {
openInspectModal(timesheetId);
}
// -------------------------------------------------------------
// Project Admin View: Validation Queue Logic
// -------------------------------------------------------------
function filterAdminQueue(status) {
currentAdminQueueFilter = status;
['all', 'submitted', 'validated', 'refused'].forEach(s => {
const btn = document.getElementById(`btn-filter-${s}`);
if (s === status) {
btn.className = "px-3 py-1.5 rounded-lg text-xs font-semibold bg-white text-slate-800 shadow-sm transition";
} else {
btn.className = "px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition";
}
});
renderAdminQueue();
}
function renderAdminQueue() {
const tbody = document.getElementById('admin-queue-tbody');
const projectFilter = document.getElementById('admin-project-filter').value;
const searchKeyword = (document.getElementById('admin-search-input').value || '').toLowerCase().trim();
// Populate project filter options
const pFilterSelect = document.getElementById('admin-project-filter');
const currentSelected = pFilterSelect.value;
pFilterSelect.innerHTML = '<option value="">All Projects</option>';
state.projects.forEach(p => {
const opt = document.createElement('option');
opt.value = p._id;
opt.textContent = p.name;
if (p._id === currentSelected) opt.selected = true;
pFilterSelect.appendChild(opt);
});
let list = state.timesheets.filter(t => t.status !== 'draft'); // Admin validates submitted/reviewed months
// Apply status filter
if (currentAdminQueueFilter !== 'all') {
list = list.filter(t => t.status === currentAdminQueueFilter);
}
// Apply project filter
if (projectFilter) {
list = list.filter(t => t.projectId === projectFilter);
}
// Apply search filter
if (searchKeyword) {
list = list.filter(t =>
(t.freelanceName || '').toLowerCase().includes(searchKeyword) ||
(t.freelanceEmail || '').toLowerCase().includes(searchKeyword) ||
(t.projectName || '').toLowerCase().includes(searchKeyword)
);
}
// Update stats counters
const pendingCount = state.timesheets.filter(t => t.status === 'submitted').length;
const valCount = state.timesheets.filter(t => t.status === 'validated').length;
const refCount = state.timesheets.filter(t => t.status === 'refused').length;
const totalCount = state.timesheets.filter(t => t.status !== 'draft').length;
document.getElementById('stat-admin-pending').textContent = pendingCount;
document.getElementById('stat-admin-validated').textContent = valCount;
document.getElementById('stat-admin-refused').textContent = refCount;
document.getElementById('stat-admin-total').textContent = totalCount;
tbody.innerHTML = '';
if (list.length === 0) {
tbody.innerHTML = `<tr><td colspan="8" class="py-12 text-center text-slate-400">No timesheets match current filter criteria.</td></tr>`;
return;
}
// Sort submitted pending review to the top
list.sort((a, b) => {
if (a.status === 'submitted' && b.status !== 'submitted') return -1;
if (b.status === 'submitted' && a.status !== 'submitted') return 1;
return (b.month || '').localeCompare(a.month || '');
});
list.forEach(ts => {
const tr = document.createElement('tr');
tr.className = ts.status === 'submitted' ? 'bg-amber-50/20 hover:bg-amber-50/40 transition' : 'hover:bg-slate-50 transition';
const hasInvoice = !!ts.invoiceFileData;
tr.innerHTML = `
<td class="py-3.5 px-4 font-semibold text-slate-900">
<div>${ts.freelanceName}</div>
<div class="text-xs font-normal text-slate-400">${ts.freelanceEmail}</div>
</td>
<td class="py-3.5 px-4 text-slate-800 font-medium">${ts.projectName}</td>
<td class="py-3.5 px-4 font-mono font-bold text-slate-700">${ts.month}</td>
<td class="py-3.5 px-4 text-center font-bold text-slate-900">${ts.totalDaysWorked || 0}</td>
<td class="py-3.5 px-4 text-center text-slate-600">${ts.totalMeetingHours || 0} hrs</td>
<td class="py-3.5 px-4">
${hasInvoice ? `
<button onclick="openInvoicePreviewModal('${escapeHtml(ts.invoiceFileName)}', '${escapeHtml(ts.invoiceFileData)}')"
class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-semibold bg-indigo-50 text-indigo-700 hover:bg-indigo-100 transition">
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
<span>View</span>
</button>
` : `<span class="text-xs text-rose-500 font-medium">None</span>`}
</td>
<td class="py-3.5 px-4">
${getStatusBadgeHTML(ts.status)}
</td>
<td class="py-3.5 px-4 text-right whitespace-nowrap">
<button onclick="openInspectModal('${ts._id}')"
class="px-3.5 py-1.5 ${ts.status === 'submitted' ? 'bg-indigo-600 hover:bg-indigo-700 text-white shadow-sm' : 'bg-slate-100 hover:bg-slate-200 text-slate-700'} rounded-xl text-xs font-bold transition">
Inspect & Validate
</button>
</td>
`;
tbody.appendChild(tr);
});
}
// -------------------------------------------------------------
// Inspect & Validate Timesheet Modal
// -------------------------------------------------------------
function openInspectModal(timesheetId) {
inspectTimesheetId = timesheetId;
const ts = state.timesheets.find(t => t._id === timesheetId);
if (!ts) return;
const assignment = state.assignments.find(a =>
a.projectId === ts.projectId && a.freelanceEmail.toLowerCase() === ts.freelanceEmail.toLowerCase()
);
const days = state.timesheet_days.filter(d => d.timesheetId === timesheetId);
document.getElementById('inspect-title').textContent = `${ts.freelanceName} — ${ts.projectName}`;
document.getElementById('inspect-subtitle').textContent = `Timesheet for Month: ${ts.month} • Submitted: ${ts.submittedAt ? new Date(ts.submittedAt).toLocaleString() : 'Draft'}`;
document.getElementById('inspect-status-badge').innerHTML = getStatusBadgeHTML(ts.status);
const rate = assignment ? (assignment.dailyRate || 0) : 0;
const totalAmount = (ts.totalDaysWorked || 0) * rate;
document.getElementById('inspect-days-worked').textContent = `${ts.totalDaysWorked || 0} days`;
document.getElementById('inspect-meeting-hours').textContent = `${ts.totalMeetingHours || 0} hrs`;
document.getElementById('inspect-daily-rate').textContent = `€${rate}/day`;
document.getElementById('inspect-total-amount').textContent = `€${totalAmount.toLocaleString()}`;
// Invoice info
const invoiceNameEl = document.getElementById('inspect-invoice-name');
const invoiceBtn = document.getElementById('btn-inspect-invoice-view');
if (ts.invoiceFileName && ts.invoiceFileData) {
invoiceNameEl.textContent = ts.invoiceFileName;
invoiceBtn.classList.remove('hidden');
} else {
invoiceNameEl.textContent = "No invoice file attached";
invoiceBtn.classList.add('hidden');
}
// Feedback display
const fbBox = document.getElementById('inspect-feedback-box');
const fbText = document.getElementById('inspect-feedback-text');
if (ts.adminFeedback) {
fbBox.classList.remove('hidden');
fbText.textContent = ts.adminFeedback;
} else {
fbBox.classList.add('hidden');
}
// Render days table
const tbody = document.getElementById('inspect-days-tbody');
tbody.innerHTML = '';
if (days.length === 0) {
tbody.innerHTML = `<tr><td colspan="4" class="py-4 text-center text-slate-400">No individual day logs recorded for this month.</td></tr>`;
} else {
days.sort((a, b) => a.date.localeCompare(b.date));
days.forEach(d => {
const tr = document.createElement('tr');
tr.className = d.worked ? "bg-indigo-50/20" : "";
tr.innerHTML = `
<td class="py-2.5 px-4 font-medium text-slate-800">${d.date}</td>
<td class="py-2.5 px-4 text-center">
${d.worked ? '<span class="text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded font-bold">Worked</span>' : '<span class="text-slate-400">Off</span>'}
</td>
<td class="py-2.5 px-4 text-slate-700">${escapeHtml(d.details) || '&mdash;'}</td>
<td class="py-2.5 px-4 text-right font-medium text-slate-700">${d.meetingDurationMinutes || 0} mins</td>
`;
tbody.appendChild(tr);
});
}
document.getElementById('modal-inspect-timesheet').classList.remove('hidden');
}
function closeInspectModal() {
document.getElementById('modal-inspect-timesheet').classList.add('hidden');
inspectTimesheetId = null;
}
function viewModalInvoice() {
if (!inspectTimesheetId) return;
const ts = state.timesheets.find(t => t._id === inspectTimesheetId);
if (ts && ts.invoiceFileData) {
openInvoicePreviewModal(ts.invoiceFileName, ts.invoiceFileData);
}
}
function validateCurrentMonth() {
if (!inspectTimesheetId) return;
const ts = state.timesheets.find(t => t._id === inspectTimesheetId);
if (!ts) return;
ts.status = 'validated';
ts.adminFeedback = ''; // clear feedback on approval
saveStore();
syncPostKallax('timesheets', ts);
showToast('Timesheet Approved', `${ts.freelanceName}'s timesheet for ${ts.month} has been validated!`, 'success');
closeInspectModal();
renderAll();
}
function openRefusePrompt() {
if (!inspectTimesheetId) return;
document.getElementById('refusal-feedback-input').value = '';
document.getElementById('modal-refuse-prompt').classList.remove('hidden');
}
function closeRefusePrompt() {
document.getElementById('modal-refuse-prompt').classList.add('hidden');
}
function confirmRefuseTimesheet() {
const feedback = document.getElementById('refusal-feedback-input').value.trim();
if (!feedback) {
alert("Please provide refusal feedback notes so the freelancer knows what to adjust.");
return;
}
const ts = state.timesheets.find(t => t._id === inspectTimesheetId);
if (!ts) return;
ts.status = 'refused';
ts.adminFeedback = feedback;
saveStore();
syncPostKallax('timesheets', ts);
showToast('Timesheet Refused', `Marked as refused with feedback. Freelancer can now edit & resubmit.`, 'error');
closeRefusePrompt();
closeInspectModal();
renderAll();
}
// -------------------------------------------------------------
// Project Admin View: Projects & Assignments Management
// -------------------------------------------------------------
function renderAdminProjects() {
const listContainer = document.getElementById('admin-projects-list');
listContainer.innerHTML = '';
if (state.projects.length === 0) {
listContainer.innerHTML = `<div class="p-8 bg-white rounded-2xl border text-center text-slate-400">No projects created yet.</div>`;
return;
}
state.projects.forEach(p => {
const assigned = state.assignments.filter(a => a.projectId === p._id);
const card = document.createElement('div');
card.className = "bg-white rounded-2xl p-6 shadow-sm border border-slate-200 space-y-4";
card.innerHTML = `
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-100 pb-4">
<div>
<div class="flex items-center gap-2">
<h3 class="text-lg font-bold text-slate-900">${p.name}</h3>
<span class="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700">${p.status || 'active'}</span>
</div>
<p class="text-xs text-slate-500 mt-0.5">${p.description || 'No description provided'}</p>
<div class="text-xs text-slate-400 mt-1">Admin: <span class="font-medium text-slate-700">${p.adminName || 'Sarah Jenkins'}</span> &lt;${p.adminEmail || 'admin@example.com'}&gt;</div>
</div>
<button onclick="openAddAssignmentModal('${p._id}', '${escapeHtml(p.name)}')"
class="px-3.5 py-2 bg-indigo-50 hover:bg-indigo-100 text-indigo-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5 self-start sm:self-auto">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
Assign Freelancer
</button>
</div>
<!-- Freelancers Table -->
<div>
<h4 class="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Assigned Freelancers (${assigned.length})</h4>
${assigned.length === 0 ? `
<p class="text-xs text-slate-400 italic">No freelancers assigned to this project yet.</p>
` : `
<div class="border border-slate-100 rounded-xl overflow-hidden">
<table class="w-full text-left text-xs">
<thead class="bg-slate-50 text-slate-500 font-semibold uppercase">
<tr>
<th class="py-2.5 px-4">Freelancer</th>
<th class="py-2.5 px-4">Start Date</th>
<th class="py-2.5 px-4">End Date</th>
<th class="py-2.5 px-4">Daily Rate</th>
<th class="py-2.5 px-4 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100">
${assigned.map(a => `
<tr class="hover:bg-slate-50">
<td class="py-2.5 px-4 font-semibold text-slate-800">
<div>${a.freelanceName}</div>
<div class="text-[11px] font-normal text-slate-400">${a.freelanceEmail}</div>
</td>
<td class="py-2.5 px-4 text-slate-700">${a.startDate}</td>
<td class="py-2.5 px-4 text-slate-700">${a.endDate}</td>
<td class="py-2.5 px-4 font-bold text-emerald-700">€${a.dailyRate || 0}</td>
<td class="py-2.5 px-4 text-right space-x-2">
<button onclick="openEditAssignmentModal('${a._id}')"
class="px-2.5 py-1 bg-white hover:bg-slate-100 border border-slate-200 text-slate-700 rounded-lg text-xs font-medium transition">
Edit Dates
</button>
<button onclick="removeAssignment('${a._id}')"
class="px-2.5 py-1 bg-white hover:bg-rose-50 border border-rose-200 text-rose-600 rounded-lg text-xs font-medium transition">
Remove
</button>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`}
</div>
`;
listContainer.appendChild(card);
});
}
// Modal: Add Assignment
function openAddAssignmentModal(projectId, projectName) {
document.getElementById('assign-project-id').value = projectId;
document.getElementById('modal-assign-project-name').textContent = projectName;
document.getElementById('assign-freelance-name').value = '';
document.getElementById('assign-freelance-email').value = '';
document.getElementById('assign-start-date').value = '2025-01-01';
document.getElementById('assign-end-date').value = '2025-12-31';
document.getElementById('assign-daily-rate').value = '550';
document.getElementById('modal-add-assignment').classList.remove('hidden');
}
function closeAddAssignmentModal() {
document.getElementById('modal-add-assignment').classList.add('hidden');
}
function handleSaveAssignment(e) {
e.preventDefault();
const projectId = document.getElementById('assign-project-id').value;
const project = state.projects.find(p => p._id === projectId);
const name = document.getElementById('assign-freelance-name').value.trim();
const email = document.getElementById('assign-freelance-email').value.trim().toLowerCase();
const startDate = document.getElementById('assign-start-date').value;
const endDate = document.getElementById('assign-end-date').value;
const dailyRate = parseInt(document.getElementById('assign-daily-rate').value, 10) || 500;
if (!name || !email || !startDate || !endDate) return;
const newAssignment = {
_id: 'assign_' + Math.random().toString(36).substring(2, 10),
projectId: projectId,
projectName: project ? project.name : 'Project',
freelanceName: name,
freelanceEmail: email,
startDate: startDate,
endDate: endDate,
dailyRate: dailyRate
};
state.assignments.push(newAssignment);
// Also register into personas list if not already there
if (!FREELANCER_PERSONAS.some(p => p.email === email)) {
FREELANCER_PERSONAS.push({ name, email });
}
saveStore();
syncPostKallax('assignments', newAssignment);
closeAddAssignmentModal();
renderAll();
showToast('Assignment Created', `${name} assigned to ${project ? project.name : 'project'}.`, 'success');
}
// Modal: Edit Assignment Dates
function openEditAssignmentModal(assignmentId) {
const a = state.assignments.find(x => x._id === assignmentId);
if (!a) return;
document.getElementById('edit-assignment-id').value = a._id;
document.getElementById('modal-edit-assign-title').textContent = `${a.freelanceName} (${a.projectName})`;
document.getElementById('edit-assign-start-date').value = a.startDate;
document.getElementById('edit-assign-end-date').value = a.endDate;
document.getElementById('edit-assign-daily-rate').value = a.dailyRate || 0;
document.getElementById('modal-edit-assignment').classList.remove('hidden');
}
function closeEditAssignmentModal() {
document.getElementById('modal-edit-assignment').classList.add('hidden');
}
function handleUpdateAssignmentDates(e) {
e.preventDefault();
const aId = document.getElementById('edit-assignment-id').value;
const a = state.assignments.find(x => x._id === aId);
if (!a) return;
a.startDate = document.getElementById('edit-assign-start-date').value;
a.endDate = document.getElementById('edit-assign-end-date').value;
a.dailyRate = parseInt(document.getElementById('edit-assign-daily-rate').value, 10) || 0;
saveStore();
syncPostKallax('assignments', a);
closeEditAssignmentModal();
renderAll();
showToast('Dates Updated', `Contract dates adjusted for ${a.freelanceName}.`, 'success');
}
function removeAssignment(assignmentId) {
const a = state.assignments.find(x => x._id === assignmentId);
if (!a) return;
if (!confirm(`Are you sure you want to remove ${a.freelanceName} from ${a.projectName}?`)) return;
state.assignments = state.assignments.filter(x => x._id !== assignmentId);
saveStore();
renderAll();
showToast('Assignment Removed', `${a.freelanceName} has been unassigned.`, 'info');
}
// Modal: Create Project
function openNewProjectModal() {
document.getElementById('new-project-name').value = '';
document.getElementById('new-project-desc').value = '';
document.getElementById('new-project-admin-name').value = currentAdmin.name;
document.getElementById('new-project-admin-email').value = currentAdmin.email;
document.getElementById('modal-create-project').classList.remove('hidden');
}
function closeNewProjectModal() {
document.getElementById('modal-create-project').classList.add('hidden');
}
function handleCreateProject(e) {
e.preventDefault();
const name = document.getElementById('new-project-name').value.trim();
const desc = document.getElementById('new-project-desc').value.trim();
const adminName = document.getElementById('new-project-admin-name').value.trim() || currentAdmin.name;
const adminEmail = document.getElementById('new-project-admin-email').value.trim() || currentAdmin.email;
if (!name) return;
const newProj = {
_id: 'proj_' + Math.random().toString(36).substring(2, 10),
name: name,
description: desc,
adminName: adminName,
adminEmail: adminEmail,
status: 'active'
};
state.projects.push(newProj);
saveStore();
syncPostKallax('projects', newProj);
closeNewProjectModal();
renderAll();
showToast('Project Created', `Project "${name}" is now ready for assignments.`, 'success');
}
// -------------------------------------------------------------
// Helper Utilities
// -------------------------------------------------------------
function getStatusBadgeHTML(status) {
const s = (status || 'draft').toLowerCase();
if (s === 'validated') {
return `<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-800 border border-emerald-300">
<svg class="w-3.5 h-3.5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>
Validated
</span>`;
}
if (s === 'submitted') {
return `<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-amber-100 text-amber-800 border border-amber-300">
<svg class="w-3.5 h-3.5 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
Submitted (Pending Review)
</span>`;
}
if (s === 'refused') {
return `<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-bold bg-rose-100 text-rose-800 border border-rose-300">
<svg class="w-3.5 h-3.5 text-rose-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
Refused
</span>`;
}
return `<span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-slate-100 text-slate-700 border border-slate-300">
Draft
</span>`;
}
function escapeHtml(str) {
if (!str) return '';
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function updateBadges() {
// Freelancer badges
const myAssignments = state.assignments.filter(a => a.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase());
document.getElementById('badge-my-projects-count').textContent = myAssignments.length;
const myTimesheets = state.timesheets.filter(t => t.freelanceEmail.toLowerCase() === currentFreelancer.email.toLowerCase());
document.getElementById('badge-history-count').textContent = myTimesheets.length;
// Admin badges
const pendingCount = state.timesheets.filter(t => t.status === 'submitted').length;
document.getElementById('badge-admin-queue-count').textContent = pendingCount;
document.getElementById('badge-admin-projects-count').textContent = state.projects.length;
}
function renderTimesheetEntryView() {
renderFreelancerProjectSelector();
const monthInput = document.getElementById('ts-month-input');
if (!monthInput.value) {
monthInput.value = "2025-05"; // default to seeded month
}
onTimesheetContextChange();
}
function renderAll() {
updateBadges();
if (currentRole === 'freelancer') {
if (currentFreelancerTab === 'entry') renderTimesheetEntryView();
if (currentFreelancerTab === 'projects') renderFreelancerProjects();
if (currentFreelancerTab === 'history') renderFreelancerHistory();
} else {
if (currentAdminTab === 'validation') renderAdminQueue();
if (currentAdminTab === 'projects') renderAdminProjects();
}
}
// -------------------------------------------------------------
// App Initialization
// -------------------------------------------------------------
window.addEventListener('DOMContentLoaded', async () => {
initStore();
await initAuth();
renderAll();
});
</script>
</body>
</html>