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
-212
View File
@@ -1,212 +0,0 @@
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 getFbConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
teamRoot: normalizePath(process.env.FILEBROWSER_TEAM_ROOT || '/Team'),
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 listFolders(config, path) {
try {
const data = await fbFetch(config, 'GET', '/api/resources', { params: { path } });
return (data?.folders || []).map(f => f.name).filter(Boolean);
} catch (e) {
if (e.status === 404) return [];
throw e;
}
}
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', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'move',
items: [{ fromSource: FB_SOURCE, fromPath: fbSrc, toSource: FB_SOURCE, toPath: fbDst }],
overwrite: false,
}),
});
return;
}
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', {
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(() => {});
}
function json(res, status, body) {
return res.status(status).json(body);
}
export default async function handler(req, res) {
if (req.method !== 'POST') return json(res, 405, { error: 'Method not allowed' });
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (secret) {
const incoming = req.headers['x-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return json(res, 401, { error: 'Unauthorized' });
}
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !serviceRoleKey) return json(res, 500, { error: 'Supabase env not configured' });
const admin = createClient(supabaseUrl, serviceRoleKey, {
auth: { persistSession: false, autoRefreshToken: false },
});
const config = getFbConfig();
if (!config.configured) return json(res, 200, { ok: true, skipped: 'FileBrowser not configured' });
const results = {
archivedTeamFolders: [],
archivedProjectFolders: [],
errors: [],
};
await fbMkdir(config, config.archiveRoot);
await fbMkdir(config, joinPath(config.archiveRoot, 'Team'));
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients'));
const { data: profiles, error: profilesError } = await admin
.from('profiles')
.select('name, role')
.in('role', ['team', 'external']);
if (profilesError) return json(res, 500, { error: profilesError.message });
const validTeamFolders = new Set((profiles || []).map(profile => safeName(profile.name)).filter(Boolean));
const teamFolders = await listFolders(config, config.teamRoot);
for (const folder of teamFolders) {
if (validTeamFolders.has(folder)) continue;
try {
await mergeMove(config, joinPath(config.teamRoot, folder), joinPath(config.archiveRoot, 'Team'));
results.archivedTeamFolders.push(folder);
} catch (e) {
results.errors.push(`team:${folder}: ${e.message}`);
}
}
const { data: companies, error: companiesError } = await admin
.from('companies')
.select('id, name');
if (companiesError) return json(res, 500, { error: companiesError.message });
const { data: projects, error: projectsError } = await admin
.from('projects')
.select('name, company_id');
if (projectsError) return json(res, 500, { error: projectsError.message });
const projectsByCompany = new Map();
for (const project of projects || []) {
if (!project?.company_id || !project?.name) continue;
const key = project.company_id;
if (!projectsByCompany.has(key)) projectsByCompany.set(key, new Set());
projectsByCompany.get(key).add(safeName(project.name));
}
for (const company of companies || []) {
const companyFolder = safeName(company.name);
if (!companyFolder) continue;
const validProjects = projectsByCompany.get(company.id) || new Set();
const projectsRoot = joinPath(config.clientRoot, companyFolder, 'Projects');
const projectFolders = await listFolders(config, projectsRoot);
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', companyFolder));
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', companyFolder, 'Projects'));
for (const folder of projectFolders) {
if (validProjects.has(folder)) continue;
try {
await mergeMove(
config,
joinPath(projectsRoot, folder),
joinPath(config.archiveRoot, 'Clients', companyFolder, 'Projects'),
);
results.archivedProjectFolders.push(`${companyFolder}/${folder}`);
} catch (e) {
results.errors.push(`project:${companyFolder}/${folder}: ${e.message}`);
}
}
}
return json(res, 200, { ok: true, ...results });
}
-222
View File
@@ -1,222 +0,0 @@
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 getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
configured: Boolean(url),
};
}
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();
throw new Error(text || `FileBrowser ${res.status}`);
}
return res;
}
async function mkdir(config, path) {
await fbFetch(config, 'POST', '/api/resources', {
params: { path, isDir: 'true' },
}).catch(() => {});
}
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 ensureTaskStructure(config, companyName, projectName, taskTitle) {
const companyDir = joinPath(config.clientRoot, safeName(companyName));
const projectsDir = joinPath(companyDir, 'Projects');
const projectDir = joinPath(projectsDir, safeName(projectName));
const taskDir = joinPath(projectDir, safeName(taskTitle));
const requestInfoDir = joinPath(taskDir, 'Request Info');
const workingFilesDir = joinPath(taskDir, 'Working Files');
const oldBooksDir = joinPath(taskDir, 'Old Books');
await mkdir(config, companyDir);
await mkdir(config, projectsDir);
await mkdir(config, projectDir);
await mkdir(config, joinPath(projectDir, '00 Project Files'));
await mkdir(config, taskDir);
await mkdir(config, requestInfoDir);
await mkdir(config, workingFilesDir);
await mkdir(config, oldBooksDir);
return { companyDir, projectDir, taskDir, requestInfoDir };
}
function json(res, status, body) {
return res.status(status).json(body);
}
export default async function handler(req, res) {
if (req.method !== 'POST') return json(res, 405, { error: 'Method not allowed' });
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (secret) {
const incoming = req.headers['x-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return json(res, 401, { error: 'Unauthorized' });
}
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !serviceRoleKey) return json(res, 500, { error: 'Supabase env not configured' });
const admin = createClient(supabaseUrl, serviceRoleKey, {
auth: { persistSession: false, autoRefreshToken: false },
});
const config = getConfig();
if (!config.configured || !config.token) return json(res, 200, { ok: true, skipped: 'FileBrowser not configured' });
const { data: tasks, error: taskError } = await admin
.from('tasks')
.select(`
id, title,
project:projects!inner(
id, name,
company:companies!inner(name)
)
`);
if (taskError) return json(res, 500, { error: taskError.message });
const results = {
ensuredTasks: 0,
processed: 0,
skipped: 0,
errors: [],
};
for (const task of tasks || []) {
const project = task?.project;
const company = project?.company;
if (!task?.title || !project?.name || !company?.name) continue;
await ensureTaskStructure(config, company.name, project.name, task.title);
results.ensuredTasks++;
}
// Fetch all submission files with task/project/company context
const { data: rows, error } = await admin
.from('submission_files')
.select(`
id, name, storage_path, size,
submission:submissions!inner(
id, version_number,
task:tasks!inner(
id, title,
project:projects!inner(
id, name,
company:companies!inner(name)
)
)
)
`);
if (error) return json(res, 500, { error: error.message });
// Group by task + version_number, skip groups with no files
const groups = new Map();
for (const row of rows || []) {
const sub = row.submission;
const task = sub?.task;
const project = task?.project;
const company = project?.company;
if (!task || !project || !company) continue;
const key = `${task.id}::${sub.version_number}`;
if (!groups.has(key)) {
groups.set(key, {
companyName: company.name,
projectName: project.name,
taskTitle: task.title,
versionNumber: sub.version_number,
files: [],
});
}
groups.get(key).files.push({ name: row.name, storage_path: row.storage_path });
}
for (const group of groups.values()) {
if (group.files.length === 0) { results.skipped++; continue; }
const revFolder = `R${String(group.versionNumber).padStart(2, '0')}`;
const { requestInfoDir } = await ensureTaskStructure(config, group.companyName, group.projectName, group.taskTitle);
const revDir = joinPath(requestInfoDir, revFolder);
await mkdir(config, revDir);
for (const file of group.files) {
try {
const { data: blob, error: downloadError } = await admin.storage
.from('submissions')
.download(file.storage_path);
if (downloadError || !blob) {
results.errors.push(`download failed: ${file.storage_path}`);
continue;
}
const fileBuffer = await blob.arrayBuffer();
const form = new FormData();
form.append('file', new Blob([fileBuffer]), file.name);
// Upload to FileBrowser
const fbFilePath = joinPath(revDir, file.name);
if (await fbExists(config, fbFilePath)) {
results.skipped++;
continue;
}
await fbFetch(config, 'POST', '/api/resources', {
params: { path: fbFilePath },
body: form,
});
results.processed++;
} catch (err) {
results.errors.push(`${file.name}: ${err.message}`);
}
}
}
return json(res, 200, { ok: true, ...results });
}
-145
View File
@@ -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 });
}
+2 -140
View File
@@ -1,126 +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 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 archiveTask(companyName, projectName, taskTitle) {
const config = getFbConfig();
if (!config.configured || !companyName || !projectName || !taskTitle) return;
const co = safeName(companyName);
const proj = safeName(projectName);
const task = safeName(taskTitle);
// 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'));
await fbMkdir(config, joinPath(config.archiveRoot, 'Clients', co, 'Projects', proj));
// Merge-move task folder into archive
const srcPath = joinPath(config.clientRoot, co, 'Projects', proj, task);
const dstParentPath = joinPath(config.archiveRoot, 'Clients', co, 'Projects', proj);
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' });
@@ -148,16 +27,9 @@ export default async function handler(req, res) {
auth: { persistSession: false, autoRefreshToken: false },
});
// Fetch task + project + company before deletion using explicit joins
const { data: taskRecord } = await admin.from('tasks').select('id, title, project_id').eq('id', taskId).single();
const { data: taskRecord } = await admin.from('tasks').select('id').eq('id', taskId).single();
if (!taskRecord) return res.status(404).json({ error: 'Task not found' });
const { data: projectRecord } = await admin.from('projects').select('id, name, company_id').eq('id', taskRecord.project_id).single();
const { data: companyRecord } = projectRecord?.company_id
? await admin.from('companies').select('id, name').eq('id', projectRecord.company_id).single()
: { data: null };
// Cleanup storage files
const { data: subs } = await admin.from('submissions').select('id').eq('task_id', taskId);
const subIds = (subs || []).map(s => s.id);
@@ -175,18 +47,8 @@ export default async function handler(req, res) {
}
}
// Delete task (DB cascade handles submissions/etc.)
const { error } = await admin.from('tasks').delete().eq('id', taskId);
if (error) return res.status(500).json({ error: error.message });
// Archive FileBrowser task folder
let archiveError = null;
try {
await archiveTask(companyRecord?.name, projectRecord?.name, taskRecord.title);
} catch (e) {
archiveError = e.message;
console.error('[delete-task] archive failed:', e.message);
}
return res.status(200).json({ ok: true, archiveError });
return res.status(200).json({ ok: true });
}
+292 -504
View File
@@ -1,6 +1,10 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'srv';
const PROJECT_DEFAULT_SUBFOLDERS = ['00 Project Files'];
const REQUEST_DEFAULT_SUBFOLDERS = ['Old Books', 'Working Files', 'Survey'];
export const config = { api: { bodyParser: false, sizeLimit: '50mb' } };
function json(res, status, body) {
res.status(status).setHeader('Content-Type', 'application/json');
@@ -24,17 +28,6 @@ function joinPath(...parts) {
return normalizePath(parts.join('/'));
}
function parentDir(path) {
const parts = normalizePath(path).split('/').filter(Boolean);
parts.pop();
return `/${parts.join('/')}`;
}
function basename(path) {
const parts = normalizePath(path).split('/').filter(Boolean);
return parts[parts.length - 1] || '';
}
function safeName(value, fallback = '') {
const cleaned = String(value || '')
.trim()
@@ -44,146 +37,67 @@ function safeName(value, fallback = '') {
return cleaned || fallback;
}
function parseBody(body) {
if (!body) return {};
if (typeof body === 'string') {
try {
return JSON.parse(body);
} catch {
return {};
}
}
return body;
}
async function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
req.on('end', () => resolve(Buffer.concat(chunks)));
req.on('error', reject);
});
}
function getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
adminUser: process.env.FILEBROWSER_ADMIN_USER || '',
adminPass: process.env.FILEBROWSER_ADMIN_PASS || '',
teamRoot: normalizePath(process.env.FILEBROWSER_TEAM_ROOT || '/'),
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/fourgebranding/Clients'),
externalSubsRoot: normalizePath(process.env.FILEBROWSER_SUBS_ROOT || '/fourgebranding/Subcontractors'),
externalClientsRoot: normalizePath(process.env.FILEBROWSER_CLIENTS_ROOT || '/fourgebranding/Clients'),
subsRoot: normalizePath(process.env.FILEBROWSER_SUBS_ROOT || '/fourgebranding/team'),
configured: Boolean(url),
};
}
let runtimeToken = '';
let runtimeTokenTs = 0;
const RUNTIME_TOKEN_TTL_MS = 30 * 60 * 1000;
function extractLoginToken(payload) {
if (typeof payload === 'string') {
const raw = payload.trim();
if (raw.split('.').length === 3) return raw;
try {
const parsed = JSON.parse(raw);
return extractLoginToken(parsed);
} catch {
return '';
}
}
if (!payload || typeof payload !== 'object') return '';
return String(
payload.token
|| payload.auth
|| payload.access_token
|| payload.jwt
|| payload?.data?.token
|| ''
).trim();
}
async function loginForToken(config) {
if (!config.url || !config.adminUser || !config.adminPass) return '';
const endpoints = ['/api/auth/login', '/api/login'];
let lastError = '';
for (const endpoint of endpoints) {
try {
const response = await fetch(`${config.url}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: config.adminUser, password: config.adminPass }),
});
if (!response.ok) {
const text = await response.text().catch(() => '');
// Some FileBrowser deployments only expose /api/auth/login.
// Ignore /api/login 404 and keep trying/using prior success signal.
if (endpoint === '/api/login' && response.status === 404) continue;
lastError = `${endpoint} -> ${response.status} ${text?.slice(0, 180) || ''}`.trim();
continue;
}
const bodyText = await response.text();
const payload = (() => {
try {
return JSON.parse(bodyText);
} catch {
return bodyText;
}
})();
const token = extractLoginToken(payload);
if (token) return token;
lastError = `${endpoint} -> 200 but token missing`;
} catch {
lastError = `${endpoint} -> request failed`;
}
}
if (lastError) {
const err = new Error(`FileBrowser login failed: ${lastError}`);
err.status = 401;
throw err;
}
return '';
}
async function getToken(config, forceRefresh = false) {
const now = Date.now();
if (!forceRefresh && config.token && String(config.token).trim()) {
return String(config.token).trim();
}
if (!forceRefresh && runtimeToken && (now - runtimeTokenTs) < RUNTIME_TOKEN_TTL_MS) {
return runtimeToken;
}
if (!forceRefresh) {
const freshPreferred = await loginForToken(config);
if (freshPreferred) {
runtimeToken = freshPreferred;
runtimeTokenTs = now;
return runtimeToken;
}
}
const fresh = await loginForToken(config);
if (!fresh) throw new Error('FileBrowser login returned no token.');
runtimeToken = fresh;
runtimeTokenTs = now;
return runtimeToken;
function getToken(config) {
const token = String(config.token || '').trim();
if (!token) throw new Error('FILEBROWSER_TOKEN not configured');
return token;
}
async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) {
const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString();
const url = `${config.url}${endpoint}?${qs}`;
const token = getToken(config);
const response = await fetch(url, {
method,
headers: { Authorization: `Bearer ${token}`, ...headers },
body,
});
async function callWith(token) {
return fetch(url, {
method,
headers: { Authorization: `Bearer ${token}`, ...headers },
body,
});
if (!response.ok) {
const text = await response.text().catch(() => '');
const error = new Error(text || `FileBrowser ${response.status}`);
error.status = response.status;
throw error;
}
let token = await getToken(config);
let res = await callWith(token);
if (res.status === 401) {
// Always force-refresh and retry once on Unauthorized.
token = await getToken(config, true);
res = await callWith(token);
const text = await response.text();
try {
return text ? JSON.parse(text) : null;
} catch {
return text;
}
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 createCallerClient(authHeader) {
@@ -203,17 +117,16 @@ async function requirePortalUser(authHeader) {
const { data: profile, error: profileError } = await callerClient
.from('profiles')
.select('id, name, role, company:companies(id, name)')
.select('id, role, company:companies(id, name)')
.eq('id', userData.user.id)
.single();
if (profileError) return { ok: false, status: 500, message: profileError.message };
if (!['team', 'external', 'client'].includes(profile?.role)) {
if (!['team', 'client'].includes(profile?.role)) {
return { ok: false, status: 403, message: 'Forbidden' };
}
// Mirror AuthContext: load all companies (FK + company_members)
let clientCompanies = [];
const clientCompanies = [];
if (profile.role === 'client') {
const seen = new Set();
if (profile.company?.id) {
@@ -224,400 +137,275 @@ async function requirePortalUser(authHeader) {
.from('company_members')
.select('company:companies(id, name)')
.eq('profile_id', userData.user.id);
for (const m of memberships || []) {
if (m.company?.id && !seen.has(m.company.id)) {
clientCompanies.push(m.company);
seen.add(m.company.id);
for (const row of memberships || []) {
if (row.company?.id && !seen.has(row.company.id)) {
seen.add(row.company.id);
clientCompanies.push(row.company);
}
}
}
return { ok: true, callerClient, profile: { ...profile, clientCompanies, email: userData.user.email } };
}
async function getExternalProjects(callerClient, userId) {
const { data, error } = await callerClient
.from('project_members')
.select('project:projects(id, name, company:companies(name))')
.eq('profile_id', userId);
if (error) throw new Error(error.message);
return (data || []).map(r => r.project).filter(Boolean);
}
function resolveUserRoot(config, profile) {
if (profile.role === 'team') return config.teamRoot;
if (profile.role === 'client') {
const companyFolder = safeName(profile.company?.name, profile.id);
return joinPath(config.clientRoot, companyFolder);
}
if (profile.role === 'external') return config.externalSubsRoot;
return '/';
}
function resolveClientPath(config, vPath, companies) {
const parts = normalizePath(vPath).split('/').filter(Boolean);
if (parts.length === 0) return { virtual: true };
const companyFolder = parts[0];
const match = companies.find(c => safeName(c.name, '') === companyFolder);
if (!match) {
const err = new Error('Access denied');
err.status = 403;
throw err;
}
const rest = parts.slice(1);
const base = joinPath(config.clientRoot, companyFolder);
const fbPath = rest.length > 0 ? joinPath(base, ...rest) : base;
return { virtual: false, fbPath };
}
function buildClientVirtualEntries(companies) {
return companies.map(c => {
const name = safeName(c.name, c.id);
return { name, type: 'dir', size: 0, mtime: null, path: `/${name}` };
});
}
function resolveExternalPath(config, vPath, profile, projects) {
const myFolder = safeName(profile.name, profile.id);
const parts = normalizePath(vPath).split('/').filter(Boolean);
if (parts.length === 0) return { virtual: true };
// Their personal Team folder
if (parts[0] === myFolder) {
const fbPath = joinPath(config.externalSubsRoot, ...parts);
return { virtual: false, fbPath };
}
// Assigned client projects — flattened: Projects/{project}/...
if (parts[0] === 'Projects') {
if (parts.length < 2) return { virtual: true };
const [, projectFolder, ...rest] = parts;
const match = projects.find(p => safeName(p.name, '') === projectFolder);
if (!match) {
const err = new Error('Access denied to this project');
err.status = 403;
throw err;
}
const company = safeName(match.company?.name, '');
const base = joinPath(config.externalClientsRoot, company, 'Projects', projectFolder);
const fbPath = rest.length > 0 ? joinPath(base, ...rest) : base;
return { virtual: false, fbPath };
}
const err = new Error('Access denied');
err.status = 403;
throw err;
}
function buildExternalVirtualEntries(vPath, profile, projects) {
const myFolder = safeName(profile.name, profile.id);
const parts = normalizePath(vPath).split('/').filter(Boolean);
if (parts.length === 0) {
const entries = [{ name: myFolder, type: 'dir', size: 0, mtime: null, path: `/${myFolder}` }];
if (projects.length > 0) entries.push({ name: 'Projects', type: 'dir', size: 0, mtime: null, path: '/Projects' });
return entries;
}
if (parts[0] === 'Projects' && parts.length === 1) {
const seen = new Set();
return projects
.map(p => safeName(p.name, ''))
.filter(name => name && !seen.has(name) && seen.add(name))
.map(name => ({ name, type: 'dir', size: 0, mtime: null, path: `/Projects/${name}` }));
}
return [];
}
function normalizeQuantumItems(data, virtualPath) {
const dirs = (data?.folders || []).map(item => ({ ...item, _type: 'directory' }));
const files = (data?.files || []).map(item => ({ ...item, _type: item.type || 'file' }));
const items = [...dirs, ...files].map(item => ({
name: item.name,
type: (item._type === 'directory' || item.type === 'directory') ? 'dir' : 'file',
size: (item._type === 'directory' || item.type === 'directory') ? 0 : (item.size || 0),
mtime: item.modified || null,
path: joinPath(virtualPath, item.name),
}));
return items.sort((a, b) => {
if (a.type !== b.type) return a.type === 'dir' ? -1 : 1;
if (a.name === '00 Project Files') return -1;
if (b.name === '00 Project Files') return 1;
return a.name.localeCompare(b.name);
});
}
function toListResponse(vPath, entries, { readOnly = false } = {}) {
return {
configured: true,
path: vPath,
canGoUp: vPath !== '/',
parentPath: parentDir(vPath),
entries,
readOnly,
ok: true,
profile: { ...profile, clientCompanies },
};
}
export const config = { api: { bodyParser: false, sizeLimit: '50mb' } };
async function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
req.on('end', () => resolve(Buffer.concat(chunks)));
req.on('error', reject);
function createAdminClient() {
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!supabaseUrl || !serviceKey) throw new Error('Supabase admin env not configured');
return createClient(supabaseUrl, serviceKey, {
auth: { persistSession: false, autoRefreshToken: false },
});
}
function isAlreadyExistsError(error) {
const message = String(error?.message || '').toLowerCase();
return error?.status === 409 || message.includes('exist') || message.includes('conflict');
}
async function ensureDirectory(config, fullPath) {
const parts = normalizePath(fullPath).split('/').filter(Boolean);
let current = '/';
for (const part of parts) {
current = joinPath(current, part);
try {
await fbFetch(config, 'POST', '/api/resources', {
params: { path: current, isDir: 'true' },
});
} catch (error) {
if (!isAlreadyExistsError(error)) throw error;
}
}
}
async function renameDirectory(config, fromPath, toPath) {
const sourcePath = normalizePath(fromPath);
const targetPath = normalizePath(toPath);
if (sourcePath === targetPath) return { renamed: false, skipped: true, path: targetPath };
try {
await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{ fromSource: FB_SOURCE, fromPath: sourcePath, toSource: FB_SOURCE, toPath: targetPath }],
overwrite: false,
}),
});
return { renamed: true, path: targetPath };
} catch (error) {
if (error?.status === 404) {
await ensureDirectory(config, targetPath);
return { renamed: false, ensured: true, path: targetPath };
}
throw error;
}
}
export default async function handler(req, res) {
const action = String(req.query?.action || '').trim();
if (req.method !== 'POST' || ![
'ensure-company-folder',
'ensure-project-folder',
'ensure-request-folder',
'ensure-profile-folder',
'upload-request-file',
'rename-company-folder',
'rename-project-folder',
'rename-profile-folder',
].includes(action)) {
return json(res, 405, { error: 'Method not allowed' });
}
const authHeader = req.headers.authorization || '';
if (!authHeader.startsWith('Bearer ')) {
return json(res, 401, { error: 'Unauthorized' });
}
const config = getConfig();
if (!config.configured) {
return json(res, 200, { ok: false, configured: false, warning: 'FileBrowser is not configured.' });
}
try {
const rawBody = await readBody(req);
const body = (() => {
if (!rawBody.length) return {};
const ct = (req.headers['content-type'] || '').split(';')[0].trim();
if (ct === 'application/json') { try { return JSON.parse(rawBody.toString()); } catch { return {}; } }
const contentType = String(req.headers['content-type'] || '').split(';')[0].trim();
if (contentType === 'application/json') {
try {
return JSON.parse(rawBody.toString());
} catch {
return {};
}
}
return {};
})();
const queryToken = String(req.query?.sb_access_token || body?.sb_access_token || '').trim();
const authHeader = req.headers.authorization || (queryToken ? `Bearer ${queryToken}` : '');
if (!authHeader) return json(res, 401, { error: 'No authorization header' });
const auth = await requirePortalUser(authHeader);
if (!auth.ok) return json(res, auth.status, { error: auth.message });
const config = getConfig();
if (!config.configured || !config.token) {
return json(res, 200, {
configured: false,
error: 'FileBrowser not configured.',
requiredEnv: ['FILEBROWSER_URL', 'FILEBROWSER_TOKEN'],
const admin = createAdminClient();
if (action === 'ensure-company-folder') {
if (auth.profile.role !== 'team') {
return json(res, 403, { error: 'Forbidden' });
}
const companyId = String(body.companyId || '').trim();
if (!companyId) return json(res, 400, { error: 'companyId is required.' });
const { data: company, error: companyError } = await admin
.from('companies')
.select('id, name')
.eq('id', companyId)
.single();
if (companyError || !company) return json(res, 404, { error: 'Company not found.' });
const fullPath = joinPath(config.clientRoot, safeName(company.name, company.id));
await ensureDirectory(config, fullPath);
return json(res, 200, { ok: true, configured: true, path: fullPath });
}
if (action === 'rename-company-folder') {
if (auth.profile.role !== 'team') {
return json(res, 403, { error: 'Forbidden' });
}
const companyId = String(body.companyId || '').trim();
const oldName = safeName(body.oldName, '');
const newName = safeName(body.newName, '');
if (!companyId || !oldName || !newName) return json(res, 400, { error: 'companyId, oldName, and newName are required.' });
const { data: company, error: companyError } = await admin
.from('companies')
.select('id')
.eq('id', companyId)
.single();
if (companyError || !company) return json(res, 404, { error: 'Company not found.' });
const result = await renameDirectory(config, joinPath(config.clientRoot, oldName), joinPath(config.clientRoot, newName));
return json(res, 200, { ok: true, configured: true, ...result });
}
if (action === 'ensure-profile-folder') {
if (auth.profile.role !== 'team') {
return json(res, 403, { error: 'Forbidden' });
}
const profileId = String(body.profileId || '').trim();
if (!profileId) return json(res, 400, { error: 'profileId is required.' });
const { data: profile, error: profileError } = await admin
.from('profiles')
.select('id, name, role')
.eq('id', profileId)
.single();
if (profileError || !profile) return json(res, 404, { error: 'Profile not found.' });
if (profile.role !== 'external') return json(res, 400, { error: 'Only subcontractor folders are supported here.' });
const fullPath = joinPath(config.subsRoot, safeName(profile.name, profile.id));
await ensureDirectory(config, fullPath);
return json(res, 200, { ok: true, configured: true, path: fullPath });
}
if (action === 'rename-profile-folder') {
if (auth.profile.role !== 'team') {
return json(res, 403, { error: 'Forbidden' });
}
const profileId = String(body.profileId || '').trim();
const oldName = safeName(body.oldName, '');
const newName = safeName(body.newName, '');
if (!profileId || !oldName || !newName) return json(res, 400, { error: 'profileId, oldName, and newName are required.' });
const { data: profile, error: profileError } = await admin
.from('profiles')
.select('id, role')
.eq('id', profileId)
.single();
if (profileError || !profile) return json(res, 404, { error: 'Profile not found.' });
if (profile.role !== 'external') return json(res, 400, { error: 'Only subcontractor folders are supported here.' });
const result = await renameDirectory(config, joinPath(config.subsRoot, oldName), joinPath(config.subsRoot, newName));
return json(res, 200, { ok: true, configured: true, ...result });
}
const projectId = String(req.query?.projectId || body.projectId || '').trim();
if (!projectId) return json(res, 400, { error: 'projectId is required.' });
const { data: project, error: projectError } = await admin
.from('projects')
.select('id, name, company_id, company:companies(id, name)')
.eq('id', projectId)
.single();
if (projectError || !project) return json(res, 404, { error: 'Project not found.' });
if (auth.profile.role === 'client') {
const allowedCompanyIds = new Set((auth.profile.clientCompanies || []).map(company => company.id));
if (!allowedCompanyIds.has(project.company_id)) return json(res, 403, { error: 'Forbidden' });
}
const companyName = safeName(project.company?.name, String(project.company_id || 'company'));
const projectName = safeName(project.name, projectId);
if (action === 'rename-project-folder') {
const oldName = safeName(body.oldName, '');
const newName = safeName(body.newName, '');
if (!oldName || !newName) return json(res, 400, { error: 'oldName and newName are required.' });
const result = await renameDirectory(
config,
joinPath(config.clientRoot, companyName, 'Projects', oldName),
joinPath(config.clientRoot, companyName, 'Projects', newName)
);
return json(res, 200, { ok: true, configured: true, ...result });
}
if (action === 'ensure-project-folder') {
const fullPath = joinPath(config.clientRoot, companyName, 'Projects', projectName);
await ensureDirectory(config, fullPath);
for (const folderName of PROJECT_DEFAULT_SUBFOLDERS) {
await ensureDirectory(config, joinPath(fullPath, folderName));
}
return json(res, 200, { ok: true, configured: true, path: fullPath });
}
const taskTitle = safeName(req.query?.taskTitle || body.taskTitle, '');
if (!taskTitle) return json(res, 400, { error: 'taskTitle is required.' });
const fullPath = joinPath(config.clientRoot, companyName, 'Projects', projectName, taskTitle);
if (action === 'upload-request-file') {
const bucket = String(body.bucket || 'submissions').trim();
const storagePath = String(body.storagePath || '').trim();
const fileName = safeName(body.fileName || req.query?.fileName || req.headers['x-file-name'], '');
if (!storagePath) return json(res, 400, { error: 'storagePath is required.' });
if (!fileName) return json(res, 400, { error: 'fileName is required.' });
const surveyPath = joinPath(fullPath, 'Survey');
await ensureDirectory(config, surveyPath);
const { data: downloadedFile, error: downloadError } = await admin.storage.from(bucket).download(storagePath);
if (downloadError || !downloadedFile) {
return json(res, 500, { error: downloadError?.message || 'Failed to download request file from storage.' });
}
const fileBuffer = Buffer.from(await downloadedFile.arrayBuffer());
const uploadUrl = `${config.url}/api/resources?source=${FB_SOURCE}&path=${encodeURIComponent(joinPath(surveyPath, fileName))}&override=true`;
const contentType = String(downloadedFile.type || '').trim() || 'application/octet-stream';
const response = await fetch(uploadUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${getToken(config)}`,
'Content-Type': contentType,
},
body: fileBuffer,
});
}
const action = req.query.action || (req.method === 'GET' ? 'list' : '');
const requestedPath = req.query.path || body?.path || '/';
let externalProjects = [];
if (auth.profile.role === 'external') {
externalProjects = await getExternalProjects(auth.callerClient, auth.profile.id);
}
function toFbPath(vPath = requestedPath) {
if (auth.profile.role === 'external') {
return resolveExternalPath(config, normalizePath(vPath), auth.profile, externalProjects);
if (!response.ok) {
const text = await response.text().catch(() => '');
return json(res, response.status, { error: text || `Upload failed (${response.status})` });
}
if (auth.profile.role === 'client') {
return resolveClientPath(config, normalizePath(vPath), auth.profile.clientCompanies);
}
const root = resolveUserRoot(config, auth.profile);
return { virtual: false, fbPath: joinPath(root, normalizePath(vPath)) };
return json(res, 200, { ok: true, configured: true, path: joinPath(surveyPath, fileName) });
}
if (req.method === 'GET' && action === 'config') {
return json(res, 200, { configured: true, role: auth.profile.role, url: config.url });
await ensureDirectory(config, fullPath);
for (const folderName of REQUEST_DEFAULT_SUBFOLDERS) {
await ensureDirectory(config, joinPath(fullPath, folderName));
}
if (req.method === 'GET' && action === 'list') {
const vPath = normalizePath(requestedPath);
if (auth.profile.role === 'external') {
const resolved = resolveExternalPath(config, vPath, auth.profile, externalProjects);
if (resolved.virtual) {
return json(res, 200, toListResponse(vPath, buildExternalVirtualEntries(vPath, auth.profile, externalProjects), { readOnly: true }));
}
const data = await fbFetch(config, 'GET', '/api/resources', { params: { path: resolved.fbPath } });
return json(res, 200, toListResponse(vPath, normalizeQuantumItems(data, vPath)));
}
if (auth.profile.role === 'client') {
const resolved = resolveClientPath(config, vPath, auth.profile.clientCompanies);
if (resolved.virtual) {
return json(res, 200, toListResponse(vPath, buildClientVirtualEntries(auth.profile.clientCompanies)));
}
const data = await fbFetch(config, 'GET', '/api/resources', { params: { path: resolved.fbPath } });
return json(res, 200, toListResponse(vPath, normalizeQuantumItems(data, vPath)));
}
const root = resolveUserRoot(config, auth.profile);
const fbPath = joinPath(root, vPath);
const data = await fbFetch(config, 'GET', '/api/resources', { params: { path: fbPath } });
return json(res, 200, toListResponse(vPath, normalizeQuantumItems(data, vPath)));
}
if (req.method === 'GET' && action === 'download') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot download virtual directory' });
const token = await getToken(config);
const downloadUrl = `${config.url}/api/resources/download?source=${FB_SOURCE}&file=${encodeURIComponent(resolved.fbPath)}`;
return json(res, 200, { url: downloadUrl, token });
}
if (req.method === 'GET' && action === 'download-blob') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot download virtual directory' });
const token = await getToken(config);
const downloadUrl = `${config.url}/api/resources/download?source=${FB_SOURCE}&file=${encodeURIComponent(resolved.fbPath)}&auth=${encodeURIComponent(token)}`;
let upstream = await fetch(downloadUrl);
if (upstream.status === 401) {
const fresh = await getToken(config, true);
const retryUrl = `${config.url}/api/resources/download?source=${FB_SOURCE}&file=${encodeURIComponent(resolved.fbPath)}&auth=${encodeURIComponent(fresh)}`;
upstream = await fetch(retryUrl);
}
if (!upstream.ok) {
const text = await upstream.text();
return json(res, upstream.status, { error: text || `Download failed (${upstream.status})` });
}
res.status(upstream.status);
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Content-Type', upstream.headers.get('content-type') || 'application/octet-stream');
res.setHeader('Content-Disposition', upstream.headers.get('content-disposition') || `attachment; filename="${basename(resolved.fbPath) || 'download'}"`);
const arrayBuffer = await upstream.arrayBuffer();
return res.send(Buffer.from(arrayBuffer));
}
if (req.method === 'POST' && action === 'upload-token') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot upload to virtual directory' });
const token = await getToken(config);
return json(res, 200, { token, url: config.url, fbPath: resolved.fbPath });
}
if (req.method === 'POST' && action === 'upload') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot upload to virtual directory' });
const contentType = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();
const uploadUrl = `${config.url}/api/resources?source=${FB_SOURCE}&path=${encodeURIComponent(resolved.fbPath)}&override=true`;
let token = await getToken(config);
let upRes = await fetch(uploadUrl, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': contentType }, body: rawBody });
if (upRes.status === 401) {
token = await getToken(config, true);
upRes = await fetch(uploadUrl, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': contentType }, body: rawBody });
}
if (!upRes.ok) { const t = await upRes.text(); return json(res, upRes.status, { error: t || `Upload failed (${upRes.status})` }); }
return json(res, 200, { success: true });
}
if (req.method === 'POST' && action === 'mkdir') {
const folderName = safeName(body?.name, '');
if (!folderName) return json(res, 400, { error: 'Folder name required' });
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot create folder in virtual directory' });
await fbFetch(config, 'POST', '/api/resources', {
params: { path: joinPath(resolved.fbPath, folderName), isDir: 'true' },
});
return json(res, 200, { success: true });
}
if (req.method === 'DELETE' && action === 'delete') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot delete virtual directory' });
if (!basename(resolved.fbPath)) return json(res, 400, { error: 'Cannot delete root' });
await fbFetch(config, 'DELETE', '/api/resources', { params: { path: resolved.fbPath } });
return json(res, 200, { success: true });
}
if (req.method === 'POST' && action === 'rename') {
const newName = safeName(body?.name, '');
if (!newName) return json(res, 400, { error: 'New name required' });
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot rename virtual directory' });
const newFbPath = joinPath(parentDir(resolved.fbPath), newName);
await fbFetch(config, 'PATCH', '/api/resources', {
params: {},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{ fromSource: FB_SOURCE, fromPath: resolved.fbPath, toSource: FB_SOURCE, toPath: newFbPath }],
overwrite: false,
}),
});
return json(res, 200, { success: true });
}
if (req.method === 'POST' && action === 'archive-move') {
// Moves srcPath into dstParentPath. If destination already exists, merges contents recursively.
const srcVPath = body?.srcPath;
const dstParentVPath = body?.dstParentPath;
if (!srcVPath || !dstParentVPath) return json(res, 400, { error: 'srcPath and dstParentPath required' });
const resolvedSrc = toFbPath(srcVPath);
const resolvedDstParent = toFbPath(dstParentVPath);
if (resolvedSrc.virtual || resolvedDstParent.virtual) return json(res, 400, { error: 'Cannot operate on virtual directories' });
async function fbExists(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(path) {
await fbFetch(config, 'POST', '/api/resources', { params: { path, isDir: 'true' } }).catch(() => {});
}
async function mergeMove(fbSrc, fbDstParent) {
const name = basename(fbSrc);
const fbDst = joinPath(fbDstParent, name);
const destExists = await fbExists(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(fbDst);
for (const dir of dirs) await mergeMove(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(() => {});
}
}
await mergeMove(resolvedSrc.fbPath, resolvedDstParent.fbPath);
return json(res, 200, { success: true });
}
if (req.method === 'POST' && action === 'move') {
const srcPath = body?.srcPath;
const dstPath = body?.dstPath;
const mode = body?.mode === 'copy' ? 'copy' : 'move';
if (!srcPath || !dstPath) return json(res, 400, { error: 'srcPath and dstPath required' });
const resolvedSrc = toFbPath(srcPath);
const resolvedDst = toFbPath(dstPath);
if (resolvedSrc.virtual || resolvedDst.virtual) return json(res, 400, { error: 'Cannot move virtual directories' });
const itemName = basename(resolvedSrc.fbPath);
const newFbPath = joinPath(resolvedDst.fbPath, itemName);
await fbFetch(config, 'PATCH', '/api/resources', {
params: {},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: mode,
items: [{ fromSource: FB_SOURCE, fromPath: resolvedSrc.fbPath, toSource: FB_SOURCE, toPath: newFbPath }],
overwrite: false,
}),
});
return json(res, 200, { success: true });
}
return json(res, 405, { error: 'Method not allowed' });
return json(res, 200, { ok: true, configured: true, path: fullPath });
} catch (error) {
return json(res, error.status || 500, { error: error.message || 'Unexpected error' });
return json(res, error?.status || 500, { error: error?.message || 'Failed to ensure request folder.' });
}
}
-144
View File
@@ -1,144 +0,0 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'srv';
function normalizePath(path) {
const parts = String(path || '/').trim().split('/').filter(p => p && p !== '.' && p !== '..');
return `/${parts.join('/')}`;
}
function joinPath(...parts) { return normalizePath(parts.join('/')); }
function safeName(v) {
return String(v || '').trim()
.replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-')
.replace(/\s+/g, ' ')
.replace(/^-+|-+$/g, '');
}
function getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
adminUser: process.env.FILEBROWSER_ADMIN_USER || '',
adminPass: process.env.FILEBROWSER_ADMIN_PASS || '',
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
configured: Boolean(url),
};
}
let _cachedToken = '';
let _cachedTokenTs = 0;
async function getToken(config) {
if (config.token) return config.token;
const now = Date.now();
if (_cachedToken && now - _cachedTokenTs < 25 * 60 * 1000) return _cachedToken;
const res = await fetch(`${config.url}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: config.adminUser, password: config.adminPass }),
});
const data = await res.json().catch(() => ({}));
const tok = data?.token || data?.access_token || '';
if (tok) { _cachedToken = tok; _cachedTokenTs = now; }
return tok;
}
async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) {
const token = await getToken(config);
const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString();
const res = await fetch(`${config.url}${endpoint}?${qs}`, {
method, headers: { Authorization: `Bearer ${token}`, ...headers }, body,
});
if (res.status === 401) {
_cachedToken = '';
const fresh = await getToken(config);
return fetch(`${config.url}${endpoint}?${qs}`, {
method, headers: { Authorization: `Bearer ${fresh}`, ...headers }, body,
});
}
return res;
}
async function listDir(config, path) {
const res = await fbFetch(config, 'GET', '/api/resources', { params: { path } });
if (!res.ok) return null;
const data = await res.json().catch(() => null);
const entries = Array.isArray(data?.entries) ? data.entries
: [...(data?.folders ?? []), ...(data?.files ?? [])];
return entries;
}
async function renameDir(config, fromPath, toPath) {
const res = await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'rename', items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }], overwrite: true }),
});
return res.ok;
}
async function deleteDir(config, path) {
const res = await fbFetch(config, 'DELETE', '/api/resources', { params: { path } });
return res.ok;
}
export default async function handler(req, res) {
if (req.method !== 'POST') return res.status(405).json({ error: 'POST only' });
const authHeader = req.headers.authorization || '';
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || '';
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const supabaseKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY;
const isServiceRole = serviceKey && authHeader === `Bearer ${serviceKey}`;
if (!isServiceRole) {
const sb = createClient(supabaseUrl, supabaseKey, {
auth: { persistSession: false },
global: { headers: { Authorization: authHeader } },
});
const { data: { user } } = await sb.auth.getUser();
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { data: profile } = await sb.from('profiles').select('role').eq('id', user.id).single();
if (profile?.role !== 'team') return res.status(403).json({ error: 'Team only' });
}
const sb = createClient(supabaseUrl, serviceKey || supabaseKey, { auth: { persistSession: false } });
const config = getConfig();
if (!config.configured) return res.status(500).json({ error: 'FileBrowser not configured' });
const { data: tasks, error } = await sb
.from('tasks')
.select('title, projects!project_id(name, companies!company_id(name))');
if (error) return res.status(500).json({ error: error.message });
const log = [];
let migrated = 0, skipped = 0, failed = 0;
for (const task of tasks || []) {
const co = safeName(task.projects?.companies?.name || '');
const pr = safeName(task.projects?.name || '');
const tk = safeName(task.title || '');
if (!co || !pr || !tk) { skipped++; continue; }
const base = joinPath(config.clientRoot, co, 'Projects', pr, tk);
const src = `${base}/Old Book`;
const dst = `${base}/Old Books`;
const srcItems = await listDir(config, src);
if (srcItems === null) { skipped++; continue; }
if (srcItems.length === 0) {
const ok = await deleteDir(config, src);
ok ? (migrated++, log.push(`deleted empty: ${src}`)) : (failed++, log.push(`delete-fail: ${src}`));
} else {
for (const item of srcItems) {
await renameDir(config, `${src}/${item.name}`, `${dst}/${item.name}`);
}
const ok = await deleteDir(config, src);
ok ? (migrated++, log.push(`merged+deleted: ${src}`)) : (failed++, log.push(`merge-fail: ${src}`));
}
}
return res.status(200).json({ migrated, skipped, failed, log });
}
-111
View File
@@ -1,111 +0,0 @@
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 parentDir(path) {
const parts = normalizePath(path).split('/').filter(Boolean);
parts.pop();
return `/${parts.join('/')}`;
}
function safeName(value) {
return String(value || '')
.trim()
.replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-')
.replace(/\s+/g, ' ')
.replace(/^-+|-+$/g, '');
}
function getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
configured: Boolean(url),
};
}
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;
}
}
async function mkdir(config, parentPath, name) {
const folderPath = joinPath(parentPath, safeName(name));
await fbFetch(config, 'POST', '/api/resources', {
params: { path: folderPath, isDir: 'true' },
}).catch(() => {});
}
async function renameFolder(config, oldName, newName) {
const oldSafe = safeName(oldName);
const newSafe = safeName(newName);
if (!oldSafe || !newSafe || oldSafe === newSafe) return;
const fromPath = joinPath(config.clientRoot, oldSafe);
const toPath = joinPath(config.clientRoot, newSafe);
await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }],
overwrite: false,
}),
}).catch(() => {});
}
export default async function handler(req, res) {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (secret) {
const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' });
}
const { type, record, old_record } = req.body || {};
if (!record?.name) return res.status(200).json({ ok: true, skipped: true });
const config = getConfig();
if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' });
const clientRoot = config.clientRoot;
const clientsParent = parentDir(clientRoot);
const clientsDirName = clientRoot.split('/').filter(Boolean).pop();
// Ensure parent Clients dir exists
await mkdir(config, clientsParent, clientsDirName);
if (type === 'UPDATE' && old_record?.name && old_record.name !== record.name) {
await renameFolder(config, old_record.name, record.name);
}
// Always ensure folder for current name exists (idempotent)
await mkdir(config, clientRoot, record.name);
res.status(200).json({ ok: true, type, name: record.name });
}
-117
View File
@@ -1,117 +0,0 @@
const FB_SOURCE = 'srv';
const MEMBER_ROLES = new Set(['team', 'external']);
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 parentDir(path) {
const parts = normalizePath(path).split('/').filter(Boolean);
parts.pop();
return `/${parts.join('/')}`;
}
function safeName(value) {
return String(value || '')
.trim()
.replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-')
.replace(/\s+/g, ' ')
.replace(/^-+|-+$/g, '');
}
function getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
membersRoot: normalizePath(process.env.FILEBROWSER_MEMBERS_ROOT || '/Team'),
configured: Boolean(url),
};
}
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;
}
}
async function mkdir(config, parentPath, name) {
const safe = safeName(name);
if (!safe) return;
await fbFetch(config, 'POST', '/api/resources', {
params: { path: joinPath(parentPath, safe), isDir: 'true' },
}).catch(() => {});
}
async function renameFolder(config, root, oldName, newName) {
const oldSafe = safeName(oldName);
const newSafe = safeName(newName);
if (!oldSafe || !newSafe || oldSafe === newSafe) return;
await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{
fromSource: FB_SOURCE, fromPath: joinPath(root, oldSafe),
toSource: FB_SOURCE, toPath: joinPath(root, newSafe),
}],
overwrite: false,
}),
}).catch(() => {});
}
export default async function handler(req, res) {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (secret) {
const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' });
}
const { type, record, old_record } = req.body || {};
// Only process team and external roles
if (!MEMBER_ROLES.has(record?.role)) return res.status(200).json({ ok: true, skipped: true });
if (!record?.name) return res.status(200).json({ ok: true, skipped: 'no name' });
const config = getConfig();
if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' });
const membersRoot = config.membersRoot;
const membersParent = parentDir(membersRoot);
const membersDirName = membersRoot.split('/').filter(Boolean).pop();
// Ensure /fourgebranding/team dir exists
await mkdir(config, membersParent, membersDirName);
if (type === 'UPDATE' && old_record?.name && old_record.name !== record.name) {
await renameFolder(config, membersRoot, old_record.name, record.name);
}
// Ensure folder for current name exists
await mkdir(config, membersRoot, record.name);
res.status(200).json({ ok: true, type, name: record.name, role: record.role });
}
-124
View File
@@ -1,124 +0,0 @@
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 getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
configured: Boolean(url),
};
}
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;
}
}
async function mkdir(config, path) {
await fbFetch(config, 'POST', '/api/resources', {
params: { path, isDir: 'true' },
}).catch(() => {});
}
async function renameFolder(config, fromPath, toPath) {
await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }],
overwrite: false,
}),
}).catch(() => {});
}
async function requireTeamUser(authHeader) {
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const supabaseAnonKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY;
if (!supabaseUrl || !supabaseAnonKey) return false;
const client = createClient(supabaseUrl, supabaseAnonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { headers: { Authorization: authHeader } },
});
const { data: userData } = await client.auth.getUser();
if (!userData?.user) return false;
const { data: profile } = await client.from('profiles').select('role').eq('id', userData.user.id).single();
return profile?.role === 'team';
}
export default async function handler(req, res) {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
const authHeader = req.headers.authorization || '';
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (authHeader.startsWith('Bearer ')) {
const isTeam = await requireTeamUser(authHeader);
if (!isTeam) return res.status(403).json({ error: 'Team members only' });
} else if (secret) {
const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' });
}
const { type, record, old_record } = req.body || {};
if (!record?.name || !record?.company_name) return res.status(200).json({ ok: true, skipped: 'missing name or company_name' });
const config = getConfig();
if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' });
const companyDir = joinPath(config.clientRoot, safeName(record.company_name));
const projectsDir = joinPath(companyDir, 'Projects');
// Ensure Clients/{company}/Projects/ exists
await mkdir(config, companyDir);
await mkdir(config, projectsDir);
if (type === 'UPDATE' && old_record?.name && old_record.name !== record.name) {
const oldPath = joinPath(projectsDir, safeName(old_record.name));
const newPath = joinPath(projectsDir, safeName(record.name));
await renameFolder(config, oldPath, newPath);
}
// Ensure folder for current project name exists
const projectDir = joinPath(projectsDir, safeName(record.name));
await mkdir(config, projectDir);
await mkdir(config, joinPath(projectDir, '00 Project Files'));
res.status(200).json({ ok: true, type, company: record.company_name, project: record.name });
}
-106
View File
@@ -1,106 +0,0 @@
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 getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
clientRoot: normalizePath(process.env.FILEBROWSER_CLIENT_ROOT || '/Clients'),
configured: Boolean(url),
};
}
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;
}
}
async function mkdir(config, path) {
await fbFetch(config, 'POST', '/api/resources', {
params: { path, isDir: 'true' },
}).catch(() => {});
}
async function renameFolder(config, fromPath, toPath) {
await fbFetch(config, 'PATCH', '/api/resources', {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'rename',
items: [{ fromSource: FB_SOURCE, fromPath, toSource: FB_SOURCE, toPath }],
overwrite: false,
}),
}).catch(() => {});
}
export default async function handler(req, res) {
if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' });
const secret = process.env.SUPABASE_WEBHOOK_SECRET;
if (secret) {
const incoming = req.headers['x-webhook-secret'] || req.headers['x-supabase-webhook-secret'] || '';
if (incoming.trim() !== secret.trim()) return res.status(401).json({ error: 'Unauthorized' });
}
const { type, record, old_record } = req.body || {};
if (!record?.title || !record?.project_name || !record?.company_name) {
return res.status(200).json({ ok: true, skipped: 'missing title, project_name, or company_name' });
}
const config = getConfig();
if (!config.configured || !config.token) return res.status(200).json({ ok: true, skipped: 'not configured' });
const projectDir = joinPath(config.clientRoot, safeName(record.company_name), 'Projects', safeName(record.project_name));
// Ensure parent dirs exist
await mkdir(config, joinPath(config.clientRoot, safeName(record.company_name)));
await mkdir(config, joinPath(config.clientRoot, safeName(record.company_name), 'Projects'));
await mkdir(config, projectDir);
if (type === 'UPDATE' && old_record?.title && old_record.title !== record.title) {
const oldPath = joinPath(projectDir, safeName(old_record.title));
const newPath = joinPath(projectDir, safeName(record.title));
await renameFolder(config, oldPath, newPath);
}
const taskDir = joinPath(projectDir, safeName(record.title));
await mkdir(config, taskDir);
await mkdir(config, joinPath(taskDir, 'Working Files'));
await mkdir(config, joinPath(taskDir, 'Request Info'));
await mkdir(config, joinPath(taskDir, 'Old Books'));
res.status(200).json({ ok: true, type, company: record.company_name, project: record.project_name, task: record.title });
}