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:
@@ -5,6 +5,7 @@ import CrmDashboard from '@/components/CrmDashboard';
|
||||
import CrmPortfolioBoard from '@/components/CrmPortfolioBoard';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import { AdDailyRow, CrmLeadRow } from '@/lib/metrics';
|
||||
import { fetchWonDeals } from '@/lib/fetch-won-deals';
|
||||
import { isAgencyRole, serviceHeaders, supabaseUrl, userRole } from '@/lib/agency';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
@@ -145,9 +146,10 @@ export default async function CrmPage() {
|
||||
}
|
||||
|
||||
const tenantId = ctx.tenantId;
|
||||
const [crmLeads, dailyRows] = await Promise.all([
|
||||
const [crmLeads, dailyRows, wonDeals] = await Promise.all([
|
||||
fetchCrmLeads(tenantId, useService, false),
|
||||
fetchAdDaily(tenantId, useService),
|
||||
fetchWonDeals(tenantId, useService),
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -156,6 +158,7 @@ export default async function CrmPage() {
|
||||
portfolioWide={false}
|
||||
crmLeads={crmLeads}
|
||||
dailyRows={dailyRows}
|
||||
wonDeals={wonDeals}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
adDailyLookbackSince,
|
||||
fetchAdDailyPaged,
|
||||
} from '@/lib/fetch-ad-daily';
|
||||
import { fetchWonDeals } from '@/lib/fetch-won-deals';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
@@ -89,128 +90,6 @@ async function fetchCrmLeads(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Won deals for cohort CAC / revenue / ROAS. */
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}));
|
||||
}
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
/** Paginate organic & web daily metrics (GSC + GA4) for active tenant / portfolio. */
|
||||
async function fetchOrganicDaily(
|
||||
tenantId: string | null,
|
||||
|
||||
Reference in New Issue
Block a user