Align Ads and Métricas on the same paginated ad_daily warehouse.
Ad Tracker only loaded 2000 newest rows, so Brava showed 0 € while Métricas summed the full month. Both now page the same table for the selected range. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
63
src/lib/fetch-ad-daily.ts
Normal file
63
src/lib/fetch-ad-daily.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { serviceHeaders, supabaseUrl } from '@/lib/agency';
|
||||
import type { AdDailyRow } from '@/lib/metrics';
|
||||
|
||||
const PAGE = 1000;
|
||||
const MAX_ROWS = 200000;
|
||||
|
||||
export async function fetchAdDailyPaged(opts: {
|
||||
tenantId: string | null;
|
||||
useServiceRole: boolean;
|
||||
since: string;
|
||||
until?: string;
|
||||
}): Promise<AdDailyRow[]> {
|
||||
const { tenantId, useServiceRole, since, until } = opts;
|
||||
const out: AdDailyRow[] = [];
|
||||
|
||||
if (useServiceRole) {
|
||||
const headers = serviceHeaders();
|
||||
const base = supabaseUrl();
|
||||
if (!headers || !base) return [];
|
||||
const tid = tenantId
|
||||
? `&tenant_id=eq.${encodeURIComponent(tenantId)}`
|
||||
: '';
|
||||
const untilF = until ? `&date=lte.${until}` : '';
|
||||
for (let offset = 0; offset < MAX_ROWS; offset += PAGE) {
|
||||
const r = await fetch(
|
||||
`${base}/rest/v1/ad_daily?select=*&date=gte.${since}${untilF}${tid}&order=date.desc&limit=${PAGE}&offset=${offset}`,
|
||||
{ headers, cache: 'no-store' }
|
||||
);
|
||||
if (!r.ok) break;
|
||||
const chunk = (await r.json()) as AdDailyRow[];
|
||||
out.push(...chunk);
|
||||
if (chunk.length < PAGE) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const supabase = await createClient();
|
||||
for (let offset = 0; offset < MAX_ROWS; offset += PAGE) {
|
||||
let q = supabase
|
||||
.from('ad_daily')
|
||||
.select('*')
|
||||
.gte('date', since)
|
||||
.order('date', { ascending: false })
|
||||
.range(offset, offset + PAGE - 1);
|
||||
if (until) q = q.lte('date', until);
|
||||
const { data, error } = await q;
|
||||
if (error) break;
|
||||
const chunk = (data as AdDailyRow[]) || [];
|
||||
out.push(...chunk);
|
||||
if (chunk.length < PAGE) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function adDailyLookbackSince(): string {
|
||||
const since = new Date();
|
||||
since.setUTCDate(
|
||||
since.getUTCDate() -
|
||||
(Math.ceil((Date.now() - Date.UTC(2025, 0, 1)) / 86400000) + 14)
|
||||
);
|
||||
return since.toISOString().slice(0, 10);
|
||||
}
|
||||
Reference in New Issue
Block a user