Instrumenta kit, fuentes y estilo creativo; el listado filtra por rango e incluye hoy. Co-authored-by: Cursor <cursoragent@cursor.com>
88 lines
2.4 KiB
TypeScript
88 lines
2.4 KiB
TypeScript
/**
|
|
* GET /api/change-history — listado del historial de cambios.
|
|
* Query: tenant_id?, entity_type?, limit?, offset?
|
|
*/
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
import { createClient } from '@/lib/supabase/server';
|
|
import { homeTenantId, isAgencyRole, userRole } from '@/lib/agency';
|
|
import { listChangeHistory } from '@/lib/change-history';
|
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
|
|
|
export const dynamic = 'force-dynamic';
|
|
|
|
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 role = userRole(user);
|
|
const isAgency = isAgencyRole(role);
|
|
const sp = req.nextUrl.searchParams;
|
|
const limit = Number(sp.get('limit') || 100);
|
|
const offset = Number(sp.get('offset') || 0);
|
|
const entityType = sp.get('entity_type') || sp.get('entityType') || null;
|
|
const since = sp.get('since') || null;
|
|
const until = sp.get('until') || null;
|
|
|
|
let tenantId =
|
|
sp.get('tenant_id') || sp.get('tenantId') || null;
|
|
|
|
if (!isAgency) {
|
|
// Cliente: solo su tenant
|
|
const own = homeTenantId(user);
|
|
const ctx = await resolveActiveTenant(user);
|
|
tenantId = own || ctx.tenantId || null;
|
|
if (!tenantId) {
|
|
return NextResponse.json({ error: 'Sin tenant' }, { status: 400 });
|
|
}
|
|
} else if (!tenantId) {
|
|
// Agencia sin filtro: usa contexto activo si hay cliente seleccionado
|
|
const ctx = await resolveActiveTenant(user);
|
|
if (ctx.tenantId && !ctx.portfolioWide) {
|
|
tenantId = ctx.tenantId;
|
|
}
|
|
// Si portfolio wide, tenantId queda null → historial global
|
|
}
|
|
|
|
const { rows, error, total } = await listChangeHistory({
|
|
tenantId,
|
|
entityType,
|
|
since,
|
|
until,
|
|
limit,
|
|
offset,
|
|
});
|
|
|
|
if (error) {
|
|
const missing =
|
|
/relation .*change_history.* does not exist|Could not find the table/i.test(
|
|
error
|
|
);
|
|
return NextResponse.json(
|
|
{
|
|
ok: false,
|
|
error: missing
|
|
? 'Falta crear la tabla change_history (sql/change_history.sql).'
|
|
: error,
|
|
rows: [],
|
|
needsMigration: missing,
|
|
},
|
|
{ status: missing ? 503 : 500 }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json({
|
|
ok: true,
|
|
rows,
|
|
total: total ?? rows.length,
|
|
tenant_id: tenantId,
|
|
portfolio_wide: isAgency && !tenantId,
|
|
since,
|
|
until,
|
|
});
|
|
}
|