Add news research assistant to post editor

This commit is contained in:
Loma Bot Ops
2026-11-23 21:59:02 +07:00
parent 5f8f0c9159
commit 6ef01cb4b6
9 changed files with 491 additions and 22 deletions
+71
View File
@@ -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");
}
}
+75
View File
@@ -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;
+109
View File
@@ -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<Article[]>([]);
const [selected, setSelected] = useState<Article | null>(null);
const [draft, setDraft] = useState<Draft | null>(null);
const [sourceRead, setSourceRead] = useState(true);
const [busy, setBusy] = useState<"search" | "summarize" | null>(null);
const [error, setError] = useState<string | null>(null);
async function request(payload: Record<string, unknown>) {
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 (
<button type="button" className="btn btn-ghost btn-sm self-start" onClick={() => setOpen(true)}>
<Icon name="search" size={15} /> หาข่าวและความรู้ใหม่
</button>
);
return (
<section className="content-research" aria-label="หาข่าวและความรู้ใหม่">
<div className="content-research-head">
<div><b>หาข่าวและความรู้ใหม่</b><p>ค้นแหล่งข่าว แล้วให้ AI สรุปเป็นร่างโพสต์ที่แก้ไขต่อได้</p></div>
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)} aria-label="ปิดเครื่องมือค้นคว้า"><Icon name="x" size={15} /></button>
</div>
<form className="content-research-search" onSubmit={(event) => { event.preventDefault(); void search(); }}>
<label className="sr-only" htmlFor="research-query">หัวข้อข่าวหรือความรู้ที่ต้องการ</label>
<div className="content-research-input"><Icon name="search" size={17} /><input id="research-query" value={query} maxLength={120} onChange={(event) => setQuery(event.target.value)} placeholder="เช่น โมเดล AI ใหม่สำหรับธุรกิจ" /></div>
<button className="btn btn-primary" disabled={busy !== null || query.trim().length < 2}>{busy === "search" ? "กำลังค้น…" : "ค้นหาข่าว"}</button>
</form>
<div className="content-research-suggestions" aria-label="หัวข้อแนะนำ">
{SUGGESTIONS.map((item) => <button type="button" key={item} disabled={busy !== null} onClick={() => void search(item)}>{item}</button>)}
</div>
{error && <Notice tone="red">{error}</Notice>}
{busy === "search" && <div className="research-loading" aria-live="polite"><span /><span /><span /> กำลังหาข่าวล่าสุด…</div>}
{!busy && query && articles.length === 0 && !error && <p className="research-empty">ยังไม่พบข่าวในหัวข้อนี้ ลองใช้คำค้นที่กว้างขึ้น</p>}
{articles.length > 0 && !draft && <div className="research-results" aria-label="ผลการค้นหา">
{articles.map((article) => <article key={article.url} data-selected={selected?.url === article.url || undefined}>
<div className="research-meta"><span>{article.source}</span><time dateTime={article.publishedAt ?? undefined}>{thaiDate(article.publishedAt)}</time></div>
<h3>{article.title}</h3>
{article.description && <p>{article.description}</p>}
<div className="research-actions"><a href={article.url} target="_blank" rel="noreferrer"><Icon name="link" size={14} /> เปิดต้นฉบับ</a><button type="button" disabled={busy !== null} onClick={() => void summarize(article)}><Icon name="sparkle" size={14} /> {busy === "summarize" && selected?.url === article.url ? "กำลังอ่านและสรุป…" : "สรุปเป็นโพสต์"}</button></div>
</article>)}
</div>}
{draft && selected && <div className="research-draft" aria-live="polite">
<div className="research-meta"><span>{selected.source}</span><a href={selected.url} target="_blank" rel="noreferrer">ตรวจต้นฉบับ <Icon name="link" size={13} /></a></div>
<h3>{draft.postTitle}</h3><p>{draft.summary}</p>
<ul>{draft.keyPoints.map((point) => <li key={point}>{point}</li>)}</ul>
{!sourceRead && <Notice tone="amber">เว็บไซต์ต้นฉบับอ่านอัตโนมัติไม่ได้ ร่างนี้อ้างอิงหัวข้อและคำโปรยเท่านั้น ควรเปิดต้นฉบับตรวจข้อเท็จจริงก่อนใช้</Notice>}
<div className="research-draft-actions"><button type="button" className="btn btn-ghost btn-sm" onClick={() => setDraft(null)}>กลับไปดูข่าว</button><button type="button" className="btn btn-primary btn-sm" onClick={() => { onApply(draft.postTitle, draft.caption); setOpen(false); }}><Icon name="check" size={15} /> นำไปใส่ในโพสต์</button></div>
</div>}
<p className="content-research-foot">AI อาจสรุปคลาดเคลื่อน ควรเปิดแหล่งข่าวและตรวจข้อเท็จจริงก่อนส่งอนุมัติ</p>
</section>
);
}
+25 -15
View File
@@ -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<string, string> = {
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<string | null>(post?.imageBlobUrl ?? null);
const [targets, setTargets] = useState<Target[]>(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<string | null>(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({
<input className="input" value={title} disabled={!canEdit} onChange={(e) => setTitle(e.target.value)} placeholder="เช่น โปรโมชั่นปลายเดือน" />
</label>
{!post && <label className="field">
{!post && <div className="field">
<span>วันวางแผนโพสต์ (ยังไม่เผยแพร่)</span>
<input className="input" type="date" value={plannedDay} disabled={!canEdit} onChange={e => setPlannedDay(e.target.value)} />
<ThaiDateTimePicker dateOnly value={plannedDay} disabled={!canEdit} onChange={setPlannedDay} label="เลือกวันวางแผนโพสต์" />
<small className="text-ink-3">เว้นว่างเพื่อเลือกวันภายหลัง · อนุมัติก่อน แล้วเลือกเวลาเผยแพร่</small>
</label>}
</div>}
{!post && canEdit && pageId && <PostGenerationQueue key={pageId} pageId={pageId} targets={targets} plannedDay={plannedDay} initialTopic={initialDraft?.topic || title} />}
{canEdit && pageId && <ContentResearchAssistant pageId={pageId} targets={targets} onApply={(nextTitle, nextCaption) => { setTitle(nextTitle); setCaption(nextCaption); setAiAssisted(true); }} />}
{canEdit && pageId && (
<CaptionAssistant
pageId={pageId}
@@ -448,15 +458,15 @@ export function PostEditor({
</div>
</div>
<div className="flex gap-2 items-end">
<label className="field flex-1 min-w-0">
<div className="field flex-1 min-w-0">
<span className="sr-only">วันและเวลาที่จะเผยแพร่</span>
<input className="input num" type="datetime-local" value={scheduleAt} onChange={(e) => setScheduleAt(e.target.value)} />
</label>
<ThaiDateTimePicker value={scheduleAt} onChange={setScheduleAt} label="เลือกวันและเวลาเผยแพร่" />
</div>
<button
type="button"
className="btn btn-primary"
disabled={Boolean(busy) || !scheduleAt}
onClick={() => act("schedule", { scheduledAt: new Date(scheduleAt).toISOString() })}
onClick={() => act("schedule", { scheduledAt: bangkokInputToIso(scheduleAt) })}
>
<Icon name="clock" size={16} /> ตั้งเวลา
</button>
+81
View File
@@ -0,0 +1,81 @@
"use client";
import { useEffect, useId, useMemo, useRef, useState } from "react";
import { Icon } from "./Icon";
const THAI_MONTHS = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];
const THAI_DAYS = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."];
const pad = (value: number) => String(value).padStart(2, "0");
function parseValue(value: string) {
const match = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?$/.exec(value);
return match ? { year: +match[1], month: +match[2] - 1, day: +match[3], hour: +(match[4] ?? 9), minute: +(match[5] ?? 0) } : null;
}
function bangkokToday() {
const parts = new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Bangkok", year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date());
const get = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((part) => part.type === type)?.value);
return { year: get("year"), month: get("month") - 1, day: get("day") };
}
export function ThaiDateTimePicker({ value, onChange, dateOnly = false, disabled = false, label = "เลือกวันและเวลา" }: { value: string; onChange: (value: string) => void; dateOnly?: boolean; disabled?: boolean; label?: string }) {
const id = useId();
const rootRef = useRef<HTMLDivElement>(null);
const selected = parseValue(value);
const [today] = useState(() => bangkokToday());
const [open, setOpen] = useState(false);
const [view, setView] = useState(() => ({ year: selected?.year ?? today.year, month: selected?.month ?? today.month }));
useEffect(() => {
const close = (event: PointerEvent) => { if (!rootRef.current?.contains(event.target as Node)) setOpen(false); };
const escape = (event: KeyboardEvent) => { if (event.key === "Escape") setOpen(false); };
document.addEventListener("pointerdown", close);
document.addEventListener("keydown", escape);
return () => { document.removeEventListener("pointerdown", close); document.removeEventListener("keydown", escape); };
}, []);
const days = useMemo(() => {
const first = new Date(Date.UTC(view.year, view.month, 1)).getUTCDay();
const count = new Date(Date.UTC(view.year, view.month + 1, 0)).getUTCDate();
return Array.from({ length: 42 }, (_, index) => { const day = index - first + 1; return day >= 1 && day <= count ? day : null; });
}, [view]);
const display = selected ? `${selected.day} ${THAI_MONTHS[selected.month]} ${selected.year + 543}${dateOnly ? "" : ` เวลา ${pad(selected.hour)}:${pad(selected.minute)} น.`}` : dateOnly ? "เลือกวันที่" : "เลือกวันและเวลา";
function pickDay(day: number) {
const time = selected ?? { hour: 9, minute: 0 };
onChange(`${view.year}-${pad(view.month + 1)}-${pad(day)}${dateOnly ? "" : `T${pad(time.hour)}:${pad(time.minute)}`}`);
if (dateOnly) setOpen(false);
}
function pickToday() {
const time = selected ?? { hour: 9, minute: 0 };
setView({ year: today.year, month: today.month });
onChange(`${today.year}-${pad(today.month + 1)}-${pad(today.day)}${dateOnly ? "" : `T${pad(time.hour)}:${pad(time.minute)}`}`);
if (dateOnly) setOpen(false);
}
function changeTime(kind: "hour" | "minute", next: number) {
const date = selected ?? { ...today, hour: 9, minute: 0 };
const result = { ...date, [kind]: next };
onChange(`${result.year}-${pad(result.month + 1)}-${pad(result.day)}T${pad(result.hour)}:${pad(result.minute)}`);
}
function moveMonth(offset: number) {
const next = new Date(Date.UTC(view.year, view.month + offset, 1));
setView({ year: next.getUTCFullYear(), month: next.getUTCMonth() });
}
function togglePicker() {
if (!open && selected) setView({ year: selected.year, month: selected.month });
setOpen((current) => !current);
}
return <div className="thai-picker" ref={rootRef}>
<button type="button" className="thai-picker-trigger num" disabled={disabled} aria-expanded={open} aria-controls={id} onClick={togglePicker}>
<span className={selected ? "" : "text-ink-4"}>{display}</span><Icon name="calendar" size={19} />
</button>
{open && <div className="thai-picker-popover" id={id} role="dialog" aria-label={label}>
<div className="thai-picker-head"><button type="button" aria-label="เดือนก่อนหน้า" onClick={() => moveMonth(-1)}>‹</button><strong>{THAI_MONTHS[view.month]} {view.year + 543}</strong><button type="button" aria-label="เดือนถัดไป" onClick={() => moveMonth(1)}>›</button></div>
<div className="thai-picker-week" aria-hidden="true">{THAI_DAYS.map((day) => <span key={day}>{day}</span>)}</div>
<div className="thai-picker-grid">{days.map((day, index) => day ? <button type="button" key={index} aria-label={`${day} ${THAI_MONTHS[view.month]} ${view.year + 543}`} aria-pressed={selected?.year === view.year && selected.month === view.month && selected.day === day} data-today={today.year === view.year && today.month === view.month && today.day === day || undefined} onClick={() => pickDay(day)}>{day}</button> : <span key={index} />)}</div>
{!dateOnly && <div className="thai-picker-time"><Icon name="clock" size={17} /><span>เวลาไทย</span><select aria-label="ชั่วโมง" value={selected?.hour ?? 9} onChange={(event) => changeTime("hour", +event.target.value)}>{Array.from({ length: 24 }, (_, hour) => <option key={hour} value={hour}>{pad(hour)}</option>)}</select><span>:</span><select aria-label="นาที" value={selected?.minute ?? 0} onChange={(event) => changeTime("minute", +event.target.value)}>{Array.from({ length: 60 }, (_, minute) => <option key={minute} value={minute}>{pad(minute)}</option>)}</select><span>น.</span></div>}
<div className="thai-picker-foot"><button type="button" onClick={pickToday}>วันนี้</button>{!dateOnly && <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen(false)}>เรียบร้อย</button>}</div>
</div>}
</div>;
}
+1 -1
View File
@@ -6,7 +6,7 @@ import { runAutomation } from "./automation";
export const AI_DAILY_LIMIT_PER_PAGE = 30;
export async function generateStructured<S extends z.ZodType>(req: {
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation";
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation" | "research";
pageId: string;
userId: string;
system: string;
+58
View File
@@ -0,0 +1,58 @@
const SEARCH_TIMEOUT_MS = 10_000;
const MAX_RESULTS = 8;
export interface NewsArticle {
title: string;
url: string;
source: string;
publishedAt: string | null;
description: string;
}
function decodeXml(value: string): string {
return value
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#39;|&apos;/g, "'")
.replace(/&#(\d+);/g, (_, code: string) => String.fromCodePoint(Math.min(Number(code), 0x10ffff)));
}
function field(item: string, name: string): string {
return decodeXml(item.match(new RegExp(`<${name}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/${name}>`, "i"))?.[1] ?? "")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
/** Search current public news through Bing's RSS endpoint; no credentials or page data leave the server. */
export async function searchNews(query: string): Promise<NewsArticle[]> {
const url = new URL("https://www.bing.com/news/search");
url.searchParams.set("q", query);
url.searchParams.set("format", "rss");
url.searchParams.set("setlang", "th-TH");
const response = await fetch(url, {
cache: "no-store",
signal: AbortSignal.timeout(SEARCH_TIMEOUT_MS),
headers: { accept: "application/rss+xml,application/xml,text/xml", "user-agent": "PagivaContentResearch/1.0" },
});
if (!response.ok) throw new Error(`news search returned ${response.status}`);
const xml = await response.text();
return [...xml.matchAll(/<item>([\s\S]*?)<\/item>/gi)]
.map((match) => {
const item = match[1];
const rawDate = field(item, "pubDate");
const timestamp = Date.parse(rawDate);
return {
title: field(item, "title"),
url: field(item, "link"),
source: field(item, "News:Source") || field(item, "source") || "แหล่งข่าว",
publishedAt: Number.isNaN(timestamp) ? null : new Date(timestamp).toISOString(),
description: field(item, "description").slice(0, 600),
} satisfies NewsArticle;
})
.filter((article) => article.title && /^https?:\/\//.test(article.url))
.slice(0, MAX_RESULTS);
}
+10
View File
@@ -63,6 +63,15 @@ export async function graphPostJson(path: string, accessToken: string, body: Rec
return parse(res);
}
/** Uploads binary media to Graph without requiring Meta to fetch a public URL. */
export async function graphPostForm(path: string, accessToken: string, body: FormData): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken), {
method: "POST",
body,
});
return parse(res);
}
export async function graphDelete(path: string, accessToken: string): Promise<GraphBody> {
const res = await fetch(buildUrl(path, accessToken), { method: "DELETE" });
return parse(res);
@@ -91,6 +100,7 @@ const GRAPH_ERROR_HINT: Record<number, string> = {
32: "เพจนี้เรียก Facebook ถี่เกินไป รอสักครู่แล้วลองใหม่",
190: "สิทธิ์เข้าถึงเพจหมดอายุหรือถูกยกเลิก — ไปที่เพจที่เชื่อม แล้วเชื่อมบัญชี Facebook ใหม่",
200: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
324: "Facebook ไม่พบหรืออ่านไฟล์รูปไม่ได้ — ลองอัปโหลดรูป JPG/PNG ใหม่อีกครั้ง",
10: "บัญชีที่เชื่อมไม่มีสิทธิ์ทำสิ่งนี้ — เชื่อมบัญชี Facebook ใหม่และอนุญาตสิทธิ์ให้ครบ",
368: "Facebook บล็อกการกระทำนี้ชั่วคราว (อาจถูกมองว่าเป็นสแปม) ลองใหม่ภายหลัง",
506: "โพสต์ซ้ำกับโพสต์ล่าสุด — แก้ข้อความก่อนเผยแพร่",
+61 -6
View File
@@ -1,4 +1,4 @@
import { bareId, graphDelete, graphGet, graphGetAll, graphPostJson } from "./client";
import { bareId, graphDelete, graphGet, graphGetAll, graphPostForm, graphPostJson, UserFacingError } from "./client";
import type { PageCredentials } from "./tokens";
/**
@@ -22,6 +22,60 @@ export interface FbPublishResult {
permalink: string | null;
}
const MAX_FACEBOOK_IMAGE_BYTES = 8 * 1024 * 1024;
const FACEBOOK_IMAGE_TYPES = new Map([
["image/jpeg", "image.jpg"],
["image/png", "image.png"],
]);
function isAllowedImageUrl(imageUrl: URL): boolean {
if (imageUrl.protocol !== "https:" && imageUrl.protocol !== "http:") return false;
const appUrl = process.env.NEXT_PUBLIC_APP_URL;
if (appUrl) {
const app = new URL(appUrl);
const uploadPrefix = `${app.pathname.replace(/\/$/, "")}/api/uploads/`;
if (imageUrl.origin === app.origin && imageUrl.pathname.startsWith(uploadPrefix)) return true;
}
return imageUrl.protocol === "https:" && imageUrl.hostname.endsWith(".public.blob.vercel-storage.com");
}
async function facebookImageSource(imageUrl: string): Promise<{ blob: Blob; filename: string }> {
let parsed: URL;
try {
parsed = new URL(imageUrl);
} catch {
throw new UserFacingError("URL รูปไม่ถูกต้อง กรุณาอัปโหลดรูปใหม่");
}
if (!isAllowedImageUrl(parsed)) {
throw new UserFacingError("URL รูปไม่ได้มาจากพื้นที่จัดเก็บของระบบ กรุณาอัปโหลดรูปใหม่");
}
const response = await fetch(parsed, { cache: "no-store", redirect: "follow" });
if (!response.ok) {
throw new UserFacingError("ระบบอ่านไฟล์รูปไม่ได้ กรุณาอัปโหลดรูปใหม่");
}
const contentType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase() ?? "";
const filename = FACEBOOK_IMAGE_TYPES.get(contentType);
if (!filename) {
throw new UserFacingError("ไฟล์รูปต้องเป็น JPG หรือ PNG กรุณาอัปโหลดรูปใหม่");
}
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && contentLength > MAX_FACEBOOK_IMAGE_BYTES) {
throw new UserFacingError("ไฟล์รูปใหญ่เกิน 8MB กรุณาอัปโหลดรูปที่เล็กลง");
}
const bytes = await response.arrayBuffer();
if (bytes.byteLength === 0) throw new UserFacingError("ไฟล์รูปว่างเปล่า กรุณาอัปโหลดรูปใหม่");
if (bytes.byteLength > MAX_FACEBOOK_IMAGE_BYTES) {
throw new UserFacingError("ไฟล์รูปใหญ่เกิน 8MB กรุณาอัปโหลดรูปที่เล็กลง");
}
return { blob: new Blob([bytes], { type: contentType }), filename };
}
/**
* Publishes now or hands Facebook a scheduled_publish_time — Facebook holds
* and fires scheduled posts itself, no cron needed.
@@ -36,11 +90,12 @@ export async function publishToFacebook(
let fbPostId: string;
if (params.imageUrl) {
const res = await graphPostJson(`/${page.fbPageId}/photos`, page.token, {
url: params.imageUrl,
caption: params.caption,
...scheduling,
});
const image = await facebookImageSource(params.imageUrl);
const body = new FormData();
body.set("source", image.blob, image.filename);
body.set("caption", params.caption);
for (const [key, value] of Object.entries(scheduling)) body.set(key, String(value));
const res = await graphPostForm(`/${page.fbPageId}/photos`, page.token, body);
// Photos return `id` (photo id) and `post_id` (feed post id) — the post id is what the feed edges use.
fbPostId = res.post_id ?? res.id;
} else {