Add AI auto sales replies for inbox

This commit is contained in:
Loma Bot Ops
2026-11-25 21:31:32 +07:00
parent dd42b81639
commit 89d46ab141
10 changed files with 272 additions and 5 deletions
@@ -0,0 +1,51 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requirePageAction } from "@/lib/auth/user";
import { audit } from "@/lib/audit";
import { errorResponse, readJson, str } from "@/lib/http";
type Ctx = { params: Promise<{ pageId: string }> };
export async function GET(_req: Request, ctx: Ctx) {
const { pageId } = await ctx.params;
const auth = await requirePageAction(pageId, "view");
if (!auth.ok) return auth.response;
const settings = await prisma.pageInboxAiAutomation.findUnique({
where: { pageId }, select: { enabled: true, personaName: true, salesGoal: true, instructions: true },
});
return NextResponse.json(settings ?? { enabled: false, personaName: "แอดมินพิม", salesGoal: "", instructions: "" });
}
export async function PUT(req: Request, ctx: Ctx) {
const { pageId } = await ctx.params;
const auth = await requirePageAction(pageId, "editRules");
if (!auth.ok) return auth.response;
try {
const body = await readJson(req);
const enabled = body.enabled === true;
const personaName = str(body.personaName).trim().slice(0, 60) || "แอดมินพิม";
const salesGoal = str(body.salesGoal).trim().slice(0, 500);
const instructions = str(body.instructions).trim().slice(0, 1200);
if (enabled) {
const profile = await prisma.pageProfile.findUnique({ where: { pageId }, select: { business: true } });
if (!profile?.business.trim()) return NextResponse.json({ error: "กรอกข้อมูลธุรกิจในโปรไฟล์เพจก่อนเปิด AI Auto" }, { status: 400 });
}
const previous = await prisma.pageInboxAiAutomation.findUnique({ where: { pageId }, select: { enabled: true } });
const settings = await prisma.$transaction(async (tx) => {
const saved = await tx.pageInboxAiAutomation.upsert({
where: { pageId },
create: { pageId, enabled, personaName, salesGoal, instructions, updatedById: auth.user.id },
update: { enabled, personaName, salesGoal, instructions, updatedById: auth.user.id },
});
await audit({
action: previous?.enabled !== enabled ? (enabled ? "INBOX_AI_ENABLED" : "INBOX_AI_DISABLED") : "INBOX_AI_SETTINGS_SAVED",
actorId: auth.user.id, actorLabel: auth.user.name, pageId,
detail: { enabled, personaName },
}, tx);
return saved;
});
return NextResponse.json({ enabled: settings.enabled, personaName, salesGoal, instructions });
} catch (error) {
return errorResponse(error, "inbox:ai-settings");
}
}
+13 -2
View File
@@ -1,16 +1,18 @@
import { NextResponse } from "next/server";
import { createHmac, timingSafeEqual } from "node:crypto";
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { prisma } from "@/lib/db";
import { FacebookApiError } from "@/lib/facebook/client";
import { getPageCredentialsByFbId, type PageCredentials } from "@/lib/facebook/tokens";
import { replyToComment, sendImageMessage, sendPrivateReply, sendSenderAction, sendTextMessage } from "@/lib/facebook/inbox";
import { claimReplySlot, matchRule, releaseReplySlot, typingDelayMs } from "@/lib/inbox/autoReply";
import { runInboxAiAutoReply } from "@/lib/inbox/aiAutoReply";
// Meta calls this with no session: GET proves ownership via the verify token,
// POST proves authenticity via the X-Hub-Signature-256 HMAC. Listed in
// SELF_AUTH_PREFIXES in src/proxy.ts. node:crypto needs the Node runtime.
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const maxDuration = 300;
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
@@ -118,7 +120,16 @@ async function handleMessage(page: PageCredentials, platform: "FACEBOOK" | "INST
if (!text || !convo.botEnabled) return;
const rule = await matchRule(page.id, "DM", text);
if (!rule) return;
if (!rule) {
await runInboxAiAutoReply({
page,
platform,
recipientId: psid,
sourceId: event.message?.mid ?? createHash("sha256").update(`${platform}:${page.id}:${psid}:${text}`).digest("hex"),
text,
});
return;
}
if (!(await claimReplySlot(rule.id, psid, event.message?.mid ?? `dm-${Date.now()}`))) return;
try {