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,52 @@
|
||||
export const GOALS = {
|
||||
MESSAGES: "เพิ่มข้อความสอบถาม",
|
||||
SALES: "เพิ่มยอดขาย",
|
||||
AWARENESS: "เพิ่มการรับรู้",
|
||||
};
|
||||
|
||||
export function parseBrief(body) {
|
||||
const business = typeof body.business === "string" ? body.business.trim() : "";
|
||||
const audience = typeof body.audience === "string" ? body.audience.trim() : "";
|
||||
if (!business || business.length > 1500) throw new Error("ระบุสินค้า/บริการ ไม่เกิน 1,500 ตัวอักษร");
|
||||
if (audience.length > 1000) throw new Error("กลุ่มลูกค้ายาวเกิน 1,000 ตัวอักษร");
|
||||
if (!Object.hasOwn(GOALS, body.goal)) throw new Error("เลือกเป้าหมายโฆษณา");
|
||||
if (!Number.isSafeInteger(body.budgetBaht) || body.budgetBaht < 1 || body.budgetBaht > 10000000) throw new Error("งบต้องเป็นจำนวนเต็ม 1–10,000,000 บาท");
|
||||
if (!Number.isSafeInteger(body.days) || body.days < 1 || body.days > 90) throw new Error("ระยะเวลาต้องเป็นจำนวนเต็ม 1–90 วัน");
|
||||
return { business, audience, goal: body.goal, budgetBaht: body.budgetBaht, days: body.days };
|
||||
}
|
||||
|
||||
/** Currency stays in whole baht; every allocated baht stays within the ceiling. */
|
||||
export function budgetPlan(brief, split) {
|
||||
const percentages = [split.testPercent, split.scalePercent, split.reservePercent];
|
||||
if (percentages.some(n => !Number.isInteger(n) || n < 0 || n > 100) || percentages.reduce((a, b) => a + b, 0) !== 100) throw new Error("Invalid budget allocation");
|
||||
if (split.testPercent === 0) throw new Error("A testing budget is required");
|
||||
const testBaht = Math.floor(brief.budgetBaht * split.testPercent / 100);
|
||||
const scaleBaht = Math.floor(brief.budgetBaht * split.scalePercent / 100);
|
||||
const reserveBaht = brief.budgetBaht - testBaht - scaleBaht;
|
||||
const spendable = testBaht + scaleBaht;
|
||||
const base = Math.floor(spendable / brief.days);
|
||||
const daily = Array.from({ length: brief.days }, (_, i) => base + (i < spendable % brief.days ? 1 : 0));
|
||||
return { testBaht, scaleBaht, reserveBaht, daily };
|
||||
}
|
||||
|
||||
/** Validate the Codex response independently of its output-schema option. */
|
||||
export function validateReport(value, schema, path = "report") {
|
||||
if (schema.type === "object") {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid ${path}`);
|
||||
for (const key of schema.required) {
|
||||
if (!(key in value)) throw new Error(`Missing ${path}.${key}`);
|
||||
}
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (!(key in schema.properties)) throw new Error(`Unexpected ${path}.${key}`);
|
||||
validateReport(child, schema.properties[key], `${path}.${key}`);
|
||||
}
|
||||
} else if (schema.type === "array") {
|
||||
if (!Array.isArray(value) || value.length > 20 || value.length < 1) throw new Error(`Invalid ${path}`);
|
||||
for (const child of value) validateReport(child, schema.items, path);
|
||||
} else if (schema.type === "string") {
|
||||
if (typeof value !== "string" || !value.trim() || value.length > 6000) throw new Error(`Invalid ${path}`);
|
||||
} else if (schema.type === "integer" && !Number.isInteger(value)) {
|
||||
throw new Error(`Invalid ${path}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["summary", "contentFindings", "contentIdeas", "adsPlan", "budgetSplit", "metricsToTrack", "limitations"],
|
||||
"properties": {
|
||||
"summary": { "type": "string" },
|
||||
"contentFindings": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"required": ["finding", "evidence", "action"],
|
||||
"properties": { "finding": { "type": "string" }, "evidence": { "type": "string" }, "action": { "type": "string" } }
|
||||
}
|
||||
},
|
||||
"contentIdeas": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"required": ["title", "format", "hook", "cta"],
|
||||
"properties": { "title": { "type": "string" }, "format": { "type": "string" }, "hook": { "type": "string" }, "cta": { "type": "string" } }
|
||||
}
|
||||
},
|
||||
"adsPlan": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"required": ["objective", "audience", "creatives", "testPlan", "scaleRule", "stopRule"],
|
||||
"properties": {
|
||||
"objective": { "type": "string" }, "audience": { "type": "string" },
|
||||
"creatives": { "type": "array", "items": { "type": "string" } },
|
||||
"testPlan": { "type": "string" }, "scaleRule": { "type": "string" }, "stopRule": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"budgetSplit": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"required": ["testPercent", "scalePercent", "reservePercent"],
|
||||
"properties": { "testPercent": { "type": "integer" }, "scalePercent": { "type": "integer" }, "reservePercent": { "type": "integer" } }
|
||||
},
|
||||
"metricsToTrack": { "type": "array", "items": { "type": "string" } },
|
||||
"limitations": { "type": "array", "items": { "type": "string" } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { FacebookApiError, graphGetAll, UserFacingError } from "@/lib/facebook/client";
|
||||
import { getPageCredentials } from "@/lib/facebook/tokens";
|
||||
|
||||
interface SourcePost {
|
||||
id: string;
|
||||
message?: string;
|
||||
created_time: string;
|
||||
reactions?: { summary?: { total_count?: number } };
|
||||
comments?: { summary?: { total_count?: number } };
|
||||
shares?: { count?: number };
|
||||
}
|
||||
|
||||
export async function collectAnalysisSource(pageId: string) {
|
||||
const page = await prisma.page.findUnique({ where: { id: pageId }, select: { name: true, status: true } });
|
||||
if (!page || page.status !== "ACTIVE") throw new UserFacingError("เชื่อมเพจให้พร้อมใช้งานก่อนวิเคราะห์");
|
||||
const credentials = await getPageCredentials(pageId);
|
||||
const basicFields = "id,message,created_time";
|
||||
const warnings: string[] = [];
|
||||
let rows: SourcePost[];
|
||||
try {
|
||||
rows = await graphGetAll<SourcePost>(`/${credentials.fbPageId}/published_posts`, credentials.token, { fields: `${basicFields},reactions.limit(0).summary(true),comments.limit(0).summary(true),shares`, limit: 25 }, 2);
|
||||
} catch (e) {
|
||||
if (!(e instanceof FacebookApiError) || e.code !== 100) throw e;
|
||||
rows = await graphGetAll<SourcePost>(`/${credentials.fbPageId}/published_posts`, credentials.token, { fields: basicFields, limit: 25 }, 2);
|
||||
warnings.push("Facebook ไม่ส่งสถิติรายโพสต์มาให้ วิเคราะห์ได้เฉพาะเนื้อหาและ snapshot ที่มี");
|
||||
}
|
||||
const since = new Date(Date.now() - 90 * 86400000);
|
||||
const posts = rows.filter(p => new Date(p.created_time) >= since).slice(0, 30).map(p => ({
|
||||
id: p.id, text: (p.message ?? "").slice(0, 1800), publishedAt: p.created_time,
|
||||
reactions: p.reactions?.summary?.total_count ?? null,
|
||||
comments: p.comments?.summary?.total_count ?? null,
|
||||
shares: p.shares?.count ?? null,
|
||||
}));
|
||||
if (posts.length === 0) throw new UserFacingError("ไม่พบโพสต์ Facebook ใน 90 วันที่ผ่านมา ยังไม่มีเนื้อหาให้วิเคราะห์");
|
||||
const snapshots = await prisma.pageInsightSnapshot.findMany({
|
||||
where: { pageId, date: { gte: since } }, orderBy: { date: "desc" }, take: 30,
|
||||
select: { date: true, views: true, engagements: true, follows: true, followDelta: true },
|
||||
});
|
||||
if (!snapshots.length) warnings.push("ยังไม่มี snapshot Insights — กดดึงข้อมูลที่หน้า Insights เพื่อเพิ่มหลักฐานรอบถัดไป");
|
||||
warnings.push("ไม่มีข้อมูลค่าโฆษณา Conversion หรือยอดขายจาก Ad Account จึงยังยืนยัน CPA/ROAS ไม่ได้");
|
||||
return { pageName: page.name, collectedAt: new Date().toISOString(), lookbackDays: 90, postCount: posts.length, posts, snapshots: snapshots.map(s => ({ ...s, date: s.date.toISOString() })), warnings };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export interface AnalysisBrief {
|
||||
business: string;
|
||||
audience: string;
|
||||
goal: "MESSAGES" | "SALES" | "AWARENESS";
|
||||
budgetBaht: number;
|
||||
days: number;
|
||||
}
|
||||
|
||||
export interface AnalysisReport {
|
||||
summary: string;
|
||||
contentFindings: { finding: string; evidence: string; action: string }[];
|
||||
contentIdeas: { title: string; format: string; hook: string; cta: string }[];
|
||||
adsPlan: { objective: string; audience: string; creatives: string[]; testPlan: string; scaleRule: string; stopRule: string };
|
||||
budgetSplit: { testPercent: number; scalePercent: number; reservePercent: number };
|
||||
metricsToTrack: string[];
|
||||
limitations: string[];
|
||||
}
|
||||
|
||||
export interface AnalysisJob {
|
||||
id: string;
|
||||
status: "QUEUED" | "RUNNING" | "COMPLETED" | "FAILED";
|
||||
brief: AnalysisBrief;
|
||||
result: AnalysisReport | null;
|
||||
error: string | null;
|
||||
createdAt: string;
|
||||
finishedAt: string | null;
|
||||
source: { postCount: number; collectedAt: string; warnings: string[] };
|
||||
}
|
||||
Reference in New Issue
Block a user