"use client"; import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Icon } from "./Icon"; import { EmptyState, Notice, numberFmt } from "./ui"; type Kind = "DM" | "COMMENT"; interface Rule { id: string; name: string; kind: Kind; keywords: string[]; reply: string; imageUrl: string | null; publicAck: string | null; isActive: boolean; priority: number; sent: number; } const EMPTY: Omit = { name: "", kind: "COMMENT", keywords: [], reply: "", imageUrl: null, publicAck: "ส่งรายละเอียดให้ทาง inbox แล้วนะคะ", isActive: true, priority: 0 }; const KIND_LABEL: Record = { COMMENT: "คอมเมนต์ → ตอบทาง inbox", DM: "ข้อความ inbox → ตอบในแชท" }; export function RulesManager({ pageId, canEdit, rules }: { pageId: string; canEdit: boolean; rules: Rule[] }) { const router = useRouter(); const [editing, setEditing] = useState<(Omit & { id?: string }) | null>(null); const [keywordsText, setKeywordsText] = useState(""); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); function open(rule: Rule | null) { setError(null); setEditing(rule ? { ...rule } : { ...EMPTY }); setKeywordsText((rule?.keywords ?? []).join(", ")); } async function save() { if (!editing) return; setBusy(true); setError(null); const res = await fetch(withBase("/api/reply-rules"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...editing, pageId, keywords: keywordsText }), }); const body = await res.json().catch(() => ({})); setBusy(false); if (!res.ok) return setError(body.error ?? "บันทึกไม่สำเร็จ"); setEditing(null); router.refresh(); } async function toggle(rule: Rule) { await fetch(withBase("/api/reply-rules"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...rule, pageId, isActive: !rule.isActive }), }); router.refresh(); } async function remove(rule: Rule) { if (!window.confirm(`ลบกฎ "${rule.name}"?`)) return; await fetch(withBase(`/api/reply-rules?id=${rule.id}`), { method: "DELETE" }); router.refresh(); } return (

กฎทั้งหมด

{canEdit && ( )}
{rules.length === 0 ? ( ) : (
    {rules.map((r) => (
)} ))} )} {editing ? (

{editing.id ? "แก้ไขกฎ" : "กฎใหม่"}

ทำงานเมื่อ
{(["COMMENT", "DM"] as Kind[]).map((k) => ( ))}