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:
@@ -268,11 +268,28 @@ async function upsertDeal(tenantId: string, d: Json) {
|
||||
}
|
||||
}
|
||||
const closed = str(d.actual_closed_date, 40);
|
||||
const pipeUrl = str(d.pipeline, 200);
|
||||
const pipeUrl = str(d.pipeline, 200) || '';
|
||||
let pipelineId: string | null = null;
|
||||
if (pipeUrl.includes('/pipelines/')) {
|
||||
pipelineId = pipeUrl.replace(/\/$/, '').split('/').pop() || null;
|
||||
}
|
||||
const tags = Array.isArray(d.tags) ? d.tags.map(String) : [];
|
||||
const tagBlob = tags.join(' ').toLowerCase();
|
||||
const dealName = str(d.name, 200) || '';
|
||||
let source =
|
||||
str(d.deal_source, 80) ||
|
||||
str(d.contact_source, 80) ||
|
||||
'';
|
||||
if (!source) {
|
||||
if (/facebook|instagram|\bmeta\b|\bfb\b/.test(tagBlob)) source = 'meta';
|
||||
else if (/google/.test(tagBlob)) source = 'google';
|
||||
else if (
|
||||
/woocommerce|ecommerce/.test(tagBlob) ||
|
||||
/^order\s+\d+/i.test(dealName)
|
||||
) {
|
||||
source = 'ecommerce';
|
||||
}
|
||||
}
|
||||
const row = {
|
||||
id,
|
||||
tenant_id: tenantId,
|
||||
@@ -284,6 +301,8 @@ async function upsertDeal(tenantId: string, d: Json) {
|
||||
lost_at: stage === 'lost' && closed ? closed : null,
|
||||
pipeline_id: pipelineId,
|
||||
pipeline_name: str(d.pipeline_desc, 120) || null,
|
||||
source: source ? source.toLowerCase() : null,
|
||||
name: dealName || null,
|
||||
};
|
||||
const base = supabaseUrl();
|
||||
await fetch(
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user