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:
Trey t
2026-03-23 21:05:26 -05:00
parent 6b08cfb73a
commit 66c2bbec8b
113 changed files with 12741 additions and 138 deletions
+11
View File
@@ -0,0 +1,11 @@
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
{children}
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
"use client";
import { useState } from "react";
import { signIn } from "next-auth/react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
export default function LoginPage() {
const router = useRouter();
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
setError("");
const formData = new FormData(e.currentTarget);
const result = await signIn("credentials", {
email: formData.get("email") as string,
password: formData.get("password") as string,
redirect: false,
});
if (result?.error) {
setError("Invalid email or password");
setLoading(false);
} else {
router.push("/");
router.refresh();
}
}
return (
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-2xl">honeyDue Marketing</CardTitle>
<CardDescription>Sign in to the command center</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
name="email"
type="email"
placeholder="admin@localhost"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
name="password"
type="password"
required
/>
</div>
{error && (
<p className="text-sm text-red-500">{error}</p>
)}
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Signing in..." : "Sign in"}
</Button>
</form>
</CardContent>
</Card>
);
}
+22
View File
@@ -0,0 +1,22 @@
"use client";
import { useState } from "react";
import { AssetGallery } from "@/components/asset-gallery";
import { PostizPushModal } from "@/components/postiz-push-modal";
export default function GlobalAssetsPage() {
const [pushModalIds, setPushModalIds] = useState<string[] | null>(null);
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Asset Library</h1>
<AssetGallery onPushToPostiz={(ids) => setPushModalIds(ids)} />
{pushModalIds && (
<PostizPushModal
assetIds={pushModalIds}
onClose={() => setPushModalIds(null)}
/>
)}
</div>
);
}
@@ -0,0 +1,29 @@
"use client";
import { use, useState } from "react";
import { AssetGallery } from "@/components/asset-gallery";
import { PostizPushModal } from "@/components/postiz-push-modal";
export default function CampaignAssetsPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const [pushModalIds, setPushModalIds] = useState<string[] | null>(null);
return (
<>
<AssetGallery
campaignId={id}
onPushToPostiz={(ids) => setPushModalIds(ids)}
/>
{pushModalIds && (
<PostizPushModal
assetIds={pushModalIds}
onClose={() => setPushModalIds(null)}
/>
)}
</>
);
}
@@ -0,0 +1,14 @@
"use client";
import { use } from "react";
import { ClaudeChat } from "@/components/claude-chat";
export default function CampaignChatPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
return <ClaudeChat campaignId={id} />;
}
+53
View File
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { use } from "react";
const tabs = [
{ label: "Details", href: "" },
{ label: "Pipeline", href: "/pipeline" },
{ label: "Assets", href: "/assets" },
{ label: "Claude Chat", href: "/chat" },
];
export default function CampaignDetailLayout({
children,
params,
}: {
children: React.ReactNode;
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const pathname = usePathname();
const basePath = `/campaigns/${id}`;
return (
<div className="space-y-6">
<nav className="flex gap-1 border-b">
{tabs.map((tab) => {
const href = `${basePath}${tab.href}`;
const isActive =
tab.href === ""
? pathname === basePath
: pathname.startsWith(href);
return (
<Link
key={tab.label}
href={href}
className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${
isActive
? "border-primary text-primary"
: "border-transparent text-muted-foreground hover:text-foreground"
}`}
>
{tab.label}
</Link>
);
})}
</nav>
{children}
</div>
);
}
+165
View File
@@ -0,0 +1,165 @@
"use client";
import { use, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { CampaignForm, type CampaignData } from "@/components/campaign-form";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Play } from "lucide-react";
interface CampaignResponse {
id: string;
name: string;
status: string;
platforms: string;
config: string | null;
}
export default function CampaignDetailsPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const router = useRouter();
const [campaign, setCampaign] = useState<CampaignResponse | null>(null);
const [launching, setLaunching] = useState(false);
const [saved, setSaved] = useState(false);
useEffect(() => {
fetch(`/api/campaigns/${id}`)
.then((r) => r.json())
.then((data) => {
setCampaign(data);
setSaved(false);
})
.catch(() => {});
}, [id]);
async function handleLaunch() {
setLaunching(true);
await fetch(`/api/campaigns/${id}/launch`, { method: "POST" });
router.push(`/campaigns/${id}/pipeline`);
}
if (!campaign) {
return <p className="text-muted-foreground">Loading...</p>;
}
const config = campaign.config ? JSON.parse(campaign.config) : {};
const platforms: string[] = JSON.parse(campaign.platforms);
const isDraft = campaign.status === "draft";
const initialData: CampaignData = {
id: campaign.id,
name: campaign.name,
platforms,
config: {
goal: config.goal || "app_downloads",
keyMessage: config.keyMessage || "",
socialProof: config.socialProof || "",
targetAudience: config.targetAudience || "",
visualDirection: config.visualDirection || "clean",
competitorApps: config.competitorApps || "",
variations: config.variations ?? 5,
useTrendReport: config.useTrendReport || false,
screenshots: config.screenshots || [],
},
};
return (
<div className="space-y-4">
{isDraft && (
<div className="flex items-center justify-between rounded-lg border border-primary/20 bg-primary/5 p-4">
<div>
<p className="font-medium">Ready to launch?</p>
<p className="text-sm text-muted-foreground">
Review your campaign details below, then launch the pipeline.
</p>
</div>
<Button onClick={handleLaunch} disabled={launching}>
<Play className="mr-2 h-4 w-4" />
{launching ? "Launching..." : "Launch Pipeline"}
</Button>
</div>
)}
{!isDraft && (
<div className="flex items-center gap-2">
<Badge variant="secondary">{campaign.status}</Badge>
<span className="text-sm text-muted-foreground">
Campaign is {campaign.status} fields are read-only.
</span>
</div>
)}
<div className="max-w-2xl">
{isDraft ? (
<CampaignForm initialData={initialData} mode="edit" />
) : (
<ReadOnlyDetails data={initialData} />
)}
</div>
</div>
);
}
function ReadOnlyDetails({ data }: { data: CampaignData }) {
const goalLabels: Record<string, string> = {
app_downloads: "App Downloads",
brand_awareness: "Brand Awareness",
engagement: "Engagement",
};
const visualLabels: Record<string, string> = {
clean: "Clean & Minimal",
bold: "Bold & Vibrant",
premium: "Premium & Dark",
warm: "Warm & Friendly",
tech: "Tech & Modern",
};
const fields = [
{ label: "Campaign Name", value: data.name },
{ label: "Platforms", value: data.platforms.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(", ") },
{ label: "Goal", value: goalLabels[data.config.goal] || data.config.goal },
{ label: "Key Message", value: data.config.keyMessage },
{ label: "Social Proof", value: data.config.socialProof },
{ label: "Target Audience", value: data.config.targetAudience },
{ label: "Visual Direction", value: visualLabels[data.config.visualDirection || ""] || data.config.visualDirection },
{ label: "Competitor Apps", value: data.config.competitorApps },
{ label: "Variations", value: String(data.config.variations ?? 5) },
];
return (
<div className="rounded-lg border">
<div className="divide-y">
{fields.map((field) => (
<div key={field.label} className="flex gap-4 px-4 py-3">
<span className="w-40 shrink-0 text-sm font-medium text-muted-foreground">
{field.label}
</span>
<span className="text-sm">{field.value || "—"}</span>
</div>
))}
{data.config.screenshots && data.config.screenshots.length > 0 && (
<div className="flex gap-4 px-4 py-3">
<span className="w-40 shrink-0 text-sm font-medium text-muted-foreground">
Screenshots
</span>
<div className="flex gap-2">
{data.config.screenshots.map((path, i) => (
<img
key={i}
src={`/api/files/${path}`}
alt={`Screenshot ${i + 1}`}
className="h-24 rounded-md border object-cover"
/>
))}
</div>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,89 @@
"use client";
import { use, useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { PipelineProgress } from "@/components/pipeline-progress";
import { usePipelineProgress } from "@/hooks/use-pipeline-progress";
import { Play } from "lucide-react";
interface Campaign {
id: string;
name: string;
status: string;
platforms: string;
agentRuns: Array<{
id: string;
agentName: string;
status: string;
durationMs?: number;
outputSummary?: string;
error?: string;
}>;
}
export default function CampaignPipelinePage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = use(params);
const [campaign, setCampaign] = useState<Campaign | null>(null);
const [launching, setLaunching] = useState(false);
const { agents, pipelineStatus } = usePipelineProgress(
campaign?.status === "running" ? id : null
);
useEffect(() => {
fetch(`/api/campaigns/${id}`)
.then((r) => r.json())
.then(setCampaign)
.catch(() => {});
}, [id, pipelineStatus]);
async function handleLaunch() {
setLaunching(true);
await fetch(`/api/campaigns/${id}/launch`, { method: "POST" });
setCampaign((prev) => (prev ? { ...prev, status: "running" } : prev));
setLaunching(false);
}
if (!campaign) {
return <p className="text-muted-foreground">Loading...</p>;
}
// Use SSE agents if pipeline is running, otherwise use stored agentRuns
const displayAgents =
campaign.status === "running"
? agents
: campaign.agentRuns.length > 0
? campaign.agentRuns.map((r) => ({
agentName: r.agentName,
status: r.status as "pending" | "running" | "completed" | "failed",
durationMs: r.durationMs ?? undefined,
outputSummary: r.outputSummary ?? undefined,
error: r.error ?? undefined,
}))
: agents;
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h2 className="text-2xl font-bold">{campaign.name}</h2>
<Badge variant="secondary" className="mt-1">
{campaign.status}
</Badge>
</div>
{campaign.status === "draft" && (
<Button onClick={handleLaunch} disabled={launching}>
<Play className="mr-2 h-4 w-4" />
{launching ? "Launching..." : "Launch Pipeline"}
</Button>
)}
</div>
<PipelineProgress agents={displayAgents} />
</div>
);
}
+9
View File
@@ -0,0 +1,9 @@
import { CampaignForm } from "@/components/campaign-form";
export default function NewCampaignPage() {
return (
<div className="mx-auto max-w-2xl">
<CampaignForm />
</div>
);
}
+89
View File
@@ -0,0 +1,89 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Plus } from "lucide-react";
interface Campaign {
id: string;
name: string;
status: string;
platforms: string;
createdAt: string;
_count: { assets: number; agentRuns: number };
}
const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
draft: "secondary",
running: "default",
review: "outline",
approved: "default",
published: "default",
};
export default function CampaignsPage() {
const [campaigns, setCampaigns] = useState<Campaign[]>([]);
useEffect(() => {
fetch("/api/campaigns")
.then((r) => r.json())
.then(setCampaigns)
.catch(() => {});
}, []);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Campaigns</h1>
<Link href="/campaigns/new" className={buttonVariants()}>
<Plus className="mr-2 h-4 w-4" />
New Campaign
</Link>
</div>
{campaigns.length === 0 ? (
<Card>
<CardContent className="py-12 text-center">
<p className="text-muted-foreground">
No campaigns yet. Create your first one to get started.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{campaigns.map((campaign) => {
const platforms = JSON.parse(campaign.platforms) as string[];
return (
<Link key={campaign.id} href={`/campaigns/${campaign.id}`}>
<Card className="hover:bg-muted/50 transition-colors cursor-pointer">
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{campaign.name}</CardTitle>
<Badge variant={statusColors[campaign.status] || "secondary"}>
{campaign.status}
</Badge>
</div>
<CardDescription>
{platforms.join(", ")} &middot;{" "}
{campaign._count.assets} assets &middot;{" "}
{new Date(campaign.createdAt).toLocaleDateString()}
</CardDescription>
</CardHeader>
</Card>
</Link>
);
})}
</div>
)}
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { AppSidebar } from "@/components/app-sidebar";
import { Header } from "@/components/header";
import { Providers } from "@/components/providers";
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<Providers>
<div className="flex min-h-screen w-full">
<AppSidebar />
<div className="flex flex-1 flex-col">
<Header />
<main className="flex-1 p-6">{children}</main>
</div>
</div>
</Providers>
);
}
+116
View File
@@ -0,0 +1,116 @@
"use client";
import Link from "next/link";
import { buttonVariants } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Megaphone, Image, Clock, Plus } from "lucide-react";
import { useEffect, useState } from "react";
interface Stats {
activeCampaigns: number;
pendingReview: number;
publishedThisWeek: number;
recentCampaigns: Array<{
id: string;
name: string;
status: string;
createdAt: string;
}>;
}
export default function DashboardPage() {
const [stats, setStats] = useState<Stats | null>(null);
useEffect(() => {
fetch("/api/stats")
.then((r) => r.json())
.then(setStats)
.catch(() => {});
}, []);
const cards = [
{
title: "Active Campaigns",
value: stats?.activeCampaigns ?? 0,
icon: Megaphone,
description: "Currently running",
},
{
title: "Pending Review",
value: stats?.pendingReview ?? 0,
icon: Clock,
description: "Assets awaiting approval",
},
{
title: "Published This Week",
value: stats?.publishedThisWeek ?? 0,
icon: Image,
description: "Assets sent to platforms",
},
];
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Dashboard</h1>
<Link href="/campaigns/new" className={buttonVariants()}>
<Plus className="mr-2 h-4 w-4" />
New Campaign
</Link>
</div>
<div className="grid gap-4 md:grid-cols-3">
{cards.map((card) => (
<Card key={card.title}>
<CardHeader className="flex flex-row items-center justify-between pb-2">
<CardTitle className="text-sm font-medium">
{card.title}
</CardTitle>
<card.icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{card.value}</div>
<p className="text-xs text-muted-foreground">
{card.description}
</p>
</CardContent>
</Card>
))}
</div>
<Card>
<CardHeader>
<CardTitle>Recent Campaigns</CardTitle>
<CardDescription>Your latest marketing campaigns</CardDescription>
</CardHeader>
<CardContent>
{stats?.recentCampaigns && stats.recentCampaigns.length > 0 ? (
<div className="space-y-3">
{stats.recentCampaigns.map((campaign) => (
<Link
key={campaign.id}
href={`/campaigns/${campaign.id}`}
className="flex items-center justify-between rounded-lg border p-3 hover:bg-muted/50 transition-colors"
>
<span className="font-medium">{campaign.name}</span>
<Badge variant="secondary">{campaign.status}</Badge>
</Link>
))}
</div>
) : (
<p className="text-sm text-muted-foreground">
No campaigns yet. Create your first one to get started.
</p>
)}
</CardContent>
</Card>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
"use client";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
interface QueueAsset {
id: string;
fileName: string;
platform?: string | null;
status: string;
postizPostId?: string | null;
metadata?: string | null;
createdAt: string;
campaign?: { name: string };
}
export default function QueuePage() {
const [assets, setAssets] = useState<QueueAsset[]>([]);
useEffect(() => {
fetch("/api/assets?status=published")
.then((r) => r.json())
.then(setAssets)
.catch(() => {});
}, []);
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Publishing Queue</h1>
<Card>
<CardHeader>
<CardTitle>Scheduled & Published</CardTitle>
<CardDescription>
Assets pushed to Postiz for publishing
</CardDescription>
</CardHeader>
<CardContent>
{assets.length === 0 ? (
<p className="text-center text-muted-foreground py-8">
No published assets yet. Approve assets and push them to Postiz.
</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>Asset</TableHead>
<TableHead>Campaign</TableHead>
<TableHead>Platform</TableHead>
<TableHead>Status</TableHead>
<TableHead>Post ID</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{assets.map((asset) => {
const metadata = asset.metadata
? JSON.parse(asset.metadata)
: {};
return (
<TableRow key={asset.id}>
<TableCell className="font-medium">
{asset.fileName}
{metadata.caption && (
<p className="text-xs text-muted-foreground line-clamp-1 mt-1">
{metadata.caption}
</p>
)}
</TableCell>
<TableCell>{asset.campaign?.name || "—"}</TableCell>
<TableCell>
{asset.platform && (
<Badge variant="outline">{asset.platform}</Badge>
)}
</TableCell>
<TableCell>
<Badge variant="default">{asset.status}</Badge>
</TableCell>
<TableCell className="text-xs text-muted-foreground">
{asset.postizPostId || "—"}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
)}
</CardContent>
</Card>
</div>
);
}
+281
View File
@@ -0,0 +1,281 @@
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { CheckCircle2, XCircle, Loader2, ExternalLink } from "lucide-react";
interface SettingsGroup {
name: string;
description: string;
docsUrl: string;
keys: string[];
}
interface SettingConfig {
label: string;
placeholder: string;
secret?: boolean;
}
const SETTINGS_GROUPS: SettingsGroup[] = [
{
name: "Postiz",
description:
"Self-hosted social media scheduling. Handles Instagram and TikTok publishing.",
docsUrl: "https://postiz.com",
keys: ["POSTIZ_URL", "POSTIZ_API_KEY"],
},
{
name: "Tavily",
description:
"AI-powered web research. Used by the Trend Scout and Research agents.",
docsUrl: "https://tavily.com",
keys: ["TAVILY_API_KEY"],
},
{
name: "Gemini",
description:
"Google Gemini powers NanoBanana MCP for AI image generation in static ads. ~$0.04-0.13/image.",
docsUrl: "https://aistudio.google.com/apikey",
keys: ["GEMINI_API_KEY"],
},
{
name: "Nextdoor",
description:
"Direct Nextdoor Ads API integration for local advertising.",
docsUrl: "https://developer.nextdoor.com",
keys: ["NEXTDOOR_API_TOKEN", "NEXTDOOR_ADVERTISER_ID"],
},
];
const SETTINGS_CONFIG: Record<string, SettingConfig> = {
POSTIZ_URL: { label: "Postiz URL", placeholder: "http://localhost:5000" },
POSTIZ_API_KEY: {
label: "Postiz API Key",
placeholder: "your-postiz-api-key",
secret: true,
},
TAVILY_API_KEY: {
label: "Tavily API Key",
placeholder: "tvly-...",
secret: true,
},
GEMINI_API_KEY: {
label: "Google Gemini API Key",
placeholder: "AIza...",
secret: true,
},
NEXTDOOR_API_TOKEN: {
label: "Nextdoor API Token",
placeholder: "your-nextdoor-token",
secret: true,
},
NEXTDOOR_ADVERTISER_ID: {
label: "Nextdoor Advertiser ID",
placeholder: "your-advertiser-id",
},
};
type IntegrationStatus = Record<
string,
{ connected: boolean; error?: string }
>;
export default function SettingsPage() {
const [settings, setSettings] = useState<Record<string, string>>({});
const [status, setStatus] = useState<IntegrationStatus>({});
const [editValues, setEditValues] = useState<Record<string, string>>({});
const [saving, setSaving] = useState<string | null>(null);
const [saved, setSaved] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch("/api/settings?status=true")
.then((r) => r.json())
.then((data) => {
setSettings(data.settings || {});
setStatus(data.status || {});
setLoading(false);
})
.catch(() => setLoading(false));
}, []);
async function handleSave(key: string) {
const value = editValues[key];
if (value === undefined) return;
setSaving(key);
const res = await fetch("/api/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key, value }),
});
if (res.ok) {
setSaved(key);
// Refresh settings
const data = await fetch("/api/settings?status=true").then((r) =>
r.json()
);
setSettings(data.settings || {});
setStatus(data.status || {});
setEditValues((prev) => {
const next = { ...prev };
delete next[key];
return next;
});
setTimeout(() => setSaved(null), 2000);
}
setSaving(null);
}
function getGroupStatus(group: SettingsGroup): {
connected: boolean;
error?: string;
} {
const key = group.name.toLowerCase();
return status[key] || { connected: false, error: "Unknown" };
}
if (loading) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold">Settings</h1>
<p className="text-muted-foreground mt-1">
Configure your third-party integrations. Values are stored securely in
the database and override environment variables.
</p>
</div>
{SETTINGS_GROUPS.map((group) => {
const groupStatus = getGroupStatus(group);
return (
<Card key={group.name}>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<CardTitle>{group.name}</CardTitle>
{groupStatus.connected ? (
<Badge
variant="outline"
className="text-green-600 border-green-200 bg-green-50"
>
<CheckCircle2 className="h-3 w-3 mr-1" />
Connected
</Badge>
) : (
<Badge
variant="outline"
className="text-amber-600 border-amber-200 bg-amber-50"
>
<XCircle className="h-3 w-3 mr-1" />
{groupStatus.error || "Not connected"}
</Badge>
)}
</div>
<a
href={group.docsUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1"
>
Docs
<ExternalLink className="h-3 w-3" />
</a>
</div>
<CardDescription>{group.description}</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{group.keys.map((key) => {
const config = SETTINGS_CONFIG[key];
const currentValue = settings[key] || "";
const isEditing = key in editValues;
const editValue = editValues[key] ?? "";
return (
<div key={key} className="space-y-2">
<Label htmlFor={key}>{config.label}</Label>
<div className="flex gap-2">
<Input
id={key}
type={config.secret && !isEditing ? "password" : "text"}
placeholder={config.placeholder}
value={isEditing ? editValue : currentValue}
onChange={(e) =>
setEditValues((prev) => ({
...prev,
[key]: e.target.value,
}))
}
onFocus={() => {
if (!isEditing) {
// Clear masked value on focus for secret fields
setEditValues((prev) => ({
...prev,
[key]: "",
}));
}
}}
/>
{isEditing && (
<Button
onClick={() => handleSave(key)}
disabled={saving === key}
size="sm"
className="shrink-0"
>
{saving === key ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : saved === key ? (
<CheckCircle2 className="h-4 w-4" />
) : (
"Save"
)}
</Button>
)}
{isEditing && (
<Button
variant="ghost"
size="sm"
className="shrink-0"
onClick={() =>
setEditValues((prev) => {
const next = { ...prev };
delete next[key];
return next;
})
}
>
Cancel
</Button>
)}
</div>
</div>
);
})}
</CardContent>
</Card>
);
})}
</div>
);
}
+109
View File
@@ -0,0 +1,109 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { buttonVariants } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
interface TrendReport {
id: string;
name: string;
filePath: string;
summary?: string | null;
createdAt: string;
}
export default function TrendsPage() {
const [reports, setReports] = useState<TrendReport[]>([]);
const [selectedReport, setSelectedReport] = useState<TrendReport | null>(null);
useEffect(() => {
fetch("/api/stats")
.then((r) => r.json())
.then((data) => {
if (data.trendReports) setReports(data.trendReports);
})
.catch(() => {});
}, []);
return (
<div className="space-y-6">
<h1 className="text-3xl font-bold">Trend Reports</h1>
{reports.length === 0 ? (
<Card>
<CardContent className="py-12 text-center">
<p className="text-muted-foreground">
No trend reports yet. Run the Trend Scout agent to generate
reports.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4 md:grid-cols-2">
{reports.map((report) => (
<Card
key={report.id}
className="cursor-pointer hover:bg-muted/50 transition-colors"
onClick={() => setSelectedReport(report)}
>
<CardHeader>
<CardTitle className="text-lg">{report.name}</CardTitle>
<CardDescription>
{new Date(report.createdAt).toLocaleDateString()}
</CardDescription>
</CardHeader>
{report.summary && (
<CardContent>
<p className="text-sm text-muted-foreground">
{report.summary}
</p>
</CardContent>
)}
<CardContent>
<Link
href={`/campaigns/new?trendReport=${report.id}`}
className={buttonVariants({ variant: "outline", size: "sm" })}
>
Create Campaign from This
</Link>
</CardContent>
</Card>
))}
</div>
)}
{/* Report Viewer */}
{selectedReport && (
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>{selectedReport.name}</CardTitle>
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedReport(null)}
>
Close
</Button>
</div>
</CardHeader>
<CardContent>
<iframe
src={`/api/files/${selectedReport.filePath}`}
className="w-full h-[600px] border rounded-md"
title={selectedReport.name}
/>
</CardContent>
</Card>
)}
</div>
);
}
+20
View File
@@ -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);
}
+34
View File
@@ -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);
}
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;
+67
View File
@@ -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 });
}
+44
View File
@@ -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);
}
+30
View File
@@ -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);
}
+44
View File
@@ -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",
},
});
}
+41
View File
@@ -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 });
}
+66
View File
@@ -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",
},
});
}
+83
View File
@@ -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 });
}
}
+147
View File
@@ -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, "&lt;")}</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 });
}
}
+83
View File
@@ -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 }
);
}
}
+61
View File
@@ -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 });
}
+57
View File
@@ -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 });
}
+50
View File
@@ -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,
});
}
+42
View File
@@ -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 });
}
+59 -58
View File
@@ -48,73 +48,74 @@
--radius-4xl: calc(var(--radius) * 2.6);
}
/* honeyDue palette — #0079FF blue primary, #FF9400 orange accent */
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--background: oklch(0.98 0.002 90);
--foreground: oklch(0.17 0.02 260);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--card-foreground: oklch(0.17 0.02 260);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--popover-foreground: oklch(0.17 0.02 260);
--primary: oklch(0.55 0.22 255);
--primary-foreground: oklch(1 0 0);
--secondary: oklch(0.95 0.01 90);
--secondary-foreground: oklch(0.17 0.02 260);
--muted: oklch(0.955 0.008 90);
--muted-foreground: oklch(0.50 0.02 260);
--accent: oklch(0.72 0.17 62);
--accent-foreground: oklch(1 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
--border: oklch(0.91 0.008 90);
--input: oklch(0.91 0.008 90);
--ring: oklch(0.55 0.22 255);
--chart-1: oklch(0.55 0.22 255);
--chart-2: oklch(0.72 0.17 62);
--chart-3: oklch(0.65 0.20 145);
--chart-4: oklch(0.55 0.17 27);
--chart-5: oklch(0.60 0.18 290);
--radius: 0.75rem;
--sidebar: oklch(0.99 0.002 90);
--sidebar-foreground: oklch(0.17 0.02 260);
--sidebar-primary: oklch(0.55 0.22 255);
--sidebar-primary-foreground: oklch(1 0 0);
--sidebar-accent: oklch(0.94 0.03 255);
--sidebar-accent-foreground: oklch(0.35 0.15 255);
--sidebar-border: oklch(0.91 0.008 90);
--sidebar-ring: oklch(0.55 0.22 255);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--background: oklch(0.16 0.02 260);
--foreground: oklch(0.96 0.005 90);
--card: oklch(0.21 0.02 260);
--card-foreground: oklch(0.96 0.005 90);
--popover: oklch(0.21 0.02 260);
--popover-foreground: oklch(0.96 0.005 90);
--primary: oklch(0.62 0.22 255);
--primary-foreground: oklch(1 0 0);
--secondary: oklch(0.26 0.02 260);
--secondary-foreground: oklch(0.96 0.005 90);
--muted: oklch(0.26 0.02 260);
--muted-foreground: oklch(0.65 0.02 260);
--accent: oklch(0.72 0.17 62);
--accent-foreground: oklch(1 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--border: oklch(1 0 0 / 12%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
--ring: oklch(0.62 0.22 255);
--chart-1: oklch(0.62 0.22 255);
--chart-2: oklch(0.72 0.17 62);
--chart-3: oklch(0.65 0.20 145);
--chart-4: oklch(0.55 0.17 27);
--chart-5: oklch(0.60 0.18 290);
--sidebar: oklch(0.19 0.02 260);
--sidebar-foreground: oklch(0.96 0.005 90);
--sidebar-primary: oklch(0.62 0.22 255);
--sidebar-primary-foreground: oklch(1 0 0);
--sidebar-accent: oklch(0.28 0.04 255);
--sidebar-accent-foreground: oklch(0.85 0.10 255);
--sidebar-border: oklch(1 0 0 / 12%);
--sidebar-ring: oklch(0.62 0.22 255);
}
@layer base {
+7 -7
View File
@@ -1,20 +1,20 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Inter, JetBrains_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
const inter = Inter({
variable: "--font-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
const jetbrainsMono = JetBrains_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "honeyDue — Marketing Command Center",
description: "AI-powered marketing pipeline for honeyDue",
};
export default function RootLayout({
@@ -25,7 +25,7 @@ export default function RootLayout({
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
className={`${inter.variable} ${jetbrainsMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
</html>
-65
View File
@@ -1,65 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}