Initial commit: page-manager Next.js app with Coolify deploy support
Replace Vercel-specific infra (Cron, Blob) with self-hosted equivalents for deployment to Coolify: in-container cron scheduler (scripts/cron-runner.mjs) and disk-based upload storage served via /api/uploads/[...path]. Add Dockerfile, .dockerignore, and /api/health for container health checks. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { getPageCredentials } from "@/lib/facebook/tokens";
|
||||
import { getPageDailyInsights, getPostInsights } from "@/lib/facebook/insights";
|
||||
|
||||
const POST_LOOKBACK_DAYS = 14;
|
||||
|
||||
export function todayUtc(): Date {
|
||||
const n = new Date();
|
||||
return new Date(Date.UTC(n.getUTCFullYear(), n.getUTCMonth(), n.getUTCDate()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Upserts today's page snapshot and recent published posts' snapshots for one
|
||||
* page. Used by the daily cron and the "ดึงข้อมูลตอนนี้" button — re-running
|
||||
* on the same day overwrites that day's row.
|
||||
*/
|
||||
export async function snapshotPage(pageId: string, date = todayUtc()): Promise<{ posts: number }> {
|
||||
const creds = await getPageCredentials(pageId);
|
||||
const ins = await getPageDailyInsights(creds);
|
||||
// page_fan_adds is retired — derive the delta from the previous snapshot.
|
||||
const prev = await prisma.pageInsightSnapshot.findFirst({
|
||||
where: { pageId, date: { lt: date } },
|
||||
orderBy: { date: "desc" },
|
||||
});
|
||||
const row = {
|
||||
views: ins.views,
|
||||
engagements: ins.engagements,
|
||||
follows: ins.follows,
|
||||
followDelta: prev ? ins.follows - prev.follows : 0,
|
||||
raw: ins.raw as Prisma.InputJsonValue,
|
||||
};
|
||||
await prisma.pageInsightSnapshot.upsert({
|
||||
where: { pageId_date: { pageId, date } },
|
||||
create: { pageId, date, ...row },
|
||||
update: row,
|
||||
});
|
||||
|
||||
const since = new Date(date.getTime() - POST_LOOKBACK_DAYS * 86400000);
|
||||
const posts = await prisma.post.findMany({
|
||||
where: { pageId, status: "PUBLISHED", fbPostId: { not: null }, updatedAt: { gte: since } },
|
||||
select: { id: true, fbPostId: true },
|
||||
});
|
||||
let done = 0;
|
||||
for (const post of posts) {
|
||||
try {
|
||||
const pi = await getPostInsights(creds, post.fbPostId!);
|
||||
const prow = { impressions: pi.impressions, engaged: pi.engaged, reactions: pi.reactions, raw: pi.raw as Prisma.InputJsonValue };
|
||||
await prisma.postInsightSnapshot.upsert({
|
||||
where: { postId_date: { postId: post.id, date } },
|
||||
create: { postId: post.id, date, ...prow },
|
||||
update: prow,
|
||||
});
|
||||
done++;
|
||||
} catch (e) {
|
||||
console.error(`[insights] post=${post.id}`, e);
|
||||
}
|
||||
}
|
||||
return { posts: done };
|
||||
}
|
||||
Reference in New Issue
Block a user