From 89d46ab1417130a70a7f917fb74ae1194597744d Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Wed, 25 Nov 2026 21:31:32 +0700 Subject: [PATCH] Add AI auto sales replies for inbox --- docs/ARCHITECTURE.md | 4 +- .../migration.sql | 26 +++++++ prisma/schema.prisma | 30 ++++++++ src/app/(console)/inbox/page.tsx | 6 +- .../api/inbox/[pageId]/ai-settings/route.ts | 51 +++++++++++++ src/app/api/webhooks/meta/route.ts | 15 +++- src/components/InboxAiSettings.tsx | 67 +++++++++++++++++ src/lib/ai/claude.ts | 2 +- src/lib/audit.ts | 3 + src/lib/inbox/aiAutoReply.ts | 73 +++++++++++++++++++ 10 files changed, 272 insertions(+), 5 deletions(-) create mode 100644 prisma/migrations/20261125190000_add_inbox_ai_automation/migration.sql create mode 100644 src/app/api/inbox/[pageId]/ai-settings/route.ts create mode 100644 src/components/InboxAiSettings.tsx create mode 100644 src/lib/inbox/aiAutoReply.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7980b7d..6887a2c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -104,6 +104,8 @@ model PostApproval { postId, approverId, approverLabel, note? @@unique([postId, model AuditLog { id, pageId?, postId?, actorId?, actorLabel, action, detail Json?, createdAt @@index([pageId, createdAt]) } // append-only model Conversation { id, pageId, platform, psid, botEnabled @default(true), lastInboundAt, stage? @@unique([pageId, platform, psid]) } +model PageInboxAiAutomation { id, pageId @unique, enabled, personaName, salesGoal, instructions, updatedById? } +model InboxAiReply { id, automationId, sourceId @unique, recipientId, outcome, createdAt } // dedupe only; no message body model ReplyRule { id, pageId, kind (DM | COMMENT), keywords String[], reply, imageUrl?, publicAck?, isActive, priority } model ReplyLog { id, ruleId, recipientId, sourceId, createdAt @@unique([ruleId, recipientId]) } // dedupe: คนเดิมได้กฎเดิมครั้งเดียว @@ -165,7 +167,7 @@ DRAFT ──ส่ง──▶ PENDING_APPROVAL ──อนุมัติค `/api/webhooks/meta` endpoint เดียวรับทุกเพจ. `entry[].id` = fbPageId → หา `Page` ใน DB (ไม่เจอ = ข้าม) 1. อ่าน raw body (`await req.text()`), verify `X-Hub-Signature-256` ด้วย `META_APP_SECRET` + `timingSafeEqual` → ไม่ผ่านคืน 403 -2. `entry[].messaging[]` = DM (ข้าม `is_echo`) → อัปเดต `Conversation.lastInboundAt` → ถ้า `botEnabled` ลอง match `ReplyRule(kind=DM)` +2. `entry[].messaging[]` = DM (ข้าม `is_echo`) → อัปเดต `Conversation.lastInboundAt` → ถ้า `botEnabled` ลอง match `ReplyRule(kind=DM)` ก่อน; เมื่อไม่ match และเปิด `PageInboxAiAutomation` ให้ AI ตอบจาก `PageProfile` หรือสลับแชทเป็นคนตอบเมื่อข้อมูลไม่พอ/ต้อง handoff. `InboxAiReply.sourceId` กัน webhook ซ้ำโดยไม่เก็บข้อความ 3. `entry[].changes[]` field `feed` (FB, `item=comment, verb=add`) หรือ `comments` (IG, shape ต่างกัน) → ข้ามคอมเมนต์ของเพจเอง → match `ReplyRule(kind=COMMENT)` → จอง `ReplyLog` ก่อนส่ง (unique กันซ้ำ) → `POST /{comment-id}/private_replies` → ส่งไม่ผ่านให้ลบ `ReplyLog` คืน 4. คืน 200 เสมอ (ไม่งั้น Meta ยิงซ้ำรัว) diff --git a/prisma/migrations/20261125190000_add_inbox_ai_automation/migration.sql b/prisma/migrations/20261125190000_add_inbox_ai_automation/migration.sql new file mode 100644 index 0000000..7741c3a --- /dev/null +++ b/prisma/migrations/20261125190000_add_inbox_ai_automation/migration.sql @@ -0,0 +1,26 @@ +CREATE TABLE "PageInboxAiAutomation" ( + "id" TEXT NOT NULL, + "pageId" TEXT NOT NULL, + "enabled" BOOLEAN NOT NULL DEFAULT false, + "personaName" TEXT NOT NULL DEFAULT 'แอดมินพิม', + "salesGoal" TEXT NOT NULL DEFAULT '', + "instructions" TEXT NOT NULL DEFAULT '', + "updatedById" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "PageInboxAiAutomation_pkey" PRIMARY KEY ("id") +); +CREATE TABLE "InboxAiReply" ( + "id" TEXT NOT NULL, + "automationId" TEXT NOT NULL, + "sourceId" TEXT NOT NULL, + "recipientId" TEXT NOT NULL, + "outcome" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "InboxAiReply_pkey" PRIMARY KEY ("id") +); +CREATE UNIQUE INDEX "PageInboxAiAutomation_pageId_key" ON "PageInboxAiAutomation"("pageId"); +CREATE UNIQUE INDEX "InboxAiReply_sourceId_key" ON "InboxAiReply"("sourceId"); +CREATE INDEX "InboxAiReply_automationId_createdAt_idx" ON "InboxAiReply"("automationId", "createdAt"); +ALTER TABLE "PageInboxAiAutomation" ADD CONSTRAINT "PageInboxAiAutomation_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "InboxAiReply" ADD CONSTRAINT "InboxAiReply_automationId_fkey" FOREIGN KEY ("automationId") REFERENCES "PageInboxAiAutomation"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a6f3a48..d6fd780 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -170,6 +170,7 @@ model Page { generationJobs PostGenerationJob[] teamPage TeamPage? contentAutomation PageContentAutomation? + inboxAiAutomation PageInboxAiAutomation? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -361,6 +362,35 @@ model Conversation { @@unique([pageId, platform, psid]) } +// Per-page AI sales assistant. Message bodies remain live in Graph and are +// never persisted here; only configuration and source-message dedupe are kept. +model PageInboxAiAutomation { + id String @id @default(cuid()) + pageId String @unique + page Page @relation(fields: [pageId], references: [id], onDelete: Cascade) + enabled Boolean @default(false) + personaName String @default("แอดมินพิม") + salesGoal String @default("") + instructions String @default("") + updatedById String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + replies InboxAiReply[] +} + +model InboxAiReply { + id String @id @default(cuid()) + automationId String + automation PageInboxAiAutomation @relation(fields: [automationId], references: [id], onDelete: Cascade) + sourceId String @unique + recipientId String + outcome String + createdAt DateTime @default(now()) + + @@index([automationId, createdAt]) +} + model ReplyRule { id String @id @default(cuid()) pageId String diff --git a/src/app/(console)/inbox/page.tsx b/src/app/(console)/inbox/page.tsx index 7a3e33e..d930e05 100644 --- a/src/app/(console)/inbox/page.tsx +++ b/src/app/(console)/inbox/page.tsx @@ -3,6 +3,7 @@ import { roleAtLeast } from "@/lib/auth/roles"; import { EmptyState, PageTitle } from "@/components/ui"; import { InboxView } from "@/components/InboxView"; import { PagePicker } from "@/components/PagePicker"; +import { InboxAiSettings } from "@/components/InboxAiSettings"; export default async function InboxPage() { const ctx = await getConsoleContext(); @@ -12,7 +13,10 @@ export default async function InboxPage() { <> {page ? ( - + <> + + + ) : (
diff --git a/src/app/api/inbox/[pageId]/ai-settings/route.ts b/src/app/api/inbox/[pageId]/ai-settings/route.ts new file mode 100644 index 0000000..f722256 --- /dev/null +++ b/src/app/api/inbox/[pageId]/ai-settings/route.ts @@ -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"); + } +} diff --git a/src/app/api/webhooks/meta/route.ts b/src/app/api/webhooks/meta/route.ts index d20a3ec..f156af3 100644 --- a/src/app/api/webhooks/meta/route.ts +++ b/src/app/api/webhooks/meta/route.ts @@ -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 { diff --git a/src/components/InboxAiSettings.tsx b/src/components/InboxAiSettings.tsx new file mode 100644 index 0000000..2c65f8f --- /dev/null +++ b/src/components/InboxAiSettings.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { withBase } from "@/lib/base-path"; +import { Icon } from "./Icon"; +import { Notice } from "./ui"; + +interface Settings { enabled: boolean; personaName: string; salesGoal: string; instructions: string } + +export function InboxAiSettings({ pageId, canManage }: { pageId: string; canManage: boolean }) { + const [settings, setSettings] = useState(null); + const [open, setOpen] = useState(false); + const [saving, setSaving] = useState(false); + const [message, setMessage] = useState<{ tone: "blue" | "red"; text: string } | null>(null); + const endpoint = withBase(`/api/inbox/${pageId}/ai-settings`); + + useEffect(() => { + let active = true; + fetch(endpoint, { cache: "no-store" }).then(async (res) => { + const body = await res.json().catch(() => null); + if (active && res.ok) setSettings(body); + }); + return () => { active = false; }; + }, [endpoint]); + + async function save(next: Settings) { + setSaving(true); setMessage(null); + const res = await fetch(endpoint, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(next) }); + const body = await res.json().catch(() => ({})); + setSaving(false); + if (!res.ok) return setMessage({ tone: "red", text: body.error ?? "บันทึก AI Auto ไม่สำเร็จ" }); + setSettings(body); setMessage({ tone: "blue", text: "บันทึกการตั้งค่า AI Auto แล้ว" }); + } + + if (!settings) return null; + return ( +
+
+ +
+

AI Auto สำหรับปิดการขาย

+

{settings.enabled ? `${settings.personaName} กำลังช่วยตอบแชท และส่งต่อให้คนเมื่อไม่มั่นใจ` : "AI ยังไม่ส่งข้อความอัตโนมัติ"}

+
+ {settings.enabled ? "กำลังทำงาน" : "ปิดอยู่"} + +
+ {open && ( +
+ AI จะตอบจากข้อมูลโปรไฟล์เพจเท่านั้น ไม่แต่งราคา สต็อก หรือโปรโมชัน และจะหยุดให้แอดมินรับช่วงเมื่อเรื่องเกินขอบเขต +
+ + +
+