feat: agency portfolio with per-client integrations hub
Admin home lists tenants, alerts, and connection health; header selector enables superadmin context; Meta/GA4/GSC/GTM/CRM/email slots live per tenant (manual status until OAuth). Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
91
src/app/api/admin/active-tenant/route.ts
Normal file
91
src/app/api/admin/active-tenant/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
VIEW_TENANT_COOKIE,
|
||||
VIEW_TENANT_NAME_COOKIE,
|
||||
VIEW_TENANT_SLUG_COOKIE,
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** POST { tenantId } — set superadmin view context cookie. null clears. */
|
||||
export async function POST(req: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
if (!isAgencyRole(userRole(user))) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const tenantId =
|
||||
typeof body.tenantId === 'string' && body.tenantId.trim()
|
||||
? body.tenantId.trim()
|
||||
: null;
|
||||
|
||||
const cookieOpts = {
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 30,
|
||||
sameSite: 'lax' as const,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
httpOnly: false,
|
||||
};
|
||||
|
||||
if (!tenantId) {
|
||||
const res = NextResponse.json({ ok: true, cleared: true });
|
||||
res.cookies.set(VIEW_TENANT_COOKIE, '', { ...cookieOpts, maxAge: 0 });
|
||||
res.cookies.set(VIEW_TENANT_SLUG_COOKIE, '', { ...cookieOpts, maxAge: 0 });
|
||||
res.cookies.set(VIEW_TENANT_NAME_COOKIE, '', { ...cookieOpts, maxAge: 0 });
|
||||
return res;
|
||||
}
|
||||
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/tenants?id=eq.${encodeURIComponent(tenantId)}&select=id,name,slug`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({ error: 'Tenant lookup failed' }, { status: 500 });
|
||||
}
|
||||
const rows = await r.json();
|
||||
const tenant = Array.isArray(rows) ? rows[0] : null;
|
||||
if (!tenant) {
|
||||
return NextResponse.json({ error: 'Tenant no encontrado' }, { status: 404 });
|
||||
}
|
||||
|
||||
const res = NextResponse.json({
|
||||
ok: true,
|
||||
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
|
||||
});
|
||||
res.cookies.set(VIEW_TENANT_COOKIE, tenant.id, cookieOpts);
|
||||
res.cookies.set(VIEW_TENANT_SLUG_COOKIE, tenant.slug || '', cookieOpts);
|
||||
res.cookies.set(VIEW_TENANT_NAME_COOKIE, tenant.name || '', cookieOpts);
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
// readable from client via document.cookie too; this is for SSR helpers
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
104
src/app/api/admin/alerts/route.ts
Normal file
104
src/app/api/admin/alerts/route.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
if (!isAgencyRole(userRole(user))) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json({ alerts: [], warning: 'no service role' });
|
||||
}
|
||||
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/agency_alerts?select=*&order=created_at.desc&limit=50`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({
|
||||
alerts: [],
|
||||
warning: 'Aplicar sql/agency_portfolio.sql',
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ alerts: await r.json() });
|
||||
}
|
||||
|
||||
/** POST { id } mark read — or { title, body, severity, tenantId } create */
|
||||
export async function POST(req: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
if (!isAgencyRole(userRole(user))) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json({ error: 'no service role' }, { status: 503 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const base = supabaseUrl();
|
||||
|
||||
if (typeof body.id === 'string' && body.markRead) {
|
||||
const r = await fetch(
|
||||
`${base}/rest/v1/agency_alerts?id=eq.${encodeURIComponent(body.id)}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: { ...headers, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ read_at: new Date().toISOString() }),
|
||||
}
|
||||
);
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({ error: await r.text() }, { status: 500 });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
const title = typeof body.title === 'string' ? body.title.trim() : '';
|
||||
if (!title) {
|
||||
return NextResponse.json({ error: 'title requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const row = {
|
||||
title,
|
||||
body: typeof body.body === 'string' ? body.body : null,
|
||||
severity: body.severity || 'info',
|
||||
tenant_id: body.tenantId || null,
|
||||
source: body.source || 'manual',
|
||||
href: body.href || null,
|
||||
};
|
||||
|
||||
const r = await fetch(`${base}/rest/v1/agency_alerts`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
body: JSON.stringify(row),
|
||||
});
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({ error: await r.text() }, { status: 500 });
|
||||
}
|
||||
const created = await r.json();
|
||||
return NextResponse.json({ alert: created[0] || created }, { status: 201 });
|
||||
}
|
||||
@@ -38,6 +38,45 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: error.message || 'Error al provisionar cliente en base de datos.' }, { status: 500 });
|
||||
}
|
||||
|
||||
// Seed integration slots (best-effort; ignore if table missing)
|
||||
try {
|
||||
const tenantId =
|
||||
data?.tenant_id || data?.id || data?.client?.tenant_id || null;
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY?.trim();
|
||||
const url = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://supabase.4ventures.es';
|
||||
if (tenantId && serviceKey) {
|
||||
const providers = [
|
||||
['meta_ads', 'Meta Ads'],
|
||||
['google_ads', 'Google Ads (MCC)'],
|
||||
['ga4', 'Google Analytics 4'],
|
||||
['search_console', 'Search Console'],
|
||||
['tag_manager', 'Tag Manager'],
|
||||
['clientify', 'Clientify'],
|
||||
['klaviyo', 'Klaviyo'],
|
||||
['mailchimp', 'Mailchimp'],
|
||||
];
|
||||
await fetch(`${url}/rest/v1/integrations`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
apikey: serviceKey,
|
||||
Authorization: `Bearer ${serviceKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'resolution=ignore-duplicates',
|
||||
},
|
||||
body: JSON.stringify(
|
||||
providers.map(([provider, label]) => ({
|
||||
tenant_id: tenantId,
|
||||
provider,
|
||||
status: 'disconnected',
|
||||
label,
|
||||
}))
|
||||
),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('seed integrations skipped', e);
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, client: data });
|
||||
} catch (err: any) {
|
||||
console.error('Server error creating client:', err);
|
||||
|
||||
180
src/app/api/admin/integrations/route.ts
Normal file
180
src/app/api/admin/integrations/route.ts
Normal file
@@ -0,0 +1,180 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
INTEGRATION_PROVIDERS,
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function requireAgency() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
|
||||
if (!isAgencyRole(userRole(user))) {
|
||||
return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
|
||||
}
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return {
|
||||
error: NextResponse.json(
|
||||
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
|
||||
{ status: 503 }
|
||||
),
|
||||
};
|
||||
}
|
||||
return { user, headers };
|
||||
}
|
||||
|
||||
/** GET ?tenantId= — integrations for one tenant (seed missing providers). */
|
||||
export async function GET(req: NextRequest) {
|
||||
const gate = await requireAgency();
|
||||
if ('error' in gate && gate.error) return gate.error;
|
||||
const { headers } = gate as { headers: { apikey: string; Authorization: string } };
|
||||
|
||||
const tenantId = req.nextUrl.searchParams.get('tenantId');
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: 'tenantId requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const base = supabaseUrl();
|
||||
const listRes = await fetch(
|
||||
`${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&select=*`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
|
||||
if (!listRes.ok) {
|
||||
const msg = await listRes.text();
|
||||
return NextResponse.json(
|
||||
{
|
||||
integrations: [],
|
||||
providers: INTEGRATION_PROVIDERS,
|
||||
warning: msg.includes('does not exist')
|
||||
? 'Aplicar sql/agency_portfolio.sql'
|
||||
: msg.slice(0, 200),
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
let integrations = await listRes.json();
|
||||
const have = new Set(
|
||||
(integrations as { provider: string }[]).map((i) => i.provider)
|
||||
);
|
||||
const missing = INTEGRATION_PROVIDERS.filter((p) => !have.has(p.id));
|
||||
|
||||
if (missing.length) {
|
||||
const rows = missing.map((p) => ({
|
||||
tenant_id: tenantId,
|
||||
provider: p.id,
|
||||
status: 'disconnected',
|
||||
label: p.label,
|
||||
}));
|
||||
await fetch(`${base}/rest/v1/integrations`, {
|
||||
method: 'POST',
|
||||
headers: { ...headers, 'Content-Type': 'application/json', Prefer: 'return=representation' },
|
||||
body: JSON.stringify(rows),
|
||||
});
|
||||
const again = await fetch(
|
||||
`${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&select=*`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (again.ok) integrations = await again.json();
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
integrations,
|
||||
providers: INTEGRATION_PROVIDERS,
|
||||
});
|
||||
}
|
||||
|
||||
/** PATCH — update one integration status/account (manual connect for now). */
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const gate = await requireAgency();
|
||||
if ('error' in gate && gate.error) return gate.error;
|
||||
const { headers } = gate as { headers: { apikey: string; Authorization: string } };
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const tenantId = typeof body.tenantId === 'string' ? body.tenantId.trim() : '';
|
||||
const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
|
||||
const status = typeof body.status === 'string' ? body.status.trim() : '';
|
||||
const externalAccountId =
|
||||
typeof body.externalAccountId === 'string'
|
||||
? body.externalAccountId.trim()
|
||||
: undefined;
|
||||
const label =
|
||||
typeof body.label === 'string' ? body.label.trim() : undefined;
|
||||
const errorMessage =
|
||||
typeof body.errorMessage === 'string' ? body.errorMessage.trim() : undefined;
|
||||
|
||||
if (!tenantId || !provider || !status) {
|
||||
return NextResponse.json(
|
||||
{ error: 'tenantId, provider y status requeridos' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (
|
||||
!['disconnected', 'pending', 'connected', 'error'].includes(status)
|
||||
) {
|
||||
return NextResponse.json({ error: 'status inválido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const patch: Record<string, unknown> = {
|
||||
status,
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
if (externalAccountId !== undefined) {
|
||||
patch.external_account_id = externalAccountId || null;
|
||||
}
|
||||
if (label !== undefined) patch.label = label || null;
|
||||
if (errorMessage !== undefined) patch.error_message = errorMessage || null;
|
||||
if (status === 'connected') {
|
||||
patch.last_sync_at = new Date().toISOString();
|
||||
patch.error_message = null;
|
||||
}
|
||||
|
||||
const base = supabaseUrl();
|
||||
const url = `${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&provider=eq.${encodeURIComponent(provider)}`;
|
||||
const r = await fetch(url, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
|
||||
if (!r.ok) {
|
||||
// upsert if missing
|
||||
const ins = await fetch(`${base}/rest/v1/integrations`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation,resolution=merge-duplicates',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
tenant_id: tenantId,
|
||||
provider,
|
||||
...patch,
|
||||
}),
|
||||
});
|
||||
if (!ins.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: await ins.text() },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
const created = await ins.json();
|
||||
return NextResponse.json({ integration: created[0] || created });
|
||||
}
|
||||
|
||||
const updated = await r.json();
|
||||
return NextResponse.json({ integration: updated[0] || updated });
|
||||
}
|
||||
105
src/app/api/admin/portfolio/route.ts
Normal file
105
src/app/api/admin/portfolio/route.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
INTEGRATION_PROVIDERS,
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** GET portfolio: tenants + integration summary + unread alerts (agency only). */
|
||||
export async function GET() {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
if (!isAgencyRole(userRole(user))) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
const base = supabaseUrl();
|
||||
const [tenantsRes, integRes, alertsRes] = await Promise.all([
|
||||
fetch(`${base}/rest/v1/tenants?select=id,name,slug,created_at&order=name.asc`, {
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}),
|
||||
fetch(
|
||||
`${base}/rest/v1/integrations?select=id,tenant_id,provider,status,label,external_account_id,last_sync_at,error_message`,
|
||||
{ headers, cache: 'no-store' }
|
||||
),
|
||||
fetch(
|
||||
`${base}/rest/v1/agency_alerts?select=*&read_at=is.null&order=created_at.desc&limit=40`,
|
||||
{ headers, cache: 'no-store' }
|
||||
),
|
||||
]);
|
||||
|
||||
const tenants = tenantsRes.ok ? await tenantsRes.json() : [];
|
||||
const integrations = integRes.ok ? await integRes.json() : [];
|
||||
const alerts = alertsRes.ok ? await alertsRes.json() : [];
|
||||
const integMissing =
|
||||
!integRes.ok &&
|
||||
(await integRes.text().catch(() => '')).toLowerCase().includes('does not exist');
|
||||
|
||||
type Integ = {
|
||||
tenant_id: string;
|
||||
provider: string;
|
||||
status: string;
|
||||
};
|
||||
const byTenant = new Map<string, Integ[]>();
|
||||
for (const row of integrations as Integ[]) {
|
||||
const list = byTenant.get(row.tenant_id) || [];
|
||||
list.push(row);
|
||||
byTenant.set(row.tenant_id, list);
|
||||
}
|
||||
|
||||
const portfolio = (tenants as { id: string; name: string; slug: string; created_at: string }[]).map(
|
||||
(t) => {
|
||||
const rows = byTenant.get(t.id) || [];
|
||||
const connected = rows.filter((r) => r.status === 'connected').length;
|
||||
const errors = rows.filter((r) => r.status === 'error').length;
|
||||
const pending = rows.filter((r) => r.status === 'pending').length;
|
||||
return {
|
||||
...t,
|
||||
integrations: rows,
|
||||
stats: {
|
||||
connected,
|
||||
errors,
|
||||
pending,
|
||||
totalProviders: INTEGRATION_PROVIDERS.length,
|
||||
health:
|
||||
errors > 0
|
||||
? 'critical'
|
||||
: connected === 0
|
||||
? 'empty'
|
||||
: pending > 0
|
||||
? 'warning'
|
||||
: 'ok',
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
portfolio,
|
||||
alerts,
|
||||
providers: INTEGRATION_PROVIDERS,
|
||||
schemaReady: !integMissing,
|
||||
warning: integMissing
|
||||
? 'Falta aplicar sql/agency_portfolio.sql en Supabase'
|
||||
: null,
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,27 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { cookies } from 'next/headers';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import {
|
||||
VIEW_TENANT_COOKIE,
|
||||
homeTenantId,
|
||||
isAgencyRole,
|
||||
serviceHeaders,
|
||||
supabaseUrl,
|
||||
userRole,
|
||||
} from '@/lib/agency';
|
||||
|
||||
async function resolveTenantId(user: {
|
||||
app_metadata?: Record<string, unknown>;
|
||||
user_metadata?: Record<string, unknown>;
|
||||
}): Promise<{ tenantId: string | null; viaView: boolean }> {
|
||||
const role = userRole(user);
|
||||
const cookieStore = await cookies();
|
||||
const viewId = cookieStore.get(VIEW_TENANT_COOKIE)?.value || null;
|
||||
if (isAgencyRole(role) && viewId) {
|
||||
return { tenantId: viewId, viaView: true };
|
||||
}
|
||||
return { tenantId: homeTenantId(user), viaView: false };
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient();
|
||||
@@ -10,13 +32,39 @@ export async function GET() {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { tenantId, viaView } = await resolveTenantId(user);
|
||||
|
||||
if (viaView && tenantId) {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json(
|
||||
{ creatives: [], warning: 'Service role required for superadmin view' },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
const r = await fetch(
|
||||
`${supabaseUrl()}/rest/v1/creatives?tenant_id=eq.${encodeURIComponent(tenantId)}&select=id,title,status,mime_type,bytes,created_at,updated_at&order=updated_at.desc`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({
|
||||
creatives: [],
|
||||
warning: await r.text(),
|
||||
viewTenantId: tenantId,
|
||||
});
|
||||
}
|
||||
return NextResponse.json({
|
||||
creatives: await r.json(),
|
||||
viewTenantId: tenantId,
|
||||
});
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('creatives')
|
||||
.select('id,title,status,mime_type,bytes,created_at,updated_at')
|
||||
.order('updated_at', { ascending: false });
|
||||
|
||||
if (error) {
|
||||
// Table may not exist yet — soft message for pre-migration
|
||||
return NextResponse.json(
|
||||
{ creatives: [], warning: error.message },
|
||||
{ status: 200 }
|
||||
@@ -35,8 +83,7 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const tenantId =
|
||||
user.app_metadata?.tenant_id || user.user_metadata?.tenant_id || null;
|
||||
const { tenantId, viaView } = await resolveTenantId(user);
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: 'Usuario sin tenant_id' }, { status: 403 });
|
||||
}
|
||||
@@ -47,14 +94,43 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: 'title requerido' }, { status: 400 });
|
||||
}
|
||||
|
||||
const row = {
|
||||
tenant_id: tenantId,
|
||||
title,
|
||||
status: 'draft',
|
||||
created_by: user.id,
|
||||
};
|
||||
|
||||
if (viaView) {
|
||||
const headers = serviceHeaders();
|
||||
if (!headers) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Service role required' },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
const r = await fetch(`${supabaseUrl()}/rest/v1/creatives`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...headers,
|
||||
'Content-Type': 'application/json',
|
||||
Prefer: 'return=representation',
|
||||
},
|
||||
body: JSON.stringify(row),
|
||||
});
|
||||
if (!r.ok) {
|
||||
return NextResponse.json({ error: await r.text() }, { status: 500 });
|
||||
}
|
||||
const data = await r.json();
|
||||
return NextResponse.json(
|
||||
{ creative: Array.isArray(data) ? data[0] : data },
|
||||
{ status: 201 }
|
||||
);
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('creatives')
|
||||
.insert({
|
||||
tenant_id: tenantId,
|
||||
title,
|
||||
status: 'draft',
|
||||
created_by: user.id,
|
||||
})
|
||||
.insert(row)
|
||||
.select('id,title,status,created_at')
|
||||
.single();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user