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,84 @@
|
||||
import Anthropic from "@anthropic-ai/sdk";
|
||||
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
|
||||
import type * as z from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { UserFacingError } from "@/lib/facebook/client";
|
||||
|
||||
export const AI_MODEL = "claude-opus-5-5";
|
||||
/** Successful AI calls allowed per page in any rolling 24 hours (cost guard). */
|
||||
export const AI_DAILY_LIMIT_PER_PAGE = 30;
|
||||
|
||||
let client: Anthropic | null = null;
|
||||
|
||||
function getClient(): Anthropic {
|
||||
if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) {
|
||||
throw new UserFacingError("ยังไม่ได้ตั้งค่า AI — ผู้ดูแลระบบต้องใส่ ANTHROPIC_API_KEY ก่อน");
|
||||
}
|
||||
// Interactive routes: fail fast rather than hold the request for the SDK's 10-minute default.
|
||||
client ??= new Anthropic({ timeout: 55_000, maxRetries: 1 });
|
||||
return client;
|
||||
}
|
||||
|
||||
function toUserFacing(e: unknown, kind: string): UserFacingError {
|
||||
if (e instanceof UserFacingError) return e;
|
||||
console.error(`[ai:${kind}] request failed`, e);
|
||||
if (e instanceof Anthropic.AuthenticationError || e instanceof Anthropic.PermissionDeniedError) {
|
||||
return new UserFacingError("API key ของ AI ใช้ไม่ได้ — ผู้ดูแลระบบต้องตรวจ ANTHROPIC_API_KEY");
|
||||
}
|
||||
if (e instanceof Anthropic.RateLimitError) return new UserFacingError("AI มีคนใช้มากหรือเกินโควตา ลองใหม่ในอีกสักครู่");
|
||||
if (e instanceof Anthropic.APIConnectionError) return new UserFacingError("ติดต่อ AI ไม่ได้ ลองใหม่อีกครั้ง");
|
||||
return new UserFacingError("AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง");
|
||||
}
|
||||
|
||||
/**
|
||||
* One structured-output call to Claude, counted against the page's daily limit.
|
||||
* Every failure becomes a UserFacingError with safe Thai text; details go to the server log.
|
||||
*/
|
||||
export async function generateStructured<S extends z.ZodType>(req: {
|
||||
kind: "caption" | "profile" | "week-plan" | "check" | "reply";
|
||||
pageId: string;
|
||||
userId: string;
|
||||
system: string;
|
||||
prompt: string;
|
||||
schema: S;
|
||||
effort: "low" | "medium";
|
||||
}): Promise<z.infer<S>> {
|
||||
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const used = await prisma.aiUsage.count({ where: { pageId: req.pageId, createdAt: { gte: since } } });
|
||||
if (used >= AI_DAILY_LIMIT_PER_PAGE) {
|
||||
throw new UserFacingError(`เพจนี้ใช้ AI ครบ ${AI_DAILY_LIMIT_PER_PAGE} ครั้งใน 24 ชั่วโมงแล้ว ลองใหม่ภายหลัง`);
|
||||
}
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await getClient().messages.parse({
|
||||
model: AI_MODEL,
|
||||
max_tokens: 16000,
|
||||
system: req.system,
|
||||
output_config: { effort: req.effort, format: zodOutputFormat(req.schema) },
|
||||
messages: [{ role: "user", content: req.prompt }],
|
||||
});
|
||||
} catch (e) {
|
||||
throw toUserFacing(e, req.kind);
|
||||
}
|
||||
|
||||
if (response.stop_reason === "refusal") {
|
||||
console.warn(`[ai:${req.kind}] refused`, response.stop_details);
|
||||
throw new UserFacingError("AI ไม่เขียนเนื้อหานี้ให้ ลองปรับหัวข้อหรือถ้อยคำ");
|
||||
}
|
||||
if (!response.parsed_output) {
|
||||
console.error(`[ai:${req.kind}] no parsed output`, { stop_reason: response.stop_reason });
|
||||
throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
|
||||
}
|
||||
|
||||
await prisma.aiUsage.create({
|
||||
data: {
|
||||
pageId: req.pageId,
|
||||
userId: req.userId,
|
||||
kind: req.kind,
|
||||
inputTokens: response.usage.input_tokens,
|
||||
outputTokens: response.usage.output_tokens,
|
||||
},
|
||||
});
|
||||
return response.parsed_output;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Prompt text shared by the AI routes that write post captions.
|
||||
|
||||
export const CAPTION_RULES = `- Write natural, conversational Thai the way Thai shop owners post on Facebook. Brand or technical words may stay in English.
|
||||
- Use only facts given in <shop_profile> and the request. Never invent prices, discounts, dates, phone numbers, URLs, statistics, awards or customer reviews. When a caption needs a missing fact, write a short Thai placeholder in square brackets, such as [ราคา] or [วันหมดโปร], for the owner to fill in.
|
||||
- Follow the shop's tone, and never use anything listed under the shop's "ห้ามพูด" field.
|
||||
- No exaggerated claims (cures, guaranteed results, before/after promises) — they break Meta's advertising policy and Thai FDA rules.
|
||||
- Each caption is only the post text: no notes to the owner, no surrounding quotation marks.`;
|
||||
|
||||
export function platformRule(instagram: boolean): string {
|
||||
return instagram
|
||||
? "This caption is also posted to Instagram: end with 3-8 relevant hashtags, stay under 2,200 characters, and don't rely on clickable links — point people to the inbox or the link in the profile instead."
|
||||
: "Facebook only: hashtags are optional (0-3).";
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Client-safe: no server imports. Shared by the AI routes and their UI.
|
||||
|
||||
export interface ShopProfile {
|
||||
business: string;
|
||||
audience: string;
|
||||
tone: string;
|
||||
avoid: string;
|
||||
cta: string;
|
||||
}
|
||||
|
||||
export const PROFILE_FIELDS: { key: keyof ShopProfile; label: string; hint: string; max: number; rows: number }[] = [
|
||||
{ key: "business", label: "ขายอะไร / จุดเด่นของร้าน", hint: "สินค้าหรือบริการ ราคาโดยประมาณ ส่งที่ไหน ต่างจากร้านอื่นตรงไหน", max: 2000, rows: 4 },
|
||||
{ key: "audience", label: "ลูกค้าหลักคือใคร", hint: "เช่น ผู้หญิงวัยทำงาน 25–40 ซื้อเป็นของขวัญ", max: 1000, rows: 2 },
|
||||
{ key: "tone", label: "น้ำเสียงของเพจ", hint: "เช่น เป็นกันเอง เรียกลูกค้าว่า “คุณลูกค้า” ใช้ emoji พอประมาณ", max: 500, rows: 2 },
|
||||
{ key: "avoid", label: "คำหรือเรื่องที่ห้ามพูด", hint: "เช่น ห้ามบอกว่ารักษาหาย ห้ามเทียบกับร้านอื่น ห้ามลงราคาส่ง", max: 1000, rows: 2 },
|
||||
{ key: "cta", label: "ให้ลูกค้าติดต่อทางไหน", hint: "เช่น ทักแชทเพจ / โทร 08x-xxx-xxxx / LINE @shop", max: 500, rows: 2 },
|
||||
];
|
||||
|
||||
export function parseProfile(body: Record<string, unknown>): { profile: ShopProfile } | { error: string } {
|
||||
const profile = {} as ShopProfile;
|
||||
for (const f of PROFILE_FIELDS) {
|
||||
const value = typeof body[f.key] === "string" ? (body[f.key] as string).trim() : "";
|
||||
if (value.length > f.max) return { error: `“${f.label}” ยาวเกิน ${f.max.toLocaleString("th-TH")} ตัวอักษร` };
|
||||
profile[f.key] = value;
|
||||
}
|
||||
if (!profile.business) return { error: "กรอกว่าร้านขายอะไรก่อน" };
|
||||
return { profile };
|
||||
}
|
||||
|
||||
/** Profile as prompt text. The fields are written by the page's own team. */
|
||||
export function profilePrompt(p: ShopProfile | null): string {
|
||||
if (!p) return "<shop_profile>\n(No profile yet — keep shop facts generic and use placeholders.)\n</shop_profile>";
|
||||
const lines = PROFILE_FIELDS.filter((f) => p[f.key]).map((f) => `${f.label}: ${p[f.key]}`);
|
||||
return `<shop_profile>\n${lines.join("\n")}\n</shop_profile>`;
|
||||
}
|
||||
|
||||
export const CAPTION_REFINEMENTS = {
|
||||
shorter: { label: "สั้นลง", instruction: "make it noticeably shorter and punchier" },
|
||||
friendlier: { label: "เป็นกันเองขึ้น", instruction: "make it warmer and more casual, like chatting with a regular customer" },
|
||||
cta: { label: "เพิ่ม CTA", instruction: "add or strengthen one clear call to action, using the shop's usual contact channel" },
|
||||
hashtags: { label: "ใส่ hashtag", instruction: "keep the text as it is and add fitting hashtags at the end" },
|
||||
} as const;
|
||||
|
||||
export type CaptionRefinement = keyof typeof CAPTION_REFINEMENTS;
|
||||
Reference in New Issue
Block a user