6994ba1a4e
Text generation now runs through a PM2 automation worker (codex exec) and images through the ChatGPT Chrome extension, replacing the Anthropic API. generateStructured keeps its signature; results are Zod-validated on the web side and the worker is reached with a bearer secret. - AI image assistant in the post editor: editable prompt step, then image (square or 3:2 only, since Instagram rejects 2:3), stored via putBlob - Full-post queue (PostGenerationJob + migration): enqueue returns 202, FIFO claim under an advisory lock, heartbeat, stale-job failure, per-user request key, cancel while QUEUED; output is always a DRAFT with audit rows - Separate 10 images/page/day quota; text quota excludes images - Worker reports Codex usage-limit as 429 with a clear Thai message - Docs: AI-AUTOMATION.md, ARCHITECTURE/README/.env.example updated Known gap: the live FIFO queue check (scripts/check-post-queue.mjs) has not passed yet; the last run hit the Codex account usage limit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
170 lines
7.6 KiB
TypeScript
170 lines
7.6 KiB
TypeScript
"use client";
|
|
/* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */
|
|
import { withBase } from "@/lib/base-path";
|
|
|
|
import { useState } from "react";
|
|
import Link from "next/link";
|
|
import { Icon } from "./Icon";
|
|
import { Notice } from "./ui";
|
|
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
|
|
// (server-only helpers live in lib/ai/image.ts — never import that file here)
|
|
|
|
async function post(body: Record<string, unknown>): Promise<{ ok: true; data: Record<string, unknown> } | { ok: false; error: string }> {
|
|
const res = await fetch(withBase("/api/ai/image"), {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
}).catch(() => null);
|
|
const data = res ? await res.json().catch(() => ({})) : {};
|
|
if (!res?.ok) return { ok: false, error: (data.error as string) ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง" };
|
|
return { ok: true, data };
|
|
}
|
|
|
|
/**
|
|
* Two explicit steps: AI drafts an image prompt the user can edit, then a
|
|
* second press makes the image. The chosen image only fills the editor —
|
|
* saving and approval stay exactly as for an uploaded picture.
|
|
*/
|
|
export function ImageAssistant({
|
|
pageId,
|
|
initialIdea,
|
|
hasImage,
|
|
onUse,
|
|
}: {
|
|
pageId: string;
|
|
initialIdea: string;
|
|
hasImage: boolean;
|
|
onUse: (url: string) => void;
|
|
}) {
|
|
const [hasPrompt, setHasPrompt] = useState(false);
|
|
const [open, setOpen] = useState(false);
|
|
const [idea, setIdea] = useState("");
|
|
const [prompt, setPrompt] = useState("");
|
|
const [size, setSize] = useState<ImageSizeKey>("square");
|
|
const [result, setResult] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState<"prompt" | "generate" | null>(null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [profileMissing, setProfileMissing] = useState(false);
|
|
|
|
async function draftPrompt() {
|
|
setBusy("prompt");
|
|
setError(null);
|
|
const r = await post({ action: "prompt", pageId, description: idea });
|
|
setBusy(null);
|
|
if (!r.ok) return setError(r.error);
|
|
setPrompt(String(r.data.prompt ?? ""));
|
|
setHasPrompt(true);
|
|
setProfileMissing(Boolean(r.data.profileMissing));
|
|
}
|
|
|
|
async function makeImage() {
|
|
setBusy("generate");
|
|
setError(null);
|
|
const r = await post({ action: "generate", pageId, prompt, size });
|
|
setBusy(null);
|
|
if (!r.ok) return setError(r.error);
|
|
setResult(String(r.data.url ?? ""));
|
|
}
|
|
|
|
if (!open) {
|
|
return (
|
|
<button
|
|
aria-expanded={false}
|
|
type="button"
|
|
className="btn btn-ghost btn-sm self-start"
|
|
onClick={() => {
|
|
setIdea((cur) => cur || initialIdea.slice(0, 1000));
|
|
setOpen(true);
|
|
}}
|
|
>
|
|
<Icon name="sparkle" size={15} /> ให้ AI สร้างรูป
|
|
</button>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<section aria-busy={busy !== null} className="rounded-[12px] border border-line bg-board p-3.5 flex flex-col gap-3" aria-label="ผู้ช่วยสร้างรูป">
|
|
<div className="flex items-center gap-2">
|
|
<Icon name="sparkle" size={16} />
|
|
<b className="text-[14px]">ให้ AI สร้างรูป</b>
|
|
<button type="button" className="btn btn-ghost btn-sm ml-auto" disabled={busy !== null} onClick={() => setOpen(false)} aria-label="ปิดผู้ช่วยสร้างรูป">
|
|
<Icon name="x" size={14} />
|
|
</button>
|
|
</div>
|
|
|
|
<label className="field">
|
|
<span>อยากได้รูปแบบไหน</span>
|
|
<textarea
|
|
className="textarea"
|
|
rows={2}
|
|
autoFocus
|
|
disabled={busy !== null}
|
|
maxLength={1000}
|
|
value={idea}
|
|
onChange={(e) => setIdea(e.target.value)}
|
|
placeholder="เช่น เค้กช็อกโกแลตบนโต๊ะไม้ แสงธรรมชาติจากหน้าต่าง โทนอบอุ่น"
|
|
/>
|
|
</label>
|
|
<div>
|
|
<button type="button" className="btn btn-primary btn-sm" disabled={busy !== null || !idea.trim()} onClick={draftPrompt}>
|
|
<Icon name="sparkle" size={14} /> {busy === "prompt" ? "AI กำลังร่างพรอมต์…" : prompt ? "ร่างพรอมต์ใหม่" : "ร่างพรอมต์ให้"}
|
|
</button>
|
|
</div>
|
|
|
|
{hasPrompt && (
|
|
<>
|
|
<label className="field">
|
|
<span className="flex">
|
|
พรอมต์สร้างรูป (แก้ได้) <span className="ml-auto num text-ink-4">{prompt.length.toLocaleString("th-TH")}</span>
|
|
</span>
|
|
<textarea className="textarea" disabled={busy !== null} rows={6} maxLength={IMAGE_PROMPT_MAX} value={prompt} onChange={(e) => setPrompt(e.target.value)} />
|
|
</label>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{(Object.keys(IMAGE_SIZES) as ImageSizeKey[]).map((k) => (
|
|
<button key={k} type="button" className="chip" aria-pressed={size === k} disabled={busy !== null} onClick={() => setSize(k)}>
|
|
{IMAGE_SIZES[k].label}
|
|
</button>
|
|
))}
|
|
<button type="button" className="btn btn-primary btn-sm ml-auto" disabled={busy !== null || !prompt.trim()} onClick={makeImage}>
|
|
<Icon name="image" size={14} /> {busy === "generate" ? "กำลังสร้างรูป… (ราว 30–60 วินาที)" : result ? "สร้างใหม่" : "สร้างรูป"}
|
|
</button>
|
|
</div>
|
|
</>
|
|
)}
|
|
|
|
{busy && <p role="status" className="text-[12px] text-ink-3">{busy === "prompt" ? "กำลังร่างพรอมต์…" : "กำลังสร้างรูป กรุณารอสักครู่…"}</p>}
|
|
{error && <div role="alert"><Notice tone="red">{error}</Notice></div>}
|
|
{profileMissing && (
|
|
<p className="text-[12px] text-ink-3">
|
|
ยังไม่มีโปรไฟล์ร้าน — <Link href="/profile" className="underline">ตั้งไว้</Link> แล้วพรอมต์จะตรงกับร้านมากขึ้น
|
|
</p>
|
|
)}
|
|
|
|
{result && (
|
|
<div className="rounded-[10px] border border-line bg-paper p-2 flex flex-col gap-2">
|
|
<img src={result} alt="รูปที่ AI สร้าง" className="w-full max-h-[320px] object-contain rounded-[6px] bg-board" />
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary btn-sm"
|
|
disabled={busy !== null}
|
|
onClick={() => {
|
|
if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return;
|
|
onUse(result);
|
|
setResult(null);
|
|
setOpen(false);
|
|
}}
|
|
>
|
|
<Icon name="check" size={14} /> ใช้รูปนี้
|
|
</button>
|
|
<button type="button" className="btn btn-ghost btn-sm" disabled={busy !== null} onClick={() => setResult(null)}>
|
|
ทิ้ง
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
<p className="text-[11px] text-ink-4">รูปจาก AI — ตรวจให้ตรงกับสินค้าจริงก่อนส่งอนุมัติ · พรอมต์จะถูกส่งไปสร้างรูปผ่านเว็บ ChatGPT บนเครื่อง worker</p>
|
|
</section>
|
|
);
|
|
}
|