import Link from "next/link"; import { headers } from "next/headers"; import { getLocale, getTranslations } from "next-intl/server"; import { auth } from "@/lib/auth"; import prisma from "@/lib/prisma"; import { AdminUserToggle } from "@/components/admin/admin-user-toggle"; import { LegacyHdToggle } from "@/components/admin/legacy-hd-toggle"; import { FeatureFlagSwitch } from "@/components/admin/feature-flag-switch"; import { formatBillingPlanName } from "@/lib/billing-plans"; import { AffiliateReviewActions } from "@/components/admin/affiliate-review-actions"; import { RuntimeSettingsForm, type RuntimeSetting, } from "@/components/admin/runtime-settings-form"; import { Badge } from "@/components/ui/badge"; import { StatusBadge } from "@/components/app/status-badge"; import { cn } from "@/lib/utils"; import { intlLocale } from "@/i18n/config"; import { APP_STORE_ID } from "@/lib/site"; import { fetchBackend } from "@/server/backend-api"; const ACTIVE_TASK_STATUSES = ["queued", "processing", "pending"]; /** The Pro subscription's "Creator offer" in App Store Connect; add each creator's custom code there. */ const APP_STORE_CREATOR_OFFER_URL = `https://appstoreconnect.apple.com/apps/${APP_STORE_ID}/distribution/subscriptions/6786756790/pricing/offer-codes/e3b69863-0319-4852-a9c8-204bd84a8183`; const th = "px-5 py-2.5 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground"; const td = "px-5 py-3 text-sm"; function Panel({ title, description, action, children }: { title: string; description: string; action?: React.ReactNode; children: React.ReactNode }) { return (

{title}

{description}

{action}
{children}
); } function TaskCell({ id, title, untitled }: { id: string; title?: string | null; untitled: string }) { return ( {title || untitled} {id.slice(0, 8)} ); } function Gate({ title, message, children }: { title: string; message: string; children?: React.ReactNode }) { return (

{title}

{message}

{children}
); } export default async function AdminPage({ searchParams, }: { searchParams: Promise<{ user?: string; q?: string }>; }) { const t = await getTranslations("admin"); const dateLocale = intlLocale(await getLocale()); const session = await auth.api.getSession({ headers: await headers() }); if (!session?.user) { return ( {t("gate.goToSignIn")} ); } const isAdmin = Boolean((session.user as { is_admin?: boolean }).is_admin); if (!isAdmin) { return ; } const { user: selectedUserId, q } = await searchParams; const userQuery = q?.trim() || ""; const adminUserId = session.user.id; async function loadRuntimeSettings(): Promise<{ settings: RuntimeSetting[]; error: string | null; }> { try { const response = await fetchBackend("/admin/runtime-settings", { method: "GET", userId: adminUserId, cache: "no-store", }); if (!response.ok) { return { settings: [], error: t("runtime.loadFailed") }; } const payload = (await response.json()) as { settings?: RuntimeSetting[] }; return { settings: payload.settings ?? [], error: null }; } catch { return { settings: [], error: t("runtime.unreachable") }; } } const [ runtimeSettings, totalUsers, adminUsers, totalTasks, completedTasks, activeTasks, recentUsers, processingNow, recentGenerations, tasksByUser, selectedUser, selectedUserTasks, affiliates, featureFlags, ] = await Promise.all([ loadRuntimeSettings(), prisma.user.count(), prisma.user.count({ where: { is_admin: true } }), prisma.task.count(), prisma.task.count({ where: { status: "completed" } }), prisma.task.count({ where: { status: { in: ACTIVE_TASK_STATUSES } } }), prisma.user.findMany({ where: userQuery ? { OR: [ { email: { contains: userQuery, mode: "insensitive" } }, { name: { contains: userQuery, mode: "insensitive" } }, { id: userQuery }, ], } : undefined, orderBy: { createdAt: "desc" }, take: 30, select: { id: true, email: true, name: true, is_admin: true, plan: true, subscription_status: true, subscription_provider: true, legacy_hd: true, createdAt: true, }, }), prisma.task.findMany({ where: { status: { in: ACTIVE_TASK_STATUSES } }, orderBy: { updated_at: "desc" }, take: 25, select: { id: true, status: true, created_at: true, updated_at: true, user: { select: { id: true, email: true, }, }, source: { select: { title: true, }, }, }, }), prisma.task.findMany({ orderBy: { created_at: "desc" }, take: 40, select: { id: true, status: true, created_at: true, generated_clips_ids: true, user: { select: { id: true, email: true, }, }, source: { select: { title: true, type: true, }, }, }, }), prisma.task.groupBy({ by: ["user_id"], _count: { _all: true, }, }), selectedUserId ? prisma.user.findUnique({ where: { id: selectedUserId }, select: { id: true, email: true, name: true, is_admin: true, }, }) : Promise.resolve(null), selectedUserId ? prisma.task.findMany({ where: { user_id: selectedUserId }, orderBy: { created_at: "desc" }, take: 40, select: { id: true, status: true, created_at: true, generated_clips_ids: true, source: { select: { title: true, type: true, }, }, }, }) : Promise.resolve([]), prisma.affiliate.findMany({ where: { status: { in: ["pending", "approved"] } }, orderBy: { created_at: "desc" }, take: 100, select: { id: true, slug: true, status: true, platform: true, profile_url: true, audience_size: true, video_url: true, promotion_plan: true, app_store_code_added_at: true, created_at: true, user: { select: { email: true, name: true } }, }, }), prisma.featureFlag.findMany({ orderBy: { key: "asc" }, select: { key: true, description: true, web_enabled: true, ios_enabled: true, admins_bypass: true, updated_at: true, updated_by_user: { select: { email: true } }, }, }), ]); // Pending applications first; each group newest first. const sortedAffiliates = [...affiliates].sort( (a, b) => Number(b.status === "pending") - Number(a.status === "pending"), ); const pendingAffiliates = affiliates.filter((affiliate) => affiliate.status === "pending").length; const generationCountByUser = new Map(tasksByUser.map((item) => [item.user_id, item._count._all])); const stats = [ { label: t("stats.users"), value: totalUsers }, { label: t("stats.admins"), value: adminUsers }, { label: t("stats.tasks"), value: totalTasks }, { label: t("stats.completed"), value: completedTasks }, { label: t("stats.processing"), value: activeTasks, live: activeTasks > 0 }, ]; return (

{t("title")}

{t("subtitle")}

{t("manageAnnouncements")}
{stats.map((stat) => (

{stat.live && }{stat.label}

{stat.value}

))}
{featureFlags.length === 0 ? ( ) : featureFlags.map((flag) => ( ))}
{t("flags.flag")}{t("flags.web")}{t("flags.ios")}{t("flags.adminsBypass")}{t("flags.updated")}
{t("flags.empty")}

{flag.key}

{flag.description &&

{flag.description}

}
{flag.updated_by_user ? t("flags.updatedBy", { date: flag.updated_at.toLocaleString(dateLocale), email: flag.updated_by_user.email }) : flag.updated_at.toLocaleString(dateLocale)}
{t("creators.offerCodes")}} >
{sortedAffiliates.length === 0 ? ( ) : sortedAffiliates.map((affiliate) => ( ))}
{t("columns.creator")}{t("columns.code")}{t("columns.channel")}{t("columns.pitch")}{t("columns.action")}
{t("creators.empty")}

{affiliate.user.name || t("unnamedUser")} {t(affiliate.status === "pending" ? "creators.statusPending" : "creators.statusApproved")}

{t("creators.applied", { email: affiliate.user.email, date: affiliate.created_at.toLocaleDateString(dateLocale) })}

{affiliate.slug?.toUpperCase()} {affiliate.platform}

{t("creators.followers", { count: affiliate.audience_size })}

{affiliate.video_url && ( {t("creators.video")} )}
{affiliate.promotion_plan || "—"}
{processingNow.length === 0 ? ( ) : processingNow.map((task) => ( ))}
{t("columns.task")}{t("columns.user")}{t("columns.status")}{t("columns.updated")}
{t("processing.empty")}
{task.user.email} {task.updated_at.toLocaleString(dateLocale)}
{userQuery && {t("users.clearSearch")}} } >
{recentUsers.map((user) => ( ))}
{t("columns.user")}{t("columns.plan")}{t("columns.tasks")}{t("columns.action")}

{user.name || t("unnamedUser")} {user.is_admin && {t("users.adminBadge")}}

{t("users.joined", { email: user.email, date: user.createdAt.toLocaleDateString(dateLocale) })}

{formatBillingPlanName(user.plan)} {user.legacy_hd && {t("users.legacyBadge")}}
{user.plan !== "free" && (

{user.subscription_status}{user.subscription_provider ? ` · ${user.subscription_provider}` : ""}

)}
{generationCountByUser.get(user.id) || 0}
{/* 1080p is only grandfathered on Pro; still allow removing a stale flag. */} {(user.plan === "pro" || user.legacy_hd) && }
{t("explorer.clear")} : undefined} > {!selectedUser ? (

{t("explorer.selectUser")}

) : (
{selectedUserTasks.length === 0 ? ( ) : selectedUserTasks.map((task) => ( ))}
{t("columns.task")}{t("columns.status")}{t("columns.clips")}{t("columns.created")}
{t("explorer.empty")}
{task.generated_clips_ids.length} {task.created_at.toLocaleString(dateLocale)}
)}
{recentGenerations.map((task) => ( ))}
{t("columns.task")}{t("columns.user")}{t("columns.status")}{t("columns.clips")}{t("columns.created")}
{task.user.email} {task.generated_clips_ids.length} {task.created_at.toLocaleString(dateLocale)}
{runtimeSettings.error ? (
{runtimeSettings.error}
) : ( )}
); }