Show global and per-channel CAC in CRM and Métricas.

Reuse won deals + ad spend for every tenant: CAC column in the metrics channel table, and a CRM hero + channel breakdown with the same formula.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-10-08 09:48:48 +02:00
parent e3fe157fa5
commit 8ef21d98d7
5 changed files with 319 additions and 166 deletions

132
src/lib/fetch-won-deals.ts Normal file
View File

@@ -0,0 +1,132 @@
/** Shared won-deal fetch for Métricas / CRM (tenant-scoped CAC). */
import { createClient } from '@/lib/supabase/server';
import { serviceHeaders, supabaseUrl } from '@/lib/agency';
import type { DealWonRow } from '@/lib/metrics';
/** 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,
}));
}
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 };
});
}
/** Won deals for cohort CAC / revenue / ROAS. Always filter by tenant when provided. */
export async function fetchWonDeals(
tenantId: string | null,
useServiceRole: boolean
): Promise<DealWonRow[]> {
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[] = [];
if (useServiceRole) {
const headers = serviceHeaders();
const base = supabaseUrl();
if (!headers || !base) return [];
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=${useSelect}${tidFilter}&stage=eq.won&order=won_at.desc.nullslast&limit=${pageSize}&offset=${offset}`,
{ headers, cache: 'no-store' }
);
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;
}
} else {
const supabase = await createClient();
let useSelect = select;
for (let offset = 0; offset < 50000; offset += pageSize) {
let q = supabase
.from('deals')
.select(useSelect)
.eq('stage', 'won')
.order('won_at', { ascending: false, nullsFirst: false })
.range(offset, offset + pageSize - 1);
if (tenantId) q = q.eq('tenant_id', tenantId);
const { data, error } = await q;
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;
}
}
return enrichDealSources(out, tenantId, useServiceRole);
}