From 6ef01cb4b6606df422c6a218afa18e613c3472cc Mon Sep 17 00:00:00 2001 From: Loma Bot Ops Date: Mon, 23 Nov 2026 21:59:02 +0700 Subject: [PATCH] Add news research assistant to post editor --- src/app/api/ai/research/route.ts | 71 +++++++++++++ src/app/globals.css | 75 ++++++++++++++ src/components/ContentResearchAssistant.tsx | 109 ++++++++++++++++++++ src/components/PostEditor.tsx | 40 ++++--- src/components/ThaiDateTimePicker.tsx | 81 +++++++++++++++ src/lib/ai/claude.ts | 2 +- src/lib/ai/news.ts | 58 +++++++++++ src/lib/facebook/client.ts | 10 ++ src/lib/facebook/posts.ts | 67 ++++++++++-- 9 files changed, 491 insertions(+), 22 deletions(-) create mode 100644 src/app/api/ai/research/route.ts create mode 100644 src/components/ContentResearchAssistant.tsx create mode 100644 src/components/ThaiDateTimePicker.tsx create mode 100644 src/lib/ai/news.ts diff --git a/src/app/api/ai/research/route.ts b/src/app/api/ai/research/route.ts new file mode 100644 index 0000000..c207d42 --- /dev/null +++ b/src/app/api/ai/research/route.ts @@ -0,0 +1,71 @@ +import { NextResponse } from "next/server"; +import * as z from "zod/v4"; +import { prisma } from "@/lib/db"; +import { requirePageAction } from "@/lib/auth/user"; +import { errorResponse, readJson, str } from "@/lib/http"; +import { UserFacingError } from "@/lib/facebook/client"; +import { generateStructured } from "@/lib/ai/claude"; +import { searchNews } from "@/lib/ai/news"; +import { websitePrompt } from "@/lib/ai/website"; +import { profilePrompt } from "@/lib/ai/shared"; +import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts"; + +export const maxDuration = 300; + +const ResearchDraft = z.object({ + summary: z.string().describe("A concise Thai summary of the source in 2-3 sentences"), + keyPoints: z.array(z.string()).describe("Three useful factual takeaways in Thai"), + postTitle: z.string().describe("A short internal Thai title for the post"), + caption: z.string().describe("A ready-to-edit Thai social caption grounded only in the source"), +}); + +const SYSTEM = `You turn a recent article into an educational Thai social post for a small business page. The owner reviews the source and edits your draft before it goes through human approval. + +Never invent facts, quotes, dates, product capabilities, or statistics. Distinguish confirmed source facts from commentary. If the source text is thin, write a cautious overview and say what should be checked. Do not copy long passages. Mention the source naturally at the end. + +${CAPTION_RULES}`; + +export async function POST(req: Request) { + const body = await readJson(req); + const pageId = str(body.pageId); + const auth = await requirePageAction(pageId, "editPost"); + if (!auth.ok) return auth.response; + + try { + const action = str(body.action); + if (action === "search") { + const query = str(body.query).trim(); + if (query.length < 2) throw new UserFacingError("พิมพ์หัวข้อที่ต้องการค้นหาอย่างน้อย 2 ตัวอักษร"); + if (query.length > 120) throw new UserFacingError("หัวข้อค้นหายาวเกิน 120 ตัวอักษร"); + const articles = await searchNews(query); + return NextResponse.json({ articles }); + } + + if (action !== "summarize") throw new UserFacingError("ไม่รู้จักคำสั่งค้นคว้านี้"); + const title = str(body.title).trim(); + const url = str(body.url).trim(); + const source = str(body.source).trim(); + const description = str(body.description).trim().slice(0, 600); + if (!title || !/^https?:\/\//.test(url)) throw new UserFacingError("ข้อมูลบทความไม่ครบ กรุณาค้นหาใหม่"); + + const page = await prisma.page.findUnique({ + where: { id: pageId }, + select: { profile: { select: { business: true, audience: true, tone: true, visualStyle: true, avoid: true, cta: true, website: true } } }, + }); + if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 }); + + const articleText = await websitePrompt(url); + const result = await generateStructured({ + kind: "research", + pageId, + userId: auth.user.id, + system: SYSTEM, + prompt: `${profilePrompt(page.profile)}\n\n${platformRule(Array.isArray(body.targets) && body.targets.includes("INSTAGRAM"))}\n\nCreate a factual post from this source.\nTitle: ${title}\nPublisher: ${source || "ไม่ระบุ"}\nURL: ${url}\nSearch excerpt: ${description || "ไม่มี"}\n\n${articleText || "The article page could not be read. Use only the title and search excerpt, keep the summary cautious, and explicitly advise the owner to verify the original."}`, + schema: ResearchDraft, + effort: "low", + }); + return NextResponse.json({ draft: result, sourceRead: Boolean(articleText) }); + } catch (error) { + return errorResponse(error, "ai:research"); + } +} diff --git a/src/app/globals.css b/src/app/globals.css index df164b4..66882c1 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1259,6 +1259,79 @@ } } + /* Thai date/time picker: Buddhist year, Thai labels, 24-hour Bangkok time. */ + .thai-picker { position: relative; width: 100%; } + .content-research { display: flex; flex-direction: column; gap: 14px; padding: 16px; background: var(--board); border-radius: 14px; } + .content-research-head { display: flex; align-items: flex-start; gap: 16px; } + .content-research-head > div { flex: 1; min-width: 0; } + .content-research-head b { display: block; color: var(--ink); font-size: 15px; font-weight: 600; } + .content-research-head p, .content-research-foot { margin-top: 3px; color: var(--ink-3); font-size: 12px; line-height: 1.55; } + .content-research-search { display: flex; gap: 8px; } + .content-research-input { flex: 1; min-width: 0; height: 42px; display: flex; align-items: center; gap: 9px; padding: 0 12px; color: var(--ink-3); background: var(--paper); border: 1px solid var(--line); border-radius: 10px; } + .content-research-input:focus-within { border-color: var(--m-blue); box-shadow: 0 0 0 3px var(--m-blue-soft); } + .content-research-input input { width: 100%; min-width: 0; color: var(--ink); background: transparent; outline: none; } + .content-research-suggestions { display: flex; flex-wrap: wrap; gap: 7px; } + .content-research-suggestions button { min-height: 32px; padding: 5px 10px; color: var(--ink-2); background: var(--paper); border: 1px solid var(--line); border-radius: 9px; font-size: 12px; } + .content-research-suggestions button:hover:not(:disabled) { color: var(--m-blue); border-color: var(--m-blue); } + .research-results { max-height: 460px; overflow-y: auto; display: flex; flex-direction: column; gap: 0; background: var(--paper); border-radius: 12px; } + .research-results article { padding: 14px; border-bottom: 1px solid var(--line); } + .research-results article:last-child { border-bottom: 0; } + .research-results article[data-selected] { background: var(--m-blue-soft); } + .research-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; color: var(--ink-3); font-size: 11px; } + .research-meta span { color: var(--m-blue); font-weight: 600; } + .research-results h3, .research-draft h3 { margin-top: 5px; color: var(--ink); font-size: 14px; font-weight: 600; line-height: 1.5; } + .research-results article > p, .research-draft > p { margin-top: 4px; color: var(--ink-2); font-size: 12px; line-height: 1.6; } + .research-actions, .research-draft-actions { display: flex; align-items: center; gap: 8px; margin-top: 10px; } + .research-actions a, .research-actions button, .research-meta a { min-height: 32px; display: inline-flex; align-items: center; gap: 5px; color: var(--m-blue); font-size: 12px; font-weight: 500; } + .research-actions button { padding: 4px 9px; margin-left: auto; background: var(--m-blue-soft); border-radius: 8px; } + .research-loading, .research-empty { min-height: 72px; display: flex; align-items: center; justify-content: center; gap: 6px; color: var(--ink-3); font-size: 12px; } + .research-loading span { width: 6px; height: 6px; background: var(--m-blue); border-radius: 50%; animation: research-pulse 900ms ease-in-out infinite alternate; } + .research-loading span:nth-child(2) { animation-delay: 150ms; } + .research-loading span:nth-child(3) { animation-delay: 300ms; } + .research-draft { padding: 15px; background: var(--paper); border-radius: 12px; } + .research-draft ul { display: grid; gap: 6px; margin: 10px 0 0 18px; color: var(--ink-2); font-size: 12px; line-height: 1.55; list-style: disc; } + .research-draft-actions { justify-content: flex-end; margin-top: 14px; } + @keyframes research-pulse { from { opacity: .35; transform: translateY(1px); } to { opacity: 1; transform: translateY(-1px); } } + @media (max-width: 639px) { + .content-research { padding: 14px; } + .content-research-search { align-items: stretch; flex-direction: column; } + .content-research-input { flex: none; height: 46px; font-size: 16px; } + .content-research-search > .btn { width: 100%; } + .research-actions { align-items: stretch; flex-direction: column; } + .research-actions a, .research-actions button { width: 100%; justify-content: center; } + .research-actions button { margin-left: 0; } + } + .thai-picker-trigger { width: 100%; height: 42px; padding: 0 12px 0 14px; display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 10px; text-align: start; } + .thai-picker-trigger:hover { border-color: var(--ink-3); } + .thai-picker-trigger:focus-visible { outline: none; border-color: var(--m-blue); box-shadow: 0 0 0 3px var(--m-blue-soft); } + .thai-picker-trigger svg { flex: none; color: var(--m-blue); } + .thai-picker-trigger:disabled { cursor: not-allowed; color: var(--ink-3); background: var(--board); } + .thai-picker-popover { position: absolute; z-index: 40; right: 0; bottom: calc(100% + 8px); width: min(360px, calc(100vw - 40px)); padding: 16px; color: var(--ink); background: var(--paper); border-radius: 16px; box-shadow: var(--shadow-lift); transform-origin: bottom right; animation: thai-picker-in 160ms cubic-bezier(.23,1,.32,1); } + .thai-picker-head { height: 40px; display: grid; grid-template-columns: 40px 1fr 40px; align-items: center; margin-bottom: 8px; } + .thai-picker-head strong { text-align: center; font-size: 15px; font-weight: 600; } + .thai-picker-head button { width: 40px; height: 40px; border-radius: 8px; color: var(--ink-2); font-size: 27px; line-height: 1; } + .thai-picker-head button:hover { color: var(--m-blue); background: var(--m-blue-soft); } + .thai-picker-week, .thai-picker-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; } + .thai-picker-week { margin-bottom: 4px; color: var(--ink-3); font-size: 11px; font-weight: 500; text-align: center; } + .thai-picker-week span { display: grid; place-items: center; height: 28px; } + .thai-picker-grid button, .thai-picker-grid > span { aspect-ratio: 1; min-width: 0; border-radius: 8px; display: grid; place-items: center; font-size: 13px; font-variant-numeric: tabular-nums; } + .thai-picker-grid button:hover { color: var(--m-blue); background: var(--m-blue-soft); } + .thai-picker-grid button[data-today] { box-shadow: inset 0 0 0 1px var(--m-blue); color: var(--m-blue); font-weight: 600; } + .thai-picker-grid button[aria-pressed="true"] { color: #fff; background: var(--m-blue); box-shadow: none; font-weight: 600; } + .thai-picker-time { display: flex; align-items: center; gap: 7px; min-height: 48px; margin-top: 12px; padding: 8px 10px; color: var(--ink-2); background: var(--board); border-radius: 10px; font-size: 13px; } + .thai-picker-time svg { color: var(--m-blue); } + .thai-picker-time select { height: 32px; padding: 0 7px; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 7px; font-variant-numeric: tabular-nums; } + .thai-picker-time select:first-of-type { margin-left: auto; } + .thai-picker-time select:focus-visible { outline: 2px solid var(--m-blue); outline-offset: 1px; } + .thai-picker-foot { display: flex; align-items: center; justify-content: space-between; min-height: 38px; margin-top: 10px; } + .thai-picker-foot > button:first-child { min-width: 48px; min-height: 36px; color: var(--m-blue); font-weight: 500; } + .thai-picker-foot > button:first-child:hover { text-decoration: underline; text-underline-offset: 3px; } + @keyframes thai-picker-in { from { opacity: 0; transform: translateY(4px) scale(.98); } } + @media (max-width: 639px) { + .thai-picker-popover { position: fixed; right: 12px; bottom: calc(76px + env(safe-area-inset-bottom)); width: calc(100vw - 24px); padding: 14px; transform-origin: bottom center; } + .thai-picker-trigger { height: 46px; font-size: 16px; } + } + @media (prefers-reduced-motion: reduce) { input[type="checkbox"], .input[type="date"]::-webkit-calendar-picker-indicator, @@ -1272,6 +1345,8 @@ animation: none; transition: none; } + .thai-picker-popover { animation: none; } + .research-loading span { animation: none; } .post-card, .post-card:hover { transition: none; diff --git a/src/components/ContentResearchAssistant.tsx b/src/components/ContentResearchAssistant.tsx new file mode 100644 index 0000000..259fe44 --- /dev/null +++ b/src/components/ContentResearchAssistant.tsx @@ -0,0 +1,109 @@ +"use client"; + +import { useState } from "react"; +import { withBase } from "@/lib/base-path"; +import { Icon } from "./Icon"; +import { Notice } from "./ui"; + +type Target = "FACEBOOK" | "INSTAGRAM"; +type Article = { title: string; url: string; source: string; publishedAt: string | null; description: string }; +type Draft = { summary: string; keyPoints: string[]; postTitle: string; caption: string }; + +const SUGGESTIONS = ["AI รุ่นใหม่", "เทคโนโลยีสำหรับธุรกิจ", "การตลาดออนไลน์", "ความรู้สำหรับเจ้าของร้าน"]; + +function thaiDate(value: string | null) { + if (!value) return "ไม่ระบุวันที่"; + return new Intl.DateTimeFormat("th-TH", { day: "numeric", month: "short", year: "numeric", timeZone: "Asia/Bangkok" }).format(new Date(value)); +} + +export function ContentResearchAssistant({ pageId, targets, onApply }: { pageId: string; targets: Target[]; onApply: (title: string, caption: string) => void }) { + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [articles, setArticles] = useState([]); + const [selected, setSelected] = useState
(null); + const [draft, setDraft] = useState(null); + const [sourceRead, setSourceRead] = useState(true); + const [busy, setBusy] = useState<"search" | "summarize" | null>(null); + const [error, setError] = useState(null); + + async function request(payload: Record) { + const response = await fetch(withBase("/api/ai/research"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, targets, ...payload }) }); + const json = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(json.error ?? "ค้นคว้าเนื้อหาไม่สำเร็จ ลองใหม่อีกครั้ง"); + return json; + } + + async function search(nextQuery = query) { + setQuery(nextQuery); + setBusy("search"); + setError(null); + setSelected(null); + setDraft(null); + try { + const json = await request({ action: "search", query: nextQuery }); + setArticles(json.articles ?? []); + } catch (err) { + setError(err instanceof Error ? err.message : "ค้นหาข่าวไม่สำเร็จ"); + } finally { + setBusy(null); + } + } + + async function summarize(article: Article) { + setSelected(article); + setDraft(null); + setBusy("summarize"); + setError(null); + try { + const json = await request({ action: "summarize", ...article }); + setDraft(json.draft); + setSourceRead(json.sourceRead !== false); + } catch (err) { + setError(err instanceof Error ? err.message : "สรุปบทความไม่สำเร็จ"); + } finally { + setBusy(null); + } + } + + if (!open) return ( + + ); + + return ( +
+
+
หาข่าวและความรู้ใหม่

ค้นแหล่งข่าว แล้วให้ AI สรุปเป็นร่างโพสต์ที่แก้ไขต่อได้

+ +
+
{ event.preventDefault(); void search(); }}> + +
setQuery(event.target.value)} placeholder="เช่น โมเดล AI ใหม่สำหรับธุรกิจ" />
+ +
+
+ {SUGGESTIONS.map((item) => )} +
+ {error && {error}} + {busy === "search" &&
กำลังหาข่าวล่าสุด…
} + {!busy && query && articles.length === 0 && !error &&

ยังไม่พบข่าวในหัวข้อนี้ ลองใช้คำค้นที่กว้างขึ้น

} + {articles.length > 0 && !draft &&
+ {articles.map((article) =>
+
{article.source}
+

{article.title}

+ {article.description &&

{article.description}

} +
เปิดต้นฉบับ
+
)} +
} + {draft && selected &&
+ +

{draft.postTitle}

{draft.summary}

+
    {draft.keyPoints.map((point) =>
  • {point}
  • )}
+ {!sourceRead && เว็บไซต์ต้นฉบับอ่านอัตโนมัติไม่ได้ ร่างนี้อ้างอิงหัวข้อและคำโปรยเท่านั้น ควรเปิดต้นฉบับตรวจข้อเท็จจริงก่อนใช้} +
+
} +

AI อาจสรุปคลาดเคลื่อน ควรเปิดแหล่งข่าวและตรวจข้อเท็จจริงก่อนส่งอนุมัติ

+
+ ); +} diff --git a/src/components/PostEditor.tsx b/src/components/PostEditor.tsx index 35c08e0..61f22ba 100644 --- a/src/components/PostEditor.tsx +++ b/src/components/PostEditor.tsx @@ -15,6 +15,8 @@ import { PostCheck } from "./PostCheck"; import { PageAvatar } from "./PageAvatar"; import { formatDateTime, Notice, StatusPill } from "./ui"; import { useToast } from "./Toast"; +import { ThaiDateTimePicker } from "./ThaiDateTimePicker"; +import { ContentResearchAssistant } from "./ContentResearchAssistant"; type Target = "FACEBOOK" | "INSTAGRAM"; @@ -66,9 +68,16 @@ const ACTION_LABEL: Record = { const EDITABLE: PostStatus[] = ["DRAFT", "PENDING_APPROVAL", "APPROVED", "FAILED", "CANCELLED"]; -function toLocalInput(d: Date): string { - const pad = (n: number) => String(n).padStart(2, "0"); - return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`; +function toBangkokInput(d: Date): string { + const parts = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Bangkok", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(d); + const get = (type: Intl.DateTimeFormatPartTypes) => parts.find((part) => part.type === type)?.value ?? ""; + return `${get("year")}-${get("month")}-${get("day")}T${get("hour")}:${get("minute")}`; +} + +function bangkokInputToIso(value: string): string { + const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value); + if (!match) return new Date(value).toISOString(); + return new Date(Date.UTC(+match[1], +match[2] - 1, +match[3], +match[4] - 7, +match[5])).toISOString(); } export function PostEditor({ @@ -102,7 +111,7 @@ export function PostEditor({ const [aiAssisted, setAiAssisted] = useState(post?.aiAssisted ?? Boolean(initialDraft)); const [imageUrl, setImageUrl] = useState(post?.imageBlobUrl ?? null); const [targets, setTargets] = useState(post?.targets ?? ["FACEBOOK"]); - const [scheduleAt, setScheduleAt] = useState(() => toLocalInput(new Date(Date.now() + 60 * 60 * 1000))); + const [scheduleAt, setScheduleAt] = useState(() => toBangkokInput(new Date(Date.now() + 60 * 60 * 1000))); const [note, setNote] = useState(""); const [plannedDay, setPlannedDay] = useState(initialDay ?? ""); const [busy, setBusy] = useState(null); @@ -197,10 +206,9 @@ export function PostEditor({ } function quickSchedule(dayOffset: number, hour: number) { - const d = new Date(); - d.setDate(d.getDate() + dayOffset); - d.setHours(hour, 0, 0, 0); - setScheduleAt(toLocalInput(d)); + const [year, month, day] = toBangkokInput(new Date()).slice(0, 10).split("-").map(Number); + const target = new Date(Date.UTC(year, month - 1, day + dayOffset)); + setScheduleAt(`${target.getUTCFullYear()}-${String(target.getUTCMonth() + 1).padStart(2, "0")}-${String(target.getUTCDate()).padStart(2, "0")}T${String(hour).padStart(2, "0")}:00`); } // The one next step for this post, surfaced in the phone action dock. @@ -260,14 +268,16 @@ export function PostEditor({ setTitle(e.target.value)} placeholder="เช่น โปรโมชั่นปลายเดือน" /> - {!post &&