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:
@@ -1,130 +1,5 @@
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
|
||||
const FB_SOURCE = 'srv';
|
||||
|
||||
function normalizePath(path) {
|
||||
const raw = String(path || '/').trim();
|
||||
const parts = raw.split('/').filter(Boolean);
|
||||
const clean = [];
|
||||
for (const part of parts) {
|
||||
if (part === '.') continue;
|
||||
if (part === '..') throw new Error('Invalid path');
|
||||
clean.push(part);
|
||||
}
|
||||
return `/${clean.join('/')}`;
|
||||
}
|
||||
|
||||
function joinPath(...parts) {
|
||||
return normalizePath(parts.join('/'));
|
||||
}
|
||||
|
||||
function safeName(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-')
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
function basename(path) {
|
||||
const parts = normalizePath(path).split('/').filter(Boolean);
|
||||
return parts[parts.length - 1] || '';
|
||||
}
|
||||
|
||||
function parentDir(path) {
|
||||
const parts = normalizePath(path).split('/').filter(Boolean);
|
||||
parts.pop();
|
||||
return `/${parts.join('/')}`;
|
||||
}
|
||||
|
||||
function getFbConfig() {
|
||||
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
|
||||
return {
|
||||
url,
|
||||
token: process.env.FILEBROWSER_TOKEN || '',
|
||||
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
|
||||
archiveRoot: normalizePath(process.env.FILEBROWSER_ARCHIVE_ROOT || '/Archive'),
|
||||
configured: Boolean(url) && Boolean(process.env.FILEBROWSER_TOKEN),
|
||||
};
|
||||
}
|
||||
|
||||
async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) {
|
||||
const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString();
|
||||
const res = await fetch(`${config.url}${endpoint}?${qs}`, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${config.token}`, ...headers },
|
||||
body,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
const err = new Error(text || `FileBrowser ${res.status}`);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
const text = await res.text();
|
||||
try { return text ? JSON.parse(text) : null; } catch { return text; }
|
||||
}
|
||||
|
||||
async function fbExists(config, path) {
|
||||
try { await fbFetch(config, 'GET', '/api/resources', { params: { path } }); return true; }
|
||||
catch (e) { if (e.status === 404) return false; throw e; }
|
||||
}
|
||||
|
||||
async function fbMkdir(config, path) {
|
||||
await fbFetch(config, 'POST', '/api/resources', { params: { path, isDir: 'true' } }).catch(() => {});
|
||||
}
|
||||
|
||||
async function mergeMove(config, fbSrc, fbDstParent) {
|
||||
const name = basename(fbSrc);
|
||||
const fbDst = joinPath(fbDstParent, name);
|
||||
const destExists = await fbExists(config, fbDst);
|
||||
if (!destExists) {
|
||||
await fbFetch(config, 'PATCH', '/api/resources', {
|
||||
params: {},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'move',
|
||||
items: [{ fromSource: FB_SOURCE, fromPath: fbSrc, toSource: FB_SOURCE, toPath: fbDst }],
|
||||
overwrite: false,
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
const data = await fbFetch(config, 'GET', '/api/resources', { params: { path: fbSrc } });
|
||||
const dirs = (data?.folders || []).map(f => f.name);
|
||||
const files = (data?.files || []).map(f => f.name);
|
||||
await fbMkdir(config, fbDst);
|
||||
for (const dir of dirs) await mergeMove(config, joinPath(fbSrc, dir), fbDst);
|
||||
for (const file of files) {
|
||||
await fbFetch(config, 'PATCH', '/api/resources', {
|
||||
params: {},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
action: 'move',
|
||||
items: [{ fromSource: FB_SOURCE, fromPath: joinPath(fbSrc, file), toSource: FB_SOURCE, toPath: joinPath(fbDst, file) }],
|
||||
overwrite: true,
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
await fbFetch(config, 'DELETE', '/api/resources', { params: { path: fbSrc } }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function archiveProject(companyName, projectName) {
|
||||
const config = getFbConfig();
|
||||
if (!config.configured || !companyName || !projectName) return;
|
||||
const co = safeName(companyName);
|
||||
const proj = safeName(projectName);
|
||||
// Ensure archive dirs exist
|
||||
await fbMkdir(config, config.archiveRoot);
|
||||
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients'));
|
||||
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', co));
|
||||
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', co, 'Projects'));
|
||||
// Merge-move project folder into archive
|
||||
const srcPath = joinPath(config.clientRoot, co, 'Projects', proj);
|
||||
const dstParentPath = joinPath(config.archiveRoot, 'Clients', co, 'Projects');
|
||||
await mergeMove(config, srcPath, dstParentPath);
|
||||
}
|
||||
|
||||
export default async function handler(req, res) {
|
||||
if (req.method !== 'DELETE') return res.status(405).json({ error: 'Method not allowed' });
|
||||
|
||||
@@ -152,22 +27,11 @@ export default async function handler(req, res) {
|
||||
auth: { persistSession: false, autoRefreshToken: false },
|
||||
});
|
||||
|
||||
// Fetch project + company name before deletion (needed for archive path)
|
||||
const { data: projRecord } = await admin
|
||||
.from('projects')
|
||||
.select('id, name, company:companies(name)')
|
||||
.eq('id', projectId)
|
||||
.single();
|
||||
|
||||
if (!projRecord) return res.status(404).json({ error: 'Project not found' });
|
||||
|
||||
// For clients, confirm they can see this project (RLS gate)
|
||||
if (profile.role === 'client') {
|
||||
const { data: proj, error: projErr } = await callerClient.from('projects').select('id').eq('id', projectId).single();
|
||||
if (projErr || !proj) return res.status(404).json({ error: 'Project not found or access denied' });
|
||||
}
|
||||
|
||||
// Cleanup storage files
|
||||
const { data: tasks } = await admin.from('tasks').select('id').eq('project_id', projectId);
|
||||
const taskIds = (tasks || []).map(t => t.id);
|
||||
|
||||
@@ -190,17 +54,8 @@ export default async function handler(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// Delete project (DB cascade handles tasks/submissions/etc.)
|
||||
const { error } = await admin.from('projects').delete().eq('id', projectId);
|
||||
if (error) return res.status(500).json({ error: error.message });
|
||||
|
||||
// Archive FileBrowser project folder (server-side, so errors are logged)
|
||||
try {
|
||||
await archiveProject(projRecord.company?.name, projRecord.name);
|
||||
} catch (e) {
|
||||
console.error('[delete-project] archive failed:', e.message);
|
||||
// Don't fail — DB delete succeeded
|
||||
}
|
||||
|
||||
return res.status(200).json({ ok: true });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user