feat: upload any validated file to the asset library
Activos now supports multi-file/folder upload to private Storage (PDF, Excel, CSV, images, ZIP, etc.) with per-tenant folders. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
77
src/app/api/assets/download/route.ts
Normal file
77
src/app/api/assets/download/route.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import { ASSETS_BUCKET, serviceSupabase } from '@/lib/assets';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** GET ?id= — signed download URL (60s) */
|
||||
export async function GET(req: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
if (!ctx.tenantId) {
|
||||
return NextResponse.json({ error: 'Selecciona un cliente' }, { status: 400 });
|
||||
}
|
||||
|
||||
const id = req.nextUrl.searchParams.get('id')?.trim();
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: 'id requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const headers = serviceHeaders();
|
||||
const svc = serviceSupabase();
|
||||
if (!headers || !svc) {
|
||||
return NextResponse.json({ error: 'no service role' }, { status: 503 });
|
||||
}
|
||||
|
||||
// Agency can download any tenant's file when in context; verify tenant match
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/asset_files?id=eq.${encodeURIComponent(id)}&select=id,tenant_id,storage_path,file_name,mime_type`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({ error: await r.text() }, { status: 500 });
|
||||
}
|
||||
const rows = await r.json();
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return NextResponse.json({ error: 'No encontrado' }, { status: 404 });
|
||||
}
|
||||
|
||||
const agency = isAgencyRole(userRole(user));
|
||||
if (!agency && row.tenant_id !== ctx.tenantId) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
if (agency && row.tenant_id !== ctx.tenantId) {
|
||||
return NextResponse.json({ error: 'Cambia al tenant del archivo' }, { status: 403 });
|
||||
}
|
||||
|
||||
const signed = await svc.storage
|
||||
.from(ASSETS_BUCKET)
|
||||
.createSignedUrl(row.storage_path, 120);
|
||||
if (signed.error || !signed.data?.signedUrl) {
|
||||
return NextResponse.json(
|
||||
{ error: signed.error?.message || 'No se pudo firmar URL' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
url: signed.data.signedUrl,
|
||||
fileName: row.file_name,
|
||||
mimeType: row.mime_type,
|
||||
});
|
||||
}
|
||||
229
src/app/api/assets/route.ts
Normal file
229
src/app/api/assets/route.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import {
|
||||
ASSETS_BUCKET,
|
||||
MAX_ASSET_BYTES,
|
||||
ensureAssetsBucket,
|
||||
sanitizeFileName,
|
||||
sanitizeFolder,
|
||||
serviceSupabase,
|
||||
} from '@/lib/assets';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
async function gate() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
||||
}
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
if (ctx.portfolioWide || !ctx.tenantId) {
|
||||
return {
|
||||
error: NextResponse.json(
|
||||
{ error: 'Selecciona un cliente en Contexto antes de gestionar activos.' },
|
||||
{ status: 400 }
|
||||
),
|
||||
};
|
||||
}
|
||||
return { user, ctx, agency: isAgencyRole(userRole(user)) };
|
||||
}
|
||||
|
||||
/** GET — list approved files for active tenant */
|
||||
export async function GET() {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { ctx, agency } = g as Awaited<ReturnType<typeof gate>> & {
|
||||
ctx: { tenantId: string };
|
||||
agency: boolean;
|
||||
};
|
||||
|
||||
const headers = serviceHeaders();
|
||||
if (agency && headers) {
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/asset_files?tenant_id=eq.${encodeURIComponent(ctx.tenantId!)}&status=eq.approved&select=*&order=created_at.desc`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) {
|
||||
const msg = await r.text();
|
||||
return NextResponse.json({
|
||||
assets: [],
|
||||
warning: msg.includes('does not exist')
|
||||
? 'Aplicar sql/asset_files.sql'
|
||||
: msg.slice(0, 200),
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ assets: await r.json() });
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
const { data, error } = await supabase
|
||||
.from('asset_files')
|
||||
.select('*')
|
||||
.eq('status', 'approved')
|
||||
.order('created_at', { ascending: false });
|
||||
if (error) {
|
||||
return NextResponse.json({
|
||||
assets: [],
|
||||
warning: error.message,
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ assets: data ?? [] });
|
||||
}
|
||||
|
||||
/** POST multipart: files[] + optional folder */
|
||||
export async function POST(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { user, ctx } = g as Awaited<ReturnType<typeof gate>> & {
|
||||
user: { id: string };
|
||||
ctx: { tenantId: string };
|
||||
};
|
||||
|
||||
const bucketOk = await ensureAssetsBucket();
|
||||
if (!bucketOk.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `Storage bucket: ${bucketOk.error}` },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const svc = serviceSupabase();
|
||||
const headers = serviceHeaders();
|
||||
if (!svc || !headers) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const form = await req.formData();
|
||||
const folder = sanitizeFolder(String(form.get('folder') || ''));
|
||||
const files = form.getAll('files').filter((f): f is File => f instanceof File);
|
||||
|
||||
if (!files.length) {
|
||||
return NextResponse.json({ error: 'Ningún archivo' }, { status: 400 });
|
||||
}
|
||||
|
||||
const uploaded: unknown[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (file.size <= 0) {
|
||||
errors.push(`${file.name}: vacío`);
|
||||
continue;
|
||||
}
|
||||
if (file.size > MAX_ASSET_BYTES) {
|
||||
errors.push(`${file.name}: supera 80 MB`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const safeName = sanitizeFileName(file.name);
|
||||
const id = randomUUID();
|
||||
const pathParts = [ctx.tenantId!, folder, `${id}_${safeName}`].filter(
|
||||
Boolean
|
||||
);
|
||||
const storagePath = pathParts.join('/');
|
||||
const buf = Buffer.from(await file.arrayBuffer());
|
||||
const sha256 = createHash('sha256').update(buf).digest('hex');
|
||||
|
||||
const up = await svc.storage.from(ASSETS_BUCKET).upload(storagePath, buf, {
|
||||
contentType: file.type || 'application/octet-stream',
|
||||
upsert: false,
|
||||
});
|
||||
if (up.error) {
|
||||
errors.push(`${file.name}: ${up.error.message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const row = {
|
||||
id,
|
||||
tenant_id: ctx.tenantId,
|
||||
title: safeName,
|
||||
folder,
|
||||
file_name: safeName,
|
||||
mime_type: file.type || 'application/octet-stream',
|
||||
bytes: file.size,
|
||||
storage_path: storagePath,
|
||||
sha256,
|
||||
status: 'approved',
|
||||
created_by: user.id,
|
||||
};
|
||||
|
||||
const ins = await fetch(`${supabaseUrl()}/rest/v1/asset_files`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
body: JSON.stringify(row),
|
||||
});
|
||||
if (!ins.ok) {
|
||||
await svc.storage.from(ASSETS_BUCKET).remove([storagePath]);
|
||||
errors.push(`${file.name}: ${await ins.text()}`);
|
||||
continue;
|
||||
}
|
||||
const created = await ins.json();
|
||||
uploaded.push(Array.isArray(created) ? created[0] : created);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ uploaded, errors },
|
||||
{ status: uploaded.length ? 201 : 400 }
|
||||
);
|
||||
}
|
||||
|
||||
/** DELETE ?id= */
|
||||
export async function DELETE(req: NextRequest) {
|
||||
const g = await gate();
|
||||
if ('error' in g && g.error) return g.error;
|
||||
const { ctx } = g as Awaited<ReturnType<typeof gate>> & {
|
||||
ctx: { tenantId: string };
|
||||
};
|
||||
|
||||
const id = req.nextUrl.searchParams.get('id')?.trim();
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: 'id requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const headers = serviceHeaders();
|
||||
const svc = serviceSupabase();
|
||||
if (!headers || !svc) {
|
||||
return NextResponse.json({ error: 'no service role' }, { status: 503 });
|
||||
}
|
||||
|
||||
const get = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/asset_files?id=eq.${encodeURIComponent(id)}&tenant_id=eq.${encodeURIComponent(ctx.tenantId!)}&select=id,storage_path`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!get.ok) {
|
||||
return NextResponse.json({ error: await get.text() }, { status: 500 });
|
||||
}
|
||||
const rows = await get.json();
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return NextResponse.json({ error: 'No encontrado' }, { status: 404 });
|
||||
}
|
||||
|
||||
await svc.storage.from(ASSETS_BUCKET).remove([row.storage_path]);
|
||||
const del = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/asset_files?id=eq.${encodeURIComponent(id)}`,
|
||||
{ method: 'DELETE', headers }
|
||||
);
|
||||
if (!del.ok) {
|
||||
return NextResponse.json({ error: await del.text() }, { status: 500 });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import React from 'react';
|
||||
import { FileText, CheckCircle2 } from 'lucide-react';
|
||||
import { CheckCircle2 } from 'lucide-react';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { resolveActiveTenant, restGet } from '@/lib/tenant-context';
|
||||
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||
import AssetsLibrary from '@/components/AssetsLibrary';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
@@ -28,15 +29,13 @@ export default async function ActivosPage() {
|
||||
const agency = isAgencyRole(userRole(user));
|
||||
let documents: Doc[] = [];
|
||||
|
||||
if (ctx.portfolioWide) {
|
||||
documents = [];
|
||||
} else if (agency && ctx.viaView && ctx.tenantId) {
|
||||
if (!ctx.portfolioWide && agency && ctx.viaView && ctx.tenantId) {
|
||||
const tid = encodeURIComponent(ctx.tenantId);
|
||||
const r = await restGet<Doc[]>(
|
||||
`/rest/v1/documents?tenant_id=eq.${tid}&status=eq.approved&select=id,type,title,content,version,created_at,status&order=created_at.desc`
|
||||
);
|
||||
documents = r.data || [];
|
||||
} else {
|
||||
} else if (!ctx.portfolioWide) {
|
||||
const { data, error } = await supabase
|
||||
.from('documents')
|
||||
.select('id,type,title,content,version,created_at,status')
|
||||
@@ -46,70 +45,59 @@ export default async function ActivosPage() {
|
||||
else documents = data ?? [];
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight text-white">
|
||||
Biblioteca de activos
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-1 max-w-2xl">
|
||||
Entregables aprobados del cliente ({ctx.label}): briefs, audits,
|
||||
copys, calendarios exportados. Fuente:{' '}
|
||||
<code>documents</code> con <code>status=approved</code> (agentes →
|
||||
Slack → OK). Distinto del pipeline de creatividades ads.
|
||||
if (ctx.portfolioWide) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold tracking-tight text-white">
|
||||
Biblioteca de activos
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
Selecciona un cliente en Contexto para subir o consultar archivos
|
||||
validados.
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 border border-gray-800 rounded-xl p-6 bg-[#111827]">
|
||||
Vista global: elige el tenant arriba y vuelve aquí.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
{ctx.portfolioWide ? (
|
||||
<p className="text-sm text-gray-500 border border-gray-800 rounded-xl p-6 bg-[#111827]">
|
||||
Selecciona un cliente en Contexto para ver su biblioteca.
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{documents.length === 0 ? (
|
||||
<div className="col-span-3 bg-[#111827] border border-gray-800 rounded-xl p-12 text-center text-gray-400">
|
||||
<FileText className="w-10 h-10 text-gray-600 mx-auto mb-3" />
|
||||
<p className="text-base font-medium text-gray-300">
|
||||
No hay activos aprobados todavía.
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Aparecerán aquí tras validación en Slack / ops.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
documents.map((doc) => (
|
||||
return (
|
||||
<div className="space-y-10">
|
||||
<AssetsLibrary tenantLabel={ctx.label} />
|
||||
|
||||
{documents.length > 0 && (
|
||||
<section className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold text-white">
|
||||
Entregables de agentes
|
||||
</h3>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Textos/briefs aprobados en <code>documents</code> (Slack / ops).
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
{documents.map((doc) => (
|
||||
<div
|
||||
key={doc.id}
|
||||
className="bg-[#111827] border border-gray-800 rounded-xl p-5 flex flex-col justify-between"
|
||||
className="bg-[#111827] border border-gray-800 rounded-xl p-5"
|
||||
>
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="uppercase text-[10px] font-bold px-2 py-0.5 rounded bg-gray-800 text-gray-300">
|
||||
{doc.type}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[11px] text-emerald-400">
|
||||
<CheckCircle2 className="w-3 h-3" /> Aprobado
|
||||
</span>
|
||||
</div>
|
||||
<h4 className="font-bold text-white text-base mb-2">
|
||||
{doc.title}
|
||||
</h4>
|
||||
<p className="text-xs text-gray-400 line-clamp-4">
|
||||
{doc.content}
|
||||
</p>
|
||||
</div>
|
||||
<div className="pt-4 border-t border-gray-800/80 mt-4 text-[11px] text-gray-400 flex justify-between">
|
||||
<span>Versión v{doc.version}</span>
|
||||
<span>
|
||||
{doc.created_at
|
||||
? new Date(doc.created_at).toLocaleDateString('es-ES')
|
||||
: '—'}
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<span className="uppercase text-[10px] font-bold px-2 py-0.5 rounded bg-gray-800 text-gray-300">
|
||||
{doc.type}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-[11px] text-emerald-400">
|
||||
<CheckCircle2 className="w-3 h-3" /> Aprobado
|
||||
</span>
|
||||
</div>
|
||||
<h4 className="font-bold text-white text-sm mb-2">{doc.title}</h4>
|
||||
<p className="text-xs text-gray-400 line-clamp-3">{doc.content}</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -135,8 +135,8 @@ export default function CreativesPage() {
|
||||
<p className="text-gray-300 font-medium">Pipeline vacío</p>
|
||||
<p className="text-xs text-gray-500 mt-2 max-w-md mx-auto">
|
||||
Úsalo para piezas en producción creativa por cliente. La biblioteca
|
||||
de activos es para documentos/briefs aprobados; esto es el flow de
|
||||
ads.
|
||||
de activos guarda archivos validados (PDF, Excel, packs…); esto es
|
||||
el flow de ads.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
Reference in New Issue
Block a user