feat: complete marketing command center with pipeline, UI, and asset generation
- Dashboard with campaign management, asset gallery, and publishing queue - 7-agent pipeline: trend scout, research, scripts, ad creative, video, copy, distribution - Campaign form with screenshot upload, goal picker, platform selection - Campaign detail view with Details/Pipeline/Assets/Chat tabs - Two-set image generation: Gemini AI (NanoBanana MCP) + Canvas Design posters - Remotion video rendering with phone.png frame and real screenshot alignment - honeyDue branding: blue #0079FF, orange #FF9400, Inter font, warm off-white - Asset cards with source badges (Gemini/Canvas/Remotion/Playwright) - Markdown/JSON render endpoint for viewing pipeline outputs as HTML - Settings page with Tavily, Gemini, Postiz, Nextdoor integration management - Claude Chat for campaign feedback loop with streaming SSE - Postiz publishing modal with scheduling - Auth with NextAuth credentials + JWT sessions - SQLite via Prisma with better-sqlite3 adapter Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
const asset = await prisma.asset.update({
|
||||
where: { id },
|
||||
data: body,
|
||||
});
|
||||
|
||||
return Response.json(asset);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const campaignId = searchParams.get("campaignId");
|
||||
const type = searchParams.get("type");
|
||||
const platform = searchParams.get("platform");
|
||||
const status = searchParams.get("status");
|
||||
const search = searchParams.get("search");
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
if (campaignId) where.campaignId = campaignId;
|
||||
if (type && type !== "all") where.type = type;
|
||||
if (platform && platform !== "all") where.platform = platform;
|
||||
if (status && status !== "all") where.status = status;
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ fileName: { contains: search } },
|
||||
{ metadata: { contains: search } },
|
||||
];
|
||||
}
|
||||
|
||||
const assets = await prisma.asset.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { campaign: { select: { name: true } } },
|
||||
});
|
||||
|
||||
return Response.json(assets);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { handlers } from "@/lib/auth";
|
||||
|
||||
export const { GET, POST } = handlers;
|
||||
@@ -0,0 +1,67 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { buildCampaignPrompt, launchPipeline } from "@/lib/claude";
|
||||
import path from "path";
|
||||
import { mkdirSync } from "fs";
|
||||
|
||||
export async function POST(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const campaign = await prisma.campaign.findUnique({ where: { id } });
|
||||
if (!campaign) {
|
||||
return Response.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (campaign.status !== "draft") {
|
||||
return Response.json(
|
||||
{ error: "Campaign is not in draft status" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const config = campaign.config ? JSON.parse(campaign.config) : {};
|
||||
const pipelineRoot =
|
||||
process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
|
||||
const taskName = campaign.name.replace(/\s+/g, "_").toLowerCase();
|
||||
const outputPath = `outputs/${taskName}_${dateStr}`;
|
||||
|
||||
// Create output directories
|
||||
const dirs = ["ads", "scripts", "video", "copy"];
|
||||
for (const dir of dirs) {
|
||||
mkdirSync(path.join(pipelineRoot, outputPath, dir), { recursive: true });
|
||||
}
|
||||
|
||||
const prompt = buildCampaignPrompt({
|
||||
name: campaign.name,
|
||||
platforms: JSON.parse(campaign.platforms),
|
||||
goal: config.goal || "brand awareness",
|
||||
keyMessage: config.keyMessage || campaign.name,
|
||||
socialProof: config.socialProof,
|
||||
targetAudience: config.targetAudience,
|
||||
visualDirection: config.visualDirection,
|
||||
competitorApps: config.competitorApps,
|
||||
variations: config.variations,
|
||||
useTrendReport: config.useTrendReport,
|
||||
screenshots: config.screenshots,
|
||||
});
|
||||
|
||||
await prisma.campaign.update({
|
||||
where: { id },
|
||||
data: { prompt, outputPath },
|
||||
});
|
||||
|
||||
// Launch pipeline asynchronously — don't await
|
||||
launchPipeline(id, prompt, pipelineRoot).catch((err) =>
|
||||
console.error(`Pipeline failed for campaign ${id}:`, err)
|
||||
);
|
||||
|
||||
return Response.json({ status: "launched", outputPath });
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const campaign = await prisma.campaign.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
agentRuns: { orderBy: { createdAt: "asc" } },
|
||||
assets: { orderBy: { createdAt: "desc" } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!campaign) {
|
||||
return Response.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return Response.json(campaign);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
const campaign = await prisma.campaign.update({
|
||||
where: { id },
|
||||
data: body,
|
||||
});
|
||||
|
||||
return Response.json(campaign);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { scanOutputDirectory } from "@/lib/scanner";
|
||||
import path from "path";
|
||||
|
||||
export async function POST(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const campaign = await prisma.campaign.findUnique({ where: { id } });
|
||||
if (!campaign) {
|
||||
return Response.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (!campaign.outputPath) {
|
||||
return Response.json({ error: "No output path set" }, { status: 400 });
|
||||
}
|
||||
|
||||
const pipelineRoot =
|
||||
process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
const result = await scanOutputDirectory(id, campaign.outputPath, pipelineRoot);
|
||||
|
||||
return Response.json(result);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { pipelineEvents } from "@/lib/claude";
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { id } = await params;
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const handler = (event: Record<string, unknown>) => {
|
||||
controller.enqueue(
|
||||
encoder.encode(`data: ${JSON.stringify(event)}\n\n`)
|
||||
);
|
||||
};
|
||||
|
||||
pipelineEvents.on(id, handler);
|
||||
|
||||
// Keep connection alive
|
||||
const keepAlive = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(`: keepalive\n\n`));
|
||||
}, 15000);
|
||||
|
||||
request.signal.addEventListener("abort", () => {
|
||||
pipelineEvents.off(id, handler);
|
||||
clearInterval(keepAlive);
|
||||
controller.close();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const campaigns = await prisma.campaign.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
_count: { select: { assets: true, agentRuns: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json(campaigns);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const body = await request.json();
|
||||
const { name, platforms, config } = body;
|
||||
|
||||
if (!name || !platforms) {
|
||||
return Response.json(
|
||||
{ error: "Name and platforms are required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const campaign = await prisma.campaign.create({
|
||||
data: {
|
||||
name,
|
||||
platforms: JSON.stringify(platforms),
|
||||
config: config ? JSON.stringify(config) : null,
|
||||
},
|
||||
});
|
||||
|
||||
return Response.json(campaign, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendChatMessage } from "@/lib/claude";
|
||||
import path from "path";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { message, sessionId, campaignId } = await request.json();
|
||||
|
||||
if (!message || !campaignId) {
|
||||
return Response.json(
|
||||
{ error: "message and campaignId required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const campaign = await prisma.campaign.findUnique({
|
||||
where: { id: campaignId },
|
||||
});
|
||||
|
||||
if (!campaign) {
|
||||
return Response.json({ error: "Campaign not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const pipelineRoot =
|
||||
process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
// Get or create ClaudeSession
|
||||
let claudeSession = await prisma.claudeSession.findFirst({
|
||||
where: { campaignId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
|
||||
if (!claudeSession) {
|
||||
claudeSession = await prisma.claudeSession.create({
|
||||
data: { campaignId },
|
||||
});
|
||||
}
|
||||
|
||||
// Save user message
|
||||
const existingMessages = claudeSession.messages
|
||||
? JSON.parse(claudeSession.messages)
|
||||
: [];
|
||||
existingMessages.push({ role: "user", content: message });
|
||||
|
||||
await prisma.claudeSession.update({
|
||||
where: { id: claudeSession.id },
|
||||
data: { messages: JSON.stringify(existingMessages) },
|
||||
});
|
||||
|
||||
const stream = await sendChatMessage(
|
||||
claudeSession.sessionId || sessionId,
|
||||
message,
|
||||
pipelineRoot
|
||||
);
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { readFile, stat } from "fs/promises";
|
||||
import path from "path";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
const PIPELINE_ROOT = process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".mp4": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
".html": "text/html",
|
||||
".json": "application/json",
|
||||
".md": "text/markdown",
|
||||
".txt": "text/plain",
|
||||
".css": "text/css",
|
||||
".js": "text/javascript",
|
||||
".svg": "image/svg+xml",
|
||||
};
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) {
|
||||
return new Response("Unauthorized", { status: 401 });
|
||||
}
|
||||
|
||||
const { path: segments } = await params;
|
||||
const filePath = path.join(PIPELINE_ROOT, ...segments);
|
||||
|
||||
// Security: prevent path traversal
|
||||
const resolved = path.resolve(filePath);
|
||||
if (!resolved.startsWith(path.resolve(PIPELINE_ROOT))) {
|
||||
return new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const fileStat = await stat(resolved);
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
const contentType = CONTENT_TYPES[ext] || "application/octet-stream";
|
||||
const fileSize = fileStat.size;
|
||||
|
||||
// Handle range requests (needed for video seeking/thumbnails)
|
||||
const range = request.headers.get("range");
|
||||
if (range) {
|
||||
const match = range.match(/bytes=(\d+)-(\d*)/);
|
||||
if (match) {
|
||||
const start = parseInt(match[1], 10);
|
||||
const end = match[2] ? parseInt(match[2], 10) : fileSize - 1;
|
||||
const buffer = await readFile(resolved);
|
||||
const chunk = buffer.subarray(start, end + 1);
|
||||
|
||||
return new Response(chunk, {
|
||||
status: 206,
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
|
||||
"Content-Length": String(chunk.length),
|
||||
"Accept-Ranges": "bytes",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = await readFile(resolved);
|
||||
return new Response(buffer, {
|
||||
headers: {
|
||||
"Content-Type": contentType,
|
||||
"Content-Length": String(fileSize),
|
||||
"Accept-Ranges": "bytes",
|
||||
"Cache-Control": "no-cache",
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { readFile } from "fs/promises";
|
||||
import path from "path";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
const PIPELINE_ROOT =
|
||||
process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
function markdownToHtml(md: string): string {
|
||||
let html = md
|
||||
// Headers
|
||||
.replace(/^#{6}\s+(.+)$/gm, "<h6>$1</h6>")
|
||||
.replace(/^#{5}\s+(.+)$/gm, "<h5>$1</h5>")
|
||||
.replace(/^#{4}\s+(.+)$/gm, "<h4>$1</h4>")
|
||||
.replace(/^###\s+(.+)$/gm, "<h3>$1</h3>")
|
||||
.replace(/^##\s+(.+)$/gm, "<h2>$1</h2>")
|
||||
.replace(/^#\s+(.+)$/gm, "<h1>$1</h1>")
|
||||
// Bold and italic
|
||||
.replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>")
|
||||
.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
|
||||
.replace(/\*(.+?)\*/g, "<em>$1</em>")
|
||||
// Code blocks
|
||||
.replace(/```(\w*)\n([\s\S]*?)```/g, "<pre><code>$2</code></pre>")
|
||||
// Inline code
|
||||
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
||||
// Unordered lists
|
||||
.replace(/^[-*]\s+(.+)$/gm, "<li>$1</li>")
|
||||
// Ordered lists
|
||||
.replace(/^\d+\.\s+(.+)$/gm, "<li>$1</li>")
|
||||
// Horizontal rules
|
||||
.replace(/^---+$/gm, "<hr>")
|
||||
// Line breaks to paragraphs
|
||||
.replace(/\n\n+/g, "</p><p>")
|
||||
// Single newlines in context
|
||||
.replace(/\n/g, "<br>");
|
||||
|
||||
// Wrap consecutive <li> in <ul>
|
||||
html = html.replace(/((?:<li>.*?<\/li><br>?)+)/g, "<ul>$1</ul>");
|
||||
|
||||
// Tables
|
||||
html = html.replace(
|
||||
/\|(.+)\|\n\|[-| :]+\|\n((?:\|.+\|\n?)+)/g,
|
||||
(_match, header: string, body: string) => {
|
||||
const ths = header
|
||||
.split("|")
|
||||
.filter((c: string) => c.trim())
|
||||
.map((c: string) => `<th>${c.trim()}</th>`)
|
||||
.join("");
|
||||
const rows = body
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((row: string) => {
|
||||
const tds = row
|
||||
.split("|")
|
||||
.filter((c: string) => c.trim())
|
||||
.map((c: string) => `<td>${c.trim()}</td>`)
|
||||
.join("");
|
||||
return `<tr>${tds}</tr>`;
|
||||
})
|
||||
.join("");
|
||||
return `<table><thead><tr>${ths}</tr></thead><tbody>${rows}</tbody></table>`;
|
||||
}
|
||||
);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<style>
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Inter', sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 40px auto;
|
||||
padding: 0 20px;
|
||||
color: #1a1a2e;
|
||||
line-height: 1.7;
|
||||
background: #f8f6f2;
|
||||
}
|
||||
h1 { font-size: 2em; border-bottom: 2px solid #0079FF; padding-bottom: 8px; color: #0079FF; }
|
||||
h2 { font-size: 1.5em; margin-top: 2em; color: #1a1a2e; }
|
||||
h3 { font-size: 1.2em; color: #555; }
|
||||
code { background: #e8e8e8; padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
|
||||
pre { background: #1a1a2e; color: #e8e8e8; padding: 16px; border-radius: 8px; overflow-x: auto; }
|
||||
pre code { background: none; padding: 0; }
|
||||
table { border-collapse: collapse; width: 100%; margin: 1em 0; }
|
||||
th, td { border: 1px solid #ddd; padding: 8px 12px; text-align: left; }
|
||||
th { background: #0079FF; color: white; }
|
||||
tr:nth-child(even) { background: #f0f0f0; }
|
||||
hr { border: none; border-top: 1px solid #ddd; margin: 2em 0; }
|
||||
ul { padding-left: 1.5em; }
|
||||
li { margin: 4px 0; }
|
||||
strong { color: #0079FF; }
|
||||
a { color: #0079FF; }
|
||||
</style>
|
||||
</head>
|
||||
<body><p>${html}</p></body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { path: segments } = await params;
|
||||
const filePath = path.join(PIPELINE_ROOT, ...segments);
|
||||
|
||||
const resolved = path.resolve(filePath);
|
||||
if (!resolved.startsWith(path.resolve(PIPELINE_ROOT))) {
|
||||
return new Response("Forbidden", { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await readFile(resolved, "utf-8");
|
||||
const ext = path.extname(resolved).toLowerCase();
|
||||
|
||||
if (ext === ".md") {
|
||||
return new Response(markdownToHtml(content), {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
if (ext === ".json") {
|
||||
const pretty = JSON.stringify(JSON.parse(content), null, 2);
|
||||
return new Response(
|
||||
`<!DOCTYPE html><html><head><meta charset="utf-8"><style>body{font-family:monospace;max-width:900px;margin:40px auto;padding:0 20px;background:#1a1a2e;color:#e8e8e8;}</style></head><body><pre>${pretty.replace(/</g, "<")}</pre></body></html>`,
|
||||
{ headers: { "Content-Type": "text/html; charset=utf-8" } }
|
||||
);
|
||||
}
|
||||
|
||||
// HTML files served as-is
|
||||
if (ext === ".html") {
|
||||
return new Response(content, {
|
||||
headers: { "Content-Type": "text/html; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback: plain text
|
||||
return new Response(content, {
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
} catch {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import {
|
||||
createNextdoorCampaign,
|
||||
createNextdoorAdGroup,
|
||||
uploadNextdoorCreative,
|
||||
createNextdoorAd,
|
||||
} from "@/lib/nextdoor";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { assetIds, budget, schedule, targeting, copy } = await request.json();
|
||||
|
||||
if (!assetIds?.length) {
|
||||
return Response.json({ error: "assetIds required" }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Create campaign
|
||||
const campaignResult = await createNextdoorCampaign(
|
||||
`Auto Campaign ${new Date().toISOString().slice(0, 10)}`,
|
||||
budget || 50,
|
||||
schedule || {
|
||||
startDate: new Date().toISOString(),
|
||||
endDate: new Date(Date.now() + 7 * 86400000).toISOString(),
|
||||
}
|
||||
);
|
||||
const ndCampaignId = campaignResult.createCampaign.campaign.id;
|
||||
|
||||
// Create ad group
|
||||
const adGroupResult = await createNextdoorAdGroup(
|
||||
ndCampaignId,
|
||||
targeting || {}
|
||||
);
|
||||
const adGroupId = adGroupResult.createAdGroup.adGroup.id;
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const id of assetIds) {
|
||||
const asset = await prisma.asset.findUnique({ where: { id } });
|
||||
if (!asset) continue;
|
||||
|
||||
try {
|
||||
// Upload creative (requires public URL — would need Postiz upload first)
|
||||
const creativeResult = await uploadNextdoorCreative(
|
||||
`/api/files/${asset.filePath}`
|
||||
);
|
||||
const creativeId = creativeResult.createCreative.creative.id;
|
||||
|
||||
// Create ad
|
||||
const metadata = asset.metadata ? JSON.parse(asset.metadata) : {};
|
||||
await createNextdoorAd(adGroupId, creativeId, {
|
||||
headline: metadata.headline || "Check this out",
|
||||
body: metadata.caption || "",
|
||||
ctaText: copy?.ctaText || "Learn More",
|
||||
destinationUrl: copy?.destinationUrl || "https://example.com",
|
||||
});
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id },
|
||||
data: { status: "published", publishedTo: JSON.stringify(["nextdoor"]) },
|
||||
});
|
||||
|
||||
results.push({ id, status: "published" });
|
||||
} catch (error) {
|
||||
results.push({
|
||||
id,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Response.json({ campaignId: ndCampaignId, adGroupId, results });
|
||||
} catch (error) {
|
||||
return Response.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { pushToPostiz, getPostizIntegrations } from "@/lib/postiz";
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
try {
|
||||
const integrations = await getPostizIntegrations();
|
||||
return Response.json(integrations);
|
||||
} catch (error) {
|
||||
return Response.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to fetch integrations" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { assetIds, scheduledAt } = await request.json();
|
||||
|
||||
if (!assetIds?.length || !scheduledAt) {
|
||||
return Response.json(
|
||||
{ error: "assetIds and scheduledAt required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const id of assetIds) {
|
||||
const asset = await prisma.asset.findUnique({ where: { id } });
|
||||
if (!asset) continue;
|
||||
|
||||
try {
|
||||
const post = await pushToPostiz(asset, scheduledAt);
|
||||
|
||||
await prisma.asset.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: "published",
|
||||
postizPostId: post.id,
|
||||
},
|
||||
});
|
||||
|
||||
results.push({ id, status: "scheduled", postId: post.id });
|
||||
} catch (error) {
|
||||
results.push({
|
||||
id,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return Response.json({ results });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import {
|
||||
getAllSettings,
|
||||
saveSetting,
|
||||
checkIntegrationStatus,
|
||||
SETTINGS_CONFIG,
|
||||
type SettingKey,
|
||||
} from "@/lib/settings";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const includeStatus = searchParams.get("status") === "true";
|
||||
|
||||
const settings = await getAllSettings();
|
||||
|
||||
// Mask secret values for display
|
||||
const masked: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
const config = SETTINGS_CONFIG[key as SettingKey];
|
||||
if (config && "secret" in config && config.secret && value) {
|
||||
masked[key] = value.slice(0, 4) + "..." + value.slice(-4);
|
||||
} else {
|
||||
masked[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const result: Record<string, unknown> = { settings: masked };
|
||||
|
||||
if (includeStatus) {
|
||||
result.status = await checkIntegrationStatus();
|
||||
}
|
||||
|
||||
return Response.json(result);
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const body = await request.json();
|
||||
const { key, value } = body;
|
||||
|
||||
if (!key || typeof value !== "string") {
|
||||
return Response.json({ error: "key and value required" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!(key in SETTINGS_CONFIG)) {
|
||||
return Response.json({ error: "Invalid setting key" }, { status: 400 });
|
||||
}
|
||||
|
||||
await saveSetting(key as SettingKey, value);
|
||||
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET() {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
const [
|
||||
activeCampaigns,
|
||||
pendingReview,
|
||||
publishedThisWeek,
|
||||
recentCampaigns,
|
||||
trendReports,
|
||||
] = await Promise.all([
|
||||
prisma.campaign.count({
|
||||
where: { status: { in: ["running", "review"] } },
|
||||
}),
|
||||
prisma.asset.count({
|
||||
where: {
|
||||
status: "draft",
|
||||
campaign: { status: { in: ["review", "running"] } },
|
||||
},
|
||||
}),
|
||||
prisma.asset.count({
|
||||
where: {
|
||||
status: "published",
|
||||
createdAt: { gte: oneWeekAgo },
|
||||
},
|
||||
}),
|
||||
prisma.campaign.findMany({
|
||||
take: 5,
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: { id: true, name: true, status: true, createdAt: true },
|
||||
}),
|
||||
prisma.trendReport.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 10,
|
||||
}),
|
||||
]);
|
||||
|
||||
return Response.json({
|
||||
activeCampaigns,
|
||||
pendingReview,
|
||||
publishedThisWeek,
|
||||
recentCampaigns,
|
||||
trendReports,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import path from "path";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
const PIPELINE_ROOT =
|
||||
process.env.PIPELINE_ROOT || path.join(process.cwd(), "pipeline");
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await auth();
|
||||
if (!session) return new Response("Unauthorized", { status: 401 });
|
||||
|
||||
const formData = await request.formData();
|
||||
const files = formData.getAll("files") as File[];
|
||||
|
||||
if (files.length === 0) {
|
||||
return Response.json({ error: "No files provided" }, { status: 400 });
|
||||
}
|
||||
|
||||
const screenshotsDir = path.join(PIPELINE_ROOT, "assets", "screenshots");
|
||||
await mkdir(screenshotsDir, { recursive: true });
|
||||
|
||||
const uploaded: { fileName: string; path: string }[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith("image/")) continue;
|
||||
|
||||
const ext = path.extname(file.name) || ".png";
|
||||
const uniqueName = `${randomUUID()}${ext}`;
|
||||
const filePath = path.join(screenshotsDir, uniqueName);
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await writeFile(filePath, buffer);
|
||||
|
||||
uploaded.push({
|
||||
fileName: file.name,
|
||||
path: `assets/screenshots/${uniqueName}`,
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ uploaded });
|
||||
}
|
||||
Reference in New Issue
Block a user