fix: Meta sync usa token agency_oauth (no solo env BPS)
El META_ACCESS_TOKEN de Dokploy solo tenía acceso a BPS; el de agency_oauth cubre el resto. Probamos candidatos y priorizamos agency. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
/** Pull Meta / Google Ads insights into ad_daily + roll up kpi_weekly. */
|
||||
|
||||
import { serviceHeaders, supabaseUrl } from '@/lib/agency';
|
||||
import { resolveMetaAccessToken } from '@/lib/ads-discovery';
|
||||
import { resolveMetaAccessTokens } from '@/lib/ads-discovery';
|
||||
import { leadFromMetaActions, linkClicksFromMetaActions, nMeta } from '@/lib/meta-leads';
|
||||
import { resolveGoogleAdsAccessToken } from '@/lib/google-ads-auth';
|
||||
|
||||
@@ -174,18 +174,38 @@ async function fetchMetaAdDaily(
|
||||
tenantId: string,
|
||||
days: number
|
||||
): Promise<AdDailyInsert[]> {
|
||||
const token = await resolveMetaAccessToken();
|
||||
if (!token) throw new Error('Sin token Meta');
|
||||
const tokens = await resolveMetaAccessTokens();
|
||||
if (!tokens.length) throw new Error('Sin token Meta');
|
||||
const act = accountId.startsWith('act_') ? accountId : `act_${accountId}`;
|
||||
// Meta rejects huge ad-level ranges — pull in ~30d windows
|
||||
const windows = dayWindows(days, 30);
|
||||
const out: AdDailyInsert[] = [];
|
||||
for (const w of windows) {
|
||||
out.push(
|
||||
...(await fetchMetaInsightsWindow(act, token, tenantId, w.since, w.until))
|
||||
);
|
||||
const errors: string[] = [];
|
||||
// Prefer agency_oauth (broader BM access); Dokploy env token may only cover BPS.
|
||||
for (const token of tokens) {
|
||||
try {
|
||||
const out: AdDailyInsert[] = [];
|
||||
for (const w of windows) {
|
||||
out.push(
|
||||
...(await fetchMetaInsightsWindow(
|
||||
act,
|
||||
token,
|
||||
tenantId,
|
||||
w.since,
|
||||
w.until
|
||||
))
|
||||
);
|
||||
}
|
||||
return out;
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
errors.push(msg);
|
||||
// Try next token on permission / auth failures
|
||||
if (!/#200|permission|OAuthException|ads_read|ads_management|invalid/i.test(msg)) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
throw new Error(errors[errors.length - 1] || 'Meta sync error');
|
||||
}
|
||||
|
||||
async function fetchGoogleWindow(
|
||||
|
||||
Reference in New Issue
Block a user