Update index.html
1 file changed+258−46
index.html+258−46View file
| @@ -2632,19 +2632,118 @@ | ||
| reader.readAsDataURL(file); | ||
| } | ||
| - function generateSampleInvoicePDF() { | ||
| - const month = document.getElementById('ts-month-input').value; | ||
| - const filename = `Invoice_${currentFreelancer.name.replace(/\s+/g, '_')}_${month}.pdf`; | ||
| + 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: SAMPLE_PDF_BASE64, | ||
| - size: "12 KB" | ||
| + data: dataUrl, | ||
| + size: `${Math.round(body.length / 1024) || 1} KB`, | ||
| + sizeBytes: body.length, | ||
| + type: 'application/pdf' | ||
| }; | ||
| - activeEditorTimesheet.invoiceFileName = filename; | ||
| - activeEditorTimesheet.invoiceFileData = SAMPLE_PDF_BASE64; | ||
| + if (activeEditorTimesheet) { | ||
| + activeEditorTimesheet.invoiceFileName = filename; | ||
| + activeEditorTimesheet.invoiceFileData = dataUrl; | ||
| + activeEditorTimesheet.invoiceFileSize = body.length; | ||
| + activeEditorTimesheet.invoiceContentType = 'application/pdf'; | ||
| + } | ||
| + | ||
| updateInvoiceUI(); | ||
| recalculateMetrics(getSelectedAssignment()); | ||
| - showToast('Sample PDF Generated', 'Official sample PDF invoice created and attached!', 'success'); | ||
| + 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() { | ||
| @@ -2686,19 +2785,28 @@ | ||
| const modal = document.getElementById('modal-invoice-preview'); | ||
| const frame = document.getElementById('preview-invoice-frame'); | ||
| const img = document.getElementById('preview-invoice-img'); | ||
| - const downloadBtn = document.getElementById('preview-invoice-download-btn'); | ||
| const titleEl = document.getElementById('preview-invoice-title'); | ||
| titleEl.textContent = title || "Invoice Preview"; | ||
| - downloadBtn.href = base64Data; | ||
| - downloadBtn.download = title || "invoice.pdf"; | ||
| + currentPreviewFile = { | ||
| + name: title || "invoice.pdf", | ||
| + data: base64Data, | ||
| + type: base64Data && base64Data.startsWith('data:image/') ? 'image/png' : 'application/pdf' | ||
| + }; | ||
| - if (base64Data.startsWith('data:image/')) { | ||
| + if (base64Data && base64Data.startsWith('data:image/')) { | ||
| img.src = base64Data; | ||
| img.classList.remove('hidden'); | ||
| frame.classList.add('hidden'); | ||
| - } else { | ||
| - frame.src = base64Data; | ||
| + } 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'); | ||
| } | ||
| @@ -2710,20 +2818,26 @@ | ||
| 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'); | ||
| } | ||
| // ------------------------------------------------------------- | ||
| // Save Draft & Submit Timesheet | ||
| // ------------------------------------------------------------- | ||
| - function saveTimesheetDraft() { | ||
| + async function saveTimesheetDraft() { | ||
| recalculateMetrics(getSelectedAssignment()); | ||
| - commitActiveTimesheet('draft'); | ||
| - showToast('Draft Saved', 'Timesheet draft saved locally.', 'success'); | ||
| + showToast('Saving...', 'Updating draft timesheet...', 'info'); | ||
| + await commitActiveTimesheet('draft'); | ||
| + showToast('Draft Saved', 'Timesheet draft saved and synced.', 'success'); | ||
| renderEditorUI(getSelectedAssignment()); | ||
| + renderFreelancerHistory(); | ||
| } | ||
| - function submitTimesheet() { | ||
| + async function submitTimesheet() { | ||
| // 1. Validate days worked >= 0.5 | ||
| recalculateMetrics(getSelectedAssignment()); | ||
| const totalDays = activeEditorTimesheet.totalDaysWorked || 0; | ||
| @@ -2738,9 +2852,9 @@ | ||
| return; | ||
| } | ||
| - // Commit as 'submitted' | ||
| + showToast('Submitting...', 'Submitting timesheet for approval...', 'info'); | ||
| activeEditorTimesheet.submittedAt = new Date().toISOString(); | ||
| - commitActiveTimesheet('submitted'); | ||
| + await commitActiveTimesheet('submitted'); | ||
| showToast('Timesheet Submitted!', `Locked for admin review. Total days: ${formatDays(totalDays)}`, 'success'); | ||
| renderEditorUI(getSelectedAssignment()); | ||
| @@ -2748,27 +2862,23 @@ | ||
| renderAdminQueue(); | ||
| } | ||
| - function unlockForResubmission() { | ||
| + async function unlockForResubmission() { | ||
| activeEditorTimesheet.status = 'draft'; | ||
| - // Save status change | ||
| - commitActiveTimesheet('draft'); | ||
| + await commitActiveTimesheet('draft'); | ||
| showToast('Unlocked for Editing', 'You can now update your days, tasks, and invoice, then re-submit.', 'info'); | ||
| renderEditorUI(getSelectedAssignment()); | ||
| + renderFreelancerHistory(); | ||
| } | ||
| - function commitActiveTimesheet(newStatus) { | ||
| + async function commitActiveTimesheet(newStatus) { | ||
| activeEditorTimesheet.status = newStatus; | ||
| if (activeAttachedInvoice) { | ||
| activeEditorTimesheet.invoiceFileName = activeAttachedInvoice.name || ''; | ||
| activeEditorTimesheet.invoiceFileData = activeAttachedInvoice.data || ''; | ||
| - activeEditorTimesheet.invoiceFileSize = activeAttachedInvoice.sizeBytes || 0; | ||
| + activeEditorTimesheet.invoiceFileSize = activeAttachedInvoice.sizeBytes || (activeAttachedInvoice.data ? activeAttachedInvoice.data.length : 0); | ||
| activeEditorTimesheet.invoiceContentType = activeAttachedInvoice.type || 'application/pdf'; | ||
| - if (activeAttachedInvoice.fileUrl) { | ||
| - activeEditorTimesheet.invoiceFileUrl = activeAttachedInvoice.fileUrl; | ||
| - } | ||
| - if (activeAttachedInvoice.fileId) { | ||
| - activeEditorTimesheet.invoiceFile = activeAttachedInvoice.fileId; | ||
| - } | ||
| + activeEditorTimesheet.invoiceFileUrl = activeAttachedInvoice.fileUrl || ''; | ||
| + activeEditorTimesheet.invoiceFile = activeAttachedInvoice.fileId || null; | ||
| } else { | ||
| activeEditorTimesheet.invoiceFileName = ''; | ||
| activeEditorTimesheet.invoiceFileData = ''; | ||
| @@ -2778,42 +2888,144 @@ | ||
| activeEditorTimesheet.invoiceFile = null; | ||
| } | ||
| - // Insert or update in state.timesheets | ||
| + // Local optimistic update | ||
| let existingIndex = state.timesheets.findIndex(t => | ||
| - t.projectId === activeEditorTimesheet.projectId && | ||
| - t.freelanceEmail.toLowerCase() === activeEditorTimesheet.freelanceEmail.toLowerCase() && | ||
| - t.month === activeEditorTimesheet.month | ||
| + (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))); | ||
| } | ||
| - // Update days | ||
| - const currentTsId = activeEditorTimesheet._id; | ||
| - // Remove old days for this timesheet | ||
| - state.timesheet_days = state.timesheet_days.filter(d => d.timesheetId !== currentTsId); | ||
| - // Append active days that are worked or have details | ||
| + 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.meetingDurationMinutes || 0) > 0) { | ||
| - state.timesheet_days.push({ | ||
| - _id: 'day_' + Math.random().toString(36).substring(2, 10), | ||
| - timesheetId: currentTsId, | ||
| + 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: d.meetingDurationMinutes || 0 | ||
| + meetingDurationMinutes: Number(d.meetingDurationMinutes) || 0 | ||
| }); | ||
| } | ||
| }); | ||
| + // Update state.timesheet_days locally | ||
| + state.timesheet_days = state.timesheet_days.filter(d => d.timesheetId !== activeEditorTimesheet._id).concat(activeWorkedDays); | ||
| saveStore(); | ||
| - syncPostKallax('timesheets', activeEditorTimesheet); | ||
| updateBadges(); | ||
| + | ||
| + // Backend REST Kallax Sync | ||
| + try { | ||
| + let serverTsId = activeEditorTimesheet._id; | ||
| + const tsPayload = cleanPayload(activeEditorTimesheet); | ||
| + | ||
| + if (!isTempId(serverTsId)) { | ||
| + // PATCH /api/timesheets/:id | ||
| + 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 { | ||
| + // POST /api/timesheets | ||
| + 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; | ||
| + }); | ||
| + } | ||
| + } | ||
| + | ||
| + // Batch save or update days to /api/timesheet_days | ||
| + 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); | ||
| + } | ||
| } | ||
| // ------------------------------------------------------------- | ||