import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { randomUUID, randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; import { SignJWT } from "jose"; import { PrismaClient } from "@prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import ts from "typescript"; // Use only a dedicated local database migrated with prisma migrate dev/deploy. const databaseUrl = process.env.CONTENT_AUTO_TEST_DATABASE_URL; assert.ok(databaseUrl && ["localhost", "127.0.0.1"].includes(new URL(databaseUrl).hostname), "Set CONTENT_AUTO_TEST_DATABASE_URL to a dedicated local test database"); const prisma = new PrismaClient({ adapter: new PrismaPg({ connectionString: databaseUrl }) }); const secret = randomBytes(32).toString("hex"); const basePath = JSON.parse(readFileSync(".next/required-server-files.json", "utf8")).config.basePath || ""; const base = `http://127.0.0.1:3217${basePath}`; const suffix = randomUUID(); function load(file, dependencies) { const source = readFileSync(new URL(file, import.meta.url), "utf8"); const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText; const exports = {}; new Function("exports", "require", compiled)(exports, (name) => { assert.ok(name in dependencies, `Unexpected dependency: ${name}`); return dependencies[name]; }); return exports; } const schedule = load("../src/lib/ai/auto-schedule.ts", {}); const { nextContentRun } = schedule; assert.equal(nextContentRun([1], ["09:00"], new Date("2026-11-22T23:00:00Z")).toISOString(), "2026-11-23T02:00:00.000Z"); assert.equal(nextContentRun([1], ["09:00"], new Date("2026-11-23T02:00:00Z")).toISOString(), "2026-11-30T02:00:00.000Z"); assert.equal(nextContentRun([0], ["00:15"], new Date("2026-11-28T17:00:00Z")).toISOString(), "2026-11-28T17:15:00.000Z"); assert.equal(nextContentRun([1], ["15:00", "09:00"], new Date("2026-11-23T03:00:00Z")).toISOString(), "2026-11-23T08:00:00.000Z"); assert.equal(nextContentRun([5], ["00:00"], new Date("2026-12-31T16:59:00Z")).toISOString(), "2026-12-31T17:00:00.000Z"); console.log("PASS Bangkok weekly slots, exact boundary, multiple times, year rollover"); const roles = load("../src/lib/auth/roles.ts", {}); const { enqueueDueContent } = load("../src/lib/ai/content-automation.ts", { "@/lib/db": { prisma }, "@/lib/audit": { SYSTEM_ACTOR: "ระบบ", audit: (data, tx) => tx.auditLog.create({ data }) }, "@/lib/auth/roles": roles, "./image": { IMAGE_DAILY_LIMIT_PER_PAGE: 10 }, "./auto-schedule": schedule, }); // No automation endpoint is configured: this test never invokes Codex, images or Graph. const server = spawn(process.execPath, ["node_modules/next/dist/bin/next", "start", "-p", "3217", "-H", "127.0.0.1"], { windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, DATABASE_URL: databaseUrl, SESSION_SECRET: secret, NEXT_PUBLIC_BASE_PATH: basePath, NEXT_PUBLIC_APP_URL: base, AI_AUTOMATION_URL: "", AI_AUTOMATION_SECRET: "", POST_QUEUE_SECRET: secret }, }); let logs = ""; server.stdout.on("data", (data) => { logs += data; }); server.stderr.on("data", (data) => { logs += data; }); async function api(method, route, cookie, body) { const response = await fetch(`${base}${route}`, { method, headers: { ...(cookie ? { Cookie: cookie } : {}), ...(body ? { "Content-Type": "application/json" } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) }); return { status: response.status, data: await response.json() }; } function status(result, expected) { assert.equal(result.status, expected, JSON.stringify(result.data)); return result.data; } async function cookie(user) { const token = await new SignJWT({ role: user.globalRole, mustChangePassword: false }).setProtectedHeader({ alg: "HS256" }).setSubject(user.id).setIssuedAt().setExpirationTime("15m").sign(new TextEncoder().encode(secret)); return `pm_session=${token}`; } try { let ready = false; for (let attempt = 0; attempt < 100; attempt++) { try { if ((await fetch(`${base}/api/health`)).ok) { ready = true; break; } } catch {} if (server.exitCode !== null) throw new Error(logs); await new Promise((resolve) => setTimeout(resolve, 200)); } assert.ok(ready, logs); const users = await Promise.all(["editor", "viewer", "outsider"].map((role) => prisma.user.create({ data: { name: role, email: `${role}-${suffix}@example.invalid`, passwordHash: "test-only", globalRole: "MEMBER" } }))); const [editor, viewer] = users; const cookies = await Promise.all(users.map(cookie)); const page = await prisma.page.create({ data: { name: "[Auto test] Fictional shop", fbPageId: `auto-test-${suffix}`, tokenCipher: "unused-test-only", profile: { create: { business: "ร้านสมมติ ขายกาแฟ", tone: "เป็นกันเอง", visualStyle: "Blue and white", website: "https://example.invalid/" } }, members: { create: [{ userId: editor.id, role: "EDITOR" }, { userId: viewer.id, role: "VIEWER" }] }, } }); const route = "/api/ai/content-auto"; const settings = { pageId: page.id, enabled: true, weekdays: [0, 1, 2, 3, 4, 5, 6], times: ["09:00", "15:00"], brief: "ให้ความรู้", targets: ["FACEBOOK"] }; status(await api("PUT", route, null, settings), 401); status(await api("PUT", route, cookies[1], settings), 403); status(await api("PUT", route, cookies[2], settings), 404); status(await api("GET", `${route}?pageId=${page.id}`, cookies[2]), 404); status(await api("PUT", route, cookies[0], { ...settings, times: ["24:00"] }), 400); status(await api("PUT", route, cookies[0], { ...settings, weekdays: [] }), 400); status(await api("PUT", route, cookies[0], { ...settings, targets: ["INSTAGRAM"] }), 400); const saved = status(await api("PUT", route, cookies[0], settings), 200).automation; assert.ok(new Date(saved.nextRunAt) > new Date()); assert.equal(status(await api("GET", `${route}?pageId=${page.id}`, cookies[0]), 200).automation.enabled, true); console.log("PASS API authentication, page membership, validation and saved schedule"); await enqueueDueContent(); assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 0); const makeDue = () => prisma.pageContentAutomation.update({ where: { pageId: page.id }, data: { enabled: true, nextRunAt: new Date(Date.now() - 7 * 86400_000) } }); await makeDue(); await Promise.all(Array.from({ length: 5 }, () => enqueueDueContent())); let jobs = await prisma.postGenerationJob.findMany({ where: { pageId: page.id } }); assert.equal(jobs.length, 1); assert.ok(jobs[0].requestKey.startsWith("auto:")); assert.equal(jobs[0].profileSnapshot.business, "ร้านสมมติ ขายกาแฟ"); assert.equal(jobs[0].profileSnapshot.visualStyle, "Blue and white"); assert.equal(jobs[0].profileSnapshot.website, "https://example.invalid/"); assert.ok((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).nextRunAt > new Date()); console.log("PASS concurrent enqueue deduplication and missed slots produce one job"); const manual = await prisma.postGenerationJob.create({ data: { pageId: page.id, requestedById: editor.id, requestKey: randomUUID(), topic: "manual", targets: ["FACEBOOK"], profileSnapshot: {} } }); status(await api("PUT", route, cookies[0], { ...settings, enabled: false }), 200); assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: jobs[0].id } })).status, "CANCELLED"); assert.equal((await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: manual.id } })).status, "QUEUED"); console.log("PASS disabling auto cancels automatic queued jobs and preserves manual jobs"); await prisma.aiUsage.createMany({ data: Array.from({ length: 10 }, () => ({ pageId: page.id, kind: "image", inputTokens: 0, outputTokens: 0 })) }); await makeDue(); await enqueueDueContent(); assert.equal(await prisma.postGenerationJob.count({ where: { pageId: page.id } }), 2); assert.match((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).lastError, /โควตา/); await prisma.pageMember.update({ where: { userId_pageId: { userId: editor.id, pageId: page.id } }, data: { role: "VIEWER" } }); await makeDue(); await enqueueDueContent(); const paused = await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } }); assert.equal(paused.enabled, false); assert.equal(paused.nextRunAt, null); assert.match(paused.lastError, /สิทธิ์/); await prisma.pageMember.update({ where: { userId_pageId: { userId: editor.id, pageId: page.id } }, data: { role: "EDITOR" } }); const team = await prisma.team.create({ data: { name: "Auto test team", ownerId: editor.id, pages: { create: { pageId: page.id } } } }); await makeDue(); await enqueueDueContent(); assert.equal((await prisma.pageContentAutomation.findUniqueOrThrow({ where: { pageId: page.id } })).enabled, false); status(await api("PUT", route, cookies[0], settings), 404); await prisma.teamMember.create({ data: { teamId: team.id, userId: editor.id, role: "OWNER" } }); status(await api("PUT", route, cookies[0], settings), 200); status(await api("PUT", route, cookies[0], { ...settings, enabled: false }), 200); console.log("PASS team membership is required for scheduler and settings"); const actions = (await prisma.auditLog.findMany({ where: { pageId: page.id }, select: { action: true } })).map((row) => row.action); for (const action of ["CONTENT_AUTO_ENABLED", "CONTENT_AUTO_DISABLED", "AI_POST_QUEUED", "AI_POST_CANCELLED", "CONTENT_AUTO_SKIPPED", "CONTENT_AUTO_PAUSED"]) assert.ok(actions.includes(action), action); assert.equal(await prisma.post.count({ where: { pageId: page.id } }), 0); console.log("PASS quota skip, permission revocation, append audit and no publication"); console.log("All content auto checks passed; isolated fixtures and audit rows retained."); } finally { server.kill(); await prisma.$disconnect(); }