fix: crash bugs in TeamInvoices + faster load

Bug fixes:
- TeamInvoices: add useAuth import/currentUser (invoice-create crash)
- TeamInvoices: setChartYear -> setExportYear (year-dropdown crash)
- TeamDashboard: drop redundant setState-in-effect (cascading renders)
- Companies: delete dead _UnusedClientCompanies (illegal hook calls)
- annotate intentional empty PDF-fallback catches

Load speed:
- preconnect/dns-prefetch to Supabase origin
- lazy-load heic-to in Converters: page chunk 2737KB -> 9KB
- split recharts into its own 'charts' vendor chunk

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Krao Hasanee
2026-06-08 12:59:11 -04:00
parent 85625f4d95
commit 04e0911e9f
101 changed files with 11786 additions and 7445 deletions
+4 -3
View File
@@ -1,4 +1,4 @@
import { useState, useRef } from 'react';
import { useId, useRef, useState } from 'react';
const MAX_FILES = 20;
const MAX_SIZE_MB = 250;
@@ -10,6 +10,7 @@ const formatSize = (bytes) => {
};
export default function FileAttachment({ files, onChange }) {
const inputId = useId();
const [errors, setErrors] = useState([]);
const [dragging, setDragging] = useState(false);
const dragCounter = useRef(0);
@@ -79,8 +80,8 @@ export default function FileAttachment({ files, onChange }) {
transition: 'all 160ms', cursor: 'pointer',
}}
>
<input type="file" multiple onChange={handleChange} style={{ display: 'none' }} id="req-file-upload" />
<label htmlFor="req-file-upload" style={{ cursor: 'pointer', textTransform: 'none', letterSpacing: 'normal', fontWeight: 400 }}>
<input type="file" multiple onChange={handleChange} style={{ display: 'none' }} id={inputId} />
<label htmlFor={inputId} style={{ cursor: 'pointer', textTransform: 'none', letterSpacing: 'normal', fontWeight: 400 }}>
<div style={{ fontSize: 20, marginBottom: 4 }}>{dragging ? '📂' : '📎'}</div>
<div style={{ fontSize: 13, color: 'var(--text-primary)' }}>
{dragging
-520
View File
@@ -1,520 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import LoadingButton from './LoadingButton';
import SortTh from './SortTh';
import { supabase } from '../lib/supabase';
import { popupMenuStyle } from '../lib/popupStyles';
const TABLE_TH = { fontSize: 10, fontWeight: 500, color: 'var(--text-muted)', letterSpacing: 0.6, textTransform: 'uppercase', padding: '0 0 12px', border: 'none', background: 'transparent', verticalAlign: 'top' };
const TABLE_TD = { padding: '5px', fontSize: 13, color: 'var(--text-primary)', border: 'none', background: 'transparent' };
const LABEL = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase' };
const ITEM_STYLE = { display: 'flex', alignItems: 'center', gap: 8, padding: '7px 14px', fontSize: 13, cursor: 'pointer', color: 'var(--text-primary)', background: 'none', border: 'none', width: '100%', textAlign: 'left', borderRadius: 4, whiteSpace: 'nowrap' };
const SEP = { height: 1, background: 'var(--border)', margin: '4px 0' };
function formatBytes(bytes) {
const value = Number(bytes || 0);
if (!value) return '—';
const units = ['B', 'KB', 'MB', 'GB'];
const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1);
return `${(value / (1024 ** index)).toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
}
function formatDate(dt) {
if (!dt) return '—';
const d = new Date(dt);
return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + ' ' + d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
}
function fileIconStyle(ext) {
const e = ext.toLowerCase();
if (['jpg','jpeg','png','gif','webp','svg','ico','bmp','tiff','avif','heic'].includes(e)) return { bg: '#16a34a', color: '#fff' };
if (['mp4','mov','avi','mkv','webm','m4v','wmv','flv'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
if (['mp3','wav','ogg','flac','aac','m4a'].includes(e)) return { bg: '#db2777', color: '#fff' };
if (e === 'pdf') return { bg: '#dc2626', color: '#fff' };
if (['doc','docx','rtf'].includes(e)) return { bg: '#2563eb', color: '#fff' };
if (['txt','md'].includes(e)) return { bg: '#64748b', color: '#fff' };
if (['xls','xlsx','csv'].includes(e)) return { bg: '#16a34a', color: '#fff' };
if (['ppt','pptx'].includes(e)) return { bg: '#ea580c', color: '#fff' };
if (['zip','rar','7z','tar','gz'].includes(e)) return { bg: '#92400e', color: '#fff' };
if (['ai','eps'].includes(e)) return { bg: '#ff6c00', color: '#fff' };
if (['psd','psb'].includes(e)) return { bg: '#001e36', color: '#31a8ff' };
if (['indd','idml'].includes(e)) return { bg: '#49021f', color: '#ff3366' };
if (['fig','sketch'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
return { bg: '#475569', color: '#fff' };
}
function FileIcon({ entry }) {
if (entry.type === 'dir') {
return (
<div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
</svg>
</div>
);
}
const ext = (entry.name.includes('.') ? entry.name.split('.').pop() : '').toUpperCase().slice(0, 4) || 'FILE';
const { bg, color } = fileIconStyle(ext);
return (
<div style={{ width: 24, height: 24, borderRadius: 4, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
<span style={{ color, fontSize: 7, fontWeight: 600, letterSpacing: 0.3, fontFamily: 'monospace' }}>{ext}</span>
</div>
);
}
function pathParts(path) { return String(path || '/').split('/').filter(Boolean); }
function pathTo(index, parts) { return `/${parts.slice(0, index + 1).join('/')}`; }
function joinVirtualPath(...parts) { return ('/' + parts.join('/')).replace(/\/+/g, '/').replace(/\/$/, '') || '/'; }
export default function FileBrowser({ initialPath = '/', rootPath = '/' }) {
const [currentPath, setCurrentPath] = useState(initialPath);
const [entries, setEntries] = useState([]);
const [parentPath, setParentPath] = useState('/');
const [canGoUp, setCanGoUp] = useState(false);
const [loading, setLoading] = useState(true);
const [working, setWorking] = useState('');
const [dragging, setDragging] = useState(false);
const [error, setError] = useState('');
const [readOnly, setReadOnly] = useState(false);
const [folderName, setFolderName] = useState('');
const [showFolderInput, setShowFolderInput] = useState(false);
const [renamingEntry, setRenamingEntry] = useState(null);
const [renameValue, setRenameValue] = useState('');
const [uploadProgress, setUploadProgress] = useState(null);
const [selected, setSelected] = useState(new Set());
const [sortKey, setSortKey] = useState('name');
const [sortDir, setSortDir] = useState('asc');
const [ctxMenu, setCtxMenu] = useState(null);
const [clipboard, setClipboard] = useState(null);
const fileInputRef = useRef(null);
const folderInputRef = useRef(null);
const breadcrumbs = useMemo(() => pathParts(currentPath), [currentPath]);
useEffect(() => {
if (!ctxMenu) return;
const close = () => setCtxMenu(null);
window.addEventListener('click', close);
return () => window.removeEventListener('click', close);
}, [ctxMenu]);
const apiFetch = async (url, options = {}) => {
const { data: { session } } = await supabase.auth.getSession();
if (!session?.access_token) throw new Error('Session expired. Please sign in again.');
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${session.access_token}`,
...(options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),
...(options.headers || {}),
},
});
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || 'File request failed.');
return data;
};
const loadFiles = async (path = currentPath) => {
setLoading(true); setError(''); setSelected(new Set());
try {
const params = new URLSearchParams({ action: 'list', path });
const data = await apiFetch(`/api/filebrowser?${params}`);
if (data.configured === false) { setError(data.error || 'File browser not configured.'); return; }
setEntries(data.entries || []);
setCurrentPath(data.path || path);
setParentPath(data.parentPath || '/');
setCanGoUp(data.canGoUp || false);
setReadOnly(data.readOnly || false);
} catch (err) { setError(err.message); }
finally { setLoading(false); }
};
useEffect(() => { loadFiles(initialPath); }, [initialPath]); // eslint-disable-line react-hooks/exhaustive-deps
const toggleSort = (col) => {
if (sortKey === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
else { setSortKey(col); setSortDir(col === 'modified' ? 'desc' : 'asc'); }
};
const sortedEntries = useMemo(() => {
return [...entries].sort((a, b) => {
const aDir = a.type === 'dir'; const bDir = b.type === 'dir';
if (aDir !== bDir) return aDir ? -1 : 1;
let av, bv;
if (sortKey === 'name') { av = (a.name || '').toLowerCase(); bv = (b.name || '').toLowerCase(); }
else if (sortKey === 'size') { av = Number(a.size || 0); bv = Number(b.size || 0); }
else if (sortKey === 'modified') { av = new Date(a.mtime || 0).getTime(); bv = new Date(b.mtime || 0).getTime(); }
else { av = ''; bv = ''; }
const r = typeof av === 'string' ? av.localeCompare(bv) : (av > bv ? 1 : av < bv ? -1 : 0);
return sortDir === 'asc' ? r : -r;
});
}, [entries, sortKey, sortDir]);
const downloadFile = async (entry) => {
setWorking(`dl:${entry.path}`);
try {
const data = await apiFetch(`/api/filebrowser?action=download&path=${encodeURIComponent(entry.path)}`);
if (data.url && data.token) {
const sep = data.url.includes('?') ? '&' : '?';
const a = document.createElement('a');
a.href = `${data.url}${sep}auth=${encodeURIComponent(data.token)}`;
a.download = entry.name; a.target = '_blank'; a.rel = 'noopener noreferrer';
document.body.appendChild(a); a.click(); document.body.removeChild(a);
}
} catch (err) { setError(err.message); }
finally { setWorking(''); }
};
const downloadSelected = async () => {
if (!selected.size) return;
setWorking('dl-sel');
try {
for (const name of selected) {
const entry = entries.find(e => e.name === name);
if (entry && entry.type !== 'dir') await downloadFile(entry);
}
} finally { setWorking(''); }
};
const deleteEntry = async (entry) => {
if (!window.confirm(`Delete "${entry.name}"? This cannot be undone.`)) return;
setWorking(`del:${entry.path}`);
try {
await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' });
await loadFiles(currentPath);
} catch (err) { setError(err.message); }
finally { setWorking(''); }
};
const deleteSelected = async () => {
if (!selected.size || !window.confirm(`Delete ${selected.size} item(s)?`)) return;
for (const name of selected) {
const entry = entries.find(e => e.name === name);
if (!entry) continue;
await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' }).catch(() => {});
}
setSelected(new Set());
await loadFiles(currentPath);
};
const createFolder = async (e) => {
e.preventDefault();
if (!folderName.trim()) return;
setWorking('mkdir');
try {
await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: folderName }) });
setFolderName(''); setShowFolderInput(false);
await loadFiles(currentPath);
} catch (err) { setError(err.message); }
finally { setWorking(''); }
};
const renameEntry = async (e) => {
e.preventDefault();
const newName = renameValue.trim();
if (!newName || newName === renamingEntry.name) { setRenamingEntry(null); return; }
setWorking(`ren:${renamingEntry.path}`);
try {
await apiFetch('/api/filebrowser?action=rename', { method: 'POST', body: JSON.stringify({ path: renamingEntry.path, name: newName }) });
setRenamingEntry(null);
await loadFiles(currentPath);
} catch (err) { setError(err.message); }
finally { setWorking(''); }
};
const pasteClipboard = async () => {
if (!clipboard) return;
setWorking('paste');
try {
for (const item of clipboard.items) {
await apiFetch('/api/filebrowser?action=' + (clipboard.mode === 'copy' ? 'copy' : 'move'), {
method: 'POST',
body: JSON.stringify({ srcPath: item.path, dstParentPath: currentPath }),
});
}
if (clipboard.mode === 'move') setClipboard(null);
await loadFiles(currentPath);
} catch (err) { setError(err.message); }
finally { setWorking(''); }
};
async function uploadOneFile(vPath, file, retries = 3) {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
await apiFetch(`/api/filebrowser?action=upload&path=${encodeURIComponent(vPath)}`, {
method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file,
});
return;
} catch (err) {
if (attempt === retries) throw err;
await new Promise(r => setTimeout(r, attempt * 1000));
}
}
}
const uploadFiles = async (files) => {
const sel = Array.from(files || []);
if (!sel.length) return;
setWorking('upload'); setUploadProgress(0); setError('');
try {
for (let i = 0; i < sel.length; i++) {
await uploadOneFile(joinVirtualPath(currentPath, sel[i].name), sel[i]);
setUploadProgress(Math.round(((i + 1) / sel.length) * 100));
}
} catch (err) { setError(err.message); }
finally { setWorking(''); setUploadProgress(null); if (fileInputRef.current) fileInputRef.current.value = ''; setDragging(false); await loadFiles(currentPath); }
};
const uploadFolder = async (files) => {
const sel = Array.from(files || []).filter(f => f.webkitRelativePath);
if (!sel.length) return;
setWorking('upload'); setUploadProgress(0); setError('');
try {
const dirsNeeded = new Set();
for (const file of sel) {
const parts = file.webkitRelativePath.split('/').slice(0, -1);
for (let i = 1; i <= parts.length; i++) dirsNeeded.add(parts.slice(0, i).join('/'));
}
for (const dir of [...dirsNeeded].sort((a, b) => a.split('/').length - b.split('/').length)) {
await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: dir.split('/').pop() }) }).catch(() => {});
}
for (let i = 0; i < sel.length; i++) {
await uploadOneFile(joinVirtualPath(currentPath, sel[i].webkitRelativePath), sel[i]);
setUploadProgress(Math.round(((i + 1) / sel.length) * 100));
}
} catch (err) { setError(err.message); }
finally { setWorking(''); setUploadProgress(null); if (folderInputRef.current) folderInputRef.current.value = ''; await loadFiles(currentPath); }
};
const handleDragEnter = (e) => { e.preventDefault(); if (!readOnly) setDragging(true); };
const handleDragOver = (e) => { e.preventDefault(); if (!readOnly) { e.dataTransfer.dropEffect = 'copy'; setDragging(true); } };
const handleDragLeave = (e) => { e.preventDefault(); if (!e.currentTarget.contains(e.relatedTarget)) setDragging(false); };
const handleDrop = async (e) => {
e.preventDefault(); setDragging(false);
if (readOnly) return;
const items = Array.from(e.dataTransfer.items || []);
const fsEntries = items.map(i => i.webkitGetAsEntry?.()).filter(Boolean);
if (fsEntries.some(en => en.isDirectory)) {
const readFsEntry = (entry) => new Promise(resolve => {
if (entry.isFile) { entry.file(file => { Object.defineProperty(file, 'webkitRelativePath', { value: entry.fullPath.replace(/^\//, ''), writable: false, configurable: true }); resolve([file]); }); }
else if (entry.isDirectory) { const reader = entry.createReader(); const readAll = acc => reader.readEntries(async entries => { if (!entries.length) { resolve(acc); return; } const nested = await Promise.all(entries.map(readFsEntry)); readAll([...acc, ...nested.flat()]); }); readAll([]); }
else { resolve([]); }
});
uploadFolder((await Promise.all(fsEntries.map(readFsEntry))).flat());
} else {
if (!e.dataTransfer.files?.length) return;
uploadFiles(e.dataTransfer.files);
}
};
const toggleSelect = (name) => setSelected(prev => { const next = new Set(prev); next.has(name) ? next.delete(name) : next.add(name); return next; });
const openCtxMenu = (e, entry, childPath) => {
e.preventDefault(); e.stopPropagation();
setCtxMenu({ x: e.clientX, y: e.clientY, entry, childPath });
};
return (
<div
style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, borderRadius: 8, border: `1px solid ${dragging ? 'var(--accent)' : 'var(--border)'}`, transition: 'border-color 140ms ease', position: 'relative', overflow: 'hidden' }}
onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragLeave={handleDragLeave} onDrop={handleDrop}
>
{dragging && (
<div style={{ position: 'absolute', inset: 0, zIndex: 10, background: 'rgba(245,165,35,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: 28, marginBottom: 8 }}></div>
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--accent)' }}>Drop files to upload</div>
</div>
</div>
)}
{/* Toolbar */}
<div style={{ padding: '18px 21px', borderBottom: '1px solid var(--border)', flexShrink: 0, position: 'relative' }}>
{/* Selection actions — absolute top-right like FileSharing */}
{selected.size > 0 && (
<div style={{ position: 'absolute', top: 18, right: 21, display: 'flex', gap: 8 }}>
<button className="btn btn-outline" disabled={Boolean(working)} onClick={downloadSelected}>Download ({selected.size})</button>
{!readOnly && <button className="btn btn-danger" disabled={Boolean(working)} onClick={deleteSelected}>Delete ({selected.size})</button>}
</div>
)}
<div style={{ paddingRight: selected.size > 0 ? 260 : 0 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: 2 }}>
<div style={LABEL}>Files</div>
{uploadProgress !== null && <span style={{ fontSize: 12, color: 'var(--text-muted)', marginLeft: 12 }}>Uploading {uploadProgress}%</span>}
{!readOnly && (
<>
<input ref={folderInputRef} type="file" style={{ display: 'none' }} onChange={e => uploadFolder(e.target.files)} {...{ webkitdirectory: '' }} />
<input ref={fileInputRef} type="file" multiple style={{ display: 'none' }} onChange={e => uploadFiles(e.target.files)} />
</>
)}
</div>
<div style={{ fontSize: 12, color: dragging ? 'var(--accent)' : 'var(--text-muted)', marginTop: 2, marginBottom: 14, transition: 'color 140ms ease' }}>
Drag and drop files or folders here.
</div>
{/* Breadcrumbs */}
<div style={{ fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
<button type="button" onClick={() => loadFiles(rootPath)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>Files</button>
{breadcrumbs.slice(pathParts(rootPath).length).map((part, i) => {
const absIdx = pathParts(rootPath).length + i;
return (
<span key={`${part}-${absIdx}`} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{ opacity: 0.4 }}>/</span>
<button type="button" onClick={() => loadFiles(pathTo(absIdx, breadcrumbs))} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: absIdx === breadcrumbs.length - 1 ? 'var(--accent)' : 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>{part}</button>
</span>
);
})}
</div>
</div>
</div>
{uploadProgress !== null && (
<div style={{ height: 2, background: 'var(--border)', flexShrink: 0 }}>
<div style={{ height: '100%', background: 'var(--accent)', width: `${uploadProgress}%`, transition: 'width 200ms' }} />
</div>
)}
{/* File table */}
<div className="scrollbar-thin-theme table-scroll-hidden" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '18px 21px' }}>
{error && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}>{error}</div>}
{loading ? (
<div className="card-empty-center">Loading</div>
) : entries.length === 0 ? (
<div className="card-empty-center">This folder is empty.</div>
) : (
<table className="table-sticky-head" style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse' }}>
<colgroup>
<col style={{ width: 32 }} />
<col />
<col style={{ width: 90 }} />
<col style={{ width: 180 }} />
</colgroup>
<thead>
<tr>
<th style={{ ...TABLE_TH, textAlign: 'center', padding: '0 5px 12px' }}>
<input type="checkbox" checked={selected.size === entries.length && entries.length > 0} onChange={e => setSelected(e.target.checked ? new Set(entries.map(en => en.name)) : new Set())} />
</th>
<SortTh col="name" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'left', paddingLeft: 5 }}>Name</SortTh>
<SortTh col="size" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Size</SortTh>
<SortTh col="modified" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Modified</SortTh>
</tr>
</thead>
<tbody>
{sortedEntries.map((entry, idx) => {
const isDir = entry.type === 'dir';
const childPath = entry.path;
const isRenaming = renamingEntry?.path === entry.path;
const rowBg = idx % 2 === 0 ? 'var(--file-row-alt-bg, rgba(255,255,255,0.02))' : 'transparent';
return (
<tr
key={`${entry.type}:${entry.path}`}
style={{ cursor: isDir ? 'pointer' : 'default' }}
onClick={() => isDir && loadFiles(childPath)}
onContextMenu={e => openCtxMenu(e, entry, childPath)}
>
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'center' }} onClick={e => { e.stopPropagation(); toggleSelect(entry.name); }}>
<input type="checkbox" checked={selected.has(entry.name)} onChange={() => toggleSelect(entry.name)} onClick={e => e.stopPropagation()} />
</td>
<td style={{ ...TABLE_TD, background: rowBg }}>
{isRenaming ? (
<form style={{ display: 'flex', gap: 6 }} onSubmit={renameEntry} onClick={e => e.stopPropagation()}>
<input autoFocus type="text" value={renameValue} onChange={e => setRenameValue(e.target.value)} disabled={Boolean(working)} onKeyDown={e => { if (e.key === 'Escape') setRenamingEntry(null); }} style={{ fontSize: 13, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--card-bg-2)', color: 'var(--text-primary)', flex: 1, minWidth: 0 }} />
<LoadingButton type="submit" className="btn btn-outline" loading={working === `ren:${entry.path}`} disabled={!renameValue.trim()} loadingText="…">Save</LoadingButton>
<button type="button" className="btn btn-outline" onClick={() => setRenamingEntry(null)}>Cancel</button>
</form>
) : (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<FileIcon entry={entry} />
{isDir ? (
<button type="button" className="dashboard-inline-link" onClick={e => { e.stopPropagation(); loadFiles(childPath); }} style={{ fontSize: 13, fontWeight: 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'left' }}>{entry.name}</button>
) : (
<span style={{ fontSize: 13, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{entry.name}</span>
)}
</div>
)}
</td>
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12 }}>{isDir ? '—' : formatBytes(entry.size)}</td>
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12 }}>{formatDate(entry.mtime)}</td>
</tr>
);
})}
</tbody>
</table>
)}
</div>
{/* Context menu — portal to escape stacking context */}
{ctxMenu && createPortal(
<div onClick={e => e.stopPropagation()} style={{ ...popupMenuStyle, position: 'fixed', left: ctxMenu.x, top: ctxMenu.y, zIndex: 9999, padding: '4px 0', minWidth: 160 }}>
{ctxMenu.entry?.type === 'dir' && (
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { loadFiles(ctxMenu.childPath); setCtxMenu(null); }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" /></svg>
Open
</button>
)}
{ctxMenu.entry?.type !== 'dir' && (
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { downloadFile(ctxMenu.entry); setCtxMenu(null); }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7,10 12,15 17,10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
Download
</button>
)}
{ctxMenu.entry && !readOnly && (
<>
<div style={SEP} />
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { setRenamingEntry(ctxMenu.entry); setRenameValue(ctxMenu.entry.name); setCtxMenu(null); }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
Rename
</button>
</>
)}
{ctxMenu.entry && (
<>
<div style={SEP} />
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'}
onClick={() => {
const items = selected.has(ctxMenu.entry.name)
? [...selected].map(n => { const en = entries.find(e => e.name === n); return { name: n, path: en?.path ?? joinVirtualPath(currentPath, n) }; })
: [{ name: ctxMenu.entry.name, path: ctxMenu.childPath }];
setClipboard({ items, mode: 'copy' }); setCtxMenu(null);
}}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
Copy
</button>
{!readOnly && (
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'}
onClick={() => {
const items = selected.has(ctxMenu.entry.name)
? [...selected].map(n => { const en = entries.find(e => e.name === n); return { name: n, path: en?.path ?? joinVirtualPath(currentPath, n) }; })
: [{ name: ctxMenu.entry.name, path: ctxMenu.childPath }];
setClipboard({ items, mode: 'move' }); setCtxMenu(null);
}}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><line x1="20" y1="4" x2="8.12" y2="15.88"/><line x1="14.47" y1="14.48" x2="20" y2="20"/><line x1="8.12" y1="8.12" x2="12" y2="12"/></svg>
Cut
</button>
)}
</>
)}
{clipboard && (
<>
<div style={SEP} />
<button style={ITEM_STYLE} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { pasteClipboard(); setCtxMenu(null); }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2"/><rect x="8" y="2" width="8" height="4" rx="1"/></svg>
Paste here{clipboard.items.length > 1 ? ` (${clipboard.items.length})` : ''}
</button>
</>
)}
{!readOnly && ctxMenu.entry && (
<>
<div style={SEP} />
<button style={{ ...ITEM_STYLE, color: 'var(--danger)' }} onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,80,80,0.08)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { setCtxMenu(null); deleteEntry(ctxMenu.entry); }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="3,6 5,6 21,6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>
Delete
</button>
</>
)}
</div>,
document.body
)}
</div>
);
}
+15 -6
View File
@@ -15,17 +15,26 @@ export default function FilterDropdown({ value, onChange, options }) {
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [open]);
const current = options.find(o => o.value === value);
return (
<div ref={ref} style={{ position: 'relative' }}>
<button className="btn btn-outline btn-sm" onClick={() => setOpen(o => !o)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div ref={ref} style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
<button
className="btn btn-outline"
onClick={() => setOpen(o => !o)}
style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}
aria-label="Filter"
title="Filter"
>
<FilterIcon />
{current?.label}
</button>
{open && (
<div style={{ position: 'absolute', top: 'calc(100% + 4px)', right: 0, background: 'var(--card-bg)', border: '1px solid var(--border)', borderRadius: 4, zIndex: 200, minWidth: 160, boxShadow: '0 4px 12px rgba(0,0,0,0.25)' }}>
<div className="site-header-avatar-menu" style={{ top: 'calc(100% + 4px)', minWidth: 160 }}>
{options.map(opt => (
<button key={opt.value} onClick={() => { onChange(opt.value); setOpen(false); }} style={{ display: 'block', width: '100%', padding: '7px 14px', textAlign: 'left', background: value === opt.value ? 'rgba(245,165,35,0.08)' : 'transparent', fontSize: 13, color: value === opt.value ? 'var(--accent)' : 'var(--text-primary)', border: 'none', cursor: 'pointer' }}>
<button
key={opt.value}
className="site-header-avatar-item"
onClick={() => { onChange(opt.value); setOpen(false); }}
style={value === opt.value ? { color: 'var(--accent)' } : undefined}
>
{opt.label}
</button>
))}
+55 -25
View File
@@ -1,5 +1,6 @@
import { useState, useEffect, useRef } from 'react';
import PageLoader from './PageLoader';
import ProfileAvatar from './ProfileAvatar';
import { NavLink, Link, useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
@@ -7,12 +8,12 @@ const ICONS = {
dashboard: <svg viewBox="0 0 16 16" fill="currentColor"><rect x="1" y="1" width="6" height="6" rx="1.5"/><rect x="9" y="1" width="6" height="6" rx="1.5"/><rect x="1" y="9" width="6" height="6" rx="1.5"/><rect x="9" y="9" width="6" height="6" rx="1.5"/></svg>,
requests: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><rect x="2" y="2" width="12" height="12" rx="1.5"/><line x1="5" y1="5.5" x2="11" y2="5.5"/><line x1="5" y1="8" x2="11" y2="8"/><line x1="5" y1="10.5" x2="8" y2="10.5"/></svg>,
projects: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M1.5 5.5C1.5 4.67 2.17 4 3 4h2.5l1.5 2H13c.83 0 1.5.67 1.5 1.5v5.5c0 .83-.67 1.5-1.5 1.5H3c-.83 0-1.5-.67-1.5-1.5V5.5z"/></svg>,
fileSharing: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M9 2H4a1.5 1.5 0 00-1.5 1.5v9A1.5 1.5 0 004 14h8a1.5 1.5 0 001.5-1.5V6L9 2z"/><polyline points="9,2 9,6 13.5,6"/></svg>,
invoices: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><rect x="2" y="1.5" width="12" height="13" rx="1"/><line x1="8" y1="4" x2="8" y2="12"/><path d="M10 5.5H7a1.5 1.5 0 000 3h2a1.5 1.5 0 010 3H5.5"/></svg>,
notes: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><rect x="3" y="1.5" width="10" height="13" rx="1"/><line x1="5.5" y1="5" x2="10.5" y2="5"/><line x1="5.5" y1="7.5" x2="10.5" y2="7.5"/><line x1="5.5" y1="10" x2="8.5" y2="10"/></svg>,
survey: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="1.5" y="9.5" width="3" height="5" rx="0.5"/><rect x="6.5" y="6" width="3" height="8.5" rx="0.5"/><rect x="11.5" y="2.5" width="3" height="12" rx="0.5"/></svg>,
brandBook: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 2.5h4a2 2 0 012 2v9a2 2 0 00-2-2h-4V2.5z"/><path d="M13.5 2.5h-4a2 2 0 00-2 2v9a2 2 0 012-2h4V2.5z"/></svg>,
converter: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="1.5" y="1.5" width="13" height="13" rx="1.5"/><circle cx="5.5" cy="5.5" r="1.5"/><path d="M1.5 11.5l3.5-3.5 3 3L11 7.5l3 3"/></svg>,
reports: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 13.5h11"/><path d="M4.5 11V7.5"/><path d="M8 11V4.5"/><path d="M11.5 11V6"/></svg>,
passwords: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="7" width="10" height="7.5" rx="1"/><path d="M5 7V5.5a3 3 0 016 0V7"/><circle cx="8" cy="10.5" r="1" fill="currentColor" stroke="none"/></svg>,
companies: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><rect x="1.5" y="5" width="13" height="9.5" rx="1"/><path d="M5.5 5V3a1 1 0 011-1h3a1 1 0 011 1v2"/><line x1="8" y1="5" x2="8" y2="14.5"/><line x1="1.5" y1="9" x2="14.5" y2="9"/></svg>,
users: <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><circle cx="6" cy="5" r="2.5"/><path d="M1 14c0-2.76 2.24-5 5-5s5 2.24 5 5"/><circle cx="12.5" cy="5.5" r="2"/><path d="M12.5 10c1.93 0 3.5 1.57 3.5 3.5"/></svg>,
@@ -28,14 +29,14 @@ function TeamNav({ onNav }) {
const primaryLinks = [
{ to: '/dashboard', label: 'Dashboard', icon: ICONS.dashboard },
{ to: '/tasks', label: 'Tasks', icon: ICONS.requests },
{ to: '/invoices', label: 'Finances', icon: ICONS.invoices },
{ to: '/file-sharing', label: 'File Sharing', icon: ICONS.fileSharing },
{ to: '/finances', label: 'Finances', icon: ICONS.invoices },
];
const utilityLinks = [
{ to: '/survey-maker', label: 'Survey Maker', icon: ICONS.survey },
{ to: '/brand-book', label: 'Brand Book Maker', icon: ICONS.brandBook },
{ to: '/converters', label: 'Image Converter', icon: ICONS.converter },
{ to: '/reports', label: 'Reports', icon: ICONS.reports },
{ to: '/fourge-passwords', label: 'Fourge Passwords', icon: ICONS.passwords },
];
@@ -73,8 +74,7 @@ function ClientNav({ onNav }) {
const links = [
{ to: '/dashboard', label: 'Dashboard', icon: ICONS.dashboard },
{ to: '/tasks', label: 'Tasks', icon: ICONS.requests },
{ to: '/file-sharing', label: 'File Sharing', icon: ICONS.fileSharing },
{ to: '/my-invoices', label: 'Invoices', icon: ICONS.invoices },
{ to: '/client-invoices', label: 'Invoices', icon: ICONS.invoices },
];
return (
@@ -94,8 +94,7 @@ function ExternalNav({ onNav }) {
const links = [
{ to: '/dashboard', label: 'Dashboard', icon: ICONS.dashboard },
{ to: '/tasks', label: 'Tasks', icon: ICONS.requests },
{ to: '/my-invoices-sub', label: 'Invoices', icon: ICONS.invoices },
{ to: '/file-sharing', label: 'File Sharing', icon: ICONS.fileSharing },
{ to: '/subs-invoices', label: 'Invoices', icon: ICONS.invoices },
{ to: '/survey-maker', label: 'Survey Maker', icon: ICONS.survey },
{ to: '/brand-book', label: 'Brand Book Maker', icon: ICONS.brandBook },
{ to: '/converters', label: 'Image Converter', icon: ICONS.converter },
@@ -127,7 +126,7 @@ function getInitialTheme() {
return 'dark';
}
export default function Layout({ children }) {
export default function Layout({ children, loading = false }) {
const { currentUser, logout } = useAuth();
const navigate = useNavigate();
const location = useLocation();
@@ -144,20 +143,54 @@ export default function Layout({ children }) {
const timeOfDay = hour < 12 ? 'morning' : hour < 17 ? 'afternoon' : 'evening';
const firstName = currentUser?.name?.split(' ')[0] || '';
const isProfileRoute = location.pathname === '/profile' || location.pathname.startsWith('/profile/');
const isFileSharingRoute = location.pathname === '/file-sharing';
const isTaskDetailRoute = location.pathname.startsWith('/tasks/') || location.pathname.startsWith('/projects/') || location.pathname.startsWith('/requests/');
const isInvoiceDetailRoute =
location.pathname.startsWith('/finances/') ||
location.pathname.startsWith('/invoices/') ||
location.pathname.startsWith('/client-invoices/') ||
location.pathname.startsWith('/subs-invoices/') ||
location.pathname.startsWith('/my-invoices-sub/') ||
location.pathname.startsWith('/sub-invoices/');
const isRequestsRoute = location.pathname === '/tasks' || location.pathname === '/requests' || location.pathname === '/team/tasks' || isTaskDetailRoute;
const isFinancesRoute = location.pathname === '/invoices' || location.pathname.startsWith('/invoices/') || location.pathname === '/sub-invoices' || location.pathname.startsWith('/sub-invoices/');
const headerTitle = isProfileRoute ? 'Profile' : isFileSharingRoute ? 'File Sharing' : isFinancesRoute ? 'Finances' : isRequestsRoute && !isTaskDetailRoute ? 'Tasks & Projects' : !isTaskDetailRoute ? `Good ${timeOfDay}${firstName ? `, ${firstName}` : ''}` : null;
const isFinancesRoute =
location.pathname === '/finances' ||
location.pathname.startsWith('/finances/') ||
location.pathname === '/invoices' ||
location.pathname.startsWith('/invoices/') ||
location.pathname === '/sub-invoices' ||
location.pathname.startsWith('/sub-invoices/') ||
location.pathname === '/client-invoices' ||
location.pathname.startsWith('/client-invoices/') ||
location.pathname === '/my-invoices' ||
location.pathname.startsWith('/my-invoices/') ||
location.pathname === '/subs-invoices' ||
location.pathname.startsWith('/subs-invoices/') ||
location.pathname === '/my-invoices-sub' ||
location.pathname.startsWith('/my-invoices-sub/');
const isReportsRoute = location.pathname === '/reports';
const financeHeaderTitle = currentUser?.role === 'team' ? 'Finances' : 'Invoices';
const headerTitle = isProfileRoute ? 'Profile' : isFinancesRoute ? financeHeaderTitle : isReportsRoute ? 'Reports' : isRequestsRoute && !isTaskDetailRoute ? 'Tasks & Projects' : !isTaskDetailRoute && !isInvoiceDetailRoute ? `Good ${timeOfDay}${firstName ? `, ${firstName}` : ''}` : null;
const headerSubtitle = isProfileRoute
? 'Account details and security settings.'
: isFileSharingRoute
? 'Browse, share and manage files.'
: isFinancesRoute
? 'Invoices, expenses and subcontractor POs.'
: isRequestsRoute && !isTaskDetailRoute
: isFinancesRoute
? currentUser?.role === 'external'
? 'Track completed work, invoice history and payment status.'
: currentUser?.role === 'client'
? 'View invoices, payment status and receipt history.'
: 'Invoices, expenses and subcontractor POs.'
: isReportsRoute
? 'Track task versions, billing state and exportable summaries.'
: isRequestsRoute && !isTaskDetailRoute
? 'Browse and manage all tasks and projects.'
: isTaskDetailRoute ? null : "Here's what's happening today.";
: isTaskDetailRoute || isInvoiceDetailRoute ? null : "Here's what's happening today.";
const detailBackTarget = isTaskDetailRoute
? '/tasks'
: currentUser?.role === 'team'
? '/finances'
: currentUser?.role === 'client'
? '/client-invoices'
: '/subs-invoices';
const detailBackLabel = isTaskDetailRoute ? 'Tasks & Projects' : financeHeaderTitle;
useEffect(() => {
document.documentElement.setAttribute('data-theme', theme);
@@ -217,7 +250,7 @@ export default function Layout({ children }) {
return (
<div className="app-layout">
{navigating && <PageLoader />}
{(navigating || loading) && <PageLoader />}
{menuOpen && <div className="sidebar-overlay" onClick={() => setMenuOpen(false)} />}
<aside className={`sidebar${menuOpen ? ' sidebar-open' : ''}`}>
@@ -245,11 +278,11 @@ export default function Layout({ children }) {
<main className="main-content">
<div className="site-header">
<div>
{isTaskDetailRoute ? (
{isTaskDetailRoute || isInvoiceDetailRoute ? (
<div>
<Link to="/tasks" className="dashboard-inline-link" style={{ display: 'inline-flex', alignItems: 'center', gap: 1, color: 'var(--text-muted)', textDecoration: 'none' }}>
<Link to={detailBackTarget} className="dashboard-inline-link" style={{ display: 'inline-flex', alignItems: 'center', gap: 1, color: 'var(--text-muted)', textDecoration: 'none' }}>
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ width: 24, height: 24, flexShrink: 0 }}><polyline points="10 4 6 8 10 12"/></svg>
<span style={{ fontSize: 24, fontWeight: 500, lineHeight: 1.2, letterSpacing: '-0.3px', position: 'relative', top: 2 }}>Tasks &amp; Projects</span>
<span style={{ fontSize: 24, fontWeight: 500, lineHeight: 1.2, letterSpacing: '-0.3px', position: 'relative', top: 2 }}>{detailBackLabel}</span>
</Link>
<div className="site-header-sub" style={{ paddingLeft: 25 }}>Return back to previous page</div>
</div>
@@ -336,10 +369,7 @@ export default function Layout({ children }) {
<div className="site-header-avatar-wrap" ref={avatarRef}>
<button className="site-header-avatar-btn" onClick={() => setAvatarOpen(o => !o)} aria-label="Account menu" style={{ overflow: 'hidden' }}>
{currentUser?.avatar_url
? <img src={currentUser.avatar_url} alt={currentUser.name} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '50%' }} />
: <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4.4 3.6-7 8-7s8 2.6 8 7" fill="currentColor"/></svg>
}
<ProfileAvatar profile={currentUser} name={currentUser?.name} size={68} fontSize={20} />
</button>
{avatarOpen && (
<div className="site-header-avatar-menu">
+1 -1
View File
@@ -30,7 +30,7 @@ export default function PageLoader({ label = 'Loading', progress = null, scope =
<>
<div style={{ height: 4, borderRadius: 2, background: 'var(--card-bg-2)', overflow: 'hidden', marginBottom: hasProgress ? 8 : 0 }}>
<div
className={hasProgress ? undefined : 'file-browser-progress-bar indeterminate'}
className={hasProgress ? undefined : 'shared-progress-bar indeterminate'}
style={{ height: '100%', borderRadius: 2, background: 'var(--accent)', width: hasProgress ? `${progress}%` : undefined, transition: 'width 0.2s ease' }}
/>
</div>
+68
View File
@@ -0,0 +1,68 @@
function normalizeName(value) {
return String(value || '').trim().toLowerCase();
}
export function resolveProfileAvatar({
avatarUrl = '',
profile = null,
profileId = '',
name = '',
profilesById = null,
profilesByName = null,
}) {
if (avatarUrl) return avatarUrl;
if (profile?.avatar_url) return profile.avatar_url;
if (profileId && profilesById?.get(profileId)?.avatar_url) return profilesById.get(profileId).avatar_url;
const normalized = normalizeName(name || profile?.name);
if (normalized && profilesByName?.get(normalized)?.avatar_url) return profilesByName.get(normalized).avatar_url;
return '';
}
export default function ProfileAvatar({
profile = null,
profileId = '',
name = '',
avatarUrl = '',
profilesById = null,
profilesByName = null,
size = 32,
fontSize = 12,
fallbackBg = 'var(--accent)',
fallbackColor = '#000',
alt = '',
style = {},
}) {
const resolvedUrl = resolveProfileAvatar({ avatarUrl, profile, profileId, name, profilesById, profilesByName });
const initials = String(name || profile?.name || '?')
.split(' ')
.map((part) => part[0])
.slice(0, 2)
.join('')
.toUpperCase();
if (resolvedUrl) {
return (
<div style={{ width: size, height: size, borderRadius: '50%', overflow: 'hidden', flexShrink: 0, ...style }}>
<img src={resolvedUrl} alt={alt || name || profile?.name || ''} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
</div>
);
}
return (
<div
style={{
width: size,
height: size,
borderRadius: '50%',
background: fallbackBg,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
...style,
}}
>
<span style={{ fontSize, fontWeight: 600, color: fallbackColor, lineHeight: 1 }}>{initials || '?'}</span>
</div>
);
}
+86 -17
View File
@@ -8,6 +8,7 @@ const defaultDeadline = () => addDaysToDateOnly(getTodayDateOnlyEST(), 3);
const modalLabelStyle = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 6 };
const modalInputStyle = { fontSize: 13, padding: '0 5px', textAlign: 'left', lineHeight: 1 };
const modalTextAreaStyle = { ...modalInputStyle, minHeight: 100, padding: '8px 5px', lineHeight: 1.4 };
const modalActionButtonStyle = { width: 132, justifyContent: 'center', flex: '0 0 132px' };
const emptyForm = (companyId = '') => ({
companyId,
project: '',
@@ -43,7 +44,11 @@ export default function RequestForm({
initialValues = null,
lockedFields = [],
}) {
const [form, setForm] = useState(() => ({ ...emptyForm(initialCompanyId), ...(initialValues || {}) }));
const [form, setForm] = useState(() => ({
...emptyForm(initialCompanyId),
requestedBy: showRequester ? (currentUser?.id || '') : '',
...(initialValues || {}),
}));
const prevCompanyIdRef = useRef(initialValues?.companyId || initialCompanyId || null);
const [files, setFiles] = useState([]);
const [existingProjects, setExistingProjects] = useState([]);
@@ -54,16 +59,17 @@ export default function RequestForm({
const [signFamilies, setSignFamilies] = useState([]);
const [signCount, setSignCount] = useState('');
const [signs, setSigns] = useState([]);
const [localError, setLocalError] = useState('');
const isBrandBook = form.serviceType === 'Brand Book';
const usesSignFields = form.serviceType === 'Brand Book';
useEffect(() => {
supabase.from('sign_families').select('name').order('sort_order').then(({ data }) => setSignFamilies((data || []).map(r => r.name)));
}, []);
useEffect(() => {
if (!isBrandBook) { setSignCount(''); setSigns([]); }
}, [isBrandBook]);
if (!usesSignFields) { setSignCount(''); setSigns([]); }
}, [usesSignFields]);
useEffect(() => {
const n = Math.max(0, parseInt(signCount) || 0);
@@ -113,9 +119,15 @@ export default function RequestForm({
prevCompanyIdRef.current = companyId;
}, [companyId]); // eslint-disable-line react-hooks/exhaustive-deps
const set = (field) => (e) => setForm(f => ({ ...f, [field]: e.target.value }));
const set = (field) => (e) => {
if (localError) setLocalError('');
setForm(f => ({ ...f, [field]: e.target.value }));
};
const setSign = (id, field, value) => setSigns(prev => prev.map(s => s.id === id ? { ...s, [field]: value } : s));
const setSign = (id, field, value) => {
if (localError) setLocalError('');
setSigns(prev => prev.map(s => s.id === id ? { ...s, [field]: value } : s));
};
const allProjectNames = [
...existingProjects.map(p => p.name),
@@ -143,18 +155,56 @@ export default function RequestForm({
};
const showCompanySelect = companies.length > 1 || showRequester;
const requesterOptions = [
...(currentUser ? [{ id: currentUser.id, name: `${currentUser.name} (You)` }] : []),
...companyUsers.filter(u => u.id !== currentUser?.id),
];
const handleSubmit = (e) => {
e.preventDefault();
const requestedByName = currentUser?.name || '';
setLocalError('');
const selectedRequester = showRequester
? requesterOptions.find(option => option.id === form.requestedBy) || null
: null;
const requestedBy = showRequester
? (selectedRequester?.id || '')
: (currentUser?.id || '');
const requestedByName = showRequester
? ((selectedRequester?.name || '').replace(/\s+\(You\)$/, '') || '')
: (currentUser?.name || '');
let normalizedSignCount = null;
let normalizedSigns = [];
if (usesSignFields) {
normalizedSignCount = parseInt(signCount, 10) || null;
const formData = new FormData(e.currentTarget);
normalizedSigns = Array.from({ length: normalizedSignCount || 0 }, (_, index) => {
const stateSign = signs[index] || {};
const domValue = formData.get(`sign_info_${index + 1}`);
const signName = typeof domValue === 'string'
? domValue.trim()
: String(stateSign.signName || '').trim();
return {
id: stateSign.id || `sign-${index + 1}`,
signName,
signFamily: stateSign.signFamily || '',
};
}).filter(sign => sign.signName || sign.signFamily);
if ((normalizedSignCount || 0) > 0 && normalizedSigns.length !== normalizedSignCount) {
setLocalError('Please fill in the sign information for each sign before submitting.');
return;
}
}
onSubmit(
{
...form,
companyId,
requestedBy: currentUser?.id || '',
requestedBy,
requestedByName,
signCount: isBrandBook ? (parseInt(signCount) || null) : null,
signs: isBrandBook ? signs : [],
signCount: usesSignFields ? normalizedSignCount : null,
signs: usesSignFields ? normalizedSigns : [],
},
files,
existingProjects
@@ -214,6 +264,24 @@ export default function RequestForm({
</div>
</div>
{showRequester && (
<div className="form-group">
<label style={modalLabelStyle}>Requested By *</label>
<select
value={form.requestedBy}
onChange={set('requestedBy')}
required
disabled={!companyId}
style={modalInputStyle}
>
<option value="">{companyId ? 'Select requester...' : 'Select company first'}</option>
{requesterOptions.map(user => (
<option key={user.id} value={user.id}>{user.name}</option>
))}
</select>
</div>
)}
{/* Row 3: Title/Location + Mark as Hot inline */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'end', marginBottom: 16 }}>
<div className="form-group" style={{ marginBottom: 0 }}>
@@ -226,7 +294,7 @@ export default function RequestForm({
</label>
</div>
{isBrandBook && (
{usesSignFields && (
<div className="form-group">
<label style={modalLabelStyle}>Sign Count *</label>
<input
@@ -242,7 +310,7 @@ export default function RequestForm({
</div>
)}
{isBrandBook && signs.length > 0 && (
{usesSignFields && signs.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
{signs.map((sign, i) => (
<div key={sign.id} style={{ border: '1px solid var(--border)', borderRadius: 6, padding: '10px 12px' }}>
@@ -251,6 +319,7 @@ export default function RequestForm({
<label style={modalLabelStyle}>Sign Information *</label>
<input
type="text"
name={`sign_info_${i + 1}`}
placeholder="e.g. Main Entry, Drive Thru"
value={sign.signName}
onChange={e => setSign(sign.id, 'signName', e.target.value)}
@@ -264,19 +333,19 @@ export default function RequestForm({
)}
<div className="form-group">
<label style={modalLabelStyle}>{isBrandBook ? 'Notes' : 'Description'} *</label>
<label style={modalLabelStyle}>{usesSignFields ? 'Notes' : 'Description'} *</label>
<textarea placeholder="Notes on the request..." value={form.description} onChange={set('description')} style={modalTextAreaStyle} required />
</div>
<FileAttachment files={files} onChange={setFiles} />
{error && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}> {error}</div>}
{(localError || error) && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}> {localError || error}</div>}
<div className="action-buttons" style={{ justifyContent: 'flex-end' }}>
<button type="submit" className="btn btn-outline" disabled={saving}>
<div className="action-buttons modal-action-row" style={{ justifyContent: 'flex-end' }}>
<button type="submit" className="btn btn-outline" disabled={saving} style={modalActionButtonStyle}>
{saving ? 'Submitting...' : submitLabel}
</button>
{onCancel && <button type="button" className="btn btn-outline" onClick={onCancel}>Cancel</button>}
{onCancel && <button type="button" className="btn btn-outline" onClick={onCancel} style={modalActionButtonStyle}>Cancel</button>}
</div>
</form>
);
@@ -0,0 +1,112 @@
import SortTh from './SortTh';
function fmt(val) {
return `$${Number(val || 0).toFixed(2)}`;
}
function inferItemType(item) {
const match = String(item?.description || '').match(/\bR(\d{2})\b/i);
if (match) {
return Number(match[1]) <= 0
? { label: 'New', badgeClass: 'badge-initial' }
: { label: 'Revision', badgeClass: 'badge-client_revision' };
}
if (item?.task_id) return { label: 'Task', badgeClass: 'badge-in_progress' };
return { label: 'Other', badgeClass: 'badge-initial' };
}
export default function SubcontractorInvoiceDetailView({
error,
headerActions,
leftCardTitle,
leftCardBody,
rightCardTitle,
rightCardBody,
sortKey,
sortDir,
onSort,
items,
notes,
total,
}) {
return (
<div className="invoice-detail-shell">
{error ? <div className="notification notification-info" style={{ marginBottom: 16, flexShrink: 0 }}>{error}</div> : null}
<div className="invoice-detail-stack">
<div className="invoice-detail-summary-grid">
<div className="card invoice-detail-card">
<div className="invoice-detail-section-title">{leftCardTitle}</div>
{leftCardBody}
</div>
<div className="card invoice-detail-card">
<div className="invoice-detail-card-header">
<div className="invoice-detail-section-title" style={{ marginBottom: 0 }}>{rightCardTitle}</div>
{headerActions ? <div className="invoice-detail-card-actions">{headerActions}</div> : null}
</div>
{rightCardBody}
</div>
</div>
<div className="card invoice-detail-card invoice-detail-line-items-card">
<div className="invoice-detail-section-title">Line Items</div>
{items.length === 0 ? (
<div className="card-empty-center" style={{ minHeight: 120 }}>No line items.</div>
) : (
<div className="scrollbar-thin-theme table-scroll-hidden" style={{ overflowY: 'auto' }}>
<table className="table-sticky-head invoice-detail-table" style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
<colgroup>
<col style={{ width: '12%' }} />
<col style={{ width: '46%' }} />
<col style={{ width: '14%' }} />
<col style={{ width: '14%' }} />
<col style={{ width: '14%' }} />
</colgroup>
<thead>
<tr>
<SortTh col="type" sortKey={sortKey} sortDir={sortDir} onSort={onSort}>Type</SortTh>
<SortTh col="description" sortKey={sortKey} sortDir={sortDir} onSort={onSort}>Description</SortTh>
<SortTh col="quantity" sortKey={sortKey} sortDir={sortDir} onSort={onSort} style={{ textAlign: 'center' }}>Qty</SortTh>
<SortTh col="unit_price" sortKey={sortKey} sortDir={sortDir} onSort={onSort} style={{ textAlign: 'right' }}>Unit Price</SortTh>
<SortTh col="line_total" sortKey={sortKey} sortDir={sortDir} onSort={onSort} style={{ textAlign: 'right' }}>Total</SortTh>
</tr>
</thead>
<tbody>
{items.map((item) => {
const itemType = inferItemType(item);
return (
<tr key={item.id}>
<td style={{ padding: '5px 0' }}>
<span className={`badge ${itemType.badgeClass}`}>{itemType.label}</span>
</td>
<td className="invoice-detail-cell">{item.description}</td>
<td className="invoice-detail-cell" style={{ textAlign: 'center' }}>{item.quantity}</td>
<td className="invoice-detail-cell" style={{ textAlign: 'right' }}>{fmt(item.unit_price)}</td>
<td className="invoice-detail-cell" style={{ textAlign: 'right', fontWeight: 400 }}>
{fmt(Number(item.unit_price || 0) * Number(item.quantity || 1))}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
<div className="invoice-detail-total-row">
<div style={{ textAlign: 'right' }}>
<div className="invoice-detail-total-label">Total</div>
<div className="invoice-detail-total-value">{fmt(total)}</div>
</div>
</div>
</div>
{notes ? (
<div className="card invoice-detail-card">
<div className="invoice-detail-section-title">Notes</div>
<p className="invoice-detail-notes">{notes}</p>
</div>
) : null}
</div>
</div>
);
}
+562
View File
@@ -0,0 +1,562 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import LoadingButton from './LoadingButton';
import { supabase } from '../lib/supabase';
import { useAuth } from '../context/AuthContext';
import { sendEmail } from '../lib/email';
import { isCompletedVersionEligible } from '../lib/invoiceVersionRules';
const INVOICE_TODAY = new Date().toISOString().split('T')[0];
const REVISION_RATE = 30;
const FIELD_LABEL_STYLE = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: 0.8, display: 'block', marginBottom: 4 };
const FIELD_INPUT_STYLE = { minHeight: 42, margin: 0 };
const FINANCE_MODAL_INPUT_STYLE = {
...FIELD_INPUT_STYLE,
width: '100%',
padding: '0 10px',
fontSize: 13,
color: 'var(--text-primary)',
background: 'var(--card-bg-2)',
border: '1px solid var(--border)',
borderRadius: 6,
fontFamily: 'inherit',
boxSizing: 'border-box',
};
const FINANCE_MODAL_TEXTAREA_STYLE = {
...FINANCE_MODAL_INPUT_STYLE,
minHeight: 72,
padding: '10px',
resize: 'vertical',
};
const FINANCE_MODAL_LINE_ITEM_INPUT_STYLE = {
...FINANCE_MODAL_INPUT_STYLE,
minHeight: 32,
padding: '0 8px',
};
const FINANCE_MODAL_NUMBER_INPUT_STYLE = {
...FINANCE_MODAL_LINE_ITEM_INPUT_STYLE,
fontVariantNumeric: 'tabular-nums',
};
const FINANCE_MODAL_TOTAL_VALUE_STYLE = {
fontSize: 24,
fontWeight: 500,
lineHeight: 1.1,
color: 'var(--accent)',
fontVariantNumeric: 'tabular-nums',
};
function asArray(value) {
if (Array.isArray(value)) return value;
if (value == null) return [];
return typeof value === 'object' ? [value] : [];
}
function versionLabel(version = 0) {
return `R${String(version).padStart(2, '0')}`;
}
function parseVersionFromDescription(description = '') {
const match = String(description).match(/\bR(\d{2})\b/i);
return match ? Number(match[1]) : 0;
}
function subcontractorVersionRate(version, newWorkRate) {
if (version <= 0) return newWorkRate;
if (version === 1) return 0;
return REVISION_RATE;
}
function newItem(description = '', unitPrice = '', quantity = 1, taskId = null, isRevision = false, versionNumber = 0, lineKey = null) {
return {
id: crypto.randomUUID(),
description,
unit_price: unitPrice,
quantity,
task_id: taskId,
is_revision: isRevision,
version_number: versionNumber,
line_key: lineKey || (taskId ? `${taskId}:${versionNumber}` : crypto.randomUUID()),
};
}
function genNumber(count) {
const year = new Date().getFullYear();
return `INVSUB-${year}-${String(count + 1).padStart(3, '0')}`;
}
export default function SubcontractorInvoiceForm({ embedded = false, onCancel, onSubmitted }) {
const navigate = useNavigate();
const { currentUser } = useAuth();
const [invoiceNumber, setInvoiceNumber] = useState('');
const [completedTasks, setCompletedTasks] = useState([]);
const [loadingTasks, setLoadingTasks] = useState(true);
const [items, setItems] = useState([newItem()]);
const [notes, setNotes] = useState('');
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [lineItemsPulse, setLineItemsPulse] = useState(false);
const dragItem = useRef(null);
const lineItemsRef = useRef(null);
const rate = Number(currentUser?.brand_book_rate || 60);
useEffect(() => {
async function load() {
if (!currentUser?.id) {
setCompletedTasks([]);
setLoadingTasks(false);
return;
}
setLoadingTasks(true);
setError('');
try {
const [{ data: tasks, error: tasksError }, { data: existingInvoices, error: invoicesError }, { data: nextNum, error: nextNumError }] = await Promise.all([
supabase
.from('tasks')
.select('id, title, status, current_version, project:projects(name)')
.in('status', ['not_started', 'in_progress', 'on_hold', 'client_review', 'client_approved', 'invoiced', 'paid'])
.eq('assigned_to', currentUser.id)
.order('title'),
supabase
.from('subcontractor_invoices')
.select('id, status, items:subcontractor_invoice_items(task_id, description)')
.in('status', ['submitted', 'paid']),
supabase.rpc('get_next_sub_invoice_number'),
]);
if (tasksError) throw tasksError;
if (invoicesError) throw invoicesError;
if (nextNumError) throw nextNumError;
setInvoiceNumber(nextNum || genNumber(0));
const invoicedUnitKeys = new Set(
(existingInvoices || []).flatMap((inv) => asArray(inv.items).map((item) => {
if (!item.task_id) return null;
return `${item.task_id}:${parseVersionFromDescription(item.description)}`;
}).filter(Boolean))
);
const taskIds = (tasks || []).map((task) => task.id).filter(Boolean);
const { data: submissionRows, error: submissionsError } = taskIds.length > 0
? await supabase
.from('submissions')
.select('task_id, deliveries(version_number, sent_by, sent_at)')
.in('task_id', taskIds)
: { data: [], error: null };
if (submissionsError) throw submissionsError;
const deliveriesByTask = new Map();
for (const row of (submissionRows || [])) {
const taskId = row.task_id;
if (!taskId) continue;
const bucket = deliveriesByTask.get(taskId) || new Map();
for (const delivery of asArray(row.deliveries)) {
if ((delivery.sent_by || '').trim().toLowerCase() !== (currentUser.name || '').trim().toLowerCase()) continue;
const version = Number(delivery.version_number || 0);
if (!bucket.has(version)) bucket.set(version, delivery);
}
deliveriesByTask.set(taskId, bucket);
}
const units = (tasks || []).flatMap((task) => {
const versions = [...(deliveriesByTask.get(task.id)?.keys() || [])].sort((a, b) => a - b);
return versions
.filter((version) => isCompletedVersionEligible(task, version))
.map((version) => {
const key = `${task.id}:${version}`;
return {
key,
task_id: task.id,
version_number: version,
is_revision: version > 0,
title: task.title,
project_name: task.project?.name || '',
description: `${task.project?.name ? `${task.project.name}` : ''}${task.title} ${versionLabel(version)}`,
rate: subcontractorVersionRate(version, rate),
};
});
}).filter((unit) => !invoicedUnitKeys.has(unit.key));
setCompletedTasks(units);
} catch (err) {
console.error('Failed to load subcontractor invoice tasks:', err);
setCompletedTasks([]);
setError(err?.message || 'Could not load completed tasks.');
} finally {
setLoadingTasks(false);
}
}
load();
}, [currentUser?.id, currentUser?.name, rate]);
const addedTaskIds = useMemo(() => new Set(items.map((item) => item.line_key).filter(Boolean)), [items]);
const focusLineItems = () => {
setLineItemsPulse(true);
lineItemsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
window.setTimeout(() => setLineItemsPulse(false), 1200);
};
const addTask = (task) => {
if (addedTaskIds.has(task.key)) return;
const toAdd = [newItem(task.description, task.rate, 1, task.task_id, task.is_revision, task.version_number, task.key)];
setItems((prev) => {
if (prev.length === 1 && !prev[0].description && !prev[0].unit_price) return toAdd;
return [...prev, ...toAdd];
});
focusLineItems();
};
const updateItem = (id, field, value) => {
setItems((prev) => prev.map((item) => (item.id === id ? { ...item, [field]: value } : item)));
};
const removeItem = (id) => setItems((prev) => prev.filter((item) => item.id !== id));
const handleDrop = (targetIndex) => {
if (dragItem.current === null || dragItem.current === targetIndex) {
dragItem.current = null;
return;
}
setItems((prev) => {
const next = [...prev];
const [moved] = next.splice(dragItem.current, 1);
next.splice(targetIndex, 0, moved);
return next;
});
dragItem.current = null;
};
const handleCancel = () => {
if (saving) return;
if (onCancel) {
onCancel();
return;
}
navigate('/subs-invoices');
};
const total = items.reduce((sum, item) => sum + (Number(item.quantity) || 0) * (Number(item.unit_price) || 0), 0);
const handleSubmit = async () => {
const valid = items.filter((item) => String(item.description).trim());
if (!valid.length) {
setError('Add at least one line item.');
return;
}
setSaving(true);
setError('');
try {
const { data: inv, error: invErr } = await supabase
.from('subcontractor_invoices')
.insert({
profile_id: currentUser.id,
invoice_number: invoiceNumber.trim(),
status: 'submitted',
notes: notes.trim(),
submitted_at: new Date().toISOString(),
})
.select()
.single();
if (invErr) throw invErr;
const { error: itemsErr } = await supabase.from('subcontractor_invoice_items').insert(
valid.map((item, idx) => ({
invoice_id: inv.id,
task_id: item.task_id || null,
description: String(item.description).trim(),
quantity: Number(item.quantity) || 1,
unit_price: Number(item.unit_price) || 0,
sort_order: idx,
}))
);
if (itemsErr) throw itemsErr;
const invoiceTotal = valid.reduce((sum, item) => sum + (Number(item.unit_price) || 0) * (Number(item.quantity) || 1), 0);
sendEmail('subcontractor_invoice_submitted', 'hello@fourgebranding.com', {
subName: currentUser.name,
subEmail: currentUser.email || '',
invoiceNumber: inv.invoice_number,
total: invoiceTotal.toFixed(2),
invoiceId: inv.id,
}).catch((err) => console.error('Sub invoice notification failed:', err));
if (onSubmitted) {
await onSubmitted(inv);
} else {
navigate(`/subs-invoices/${inv.id}`);
}
} catch (err) {
setError(err?.message || 'Failed to submit invoice.');
setSaving(false);
}
};
return (
<div style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, gap: 0 }}>
{!embedded && (
<>
<button className="back-link" onClick={handleCancel}> Back to Invoices</button>
<div className="page-header">
<div>
<div className="page-title">New Invoice</div>
<div className="page-subtitle">
Invoice date: {new Date(INVOICE_TODAY).toLocaleDateString()} · {invoiceNumber}
</div>
</div>
</div>
</>
)}
{embedded ? (
<div style={{ display: 'flex', gap: 24, alignItems: 'stretch', flex: 1, minHeight: 0 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: '0 0 260px', overflowY: 'auto' }}>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>New Invoice</div>
<div>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>Invoice Date</div>
<input type="text" value={new Date(INVOICE_TODAY).toLocaleDateString()} readOnly style={FINANCE_MODAL_INPUT_STYLE} />
</div>
<div>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>Invoice Number</div>
<input type="text" value={invoiceNumber} onChange={(e) => setInvoiceNumber(e.target.value)} style={FINANCE_MODAL_INPUT_STYLE} />
</div>
<div>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>Notes</div>
<textarea
placeholder="Additional notes for the team..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
style={FINANCE_MODAL_TEXTAREA_STYLE}
/>
</div>
<div style={{ marginTop: 'auto', paddingTop: 8 }}>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>Total</div>
<div style={FINANCE_MODAL_TOTAL_VALUE_STYLE}>${total.toFixed(2)}</div>
</div>
{error && <div style={{ fontSize: 12, color: 'var(--danger)' }}>{error}</div>}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14, flex: 1, minHeight: 0, overflowY: 'auto' }}>
<div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 3 }}>Completed Tasks</div>
{completedTasks.length > 0 && !loadingTasks && (
<button
type="button"
className="btn btn-outline"
style={{ fontSize: 11 }}
onClick={() => completedTasks.forEach((task) => { if (!addedTaskIds.has(task.key)) addTask(task); })}
>
+ All
</button>
)}
</div>
{loadingTasks ? (
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>Loading</div>
) : completedTasks.length === 0 ? (
<div style={{ fontSize: 12, color: 'var(--text-muted)' }}>No completed tasks available to invoice.</div>
) : (
completedTasks.map((task) => {
const alreadyAdded = addedTaskIds.has(task.key);
return (
<div key={task.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 10px', background: 'var(--card-bg-2)', borderRadius: 4, border: '1px solid var(--border)', marginBottom: 4 }}>
<div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<span className={`badge ${task.is_revision ? 'badge-client_revision' : 'badge-initial'}`}>
{task.is_revision ? 'Revision' : 'New'}
</span>
<div style={{ fontSize: 12 }}>{task.project_name ? `${task.project_name}` : ''}{task.title} · {versionLabel(task.version_number)}</div>
</div>
<div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
{task.version_number === 0
? `$${rate.toFixed(2)}`
: task.version_number === 1
? 'Free'
: `$${REVISION_RATE.toFixed(2)}`}
</div>
</div>
<button
type="button"
className="btn btn-outline"
style={{ fontSize: 11 }}
onClick={() => !alreadyAdded && addTask(task)}
disabled={alreadyAdded}
>
{alreadyAdded ? 'Added' : '+ Add'}
</button>
</div>
);
})
)}
</div>
<div
ref={lineItemsRef}
style={{
flex: 1,
border: '1px solid var(--border)',
borderColor: lineItemsPulse ? 'var(--accent)' : 'var(--border)',
borderRadius: 8,
padding: 12,
boxShadow: lineItemsPulse ? '0 0 0 1px color-mix(in srgb, var(--accent) 45%, transparent)' : 'none',
transition: 'border-color 180ms ease, box-shadow 180ms ease',
}}
>
<div style={{ ...FIELD_LABEL_STYLE, marginBottom: 6 }}>Line Items ({items.filter((item) => String(item.description || '').trim()).length})</div>
<div style={{ display: 'grid', gridTemplateColumns: '20px 90px 1fr 60px 100px 90px 28px', gap: 6, marginBottom: 6 }}>
{['', 'Type', 'Description', 'Qty', 'Unit Price', 'Total', ''].map((header, index) => (
<div key={index} style={{ fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.5, color: 'var(--text-muted)', textAlign: index > 3 ? 'right' : 'left' }}>{header}</div>
))}
</div>
{items.map((item, index) => (
<div
key={item.id}
onDragOver={(e) => e.preventDefault()}
onDrop={() => handleDrop(index)}
style={{ display: 'grid', gridTemplateColumns: '20px 90px 1fr 60px 100px 90px 28px', gap: 6, alignItems: 'center', marginBottom: 4 }}
>
<div draggable onDragStart={(e) => { dragItem.current = index; e.dataTransfer.effectAllowed = 'move'; }} style={{ cursor: 'grab', color: 'var(--text-muted)', fontSize: 12, textAlign: 'center', userSelect: 'none' }}></div>
<span className={`badge ${item.is_revision ? 'badge-client_revision' : 'badge-initial'}`}>
{item.is_revision ? 'Revision' : 'New'}
</span>
<input style={FINANCE_MODAL_LINE_ITEM_INPUT_STYLE} type="text" placeholder="Description…" value={item.description} onChange={(e) => updateItem(item.id, 'description', e.target.value)} />
<input style={{ ...FINANCE_MODAL_NUMBER_INPUT_STYLE, textAlign: 'center' }} type="number" min="0.5" step="0.5" value={item.quantity} onChange={(e) => updateItem(item.id, 'quantity', e.target.value)} />
<input style={{ ...FINANCE_MODAL_NUMBER_INPUT_STYLE, textAlign: 'right' }} type="number" min="0" step="0.01" placeholder="0.00" value={item.unit_price} onChange={(e) => updateItem(item.id, 'unit_price', e.target.value)} />
<div style={{ minHeight: 32, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', textAlign: 'right', fontSize: 13, color: 'var(--text-primary)', paddingRight: 2, fontVariantNumeric: 'tabular-nums' }}>${((Number(item.quantity) || 0) * (Number(item.unit_price) || 0)).toFixed(2)}</div>
<button type="button" onClick={() => removeItem(item.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--danger)', fontSize: 14, padding: 2 }}></button>
</div>
))}
<button type="button" className="btn btn-outline" style={{ marginTop: 8, fontSize: 12 }} onClick={() => { setItems((prev) => [...prev, newItem()]); focusLineItems(); }}>+ Line Item</button>
</div>
</div>
</div>
) : (
<>
{error && <div className="notification notification-info" style={{ marginBottom: 16 }}>{error}</div>}
<div className="card" style={{ marginBottom: 24 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<div className="card-title" style={{ marginBottom: 0 }}>Completed Tasks</div>
{completedTasks.length > 0 && !loadingTasks && (
<button
className="btn btn-outline btn-sm"
onClick={() => completedTasks.forEach((task) => { if (!addedTaskIds.has(task.key)) addTask(task); })}
>
+ Add All
</button>
)}
</div>
{loadingTasks ? (
<p style={{ fontSize: 13, color: 'var(--text-muted)' }}>Loading...</p>
) : completedTasks.length === 0 ? (
<p style={{ fontSize: 13, color: 'var(--text-muted)' }}>No completed tasks available to invoice.</p>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{completedTasks.map((task) => {
const alreadyAdded = addedTaskIds.has(task.key);
return (
<div key={task.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 12px', background: 'var(--bg)', borderRadius: 4, border: '1px solid var(--border)' }}>
<div>
<div style={{ fontSize: 13, fontWeight: 400 }}>
{task.project_name ? `${task.project_name}` : ''}{task.title} · {versionLabel(task.version_number)}
</div>
<div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
{task.version_number === 0
? `New Book · $${rate.toFixed(2)}`
: task.version_number === 1
? `Revision ${versionLabel(task.version_number)} · Free`
: `Revision ${versionLabel(task.version_number)} · $${REVISION_RATE.toFixed(2)}`}
</div>
</div>
<button
className={`btn btn-sm ${alreadyAdded ? 'btn-outline' : 'btn-primary'}`}
onClick={() => !alreadyAdded && addTask(task)}
disabled={alreadyAdded}
>
{alreadyAdded ? 'Added' : '+ Add'}
</button>
</div>
);
})}
</div>
)}
</div>
<div
ref={lineItemsRef}
className="card"
style={{
marginBottom: 24,
borderColor: lineItemsPulse ? 'var(--accent)' : 'var(--border)',
boxShadow: lineItemsPulse ? '0 0 0 1px color-mix(in srgb, var(--accent) 45%, transparent)' : 'none',
transition: 'border-color 180ms ease, box-shadow 180ms ease',
}}
>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<div className="card-title" style={{ marginBottom: 0 }}>Line Items ({items.filter((item) => String(item.description || '').trim()).length})</div>
</div>
<div style={{ display: 'grid', gridTemplateColumns: '20px 90px 1fr 80px 120px 120px 40px', gap: 8, marginBottom: 8 }}>
{['', 'Type', 'Description', 'Qty / Hrs', 'Rate', 'Total', ''].map((header, index) => (
<div key={index} style={{ fontSize: 11, fontWeight: 400, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-muted)', textAlign: index > 3 ? 'right' : 'left' }}>{header}</div>
))}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{items.map((item, index) => (
<div
key={item.id}
onDragOver={(e) => e.preventDefault()}
onDrop={() => handleDrop(index)}
style={{ display: 'grid', gridTemplateColumns: '20px 90px 1fr 80px 120px 120px 40px', gap: 8, alignItems: 'center' }}
>
<div draggable onDragStart={(e) => { dragItem.current = index; e.dataTransfer.effectAllowed = 'move'; }} style={{ cursor: 'grab', color: 'var(--text-muted)', fontSize: 14, textAlign: 'center', userSelect: 'none' }}></div>
<span className={`badge ${item.is_revision ? 'badge-client_revision' : 'badge-initial'}`}>
{item.is_revision ? 'Revision' : 'New'}
</span>
<input type="text" placeholder="Description..." value={item.description} onChange={(e) => updateItem(item.id, 'description', e.target.value)} style={{ margin: 0 }} />
<input type="number" min="0.5" step="0.5" value={item.quantity} onChange={(e) => updateItem(item.id, 'quantity', e.target.value)} style={{ margin: 0, textAlign: 'center' }} />
<input type="number" min="0" step="0.01" placeholder="0.00" value={item.unit_price} onChange={(e) => updateItem(item.id, 'unit_price', e.target.value)} style={{ margin: 0, textAlign: 'right' }} />
<div style={{ textAlign: 'right', fontSize: 14, fontWeight: 400, color: 'var(--text-primary)', paddingRight: 4 }}>
${((Number(item.quantity) || 0) * (Number(item.unit_price) || 0)).toFixed(2)}
</div>
<button onClick={() => removeItem(item.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--danger)', fontSize: 16, padding: 4 }}></button>
</div>
))}
</div>
<button className="btn btn-outline btn-sm" style={{ marginTop: 12 }} onClick={() => { setItems((prev) => [...prev, newItem()]); focusLineItems(); }}>
+ Add Line Item
</button>
<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: 11, fontWeight: 400, textTransform: 'uppercase', letterSpacing: '0.5px', color: 'var(--text-muted)', marginBottom: 4 }}>Total</div>
<div style={{ fontSize: 26, fontWeight: 400, color: 'var(--accent)' }}>${total.toFixed(2)}</div>
</div>
</div>
</div>
<div className="card" style={{ marginBottom: 24 }}>
<div className="card-title">Notes</div>
<textarea
placeholder="Additional notes for the team..."
value={notes}
onChange={(e) => setNotes(e.target.value)}
style={{ minHeight: 80 }}
/>
</div>
</>
)}
<div className={embedded ? 'modal-action-row' : 'action-buttons'} style={embedded ? { paddingTop: 14, marginTop: 14, flexShrink: 0 } : undefined}>
<LoadingButton className="btn btn-primary" onClick={handleSubmit} loading={saving} loadingText="Submitting...">
Submit Invoice
</LoadingButton>
<button className="btn btn-outline" onClick={handleCancel} disabled={saving}>Cancel</button>
</div>
</div>
);
}