Merge branch 'deploy/coolify' of https://git.4tech-innovation.cloud/Chaloemphong/PAGIVA into deploy/coolify

# Conflicts:
#	src/app/globals.css
This commit is contained in:
chaloemphong
2026-11-23 15:25:52 +07:00
43 changed files with 2183 additions and 115 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ import { generateStructured } from "@/lib/ai/claude";
import { CAPTION_REFINEMENTS, profilePrompt, type CaptionRefinement } from "@/lib/ai/shared";
import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts";
export const maxDuration = 120;
export const maxDuration = 300;
const CaptionVariants = z.object({
variants: z.array(
+1 -1
View File
@@ -7,7 +7,7 @@ import { UserFacingError } from "@/lib/facebook/client";
import { generateStructured } from "@/lib/ai/claude";
import { profilePrompt } from "@/lib/ai/shared";
export const maxDuration = 120;
export const maxDuration = 300;
const LEVELS = ["high", "medium", "low"] as const;
+90
View File
@@ -0,0 +1,90 @@
import { NextResponse } from "next/server";
import * as z from "zod/v4";
import { appUrl } from "@/lib/base-path";
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 { profilePrompt } from "@/lib/ai/shared";
import { assertImageQuota, generateImage } from "@/lib/ai/image";
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
import { putBlob } from "@/lib/storage/blob";
export const maxDuration = 360;
const ImagePrompt = z.object({
prompt: z.string().describe("The finished English prompt for the image model"),
});
const SYSTEM = `You write prompts for an AI image generator. The images illustrate Facebook and Instagram posts for a small Thai business page; a person reads and may edit your prompt before any image is made.
- Output one English prompt of 60-140 words: subject, setting, composition, lighting, colour mood, and photographic or illustration style.
- Show only what the owner described or what <shop_profile> states. Never invent products, packaging, prices or claims.
- Ask for no text, lettering, logos, watermarks or brand names inside the image (image models spell Thai badly; the caption carries the words).
- No identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic.
- No before/after imagery and no exaggerated results (cures, guaranteed outcomes).
- Match the shop's tone and audience through the visual mood.`;
/**
* Two steps, both explicit button presses in the editor:
* - `{ action: "prompt", pageId, description }` → an editable prompt (Codex CLI, nothing saved)
* - `{ action: "generate", pageId, prompt, size }` → the image (ChatGPT browser), stored like an upload → `{ url }`
* The returned URL only fills the editor; the post still goes through normal approval.
*/
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 {
// SUPERADMIN passes the role check for any id, so confirm the page exists.
const page = await prisma.page.findUnique({
where: { id: pageId },
select: { profile: { select: { business: true, audience: true, tone: true, avoid: true, cta: true } } },
});
if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 });
const action = str(body.action);
if (action === "prompt") {
const description = str(body.description).trim();
if (!description) throw new UserFacingError("บอก AI ว่าอยากได้รูปแบบไหน");
if (description.length > 1000) throw new UserFacingError("คำอธิบายยาวเกิน 1,000 ตัวอักษร");
const result = await generateStructured({
kind: "image-prompt",
pageId,
userId: auth.user.id,
system: SYSTEM,
prompt: `${profilePrompt(page.profile)}\n\nWrite the image prompt for the idea below.\n\n<idea>\n${description}\n</idea>`,
schema: ImagePrompt,
effort: "low",
});
const prompt = result.prompt.trim();
if (!prompt) throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
return NextResponse.json({ prompt, profileMissing: !page.profile });
}
if (action === "generate") {
const prompt = str(body.prompt).trim();
const size = str(body.size);
if (!prompt) throw new UserFacingError("ใส่คำอธิบายรูปก่อน");
if (prompt.length > IMAGE_PROMPT_MAX) throw new UserFacingError(`คำอธิบายรูปยาวเกิน ${IMAGE_PROMPT_MAX.toLocaleString("th-TH")} ตัวอักษร`);
if (!Object.hasOwn(IMAGE_SIZES, size)) throw new UserFacingError("ไม่รู้จักขนาดรูปนี้");
await assertImageQuota(pageId);
const image = await generateImage(prompt, size as ImageSizeKey);
const file = new File([new Uint8Array(image.bytes)], "ai-image.jpg", { type: image.contentType });
const blob = await putBlob(`posts/${pageId}/ai-image.jpg`, file, { contentType: image.contentType }, appUrl(new URL(req.url).origin));
// Recorded only after the image is stored, so a failed save doesn't spend quota.
await prisma.aiUsage.create({
data: { pageId, userId: auth.user.id, kind: "image", inputTokens: image.inputTokens, outputTokens: image.outputTokens },
});
return NextResponse.json({ url: blob.url });
}
throw new UserFacingError("ไม่รู้จักคำสั่งนี้");
} catch (e) {
return errorResponse(e, "ai:image");
}
}
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { actorLabel, requirePageAction } from "@/lib/auth/user";
import { audit } from "@/lib/audit";
import { JOB_SELECT } from "@/lib/ai/post-queue";
export async function GET(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) {
const { id } = await ctx.params;
const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } });
if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 });
const auth = await requirePageAction(job.pageId, "editPost");
if (!auth.ok) return auth.response;
return NextResponse.json({ job: await prisma.postGenerationJob.findUnique({ where: { id }, select: JOB_SELECT }) }, { headers: { "Cache-Control": "no-store" } });
}
export async function DELETE(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) {
const { id } = await ctx.params;
const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } });
if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 });
const auth = await requirePageAction(job.pageId, "editPost");
if (!auth.ok) return auth.response;
const cancelled = await prisma.$transaction(async (tx) => {
const changed = await tx.postGenerationJob.updateMany({ where: { id, status: "QUEUED" }, data: { status: "CANCELLED", stage: "cancelled", finishedAt: new Date() } });
if (!changed.count) return false;
await audit({ action: "AI_POST_CANCELLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: job.pageId, detail: { jobId: id } }, tx);
return true;
});
if (!cancelled) return NextResponse.json({ error: "ยกเลิกได้เฉพาะงานที่ยังรอคิว งานนี้เริ่มทำหรือจบแล้ว" }, { status: 409 });
return NextResponse.json({ ok: true });
}
+56
View File
@@ -0,0 +1,56 @@
import { NextResponse } from "next/server";
import * as z from "zod/v4";
import { prisma } from "@/lib/db";
import { actorLabel, requirePageAction } from "@/lib/auth/user";
import { audit } from "@/lib/audit";
import { readJson, str, errorResponse } from "@/lib/http";
import { UserFacingError } from "@/lib/facebook/client";
import { JOB_SELECT } from "@/lib/ai/post-queue";
import { IMAGE_DAILY_LIMIT_PER_PAGE } from "@/lib/ai/image";
import { bkkMidnight, isDayKey } from "@/lib/board";
const Input = z.object({ requestKey: z.uuid(), topic: z.string().trim().min(1).max(1000), targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2), plannedDay: z.string().optional() });
export async function GET(req: Request) {
const pageId = new URL(req.url).searchParams.get("pageId") || "";
const auth = await requirePageAction(pageId, "editPost");
if (!auth.ok) return auth.response;
const jobs = await prisma.postGenerationJob.findMany({ where: { pageId }, select: JOB_SELECT, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: 30 });
return NextResponse.json({ jobs }, { headers: { "Cache-Control": "no-store" } });
}
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 input = Input.safeParse(body);
if (!input.success) throw new UserFacingError("กรอกหัวข้อไม่เกิน 1,000 ตัวอักษร และเลือกช่องทางก่อนเข้าคิว");
const { requestKey, topic, plannedDay } = input.data;
const targets = [...new Set(input.data.targets)].sort();
if (plannedDay && !isDayKey(plannedDay)) throw new UserFacingError("วันที่วางแผนโพสต์ไม่ถูกต้อง");
const plannedAt = plannedDay ? bkkMidnight(plannedDay) : null;
const result = await prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
const existing = await tx.postGenerationJob.findUnique({ where: { requestedById_requestKey: { requestedById: auth.user.id, requestKey } } });
if (existing) {
if (existing.pageId !== pageId || existing.topic !== topic || existing.targets.join() !== targets.join() || existing.plannedAt?.toISOString() !== plannedAt?.toISOString()) throw new UserFacingError("คำขอนี้ใช้กับงานอื่นแล้ว กรุณาสร้างคำขอใหม่");
return { job: existing, duplicate: true };
}
const page = await tx.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, profile: { select: { business: true, audience: true, tone: true, avoid: true, cta: true } } } });
if (!page || page.status === "DISCONNECTED") throw new UserFacingError("ไม่พบเพจที่พร้อมสร้างโพสต์");
if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อน เพื่อให้ AI สร้างโพสต์จากข้อมูลจริงของร้าน");
if (targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram");
const pending = await tx.postGenerationJob.count({ where: { pageId, status: { in: ["QUEUED", "RUNNING"] } } });
if (pending >= 5) throw new UserFacingError("เพจนี้มีงานค้างครบ 5 งานแล้ว รอให้เสร็จก่อนเพิ่มคิว");
const used = await tx.aiUsage.count({ where: { pageId, kind: "image", createdAt: { gte: new Date(Date.now() - 24 * 60 * 60_000) } } });
if (used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) throw new UserFacingError("โควตาภาพของเพจนี้ถูกใช้หรือจองเต็มแล้ว ลองใหม่ภายหลัง");
const job = await tx.postGenerationJob.create({ data: { pageId, requestedById: auth.user.id, requestKey, topic, targets, plannedAt, profileSnapshot: page.profile } });
await audit({ action: "AI_POST_QUEUED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { jobId: job.id } }, tx);
return { job, duplicate: false };
});
const job = await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: result.job.id }, select: JOB_SELECT });
return NextResponse.json({ job, duplicate: result.duplicate }, { status: result.duplicate ? 200 : 202 });
} catch (error) { return errorResponse(error, "post-queue:create"); }
}
+1 -1
View File
@@ -10,7 +10,7 @@ import { MAX_MESSAGE_LENGTH } from "@/lib/facebook/messagingWindow";
import { generateStructured } from "@/lib/ai/claude";
import { profilePrompt } from "@/lib/ai/shared";
export const maxDuration = 120;
export const maxDuration = 300;
const Replies = z.object({ replies: z.array(z.string().describe("One complete chat reply in Thai")) });
+1 -1
View File
@@ -9,7 +9,7 @@ import { profilePrompt } from "@/lib/ai/shared";
import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts";
import { addDays, bkkDayKey, bkkMidnight, isDayKey, weekStartOf } from "@/lib/board";
export const maxDuration = 120;
export const maxDuration = 300;
const WeekPlan = z.object({
posts: z.array(
+16
View File
@@ -0,0 +1,16 @@
import { timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";
import { appUrl } from "@/lib/base-path";
import { processNextPostJob } from "@/lib/ai/post-queue";
export const runtime = "nodejs";
export const maxDuration = 900;
/** Only the private queue worker can claim/process jobs; no user cookie is accepted. */
export async function POST(req: Request) {
const secret = process.env.POST_QUEUE_SECRET;
const expected = Buffer.from(`Bearer ${secret || ""}`);
const provided = Buffer.from(req.headers.get("authorization") || "");
if (!secret || secret.length < 32 || expected.length !== provided.length || !timingSafeEqual(expected, provided)) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin)));
}
@@ -6,7 +6,7 @@ import { generateStructured } from "@/lib/ai/claude";
import { collectAnalysisSource } from "@/lib/analysis/source";
import { PROFILE_FIELDS, type ShopProfile } from "@/lib/ai/shared";
export const maxDuration = 120;
export const maxDuration = 300;
const DraftProfile = z.object({
business: z.string().describe("What the shop sells, price ranges, delivery area and selling points seen in the posts"),
+175 -1
View File
@@ -258,7 +258,6 @@
.login-form .input { height: 46px; }
.login-divider { display: flex; align-items: center; gap: 12px; color: var(--ink-4); font-size: 12px; }
.login-divider::before, .login-divider::after { content: ""; flex: 1; height: 1px; background: var(--line); }
input[type="checkbox"] { accent-color: var(--m-blue); }
@media (max-width: 1199px) {
.welcome-panel { padding: 28px; gap: 24px; }
.workflow-preview { padding: 18px; }
@@ -532,6 +531,14 @@
input.input[type="time"]::-webkit-calendar-picker-indicator:hover {
background: var(--m-blue-soft);
}
.input:disabled,
.select:disabled,
.textarea:disabled {
background: var(--board);
border-color: var(--line-2);
color: var(--ink-3);
cursor: not-allowed;
}
@media (max-width: 959px) {
.input,
.select,
@@ -544,6 +551,168 @@
}
}
/* ---------- date / datetime-local ----------
The browser's own popup can't be themed, so the field and its calendar
button are: segments highlight in the action blue, the icon is ours. */
.input[type="date"],
.input[type="datetime-local"] {
-webkit-appearance: none;
appearance: none;
display: flex;
align-items: center;
position: relative;
min-width: 0;
padding-inline-end: 40px; /* room for the calendar button */
text-align: start;
accent-color: var(--m-blue);
}
.input[type="date"]::-webkit-datetime-edit,
.input[type="datetime-local"]::-webkit-datetime-edit {
flex: 1 1 auto;
min-width: 0;
}
.input[type="date"]::-webkit-datetime-edit,
.input[type="datetime-local"]::-webkit-datetime-edit,
.input[type="date"]::-webkit-datetime-edit-fields-wrapper,
.input[type="datetime-local"]::-webkit-datetime-edit-fields-wrapper {
padding: 0;
}
.input[type="date"]::-webkit-datetime-edit-text,
.input[type="datetime-local"]::-webkit-datetime-edit-text {
padding: 0 1px;
color: var(--ink-4);
}
.input[type="date"]::-webkit-datetime-edit-year-field,
.input[type="date"]::-webkit-datetime-edit-month-field,
.input[type="date"]::-webkit-datetime-edit-day-field,
.input[type="datetime-local"]::-webkit-datetime-edit-year-field,
.input[type="datetime-local"]::-webkit-datetime-edit-month-field,
.input[type="datetime-local"]::-webkit-datetime-edit-day-field,
.input[type="datetime-local"]::-webkit-datetime-edit-hour-field,
.input[type="datetime-local"]::-webkit-datetime-edit-minute-field,
.input[type="datetime-local"]::-webkit-datetime-edit-ampm-field {
padding: 2px 3px;
border-radius: 5px;
}
.input[type="date"]::-webkit-datetime-edit-year-field:focus,
.input[type="date"]::-webkit-datetime-edit-month-field:focus,
.input[type="date"]::-webkit-datetime-edit-day-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-year-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-month-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-day-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-hour-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-minute-field:focus,
.input[type="datetime-local"]::-webkit-datetime-edit-ampm-field:focus {
background: var(--m-blue);
color: #fff;
outline: none;
}
.input[type="date"]::-webkit-calendar-picker-indicator,
.input[type="datetime-local"]::-webkit-calendar-picker-indicator {
box-sizing: border-box;
position: absolute;
inset-inline-end: 11px;
top: 50%;
translate: 0 -50%;
width: 20px;
height: 20px;
margin: 0;
padding: 0;
cursor: pointer;
opacity: 1;
background: var(--ink-3);
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='5' width='18' height='16' rx='3'/%3E%3Cpath d='M3 10h18M8 3v4M16 3v4'/%3E%3C/svg%3E") center / 18px 18px no-repeat;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='5' width='18' height='16' rx='3'/%3E%3Cpath d='M3 10h18M8 3v4M16 3v4'/%3E%3C/svg%3E") center / 18px 18px no-repeat;
transition: background-color 0.15s;
}
.input[type="date"]::-webkit-calendar-picker-indicator:hover,
.input[type="datetime-local"]::-webkit-calendar-picker-indicator:hover,
.input[type="date"]:focus::-webkit-calendar-picker-indicator,
.input[type="datetime-local"]:focus::-webkit-calendar-picker-indicator {
background: var(--m-blue);
}
.input[type="date"]:disabled::-webkit-calendar-picker-indicator,
.input[type="datetime-local"]:disabled::-webkit-calendar-picker-indicator {
background: var(--ink-4);
cursor: not-allowed;
}
@media (max-width: 959px) {
.input[type="date"],
.input[type="datetime-local"] {
padding-inline-end: 48px;
}
.input[type="date"]::-webkit-calendar-picker-indicator,
.input[type="datetime-local"]::-webkit-calendar-picker-indicator {
inset-inline-end: 9px;
width: 28px;
height: 28px;
-webkit-mask-size: 20px 20px;
mask-size: 20px 20px;
}
}
/* ---------- checkbox ---------- */
input[type="checkbox"] {
-webkit-appearance: none;
appearance: none;
flex-shrink: 0;
width: 18px;
height: 18px;
margin: 0;
border: 1.5px solid var(--ink-3);
border-radius: 5px;
background-color: var(--paper);
background-position: center;
background-repeat: no-repeat;
background-size: 14px 14px;
cursor: pointer;
transition: background-color 0.15s, border-color 0.15s;
}
input[type="checkbox"]:hover:not(:disabled) {
border-color: var(--m-blue);
background-color: var(--m-blue-soft);
}
input[type="checkbox"]:checked,
input[type="checkbox"]:indeterminate {
border-color: var(--m-blue);
background-color: var(--m-blue);
}
input[type="checkbox"]:checked {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='white' stroke-width='2.4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.5 8.5l3 3 6-6.5'/%3E%3C/svg%3E");
}
input[type="checkbox"]:indeterminate {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='white' stroke-width='2.4' stroke-linecap='round'%3E%3Cpath d='M4 8h8'/%3E%3C/svg%3E");
}
input[type="checkbox"]:checked:hover:not(:disabled),
input[type="checkbox"]:indeterminate:hover:not(:disabled) {
border-color: var(--m-blue-ink);
background-color: var(--m-blue-ink);
}
input[type="checkbox"]:disabled {
cursor: not-allowed;
border-color: var(--line);
background-color: var(--line-2);
}
input[type="checkbox"]:disabled:checked {
border-color: var(--ink-4);
background-color: var(--ink-4);
}
@media (max-width: 959px) {
input[type="checkbox"] {
width: 22px;
height: 22px;
background-size: 16px 16px;
}
}
@media (forced-colors: active) {
input[type="checkbox"] {
-webkit-appearance: auto;
appearance: auto;
}
}
.chip {
display: inline-flex;
align-items: center;
@@ -1091,6 +1260,11 @@
}
@media (prefers-reduced-motion: reduce) {
input[type="checkbox"],
.input[type="date"]::-webkit-calendar-picker-indicator,
.input[type="datetime-local"]::-webkit-calendar-picker-indicator {
transition: none;
}
.sheet,
.scrim,
.toast,