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:
@@ -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 });
|
||||
}
|
||||
Reference in New Issue
Block a user