| <!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> |
| |
| <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; } |
| |
| ::-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"> |
| |
| |
| <div id="toast-container" class="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm pointer-events-none"></div> |
| |
| |
| <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"> |
| |
| |
| <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> |
| |
| |
| <div class="flex items-center space-x-3"> |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <div id="admin-testing-notice" class="hidden bg-indigo-50 border-b border-indigo-200 text-indigo-800 text-xs py-2 px-4 font-medium"> |
| <div class="max-w-7xl mx-auto flex flex-wrap items-center justify-center gap-2"> |
| <span>⚡ <strong>Admin Preview Mode:</strong> Viewing as</span> |
| <select id="preview-freelancer-select" onchange="changePreviewFreelancer(this.value)" class="text-xs py-0.5 px-2 rounded-lg border border-indigo-300 bg-white font-semibold text-indigo-900 focus:ring-1 focus:ring-indigo-500 shadow-sm"> |
| </select> |
| <span>• Switch back to <button onclick="switchRole('admin')" class="underline font-bold text-indigo-950 hover:text-indigo-700 ml-0.5">Project Admin View</button> anytime.</span> |
| </div> |
| </div> |
| |
| |
| <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> |
| |
| |
| <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"> |
| |
| |
| <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> |
| |
| |
| <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 class="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8"> |
| |
| |
| |
| |
| <div id="freelancer-view-container"> |
| |
| |
| <div id="f-view-entry" class="space-y-6"> |
| |
| |
| <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"> |
| |
| <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]"> |
| |
| </select> |
| </div> |
| |
| |
| <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> |
| |
| |
| <div id="ts-contract-info" class="pt-5 flex items-center gap-2 text-xs text-slate-600"> |
| |
| </div> |
| </div> |
| |
| |
| <div class="flex items-center gap-3"> |
| <div id="ts-status-badge-container"> |
| |
| </div> |
| </div> |
| |
| </div> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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 flex-wrap items-center gap-2"> |
| <button type="button" onclick="quickFillWorkdays(1.0)" 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"> |
| Fill Weekdays (Full) |
| </button> |
| <button type="button" onclick="quickFillWorkdays(0.5)" id="btn-quick-fill-half" |
| 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"> |
| Fill Weekdays (Half) |
| </button> |
| <button type="button" onclick="clearWeekdays()" 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 Weekdays |
| </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-64 text-center">Work Logged</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"> |
| |
| </tbody> |
| </table> |
| </div> |
| </div> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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="downloadCurrentAttachedInvoice()" id="btn-download-invoice" |
| class="px-3 py-1.5 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-semibold rounded-lg transition flex items-center gap-1 shadow-sm"> |
| <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /> |
| </svg> |
| Download |
| </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" title="Remove invoice"> |
| <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> |
| |
| |
| <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> |
| |
| |
| <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"> |
| |
| </div> |
| </div> |
| |
| |
| <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"> |
| |
| </tbody> |
| </table> |
| </div> |
| </div> |
| </div> |
| |
| </div> |
| |
| |
| |
| |
| <div id="admin-view-container" class="hidden space-y-6"> |
| |
| |
| <div id="a-view-validation" class="space-y-6"> |
| |
| |
| <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> |
| |
| |
| <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"> |
| |
| <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> |
| |
| |
| <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> |
| |
| </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> |
| |
| |
| <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"> |
| |
| </tbody> |
| </table> |
| </div> |
| </div> |
| |
| </div> |
| |
| |
| <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"> |
| |
| </div> |
| </div> |
| |
| </div> |
| |
| </main> |
| |
| |
| |
| |
| |
| |
| <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]"> |
| |
| |
| <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> |
| |
| |
| <div class="p-6 overflow-y-auto space-y-6 flex-1"> |
| |
| |
| <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> |
| |
| |
| <div class="p-4 rounded-2xl bg-indigo-50/50 border border-indigo-100 flex flex-col sm:flex-row sm:items-center justify-between gap-3"> |
| <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 flex-shrink-0"> |
| <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> |
| <p id="inspect-invoice-meta" class="text-xs text-slate-400 mt-0.5"></p> |
| </div> |
| </div> |
| <div class="flex items-center gap-2"> |
| <button type="button" id="btn-inspect-invoice-view" onclick="viewModalInvoice()" |
| class="px-3.5 py-2 bg-white hover:bg-slate-50 text-indigo-700 border border-indigo-200 rounded-xl text-xs font-bold 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /> |
| <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /> |
| </svg> |
| View Preview |
| </button> |
| <button type="button" id="btn-inspect-invoice-download" onclick="downloadModalInvoice()" |
| class="px-3.5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-bold 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 |
| </button> |
| </div> |
| </div> |
| |
| |
| <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> |
| |
| |
| <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-28 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"> |
| |
| </tbody> |
| </table> |
| </div> |
| </div> |
| |
| </div> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <div id="modal-edit-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">Edit Project</h3> |
| <p class="text-xs text-slate-500 mt-0.5">Update project scope, active status, and client administrator contact.</p> |
| </div> |
| <form id="form-edit-project" onsubmit="handleUpdateProject(event)" class="p-6 space-y-4"> |
| <input type="hidden" id="edit-project-id"> |
| <div> |
| <label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Project Name *</label> |
| <input type="text" id="edit-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="edit-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> |
| <label class="block text-xs font-semibold text-slate-700 uppercase mb-1">Status</label> |
| <select id="edit-project-status" class="w-full text-sm p-2.5 rounded-xl border border-slate-300 focus:ring-indigo-500 bg-white"> |
| <option value="active">Active</option> |
| <option value="completed">Completed</option> |
| <option value="archived">Archived</option> |
| </select> |
| </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="edit-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="edit-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="closeEditProjectModal()" 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 Changes |
| </button> |
| </div> |
| </form> |
| </div> |
| </div> |
| |
| |
| <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="#" onclick="handleModalPreviewDownload(event)" |
| 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> |
| |
| |
| <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"> |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| <div id="auth-notice-alert" class="hidden mx-6 mt-3 p-3.5 bg-emerald-50 border border-emerald-300 text-emerald-900 text-xs rounded-xl flex items-start gap-2.5"> |
| <svg class="w-5 h-5 text-emerald-600 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"> |
| <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" /> |
| </svg> |
| <div class="flex-1"> |
| <div class="font-bold text-emerald-950 text-xs" id="auth-notice-title">Verification Required</div> |
| <div class="mt-0.5 leading-relaxed text-emerald-800" id="auth-notice-msg">A verification link has been sent to your email. Please verify your email before logging in.</div> |
| </div> |
| </div> |
| |
| |
| <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> |
| |
| |
| <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> |
| |
| |
| |
| |
| <script> |
| |
| |
| |
| 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, |
| invoiceFileSize: 12450, |
| invoiceContentType: "application/pdf", |
| invoiceFileUrl: "", |
| 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, |
| workAmount: 1.0, |
| details: "Sprint planning and initial setup of checkout module", |
| meetingDurationMinutes: 60 |
| }, |
| { |
| _id: "6a9c60a98176c20c8259191c", |
| timesheetId: "6a9c60a38176c20c82591918", |
| date: "2025-05-05", |
| worked: true, |
| workAmount: 1.0, |
| details: "Implemented Stripe payment webhook handling", |
| meetingDurationMinutes: 30 |
| } |
| ] |
| }; |
| |
| |
| |
| |
| |
| |
| const STORAGE_KEY = "TIMESHEETS_APP_STORE_V1"; |
| let state = { |
| projects: [], |
| assignments: [], |
| timesheets: [], |
| timesheet_days: [] |
| }; |
| |
| |
| 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!" |
| } |
| }; |
| |
| |
| 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" } |
| ]; |
| |
| |
| const AUTH_TOKEN_KEY = "TIMESHEETS_AUTH_TOKEN_V1"; |
| const AUTH_USER_KEY = "TIMESHEETS_AUTH_USER_V1"; |
| const PROJECT_ID = '921e3a77-5246-4c5b-8eba-edc74b1ba247'; |
| let authToken = localStorage.getItem(AUTH_TOKEN_KEY) || null; |
| let currentUser = null; |
| |
| let currentRole = "freelancer"; |
| let currentFreelancer = FREELANCER_PERSONAS[0]; |
| let currentAdmin = ADMIN_PERSONAS[0]; |
| |
| |
| let currentFreelancerTab = "entry"; |
| let currentAdminTab = "validation"; |
| let currentAdminQueueFilter = "all"; |
| |
| |
| let activeEditorTimesheet = null; |
| let activeEditorDays = []; |
| let activeAttachedInvoice = null; |
| |
| |
| let inspectTimesheetId = null; |
| |
| |
| 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); |
| } |
| } |
| |
| |
| |
| |
| 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 |
| }); |
| } |
| |
| function unwrapRow(data) { |
| if (!data || typeof data !== 'object') return data; |
| return data.row || data.item || data; |
| } |
| |
| function isTempId(id) { |
| if (!id || typeof id !== 'string') return true; |
| return id.startsWith('draft_') || id.startsWith('proj_') || id.startsWith('assign_') || id.startsWith('day_') || id.startsWith('temp_'); |
| } |
| |
| function cleanPayload(obj, omitKeys = ['_id', '_createdAt', '_updatedAt', 'ownerId']) { |
| if (!obj || typeof obj !== 'object') return obj; |
| const copy = { ...obj }; |
| for (const k of omitKeys) { |
| delete copy[k]; |
| } |
| return copy; |
| } |
| |
| |
| async function tryKallaxSync() { |
| try { |
| const [projRes, assignRes, tsRes, daysRes] = await Promise.allSettled([ |
| apiFetch(`/api/p/${PROJECT_ID}/tables/projects/rows`).then(r => r.ok ? r.json() : null), |
| apiFetch(`/api/p/${PROJECT_ID}/tables/assignments/rows`).then(r => r.ok ? r.json() : null), |
| apiFetch(`/api/p/${PROJECT_ID}/tables/timesheets/rows`).then(r => r.ok ? r.json() : null), |
| apiFetch(`/api/p/${PROJECT_ID}/tables/timesheet_days/rows`).then(r => r.ok ? r.json() : null) |
| ]); |
| |
| const getItems = (res) => { |
| if (res.status === 'fulfilled' && res.value) { |
| if (Array.isArray(res.value)) return res.value; |
| if (Array.isArray(res.value.items)) return res.value.items; |
| } |
| return null; |
| }; |
| |
| let changed = false; |
| const pItems = getItems(projRes); |
| if (pItems !== null) { |
| state.projects = pItems; |
| changed = true; |
| } |
| const aItems = getItems(assignRes); |
| if (aItems !== null) { |
| state.assignments = aItems; |
| changed = true; |
| } |
| const tItems = getItems(tsRes); |
| if (tItems !== null) { |
| state.timesheets = tItems; |
| changed = true; |
| } |
| const dItems = getItems(daysRes); |
| if (dItems !== null) { |
| state.timesheet_days = dItems; |
| changed = true; |
| } |
| |
| if (changed) { |
| saveStore(); |
| renderAll(); |
| } |
| } catch (err) { |
| console.warn("Operating in offline/local storage mode:", err); |
| } |
| } |
| |
| async function syncPostKallax(endpoint, data) { |
| try { |
| const payload = cleanPayload(data); |
| if (data._id && !isTempId(data._id)) { |
| const updateRes = await apiFetch(`/api/p/${PROJECT_ID}/tables/${endpoint}/rows/${data._id}`, { |
| method: 'PATCH', |
| body: JSON.stringify(payload) |
| }); |
| if (updateRes.ok) return unwrapRow(await updateRes.json()); |
| } |
| const createRes = await apiFetch(`/api/p/${PROJECT_ID}/tables/${endpoint}/rows`, { |
| method: 'POST', |
| body: JSON.stringify(payload) |
| }); |
| if (createRes.ok) { |
| const resData = unwrapRow(await createRes.json()); |
| if (resData && resData._id && data._id && isTempId(data._id)) { |
| data._id = resData._id; |
| } |
| return resData; |
| } |
| } catch (err) { |
| |
| } |
| } |
| |
| |
| |
| |
| async function initAuth() { |
| const savedUser = localStorage.getItem(AUTH_USER_KEY); |
| if (savedUser) { |
| try { |
| currentUser = JSON.parse(savedUser); |
| } catch (e) { |
| currentUser = null; |
| } |
| } |
| |
| if (currentUser && authToken) { |
| 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'); |
| |
| |
| 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"; |
| } |
| } |
| |
| |
| 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/p/${PROJECT_ID}/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/p/' + PROJECT_ID + '/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(); |
| } |
| }); |
| |
| |
| function populatePersonaDropdown() { |
| updateHeaderAuthUI(); |
| } |
| |
| function changePersona(val) { |
| renderAll(); |
| } |
| |
| |
| |
| |
| 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); |
| } |
| |
| |
| |
| |
| function switchRole(role) { |
| if (!currentUser) { |
| openAuthModal('login'); |
| return; |
| } |
| |
| |
| 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'); |
| const pSelect = document.getElementById('preview-freelancer-select'); |
| if (pSelect) { |
| const allEmails = new Set(); |
| const list = []; |
| FREELANCER_PERSONAS.forEach(p => { |
| if (!allEmails.has(p.email.toLowerCase())) { |
| allEmails.add(p.email.toLowerCase()); |
| list.push(p); |
| } |
| }); |
| state.assignments.forEach(a => { |
| if (!allEmails.has(a.freelanceEmail.toLowerCase())) { |
| allEmails.add(a.freelanceEmail.toLowerCase()); |
| list.push({ name: a.freelanceName, email: a.freelanceEmail }); |
| } |
| }); |
| pSelect.innerHTML = list.map(f => `<option value="${f.email}" ${f.email.toLowerCase() === (currentFreelancer.email || '').toLowerCase() ? 'selected' : ''}>${f.name} (${f.email})</option>`).join(''); |
| } |
| } 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(); |
| } |
| |
| function changePreviewFreelancer(email) { |
| if (!email) return; |
| const p = FREELANCER_PERSONAS.find(x => x.email.toLowerCase() === email.toLowerCase()) || |
| state.assignments.find(x => x.freelanceEmail.toLowerCase() === email.toLowerCase()); |
| if (p) { |
| currentFreelancer = { name: p.name || p.freelanceName, email: p.email || p.freelanceEmail }; |
| renderAll(); |
| } |
| } |
| |
| |
| |
| |
| 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(); |
| } |
| |
| |
| |
| |
| 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; |
| } |
| |
| |
| 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} → ${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>`; |
| } |
| |
| |
| 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)); |
| |
| 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: existingTs.invoiceFileSize ? (Math.round(existingTs.invoiceFileSize / 1024) + " KB") : "Attached", |
| sizeBytes: existingTs.invoiceFileSize || 0, |
| type: existingTs.invoiceContentType || "application/pdf", |
| fileUrl: existingTs.invoiceFileUrl || "" |
| }; |
| } else { |
| activeAttachedInvoice = null; |
| } |
| } else { |
| |
| 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: '', |
| invoiceFileSize: 0, |
| invoiceContentType: '', |
| invoiceFileUrl: '', |
| invoiceFile: null, |
| 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; |
| 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(); |
| 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]; |
| let workAmount = 0; |
| if (existing) { |
| if (existing.workAmount !== undefined && existing.workAmount !== null) { |
| workAmount = Number(existing.workAmount); |
| } else if (existing.worked) { |
| workAmount = 1.0; |
| } |
| } |
| |
| activeEditorDays.push({ |
| date: dStr, |
| dayOfWeek, |
| isWeekend, |
| inRange, |
| workAmount: workAmount, |
| worked: workAmount > 0, |
| 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'; |
| |
| |
| const statusContainer = document.getElementById('ts-status-badge-container'); |
| statusContainer.innerHTML = getStatusBadgeHTML(activeEditorTimesheet.status); |
| |
| |
| 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'); |
| } |
| |
| |
| document.getElementById('btn-save-draft').disabled = isLocked; |
| document.getElementById('btn-submit-timesheet').disabled = isLocked; |
| const btnQuickFill = document.getElementById('btn-quick-fill'); |
| if (btnQuickFill) btnQuickFill.disabled = isLocked; |
| const btnQuickFillHalf = document.getElementById('btn-quick-fill-half'); |
| if (btnQuickFillHalf) btnQuickFillHalf.disabled = isLocked; |
| const btnClearDays = document.getElementById('btn-clear-days'); |
| if (btnClearDays) btnClearDays.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'); |
| if (btnQuickFill) btnQuickFill.classList.add('opacity-50', 'cursor-not-allowed'); |
| if (btnQuickFillHalf) btnQuickFillHalf.classList.add('opacity-50', 'cursor-not-allowed'); |
| if (btnClearDays) btnClearDays.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'); |
| if (btnQuickFill) btnQuickFill.classList.remove('opacity-50', 'cursor-not-allowed'); |
| if (btnQuickFillHalf) btnQuickFillHalf.classList.remove('opacity-50', 'cursor-not-allowed'); |
| if (btnClearDays) btnClearDays.classList.remove('opacity-50', 'cursor-not-allowed'); |
| } |
| |
| |
| 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.workAmount === 1.0 |
| ? 'bg-indigo-50/30' |
| : item.workAmount === 0.5 |
| ? 'bg-amber-50/30' |
| : item.isWeekend |
| ? 'bg-amber-50/20' |
| : 'hover:bg-slate-50'; |
| |
| tr.className = `transition ${rowBg}`; |
| |
| const isWorked = (item.workAmount || 0) > 0; |
| |
| 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 whitespace-nowrap"> |
| <div class="inline-flex items-center rounded-lg bg-slate-100 p-0.5 border border-slate-200 shadow-inner"> |
| <button type="button" onclick="setWorkAmount(${idx}, 0)" ${isLocked || !item.inRange ? 'disabled' : ''} |
| title="Off (0.0 days)" |
| class="px-2.5 py-1 text-xs rounded-md font-semibold transition ${item.workAmount === 0 ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-800'} disabled:cursor-not-allowed"> |
| Off (0) |
| </button> |
| <button type="button" onclick="setWorkAmount(${idx}, 0.5)" ${isLocked || !item.inRange ? 'disabled' : ''} |
| title="Half Day (0.5 days)" |
| class="px-2.5 py-1 text-xs rounded-md font-semibold transition ${item.workAmount === 0.5 ? 'bg-amber-500 text-white shadow-sm' : 'text-slate-500 hover:text-slate-800'} disabled:cursor-not-allowed"> |
| Half Day (0.5) |
| </button> |
| <button type="button" onclick="setWorkAmount(${idx}, 1.0)" ${isLocked || !item.inRange ? 'disabled' : ''} |
| title="Full Day (1.0 days)" |
| class="px-2.5 py-1 text-xs rounded-md font-semibold transition ${item.workAmount === 1.0 ? 'bg-indigo-600 text-white shadow-sm' : 'text-slate-500 hover:text-slate-800'} disabled:cursor-not-allowed"> |
| Full Day (1.0) |
| </button> |
| </div> |
| </td> |
| <td class="py-3 px-4"> |
| <input type="text" value="${escapeHtml(item.details)}" placeholder="${isWorked ? 'What did you accomplish today?' : 'Mark worked to enter details'}" |
| ${isLocked || !isWorked ? '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 || !isWorked ? '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); |
| }); |
| |
| |
| updateInvoiceUI(); |
| |
| |
| recalculateMetrics(assignment); |
| } |
| |
| function setWorkAmount(idx, amount) { |
| const num = Number(amount); |
| activeEditorDays[idx].workAmount = num; |
| activeEditorDays[idx].worked = num > 0; |
| if (num === 0) { |
| |
| activeEditorDays[idx].meetingDurationMinutes = 0; |
| } |
| renderEditorUI(getSelectedAssignment()); |
| } |
| |
| function toggleWorkedDay(idx, checked) { |
| setWorkAmount(idx, checked ? 1.0 : 0); |
| } |
| |
| 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(amount = 1.0) { |
| const isHalf = amount === 0.5; |
| const desc = isHalf ? "Half-day development & tasks" : "Full-day development & tasks"; |
| activeEditorDays.forEach(d => { |
| if (d.inRange && !d.isWeekend) { |
| d.workAmount = amount; |
| d.worked = true; |
| if (!d.details) d.details = desc; |
| } |
| }); |
| renderEditorUI(getSelectedAssignment()); |
| const label = isHalf ? 'Half Days (0.5)' : 'Full Days (1.0)'; |
| showToast('Quick-fill Applied', `Marked all working weekdays within contract range as ${label}.`, 'info'); |
| } |
| |
| function clearWeekdays() { |
| activeEditorDays.forEach(d => { |
| if (d.inRange && !d.isWeekend) { |
| d.workAmount = 0; |
| d.worked = false; |
| d.details = ''; |
| d.meetingDurationMinutes = 0; |
| } |
| }); |
| renderEditorUI(getSelectedAssignment()); |
| showToast('Cleared Weekdays', 'Reset all working weekdays to Off.', 'info'); |
| } |
| |
| function clearAllDays() { |
| activeEditorDays.forEach(d => { |
| d.workAmount = 0; |
| 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 => { |
| const amount = d.workAmount !== undefined ? Number(d.workAmount) : (d.worked ? 1.0 : 0); |
| if (amount > 0) { |
| daysCount += amount; |
| meetingMins += (d.meetingDurationMinutes || 0); |
| } |
| }); |
| |
| daysCount = Math.round(daysCount * 10) / 10; |
| const meetingHours = Math.round((meetingMins / 60) * 10) / 10; |
| const rate = assignment ? (assignment.dailyRate || 0) : 0; |
| const estTotal = Math.round(daysCount * rate * 100) / 100; |
| |
| document.getElementById('stat-days-worked').textContent = formatDays(daysCount); |
| document.getElementById('stat-meeting-hours').textContent = `${meetingHours} hrs (${meetingMins}m)`; |
| document.getElementById('stat-estimated-billing').textContent = `€${estTotal.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })}`; |
| |
| |
| activeEditorTimesheet.totalDaysWorked = daysCount; |
| activeEditorTimesheet.totalMeetingHours = meetingHours; |
| |
| |
| 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"; |
| } |
| } |
| |
| |
| |
| |
| let currentPreviewFile = null; |
| let currentPreviewBlobUrl = null; |
| |
| function dataUrlToBlob(dataUrl, fallbackMime) { |
| if (!dataUrl || typeof dataUrl !== 'string') return null; |
| try { |
| const commaIdx = dataUrl.indexOf(','); |
| if (commaIdx === -1) return null; |
| const semiIdx = dataUrl.indexOf(';'); |
| const mime = (semiIdx > 5 && semiIdx < commaIdx) ? dataUrl.substring(5, semiIdx) : (fallbackMime || 'application/pdf'); |
| const bstr = atob(dataUrl.substring(commaIdx + 1)); |
| let n = bstr.length; |
| const u8arr = new Uint8Array(n); |
| while (n--) { |
| u8arr[n] = bstr.charCodeAt(n); |
| } |
| return new Blob([u8arr], { type: mime }); |
| } catch (err) { |
| return null; |
| } |
| } |
| |
| function downloadInvoiceFile(fileObj) { |
| if (!fileObj) return; |
| const filename = fileObj.name || 'invoice.pdf'; |
| const mime = fileObj.type || (filename.toLowerCase().endsWith('.pdf') ? 'application/pdf' : 'application/octet-stream'); |
| let blob = fileObj.blob; |
| if (!blob && fileObj.data) { |
| blob = dataUrlToBlob(fileObj.data, mime); |
| } |
| if (blob) { |
| const url = URL.createObjectURL(blob); |
| const a = document.createElement('a'); |
| a.href = url; |
| a.download = filename; |
| document.body.appendChild(a); |
| a.click(); |
| setTimeout(function() { |
| document.body.removeChild(a); |
| URL.revokeObjectURL(url); |
| }, 2000); |
| } else if (fileObj.data) { |
| const a = document.createElement('a'); |
| a.href = fileObj.data; |
| a.download = filename; |
| document.body.appendChild(a); |
| a.click(); |
| setTimeout(function() { document.body.removeChild(a); }, 1000); |
| } |
| } |
| |
| function testInvoiceHelper() { |
| return true; |
| } |
| |
| 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, |
| 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 generateDynamicInvoicePDF() { |
| const assignment = getSelectedAssignment(); |
| const month = document.getElementById('ts-month-input').value || '2025-05'; |
| const freelancerName = (currentFreelancer && currentFreelancer.name) ? currentFreelancer.name : 'Freelancer'; |
| const freelancerEmail = (currentFreelancer && currentFreelancer.email) ? currentFreelancer.email : ''; |
| const projectName = assignment ? assignment.projectName : (activeEditorTimesheet ? activeEditorTimesheet.projectName : 'Project'); |
| const days = activeEditorTimesheet ? (activeEditorTimesheet.totalDaysWorked || 0) : 0; |
| const rate = assignment ? (assignment.dailyRate || 0) : 0; |
| const totalDue = Math.round(days * rate * 100) / 100; |
| const invoiceNum = 'INV-' + month.replace('-', '') + '-' + Math.floor(1000 + Math.random() * 9000); |
| const dateStr = new Date().toISOString().split('T')[0]; |
| |
| const lines = [ |
| `INVOICE / FACTURE: ${invoiceNum}`, |
| `Date: ${dateStr} | Period: ${month}`, |
| `Freelancer: ${freelancerName} <${freelancerEmail}>`, |
| `Client Project: ${projectName}`, |
| `------------------------------------------------------------`, |
| `Days Worked: ${days} day(s)`, |
| `Daily Rate: ${rate} EUR / day`, |
| `Total Amount Due: ${totalDue.toFixed(2)} EUR`, |
| `------------------------------------------------------------`, |
| `Status: Pending Submission / Approval`, |
| `Generated dynamically via Freelance Timesheets Platform.` |
| ]; |
| |
| let textStream = "BT\n/F1 14 Tf\n50 720 Td\n"; |
| lines.forEach((line, i) => { |
| const escaped = line.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)'); |
| if (i === 0) { |
| textStream += `/F1 18 Tf\n(${escaped}) Tj\n/F1 12 Tf\n0 -30 Td\n`; |
| } else { |
| textStream += `(${escaped}) Tj\n0 -22 Td\n`; |
| } |
| }); |
| textStream += "ET"; |
| |
| const streamLen = textStream.length; |
| let body = `%PDF-1.4\n`; |
| const offsets = []; |
| |
| offsets.push(body.length); |
| body += `1 0 obj\n<<\n/Type /Catalog\n/Pages 2 0 R\n>>\nendobj\n`; |
| |
| offsets.push(body.length); |
| body += `2 0 obj\n<<\n/Type /Pages\n/Kids [3 0 R]\n/Count 1\n>>\nendobj\n`; |
| |
| offsets.push(body.length); |
| body += `3 0 obj\n<<\n/Type /Page\n/Parent 2 0 R\n/MediaBox [0 0 612 792]\n/Contents 4 0 R\n/Resources <<\n/Font <<\n/F1 5 0 R\n>>\n>>\n>>\nendobj\n`; |
| |
| offsets.push(body.length); |
| body += `4 0 obj\n<<\n/Length ${streamLen}\n>>\nstream\n${textStream}\nendstream\nendobj\n`; |
| |
| offsets.push(body.length); |
| body += `5 0 obj\n<<\n/Type /Font\n/Subtype /Type1\n/BaseFont /Helvetica\n>>\nendobj\n`; |
| |
| const startxref = body.length; |
| body += `xref\n0 6\n0000000000 65535 f \n`; |
| for (let i = 0; i < offsets.length; i++) { |
| body += `${String(offsets[i]).padStart(10, '0')} 00000 n \n`; |
| } |
| body += `trailer\n<<\n/Size 6\n/Root 1 0 R\n>>\nstartxref\n${startxref}\n%%EOF`; |
| |
| let b64 = ''; |
| try { |
| b64 = btoa(unescape(encodeURIComponent(body))); |
| } catch (err) { |
| b64 = btoa(body); |
| } |
| const dataUrl = `data:application/pdf;base64,${b64}`; |
| const filename = `Invoice_${freelancerName.replace(/\\s+/g, '_')}_${month}.pdf`; |
| |
| activeAttachedInvoice = { |
| name: filename, |
| data: dataUrl, |
| size: `${Math.round(body.length / 1024) || 1} KB`, |
| sizeBytes: body.length, |
| type: 'application/pdf' |
| }; |
| if (activeEditorTimesheet) { |
| activeEditorTimesheet.invoiceFileName = filename; |
| activeEditorTimesheet.invoiceFileData = dataUrl; |
| activeEditorTimesheet.invoiceFileSize = body.length; |
| activeEditorTimesheet.invoiceContentType = 'application/pdf'; |
| } |
| |
| updateInvoiceUI(); |
| recalculateMetrics(getSelectedAssignment()); |
| showToast('Dynamic PDF Generated', `Generated ${filename} (${totalDue} EUR).`, 'success'); |
| } |
| |
| function generateSampleInvoicePDF() { |
| generateDynamicInvoicePDF(); |
| } |
| |
| function downloadCurrentAttachedInvoice() { |
| if (!activeAttachedInvoice || !activeAttachedInvoice.data) { |
| showToast('No Invoice Attached', 'Please attach or generate an invoice first.', 'error'); |
| return; |
| } |
| downloadInvoiceFile({ |
| name: activeAttachedInvoice.name, |
| data: activeAttachedInvoice.data, |
| type: activeAttachedInvoice.type || 'application/pdf' |
| }); |
| } |
| |
| function handleModalPreviewDownload(event) { |
| if (event) event.preventDefault(); |
| if (currentPreviewFile) { |
| downloadInvoiceFile(currentPreviewFile); |
| } |
| } |
| |
| 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 titleEl = document.getElementById('preview-invoice-title'); |
| |
| titleEl.textContent = title || "Invoice Preview"; |
| currentPreviewFile = { |
| name: title || "invoice.pdf", |
| data: base64Data, |
| type: base64Data && base64Data.startsWith('data:image/') ? 'image/png' : 'application/pdf' |
| }; |
| |
| if (base64Data && base64Data.startsWith('data:image/')) { |
| img.src = base64Data; |
| img.classList.remove('hidden'); |
| frame.classList.add('hidden'); |
| } else if (base64Data) { |
| const blob = dataUrlToBlob(base64Data, 'application/pdf'); |
| if (blob) { |
| if (currentPreviewBlobUrl) URL.revokeObjectURL(currentPreviewBlobUrl); |
| currentPreviewBlobUrl = URL.createObjectURL(blob); |
| frame.src = currentPreviewBlobUrl; |
| } 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'; |
| if (currentPreviewBlobUrl) { |
| URL.revokeObjectURL(currentPreviewBlobUrl); |
| currentPreviewBlobUrl = null; |
| } |
| modal.classList.add('hidden'); |
| } |
| |
| |
| |
| |
| async function saveTimesheetDraft() { |
| recalculateMetrics(getSelectedAssignment()); |
| showToast('Saving...', 'Updating draft timesheet...', 'info'); |
| await commitActiveTimesheet('draft'); |
| showToast('Draft Saved', 'Timesheet draft saved and synced.', 'success'); |
| renderEditorUI(getSelectedAssignment()); |
| renderFreelancerHistory(); |
| } |
| |
| async function submitTimesheet() { |
| |
| recalculateMetrics(getSelectedAssignment()); |
| const totalDays = activeEditorTimesheet.totalDaysWorked || 0; |
| if (totalDays < 0.5) { |
| showToast('Validation Error', 'Please log at least 0.5 days worked before submitting.', 'error'); |
| return; |
| } |
| |
| |
| if (!activeAttachedInvoice || !activeAttachedInvoice.data) { |
| showToast('Mandatory Invoice Missing', 'Please attach an invoice PDF or image before submitting.', 'error'); |
| return; |
| } |
| |
| showToast('Submitting...', 'Submitting timesheet for approval...', 'info'); |
| activeEditorTimesheet.submittedAt = new Date().toISOString(); |
| await commitActiveTimesheet('submitted'); |
| |
| showToast('Timesheet Submitted!', `Locked for admin review. Total days: ${formatDays(totalDays)}`, 'success'); |
| renderEditorUI(getSelectedAssignment()); |
| renderFreelancerHistory(); |
| renderAdminQueue(); |
| } |
| |
| async function unlockForResubmission() { |
| activeEditorTimesheet.status = 'draft'; |
| await commitActiveTimesheet('draft'); |
| showToast('Unlocked for Editing', 'You can now update your days, tasks, and invoice, then re-submit.', 'info'); |
| renderEditorUI(getSelectedAssignment()); |
| renderFreelancerHistory(); |
| } |
| |
| async function commitActiveTimesheet(newStatus) { |
| activeEditorTimesheet.status = newStatus; |
| if (activeAttachedInvoice) { |
| activeEditorTimesheet.invoiceFileName = activeAttachedInvoice.name || ''; |
| activeEditorTimesheet.invoiceFileData = activeAttachedInvoice.data || ''; |
| activeEditorTimesheet.invoiceFileSize = activeAttachedInvoice.sizeBytes || (activeAttachedInvoice.data ? activeAttachedInvoice.data.length : 0); |
| activeEditorTimesheet.invoiceContentType = activeAttachedInvoice.type || 'application/pdf'; |
| activeEditorTimesheet.invoiceFileUrl = activeAttachedInvoice.fileUrl || ''; |
| activeEditorTimesheet.invoiceFile = activeAttachedInvoice.fileId || null; |
| } else { |
| activeEditorTimesheet.invoiceFileName = ''; |
| activeEditorTimesheet.invoiceFileData = ''; |
| activeEditorTimesheet.invoiceFileSize = 0; |
| activeEditorTimesheet.invoiceContentType = ''; |
| activeEditorTimesheet.invoiceFileUrl = ''; |
| activeEditorTimesheet.invoiceFile = null; |
| } |
| |
| |
| let existingIndex = state.timesheets.findIndex(t => |
| (t._id && t._id === activeEditorTimesheet._id) || |
| (t.projectId === activeEditorTimesheet.projectId && |
| t.freelanceEmail.toLowerCase() === activeEditorTimesheet.freelanceEmail.toLowerCase() && |
| t.month === activeEditorTimesheet.month) |
| ); |
| |
| if (existingIndex >= 0) { |
| if (!activeEditorTimesheet._id || isTempId(activeEditorTimesheet._id)) { |
| if (!isTempId(state.timesheets[existingIndex]._id)) { |
| activeEditorTimesheet._id = state.timesheets[existingIndex]._id; |
| } |
| } |
| state.timesheets[existingIndex] = JSON.parse(JSON.stringify(activeEditorTimesheet)); |
| } else { |
| state.timesheets.push(JSON.parse(JSON.stringify(activeEditorTimesheet))); |
| } |
| |
| const oldDays = state.timesheet_days.filter(d => d.timesheetId === activeEditorTimesheet._id); |
| const activeWorkedDays = []; |
| activeEditorDays.forEach(d => { |
| const amount = d.workAmount !== undefined && d.workAmount !== null ? Number(d.workAmount) : (d.worked ? 1.0 : 0); |
| if (amount > 0 || (d.details && d.details.trim()) || (d.meetingDurationMinutes || 0) > 0) { |
| const existingDay = oldDays.find(od => od.date === d.date); |
| activeWorkedDays.push({ |
| _id: existingDay ? existingDay._id : ('day_' + Math.random().toString(36).substring(2, 10)), |
| timesheetId: activeEditorTimesheet._id, |
| date: d.date, |
| workAmount: amount, |
| worked: amount > 0, |
| details: d.details || '', |
| meetingDurationMinutes: Number(d.meetingDurationMinutes) || 0 |
| }); |
| } |
| }); |
| |
| |
| state.timesheet_days = state.timesheet_days.filter(d => d.timesheetId !== activeEditorTimesheet._id).concat(activeWorkedDays); |
| saveStore(); |
| updateBadges(); |
| |
| |
| try { |
| let serverTsId = activeEditorTimesheet._id; |
| const tsPayload = cleanPayload(activeEditorTimesheet); |
| |
| if (!isTempId(serverTsId)) { |
| |
| const tsRes = await apiFetch(`/api/timesheets/${serverTsId}`, { |
| method: 'PATCH', |
| body: JSON.stringify(tsPayload) |
| }); |
| if (tsRes.ok) { |
| const updatedTs = await tsRes.json(); |
| const idx = state.timesheets.findIndex(t => t._id === serverTsId); |
| if (idx >= 0) Object.assign(state.timesheets[idx], updatedTs); |
| } |
| } else { |
| |
| const tsRes = await apiFetch('/api/timesheets', { |
| method: 'POST', |
| body: JSON.stringify(tsPayload) |
| }); |
| if (tsRes.ok) { |
| const createdTs = await tsRes.json(); |
| const oldTempId = activeEditorTimesheet._id; |
| serverTsId = createdTs._id; |
| activeEditorTimesheet._id = serverTsId; |
| |
| const idx = state.timesheets.findIndex(t => t._id === oldTempId); |
| if (idx >= 0) state.timesheets[idx] = createdTs; |
| state.timesheet_days.forEach(d => { |
| if (d.timesheetId === oldTempId) d.timesheetId = serverTsId; |
| }); |
| activeWorkedDays.forEach(d => { |
| d.timesheetId = serverTsId; |
| }); |
| } |
| } |
| |
| |
| const dayPromises = []; |
| |
| for (const d of activeWorkedDays) { |
| const dayPayload = { |
| timesheetId: serverTsId, |
| date: d.date, |
| workAmount: d.workAmount, |
| worked: d.worked, |
| details: d.details || '', |
| meetingDurationMinutes: d.meetingDurationMinutes || 0 |
| }; |
| |
| if (!isTempId(d._id)) { |
| dayPromises.push( |
| apiFetch(`/api/timesheet_days/${d._id}`, { |
| method: 'PATCH', |
| body: JSON.stringify(cleanPayload(dayPayload)) |
| }).then(r => r.ok ? r.json() : null).then(saved => { |
| if (saved && saved._id) { |
| const idx = state.timesheet_days.findIndex(x => x._id === d._id); |
| if (idx >= 0) state.timesheet_days[idx] = saved; |
| } |
| }) |
| ); |
| } else { |
| dayPromises.push( |
| apiFetch('/api/timesheet_days', { |
| method: 'POST', |
| body: JSON.stringify(dayPayload) |
| }).then(r => r.ok ? r.json() : null).then(saved => { |
| if (saved && saved._id) { |
| const tempId = d._id; |
| d._id = saved._id; |
| const idx = state.timesheet_days.findIndex(x => x._id === tempId); |
| if (idx >= 0) state.timesheet_days[idx] = saved; |
| } |
| }) |
| ); |
| } |
| } |
| |
| for (const od of oldDays) { |
| if (!isTempId(od._id) && !activeWorkedDays.some(ad => ad._id === od._id || ad.date === od.date)) { |
| dayPromises.push( |
| apiFetch(`/api/timesheet_days/${od._id}`, { |
| method: 'DELETE' |
| }).catch(() => null) |
| ); |
| } |
| } |
| |
| await Promise.allSettled(dayPromises); |
| saveStore(); |
| } catch (err) { |
| console.warn('Backend sync failed, state maintained in offline store:', err); |
| } |
| } |
| |
| |
| |
| |
| 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(); |
| } |
| |
| |
| |
| |
| 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; |
| } |
| |
| |
| 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">${formatDays(ts.totalDaysWorked || 0)}</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">—</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); |
| } |
| |
| |
| |
| |
| 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(); |
| |
| |
| 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'); |
| |
| |
| if (currentAdminQueueFilter !== 'all') { |
| list = list.filter(t => t.status === currentAdminQueueFilter); |
| } |
| |
| |
| if (projectFilter) { |
| list = list.filter(t => t.projectId === projectFilter); |
| } |
| |
| |
| if (searchKeyword) { |
| list = list.filter(t => |
| (t.freelanceName || '').toLowerCase().includes(searchKeyword) || |
| (t.freelanceEmail || '').toLowerCase().includes(searchKeyword) || |
| (t.projectName || '').toLowerCase().includes(searchKeyword) |
| ); |
| } |
| |
| |
| 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; |
| } |
| |
| |
| 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">${formatDays(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); |
| }); |
| } |
| |
| |
| |
| |
| 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 totalDays = Number(ts.totalDaysWorked) || 0; |
| const totalAmount = Math.round(totalDays * rate * 100) / 100; |
| |
| document.getElementById('inspect-days-worked').textContent = formatDays(totalDays); |
| 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(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })}`; |
| |
| |
| 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'); |
| } |
| |
| |
| 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'); |
| } |
| |
| |
| 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'); |
| const amount = d.workAmount !== undefined && d.workAmount !== null ? Number(d.workAmount) : (d.worked ? 1.0 : 0); |
| tr.className = amount >= 1.0 ? "bg-indigo-50/20" : (amount > 0 ? "bg-amber-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"> |
| ${getDayWorkBadgeHTML(d)} |
| </td> |
| <td class="py-2.5 px-4 text-slate-700">${escapeHtml(d.details) || '—'}</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); |
| } |
| } |
| |
| async function validateCurrentMonth() { |
| if (!inspectTimesheetId) return; |
| const ts = state.timesheets.find(t => t._id === inspectTimesheetId); |
| if (!ts) return; |
| |
| ts.status = 'validated'; |
| ts.adminFeedback = ''; |
| saveStore(); |
| |
| if (!isTempId(ts._id)) { |
| try { |
| const res = await apiFetch(`/api/timesheets/${ts._id}`, { |
| method: 'PATCH', |
| body: JSON.stringify({ status: 'validated', adminFeedback: '' }) |
| }); |
| if (res.ok) { |
| const serverTs = await res.json(); |
| Object.assign(ts, serverTs); |
| saveStore(); |
| } |
| } catch (err) { |
| console.warn('PATCH /api/timesheets/:id failed, updated locally:', err); |
| } |
| } |
| |
| 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'); |
| } |
| |
| async 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(); |
| |
| if (!isTempId(ts._id)) { |
| try { |
| const res = await apiFetch(`/api/timesheets/${ts._id}`, { |
| method: 'PATCH', |
| body: JSON.stringify({ status: 'refused', adminFeedback: feedback }) |
| }); |
| if (res.ok) { |
| const serverTs = await res.json(); |
| Object.assign(ts, serverTs); |
| saveStore(); |
| } |
| } catch (err) { |
| console.warn('PATCH /api/timesheets/:id failed, updated locally:', err); |
| } |
| } |
| |
| showToast('Timesheet Refused', `Marked as refused with feedback. Freelancer can now edit & resubmit.`, 'error'); |
| closeRefusePrompt(); |
| closeInspectModal(); |
| renderAll(); |
| } |
| |
| |
| |
| |
| 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">${escapeHtml(p.name)}</h3> |
| <span class="text-[10px] uppercase font-bold px-2 py-0.5 rounded-full ${p.status === 'completed' ? 'bg-blue-50 text-blue-700' : (p.status === 'archived' ? 'bg-slate-100 text-slate-600' : 'bg-emerald-50 text-emerald-700')}">${escapeHtml(p.status || 'active')}</span> |
| </div> |
| <p class="text-xs text-slate-500 mt-0.5">${escapeHtml(p.description || 'No description provided')}</p> |
| <div class="text-xs text-slate-400 mt-1">Admin: <span class="font-medium text-slate-700">${escapeHtml(p.adminName || 'Sarah Jenkins')}</span> <${escapeHtml(p.adminEmail || 'admin@example.com')}></div> |
| </div> |
| <div class="flex items-center gap-2 flex-wrap self-start sm:self-auto"> |
| <button onclick="openEditProjectModal('${p._id}')" |
| class="px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-xs font-bold transition flex items-center gap-1.5 shadow-sm"> |
| <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="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> |
| Edit |
| </button> |
| <button onclick="deleteProject('${p._id}')" |
| class="px-3 py-2 bg-rose-50 hover:bg-rose-100 text-rose-600 border border-rose-200 rounded-xl text-xs font-bold transition flex items-center gap-1.5 shadow-sm"> |
| <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="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> |
| Delete |
| </button> |
| <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 shadow-sm"> |
| <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> |
| </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>${escapeHtml(a.freelanceName)}</div> |
| <div class="text-[11px] font-normal text-slate-400">${escapeHtml(a.freelanceEmail)}</div> |
| </td> |
| <td class="py-2.5 px-4 text-slate-700">${escapeHtml(a.startDate)}</td> |
| <td class="py-2.5 px-4 text-slate-700">${escapeHtml(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 shadow-sm"> |
| 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 shadow-sm"> |
| Remove |
| </button> |
| </td> |
| </tr> |
| `).join('')} |
| </tbody> |
| </table> |
| </div> |
| `} |
| </div> |
| `; |
| listContainer.appendChild(card); |
| }); |
| } |
| |
| |
| 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'); |
| } |
| |
| async 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 payload = { |
| projectId: projectId, |
| projectName: project ? project.name : 'Project', |
| freelanceName: name, |
| freelanceEmail: email, |
| startDate: startDate, |
| endDate: endDate, |
| dailyRate: dailyRate |
| }; |
| |
| let newAssignment = null; |
| try { |
| const res = await apiFetch('/api/assignments', { |
| method: 'POST', |
| body: JSON.stringify(payload) |
| }); |
| if (res.ok) { |
| newAssignment = await res.json(); |
| } |
| } catch (err) { |
| console.warn('POST /api/assignments failed, fallback to local store:', err); |
| } |
| |
| if (!newAssignment || !newAssignment._id) { |
| newAssignment = { |
| _id: 'assign_' + Math.random().toString(36).substring(2, 10), |
| ...payload |
| }; |
| } |
| |
| state.assignments.push(newAssignment); |
| if (!FREELANCER_PERSONAS.some(p => p.email === email)) { |
| FREELANCER_PERSONAS.push({ name, email }); |
| } |
| |
| saveStore(); |
| closeAddAssignmentModal(); |
| renderAll(); |
| showToast('Assignment Created', `${name} assigned to ${project ? project.name : 'project'}.`, 'success'); |
| } |
| |
| |
| 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'); |
| } |
| |
| async 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; |
| |
| const updateData = { |
| startDate: document.getElementById('edit-assign-start-date').value, |
| endDate: document.getElementById('edit-assign-end-date').value, |
| dailyRate: parseInt(document.getElementById('edit-assign-daily-rate').value, 10) || 0 |
| }; |
| |
| Object.assign(a, updateData); |
| saveStore(); |
| closeEditAssignmentModal(); |
| renderAll(); |
| |
| if (!isTempId(aId)) { |
| try { |
| const res = await apiFetch(`/api/assignments/${aId}`, { |
| method: 'PATCH', |
| body: JSON.stringify(updateData) |
| }); |
| if (res.ok) { |
| const serverData = await res.json(); |
| Object.assign(a, serverData); |
| saveStore(); |
| } |
| } catch (err) { |
| console.warn('PATCH /api/assignments/:id failed, maintained locally:', err); |
| } |
| } |
| showToast('Dates Updated', `Contract dates adjusted for ${a.freelanceName}.`, 'success'); |
| } |
| |
| async 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(); |
| |
| if (!isTempId(assignmentId)) { |
| try { |
| await apiFetch(`/api/assignments/${assignmentId}`, { |
| method: 'DELETE' |
| }); |
| } catch (err) { |
| console.warn('DELETE /api/assignments/:id failed, removed locally:', err); |
| } |
| } |
| showToast('Assignment Removed', `${a.freelanceName} has been unassigned.`, 'info'); |
| } |
| |
| |
| 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'); |
| } |
| |
| async 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 payload = { |
| name: name, |
| description: desc, |
| adminName: adminName, |
| adminEmail: adminEmail, |
| status: 'active' |
| }; |
| |
| let newProj = null; |
| try { |
| const res = await apiFetch('/api/projects', { |
| method: 'POST', |
| body: JSON.stringify(payload) |
| }); |
| if (res.ok) { |
| newProj = await res.json(); |
| } |
| } catch (err) { |
| console.warn('POST /api/projects failed, fallback to local store:', err); |
| } |
| |
| if (!newProj || !newProj._id) { |
| newProj = { |
| _id: 'proj_' + Math.random().toString(36).substring(2, 10), |
| ...payload |
| }; |
| } |
| |
| state.projects.push(newProj); |
| saveStore(); |
| closeNewProjectModal(); |
| renderAll(); |
| showToast('Project Created', `Project "${name}" is now ready for assignments.`, 'success'); |
| } |
| |
| |
| function openEditProjectModal(projectId) { |
| const p = state.projects.find(x => x._id === projectId); |
| if (!p) return; |
| document.getElementById('edit-project-id').value = p._id; |
| document.getElementById('edit-project-name').value = p.name || ''; |
| document.getElementById('edit-project-desc').value = p.description || ''; |
| document.getElementById('edit-project-status').value = p.status || 'active'; |
| document.getElementById('edit-project-admin-name').value = p.adminName || ''; |
| document.getElementById('edit-project-admin-email').value = p.adminEmail || ''; |
| document.getElementById('modal-edit-project').classList.remove('hidden'); |
| } |
| |
| function closeEditProjectModal() { |
| document.getElementById('modal-edit-project').classList.add('hidden'); |
| } |
| |
| async function handleUpdateProject(e) { |
| e.preventDefault(); |
| const pId = document.getElementById('edit-project-id').value; |
| const p = state.projects.find(x => x._id === pId); |
| if (!p) return; |
| |
| const updatedData = { |
| name: document.getElementById('edit-project-name').value.trim(), |
| description: document.getElementById('edit-project-desc').value.trim(), |
| status: document.getElementById('edit-project-status').value, |
| adminName: document.getElementById('edit-project-admin-name').value.trim(), |
| adminEmail: document.getElementById('edit-project-admin-email').value.trim() |
| }; |
| |
| if (!updatedData.name) return; |
| |
| Object.assign(p, updatedData); |
| |
| state.assignments.forEach(a => { |
| if (a.projectId === pId) a.projectName = updatedData.name; |
| }); |
| state.timesheets.forEach(t => { |
| if (t.projectId === pId) t.projectName = updatedData.name; |
| }); |
| |
| saveStore(); |
| closeEditProjectModal(); |
| renderAll(); |
| |
| if (!isTempId(pId)) { |
| try { |
| const res = await apiFetch(`/api/projects/${pId}`, { |
| method: 'PATCH', |
| body: JSON.stringify(cleanPayload(updatedData)) |
| }); |
| if (res.ok) { |
| const serverData = await res.json(); |
| Object.assign(p, serverData); |
| saveStore(); |
| } |
| } catch (err) { |
| console.warn('PATCH /api/projects/:id failed, maintained locally:', err); |
| } |
| } |
| showToast('Project Updated', `Project "${updatedData.name}" has been updated.`, 'success'); |
| } |
| |
| async function deleteProject(projectId) { |
| const p = state.projects.find(x => x._id === projectId); |
| if (!p) return; |
| if (!confirm(`Are you sure you want to delete project "${p.name}"? This action cannot be undone.`)) return; |
| |
| state.projects = state.projects.filter(x => x._id !== projectId); |
| saveStore(); |
| renderAll(); |
| |
| if (!isTempId(projectId)) { |
| try { |
| await apiFetch(`/api/projects/${projectId}`, { |
| method: 'DELETE' |
| }); |
| } catch (err) { |
| console.warn('DELETE /api/projects/:id failed, removed locally:', err); |
| } |
| } |
| showToast('Project Deleted', `Project "${p.name}" was removed.`, 'info'); |
| } |
| |
| |
| |
| |
| 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 formatDays(days) { |
| const num = Math.round((Number(days) || 0) * 10) / 10; |
| const formatted = Number.isInteger(num) ? num.toString() : (Math.round(num * 10) / 10).toString(); |
| return `${formatted} ${num === 1 ? 'day' : 'days'}`; |
| } |
| |
| function formatDaysCountOnly(days) { |
| const num = Math.round((Number(days) || 0) * 10) / 10; |
| return Number.isInteger(num) ? num.toString() : (Math.round(num * 10) / 10).toString(); |
| } |
| |
| function getDayWorkBadgeHTML(dayOrAmount) { |
| let amount = 0; |
| if (typeof dayOrAmount === 'object' && dayOrAmount !== null) { |
| if (dayOrAmount.workAmount !== undefined && dayOrAmount.workAmount !== null) { |
| amount = Number(dayOrAmount.workAmount); |
| } else if (dayOrAmount.worked) { |
| amount = 1.0; |
| } |
| } else { |
| amount = Number(dayOrAmount) || 0; |
| } |
| |
| if (amount >= 1.0) { |
| return '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold bg-indigo-100 text-indigo-800 border border-indigo-200">Full Day</span>'; |
| } else if (amount > 0) { |
| return '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold bg-amber-100 text-amber-800 border border-amber-200">Half Day</span>'; |
| } else { |
| return '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-500">Off</span>'; |
| } |
| } |
| |
| function escapeHtml(str) { |
| if (!str) return ''; |
| return String(str) |
| .replace(/&/g, '&') |
| .replace(/</g, '<') |
| .replace(/>/g, '>') |
| .replace(/"/g, '"') |
| .replace(/'/g, '''); |
| } |
| |
| function updateBadges() { |
| |
| 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; |
| |
| |
| 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"; |
| } |
| 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(); |
| } |
| } |
| |
| |
| |
| |
| window.addEventListener('DOMContentLoaded', async () => { |
| initStore(); |
| await initAuth(); |
| await tryKallaxSync(); |
| renderAll(); |
| }); |
| </script> |
| </body> |
| </html> |