Session 2026-05-20: UI fixes, invoice filtering, file browser, request approvals, sub invoice task scope

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Krao Hasanee
2026-05-20 21:32:55 -04:00
parent ff159c5937
commit 565d2ed4bc
34 changed files with 3384 additions and 1161 deletions
+179
View File
@@ -0,0 +1,179 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'files';
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 || '/fourgebranding/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(() => {});
}
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' });
// 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 });
}
const results = { processed: 0, skipped: 0, errors: [] };
for (const group of groups.values()) {
if (group.files.length === 0) { results.skipped++; continue; }
const revFolder = `R${String(group.versionNumber).padStart(2, '0')}`;
const companyDir = joinPath(config.clientRoot, safeName(group.companyName));
const projectDir = joinPath(companyDir, 'Projects', safeName(group.projectName));
const taskDir = joinPath(projectDir, safeName(group.taskTitle));
const requestInfoDir = joinPath(taskDir, 'Request Info');
const revDir = joinPath(requestInfoDir, revFolder);
// Ensure all parent dirs exist
await mkdir(config, companyDir);
await mkdir(config, joinPath(companyDir, 'Projects'));
await mkdir(config, projectDir);
await mkdir(config, taskDir);
await mkdir(config, requestInfoDir);
await mkdir(config, revDir);
for (const file of group.files) {
try {
// Get signed URL from Supabase Storage
const { data: signed, error: signedError } = await admin.storage
.from('submissions')
.createSignedUrl(file.storage_path, 60);
if (signedError || !signed?.signedUrl) {
results.errors.push(`signed url failed: ${file.storage_path}`);
continue;
}
// Download file from Supabase Storage
const fileRes = await fetch(signed.signedUrl);
if (!fileRes.ok) {
results.errors.push(`download failed: ${file.name}`);
continue;
}
const fileBuffer = await fileRes.arrayBuffer();
// Upload to FileBrowser
const fbFilePath = joinPath(revDir, file.name);
await fbFetch(config, 'POST', '/api/resources', {
params: { path: fbFilePath, override: 'true' },
headers: { 'Content-Type': 'application/octet-stream' },
body: fileBuffer,
});
results.processed++;
} catch (err) {
results.errors.push(`${file.name}: ${err.message}`);
}
}
}
return json(res, 200, { ok: true, ...results });
}
+206
View File
@@ -0,0 +1,206 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'files';
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 || '/fourgebranding/Clients'),
archiveRoot: normalizePath(process.env.FILEBROWSER_ARCHIVE_ROOT || '/fourgebranding/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' });
const authHeader = req.headers.authorization || '';
if (!authHeader.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' });
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const anonKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
const callerClient = createClient(supabaseUrl, anonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { headers: { Authorization: authHeader } },
});
const { data: userData } = await callerClient.auth.getUser();
if (!userData?.user) return res.status(401).json({ error: 'Unauthorized' });
const { data: profile } = await callerClient.from('profiles').select('id, role').eq('id', userData.user.id).single();
if (!profile || !['team', 'client'].includes(profile.role)) return res.status(403).json({ error: 'Forbidden' });
const projectId = req.query.id;
if (!projectId) return res.status(400).json({ error: 'Project ID required' });
const admin = createClient(supabaseUrl, serviceKey, {
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);
if (taskIds.length) {
const { data: subs } = await admin.from('submissions').select('id').in('task_id', taskIds);
const subIds = (subs || []).map(s => s.id);
if (subIds.length) {
const { data: subFiles } = await admin.from('submission_files').select('storage_path').in('submission_id', subIds);
const subPaths = (subFiles || []).map(f => f.storage_path).filter(Boolean);
if (subPaths.length) await admin.storage.from('submissions').remove(subPaths);
const { data: deliveries } = await admin.from('deliveries').select('id').in('submission_id', subIds);
const delIds = (deliveries || []).map(d => d.id);
if (delIds.length) {
const { data: delFiles } = await admin.from('delivery_files').select('storage_path').in('delivery_id', delIds);
const delPaths = (delFiles || []).map(f => f.storage_path).filter(Boolean);
if (delPaths.length) await admin.storage.from('deliveries').remove(delPaths);
}
}
}
// 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 });
}
+192
View File
@@ -0,0 +1,192 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'files';
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 || '/fourgebranding/Clients'),
archiveRoot: normalizePath(process.env.FILEBROWSER_ARCHIVE_ROOT || '/fourgebranding/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' });
const authHeader = req.headers.authorization || '';
if (!authHeader.startsWith('Bearer ')) return res.status(401).json({ error: 'Unauthorized' });
const supabaseUrl = process.env.VITE_SUPABASE_URL || process.env.SUPABASE_URL;
const anonKey = process.env.VITE_SUPABASE_ANON_KEY || process.env.SUPABASE_ANON_KEY;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
const callerClient = createClient(supabaseUrl, anonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { headers: { Authorization: authHeader } },
});
const { data: userData } = await callerClient.auth.getUser();
if (!userData?.user) return res.status(401).json({ error: 'Unauthorized' });
const { data: profile } = await callerClient.from('profiles').select('id, role').eq('id', userData.user.id).single();
if (!profile || !['team', 'client'].includes(profile.role)) return res.status(403).json({ error: 'Forbidden' });
const taskId = req.query.id;
if (!taskId) return res.status(400).json({ error: 'Task ID required' });
const admin = createClient(supabaseUrl, serviceKey, {
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();
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);
if (subIds.length) {
const { data: subFiles } = await admin.from('submission_files').select('storage_path').in('submission_id', subIds);
const subPaths = (subFiles || []).map(f => f.storage_path).filter(Boolean);
if (subPaths.length) await admin.storage.from('submissions').remove(subPaths);
const { data: deliveries } = await admin.from('deliveries').select('id').in('submission_id', subIds);
const delIds = (deliveries || []).map(d => d.id);
if (delIds.length) {
const { data: delFiles } = await admin.from('delivery_files').select('storage_path').in('delivery_id', delIds);
const delPaths = (delFiles || []).map(f => f.storage_path).filter(Boolean);
if (delPaths.length) await admin.storage.from('deliveries').remove(delPaths);
}
}
// 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 });
}
+461
View File
@@ -0,0 +1,461 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'files';
function json(res, status, body) {
res.status(status).setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.send(JSON.stringify(body));
}
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: path traversal not allowed');
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 basename(path) {
const parts = normalizePath(path).split('/').filter(Boolean);
return parts[parts.length - 1] || '';
}
function safeName(value, fallback = '') {
const cleaned = String(value || '')
.trim()
.replace(/[\\/:*?"<>|#%{}^~[\]`]+/g, '-')
.replace(/\s+/g, ' ')
.replace(/^-+|-+$/g, '');
return cleaned || fallback;
}
function getConfig() {
const url = String(process.env.FILEBROWSER_URL || '').trim().replace(/\/+$/, '');
return {
url,
token: process.env.FILEBROWSER_TOKEN || '',
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'),
configured: Boolean(url),
};
}
function getToken(config) {
if (!config.token) throw new Error('FILEBROWSER_TOKEN not configured');
return config.token;
}
async function fbFetch(config, method, endpoint, { params = {}, headers = {}, body } = {}) {
const token = getToken(config);
const qs = new URLSearchParams({ source: FB_SOURCE, ...params }).toString();
const url = `${config.url}${endpoint}?${qs}`;
const res = await fetch(url, {
method,
headers: { Authorization: `Bearer ${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 createCallerClient(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) throw new Error('Supabase env not configured');
return createClient(supabaseUrl, supabaseAnonKey, {
auth: { persistSession: false, autoRefreshToken: false },
global: { headers: { Authorization: authHeader } },
});
}
async function requirePortalUser(authHeader) {
const callerClient = await createCallerClient(authHeader);
const { data: userData, error: userError } = await callerClient.auth.getUser();
if (userError || !userData?.user) return { ok: false, status: 401, message: 'Unauthorized' };
const { data: profile, error: profileError } = await callerClient
.from('profiles')
.select('id, name, 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)) {
return { ok: false, status: 403, message: 'Forbidden' };
}
// Mirror AuthContext: load all companies (FK + company_members)
let clientCompanies = [];
if (profile.role === 'client') {
const seen = new Set();
if (profile.company?.id) {
clientCompanies.push(profile.company);
seen.add(profile.company.id);
}
const { data: memberships } = await callerClient
.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);
}
}
}
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,
};
}
export default async function handler(req, res) {
try {
const authHeader = req.headers.authorization || '';
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 action = req.query.action || (req.method === 'GET' ? 'list' : '');
const requestedPath = req.query.path || req.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 (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)) };
}
if (req.method === 'GET' && action === 'config') {
return json(res, 200, { configured: true, role: auth.profile.role, url: config.url });
}
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 = 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 === 'POST' && action === 'upload-token') {
const resolved = toFbPath();
if (resolved.virtual) return json(res, 400, { error: 'Cannot upload to virtual directory' });
const token = getToken(config);
return json(res, 200, { token, url: config.url, fbPath: resolved.fbPath });
}
if (req.method === 'POST' && action === 'mkdir') {
const folderName = safeName(req.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(req.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 = req.body?.srcPath;
const dstParentVPath = req.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 = req.body?.srcPath;
const dstPath = req.body?.dstPath;
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: 'move',
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' });
} catch (error) {
return json(res, error.status || 500, { error: error.message || 'Unexpected error' });
}
}
+111
View File
@@ -0,0 +1,111 @@
const FB_SOURCE = 'files';
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 || '/fourgebranding/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
@@ -0,0 +1,117 @@
const FB_SOURCE = 'files';
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 || '/fourgebranding/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
@@ -0,0 +1,124 @@
import { createClient } from '@supabase/supabase-js';
const FB_SOURCE = 'files';
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 || '/fourgebranding/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 });
}
+105
View File
@@ -0,0 +1,105 @@
const FB_SOURCE = 'files';
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 || '/fourgebranding/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'));
res.status(200).json({ ok: true, type, company: record.company_name, project: record.project_name, task: record.title });
}