fix: ventas KPI = Online Clientify (89) y atribución por fuente real

Excluye Málaga del cohort; enriquece source desde lead/Clientify para que el cruce ads vs CRM deje de volcar todo en sin-atribuir.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-09-28 12:19:57 +02:00
parent 48fb31d247
commit 062c43325d
6 changed files with 206 additions and 27 deletions

View File

@@ -138,7 +138,10 @@ async function fetchWonDeals(
tenantId: string | null,
useServiceRole: boolean
): Promise<DealWonRow[]> {
const select = 'amount,won_at,stage,tenant_id,pipeline_id,pipeline_name';
const select =
'amount,won_at,stage,tenant_id,pipeline_id,pipeline_name,source,name,lead_id';
const selectFallback =
'amount,won_at,stage,tenant_id,pipeline_id,pipeline_name,lead_id';
const pageSize = 1000;
const out: DealWonRow[] = [];
@@ -149,32 +152,107 @@ async function fetchWonDeals(
const tidFilter = tenantId
? `&tenant_id=eq.${encodeURIComponent(tenantId)}`
: '';
let useSelect = select;
for (let offset = 0; offset < 50000; offset += pageSize) {
const r = await fetch(
`${base}/rest/v1/deals?select=${select}${tidFilter}&stage=eq.won&order=won_at.desc.nullslast&limit=${pageSize}&offset=${offset}`,
`${base}/rest/v1/deals?select=${useSelect}${tidFilter}&stage=eq.won&order=won_at.desc.nullslast&limit=${pageSize}&offset=${offset}`,
{ headers, cache: 'no-store' }
);
if (!r.ok) break;
if (!r.ok) {
if (useSelect !== selectFallback && offset === 0) {
useSelect = selectFallback;
offset = -pageSize;
continue;
}
break;
}
const chunk = (await r.json()) as DealWonRow[];
out.push(...chunk);
if (chunk.length < pageSize) break;
}
return out;
} else {
const supabase = await createClient();
let useSelect = select;
for (let offset = 0; offset < 50000; offset += pageSize) {
const { data, error } = await supabase
.from('deals')
.select(useSelect)
.eq('stage', 'won')
.order('won_at', { ascending: false, nullsFirst: false })
.range(offset, offset + pageSize - 1);
if (error && useSelect !== selectFallback && offset === 0) {
useSelect = selectFallback;
offset = -pageSize;
continue;
}
if (error) break;
const chunk = (data as DealWonRow[]) || [];
out.push(...chunk);
if (chunk.length < pageSize) break;
}
}
const supabase = await createClient();
for (let offset = 0; offset < 50000; offset += pageSize) {
const { data } = await supabase
.from('deals')
.select(select)
.eq('stage', 'won')
.order('won_at', { ascending: false, nullsFirst: false })
.range(offset, offset + pageSize - 1);
const chunk = (data as DealWonRow[]) || [];
out.push(...chunk);
if (chunk.length < pageSize) break;
return enrichDealSources(out, tenantId, useServiceRole);
}
/** Fill deal.source from linked lead when missing. */
async function enrichDealSources(
deals: DealWonRow[],
tenantId: string | null,
useServiceRole: boolean
): Promise<DealWonRow[]> {
const need = deals.filter((d) => !d.source && d.lead_id);
if (!need.length) {
return deals.map((d) => ({
...d,
source:
d.source ||
(/^order\s+\d+/i.test(d.name || '') ? 'ecommerce' : d.source) ||
null,
}));
}
return out;
const leadIds = [...new Set(need.map((d) => d.lead_id!).filter(Boolean))];
const leadSource = new Map<string, string>();
if (useServiceRole) {
const headers = serviceHeaders();
const base = supabaseUrl();
if (headers && base) {
for (let i = 0; i < leadIds.length; i += 200) {
const chunk = leadIds.slice(i, i + 200);
const tidFilter = tenantId
? `&tenant_id=eq.${encodeURIComponent(tenantId)}`
: '';
const r = await fetch(
`${base}/rest/v1/leads?select=id,source&id=in.(${chunk.map(encodeURIComponent).join(',')})${tidFilter}`,
{ headers, cache: 'no-store' }
);
if (!r.ok) continue;
const rows = (await r.json()) as { id: string; source?: string }[];
for (const row of rows) {
if (row.source) leadSource.set(row.id, row.source);
}
}
}
} else {
const supabase = await createClient();
for (let i = 0; i < leadIds.length; i += 200) {
const chunk = leadIds.slice(i, i + 200);
const { data } = await supabase
.from('leads')
.select('id,source')
.in('id', chunk);
for (const row of (data as { id: string; source?: string }[]) || []) {
if (row.source) leadSource.set(row.id, row.source);
}
}
}
return deals.map((d) => {
let source = d.source || (d.lead_id ? leadSource.get(d.lead_id) : null) || null;
if (!source && /^order\s+\d+/i.test(d.name || '')) source = 'ecommerce';
return { ...d, source };
});
}
export default async function KpisPage() {