feat: Orgánico siempre al día (auto-sync al abrir + cron diario)
El botón Sync 28d pasa a «Actualizar ahora»; la vista refresca sola si faltan datos y hay endpoint /api/cron/organic-sync. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -8,8 +8,14 @@ import {
|
||||
} from '@/lib/agency';
|
||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||
import type { GeoSnapshot, OrganicDailyRow } from '@/lib/organic';
|
||||
import {
|
||||
organicNeedsRefresh,
|
||||
syncAllConnectedOrganic,
|
||||
} from '@/lib/google-organic';
|
||||
import { getAgencyOAuthStatus } from '@/lib/google-drive';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
export const maxDuration = 120;
|
||||
|
||||
async function gate() {
|
||||
const supabase = await createClient();
|
||||
@@ -47,6 +53,25 @@ export async function GET(req: NextRequest) {
|
||||
const tid = ctx.tenantId;
|
||||
const since = req.nextUrl.searchParams.get('since') || '';
|
||||
const until = req.nextUrl.searchParams.get('until') || '';
|
||||
const skipAuto = req.nextUrl.searchParams.get('skipAutoSync') === '1';
|
||||
|
||||
// Keep Orgánico fresh when opening the page (if Google OAuth is connected)
|
||||
let autoSynced: { daysWritten: number; warning?: string } | null = null;
|
||||
if (!skipAuto) {
|
||||
try {
|
||||
const oauth = await getAgencyOAuthStatus();
|
||||
if (oauth.connected && (await organicNeedsRefresh(tid))) {
|
||||
const r = await syncAllConnectedOrganic({ tenantId: tid, days: 28 });
|
||||
const one = r.results.find((x) => x.tenantId === tid);
|
||||
autoSynced = {
|
||||
daysWritten: one?.daysWritten || 0,
|
||||
warning: one?.warning,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// non-fatal — still return cached organic rows
|
||||
}
|
||||
}
|
||||
|
||||
if (agency && headers) {
|
||||
const base = supabaseUrl();
|
||||
@@ -109,7 +134,8 @@ export async function GET(req: NextRequest) {
|
||||
geo,
|
||||
integrations,
|
||||
workspace,
|
||||
warning: warningParts[0] || null,
|
||||
autoSynced,
|
||||
warning: warningParts[0] || autoSynced?.warning || null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -144,7 +170,8 @@ export async function GET(req: NextRequest) {
|
||||
geo: ge.data || [],
|
||||
integrations: integ.data || [],
|
||||
workspace: (ten.data?.settings as { organico?: unknown } | null)?.organico || {},
|
||||
warning: o.error?.message || ge.error?.message || null,
|
||||
autoSynced,
|
||||
warning: o.error?.message || ge.error?.message || autoSynced?.warning || null,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user