Files
boutmoun123 1b753a419a
API Gateway CI / Build, lint, and test (push) Successful in 13m33s
API Gateway CI / Build API Gateway image (push) Successful in 5m43s
feat: sync marketplace dashboard and staging CI
2026-11-02 17:28:58 +03:00

586 lines
22 KiB
TypeScript

"use client";
import {
Activity,
Ban,
BellRing,
Bot,
Bookmark,
Cable,
EyeOff,
Heart,
MessageCircleMore,
RefreshCcw,
Search,
Smartphone,
Sparkles,
UsersRound,
Workflow,
type LucideIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { NoPermissionState } from "@/components/auth/no-permission-state";
import { useSuperAdminSession } from "@/components/auth/session-context";
import { PageHeader } from "@/components/dashboard/page-header";
import { PaginationControls } from "@/components/dashboard/pagination-controls";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Drawer } from "@/components/ui/drawer";
import { EmptyState } from "@/components/ui/empty-state";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useToast } from "@/components/ui/toast";
import { getItems, getPagination } from "@/lib/api/core";
import {
getSuperAdminRelationships,
getSuperAdminRelationshipsSummary,
} from "@/lib/api/superadmin";
import { formatDateTime } from "@/lib/format";
import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions";
import { cn } from "@/lib/utils";
import type {
SuperAdminRelationshipRecord,
SuperAdminRelationshipsResponse,
SuperAdminRelationshipsSummary,
SuperAdminRelationshipType,
} from "@/types/api";
type RelationshipConfig = {
label: string;
description: string;
icon: LucideIcon;
accent: string;
fields: Array<{ key: string; label: string }>;
statuses?: string[];
};
const relationshipConfig: Record<SuperAdminRelationshipType, RelationshipConfig> = {
follows: {
label: "Follows",
description: "Audience graph and user-to-user following links.",
icon: UsersRound,
accent: "from-sky-500/20 to-cyan-400/5",
fields: [],
},
blocks: {
label: "Blocks",
description: "Safety boundaries created between platform accounts.",
icon: Ban,
accent: "from-rose-500/20 to-red-400/5",
fields: [],
},
reactions: {
label: "Reactions",
description: "Post and comment reactions across every reaction type.",
icon: Heart,
accent: "from-pink-500/20 to-rose-400/5",
fields: [
{ key: "reactionType", label: "Reaction" },
{ key: "targetType", label: "Target" },
],
statuses: ["like", "love", "haha", "wow", "sad", "angry", "post", "comment"],
},
saves: {
label: "Saves",
description: "Saved-post links and their related owners.",
icon: Bookmark,
accent: "from-amber-500/20 to-yellow-400/5",
fields: [],
},
conversations: {
label: "Conversations",
description: "Conversation topology, participants, and recent activity.",
icon: MessageCircleMore,
accent: "from-violet-500/20 to-purple-400/5",
fields: [
{ key: "title", label: "Title" },
{ key: "lastMessageText", label: "Latest message" },
{ key: "isGroup", label: "Group" },
],
},
messages: {
label: "Messages",
description: "Message flow for moderation and operational investigation.",
icon: BellRing,
accent: "from-indigo-500/20 to-blue-400/5",
fields: [
{ key: "content", label: "Content" },
{ key: "messageType", label: "Type" },
{ key: "isUnsent", label: "Unsent" },
],
statuses: ["text", "image", "video", "audio"],
},
collaborations: {
label: "Collaborations",
description: "Creative requests between artists, posts, and outcomes.",
icon: Workflow,
accent: "from-emerald-500/20 to-teal-400/5",
fields: [
{ key: "collaborationType", label: "Type" },
{ key: "status", label: "Status" },
{ key: "message", label: "Message" },
],
statuses: ["pending", "approved", "rejected", "cancelled", "duet", "arrangement", "composition"],
},
devices: {
label: "Devices",
description: "Registered devices without exposing push notification tokens.",
icon: Smartphone,
accent: "from-cyan-500/20 to-sky-400/5",
fields: [
{ key: "platform", label: "Platform" },
{ key: "appVersion", label: "App version" },
{ key: "locale", label: "Locale" },
{ key: "isActive", label: "Active" },
],
statuses: ["android", "ios", "web"],
},
engagement: {
label: "Engagement",
description: "Watch behavior, sessions, progress, and ranking signals.",
icon: Activity,
accent: "from-orange-500/20 to-amber-400/5",
fields: [
{ key: "type", label: "Event" },
{ key: "progressPercent", label: "Progress" },
{ key: "watchTimeMs", label: "Watch time" },
],
},
preferences: {
label: "Preferences",
description: "Not-interested signals shaping personalized feeds.",
icon: EyeOff,
accent: "from-slate-500/20 to-zinc-400/5",
fields: [{ key: "notInterested", label: "Not interested" }],
},
outbox: {
label: "Outbox",
description: "Reliable asynchronous events, retries, and failures.",
icon: Cable,
accent: "from-red-500/20 to-orange-400/5",
fields: [
{ key: "eventType", label: "Event" },
{ key: "status", label: "Status" },
{ key: "attempts", label: "Attempts" },
{ key: "lastError", label: "Last error" },
],
statuses: ["pending", "processed", "failed"],
},
ai_music: {
label: "AI music",
description: "Generated audio archive, owners, prompts, and media state.",
icon: Bot,
accent: "from-fuchsia-500/20 to-violet-400/5",
fields: [
{ key: "title", label: "Title" },
{ key: "type", label: "Type" },
{ key: "tag", label: "Tag" },
{ key: "durationSeconds", label: "Duration" },
],
statuses: ["text_to_music", "audio_to_music", "other"],
},
};
const relationshipTypes = Object.keys(relationshipConfig) as SuperAdminRelationshipType[];
function formatValue(value: unknown) {
if (value === null || typeof value === "undefined" || value === "") return "—";
if (typeof value === "boolean") return value ? "Yes" : "No";
if (typeof value === "number") return new Intl.NumberFormat("en-US").format(value);
if (Array.isArray(value)) return value.length ? `${value.length} items` : "—";
if (typeof value === "object") return "Structured data";
return String(value);
}
function getUserLabel(record: SuperAdminRelationshipRecord, field: string) {
const related = record.relatedUsers?.find((item) => item.field === field)?.user;
if (!related) return null;
return related.stageName || related.name || related.username || related.email || related._id;
}
function getRecordTitle(record: SuperAdminRelationshipRecord, type: SuperAdminRelationshipType) {
const userFields = record.relatedUsers ?? [];
if (userFields.length >= 2) {
const first = getUserLabel(record, userFields[0].field);
const second = getUserLabel(record, userFields[1].field);
if (first && second) return `${first} → ${second}`;
}
if (userFields.length === 1) {
return getUserLabel(record, userFields[0].field) ?? relationshipConfig[type].label;
}
return (
formatValue(record.title) !== "—"
? formatValue(record.title)
: formatValue(record.eventType) !== "—"
? formatValue(record.eventType)
: `${relationshipConfig[type].label} record`
);
}
function RecordSkeleton() {
return (
<div className="relation-card animate-pulse">
<div className="h-4 w-1/3 rounded bg-muted" />
<div className="mt-4 h-3 w-full rounded bg-muted/70" />
<div className="mt-2 h-3 w-2/3 rounded bg-muted/60" />
</div>
);
}
export default function RelationshipsPage() {
const { permissions } = useSuperAdminSession();
const canRead = hasPermission(permissions, SUPERADMIN_PERMISSIONS.RELATIONSHIPS_READ);
const [activeType, setActiveType] = useState<SuperAdminRelationshipType>("follows");
const [summary, setSummary] = useState<SuperAdminRelationshipsSummary | null>(null);
const [response, setResponse] = useState<SuperAdminRelationshipsResponse | null>(null);
const [selectedRecord, setSelectedRecord] = useState<SuperAdminRelationshipRecord | null>(null);
const [query, setQuery] = useState("");
const [status, setStatus] = useState("all");
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const filtersRef = useRef({ query, status });
const { toast } = useToast();
filtersRef.current = { query, status };
const config = relationshipConfig[activeType];
const loadData = useCallback(
async (silent = false) => {
if (!canRead) {
setLoading(false);
return;
}
if (silent) setRefreshing(true);
else setLoading(true);
try {
const current = filtersRef.current;
const [nextSummary, nextResponse] = await Promise.all([
getSuperAdminRelationshipsSummary(),
getSuperAdminRelationships({
type: activeType,
page,
limit: 18,
q: current.query || undefined,
status: current.status === "all" ? undefined : current.status,
sortOrder: "desc",
}),
]);
setSummary(nextSummary);
setResponse(nextResponse);
} catch (error) {
toast({
title: "Relationship data could not be loaded",
description: String(error),
variant: "danger",
});
} finally {
setLoading(false);
setRefreshing(false);
}
},
[activeType, canRead, page, toast],
);
useEffect(() => {
void loadData();
}, [loadData]);
const records = getItems(response) as SuperAdminRelationshipRecord[];
const pagination = getPagination(response);
const activeTotal = summary?.totals[activeType] ?? 0;
const connectedDomains = useMemo(
() => relationshipTypes.filter((type) => (summary?.totals[type] ?? 0) > 0).length,
[summary],
);
const selectType = (type: SuperAdminRelationshipType) => {
setActiveType(type);
setPage(1);
setStatus("all");
setSelectedRecord(null);
};
const applyFilters = () => {
if (page === 1) void loadData();
else setPage(1);
};
if (!canRead) {
return (
<div className="space-y-5 pb-10">
<PageHeader
eyebrow="Platform graph"
title="Relationships center"
subtitle="Explore social, operational, media, and behavioral links across the platform."
/>
<NoPermissionState description="This page needs the relationships.read permission." />
</div>
);
}
return (
<div className="space-y-6 pb-10">
<PageHeader
eyebrow="Platform graph"
title="Relationships center"
subtitle="One operational view for social links, conversations, devices, signals, and reliable events."
actions={
<Button variant="outline" onClick={() => void loadData(true)} disabled={refreshing}>
<RefreshCcw className={cn("h-4 w-4", refreshing && "animate-spin")} />
Refresh
</Button>
}
/>
<section className="hero-surface page-enter grid gap-5 p-5 md:grid-cols-[1.4fr_1fr] md:p-7">
<div className="relative z-10">
<Badge variant="warning">Live relationship intelligence</Badge>
<h2 className="mt-4 max-w-2xl font-heading text-2xl font-bold leading-tight md:text-3xl">
Understand how every account, post, device, and event connects.
</h2>
<p className="mt-3 max-w-2xl text-sm leading-7 text-muted-foreground">
Search by identity or database ID, investigate platform signals, and move from aggregate
health to individual records without exposing push tokens or oversized event payloads.
</p>
</div>
<div className="relative z-10 grid grid-cols-3 gap-3">
<div className="metric-glass">
<span>Records</span>
<strong>{summary?.total?.toLocaleString() ?? "—"}</strong>
</div>
<div className="metric-glass">
<span>Domains</span>
<strong>{connectedDomains}</strong>
</div>
<div className="metric-glass">
<span>Active view</span>
<strong>{activeTotal.toLocaleString()}</strong>
</div>
</div>
</section>
<section className="scrollbar-thin flex gap-3 overflow-x-auto pb-2">
{relationshipTypes.map((type) => {
const item = relationshipConfig[type];
const Icon = item.icon;
const active = type === activeType;
return (
<button
key={type}
type="button"
aria-pressed={active}
aria-label={`Show ${item.label} relationships`}
onClick={() => selectType(type)}
className={cn("domain-tab group", active && "domain-tab-active")}
>
<span className={cn("domain-icon bg-gradient-to-br", item.accent)}>
<Icon className="h-4 w-4" />
</span>
<span className="text-start">
<span className="block whitespace-nowrap text-sm font-semibold">{item.label}</span>
<span className="block text-xs text-muted-foreground">
{(summary?.totals[type] ?? 0).toLocaleString()}
</span>
</span>
</button>
);
})}
</section>
<Card className="overflow-visible">
<CardContent className="grid gap-3 p-4 md:grid-cols-[1fr_220px_auto]">
<div className="relative">
<Search className="pointer-events-none absolute start-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") applyFilters();
}}
placeholder="Search user, email, status, type, or database ID"
className="ps-10"
/>
</div>
<Select value={status} onValueChange={setStatus}>
<SelectTrigger>
<SelectValue placeholder="All states" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All states</SelectItem>
{(config.statuses ?? []).map((item) => (
<SelectItem key={item} value={item}>
{item.replaceAll("_", " ")}
</SelectItem>
))}
</SelectContent>
</Select>
<Button onClick={applyFilters}>
<Sparkles className="h-4 w-4" />
Apply
</Button>
</CardContent>
</Card>
<section>
<div className="mb-4 flex flex-wrap items-end justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<config.icon className="h-5 w-5 text-primary" />
<h2 className="font-heading text-xl font-bold">{config.label}</h2>
</div>
<p className="mt-1 text-sm text-muted-foreground">{config.description}</p>
</div>
<Badge variant="muted">{activeTotal.toLocaleString()} total records</Badge>
</div>
{loading ? (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{Array.from({ length: 9 }, (_, index) => (
<RecordSkeleton key={index} />
))}
</div>
) : records.length ? (
<div className="stagger-grid grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{records.map((record) => (
<button
type="button"
key={record._id}
aria-label={`Open relationship record ${record._id}`}
onClick={() => setSelectedRecord(record)}
className="relation-card group text-start"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="truncate font-heading text-base font-bold text-foreground">
{getRecordTitle(record, activeType)}
</p>
<p className="mt-1 truncate font-mono text-[11px] text-muted-foreground">
{record._id}
</p>
</div>
<span className={cn("domain-icon shrink-0 bg-gradient-to-br", config.accent)}>
<config.icon className="h-4 w-4" />
</span>
</div>
{record.relatedUsers?.length ? (
<div className="mt-4 flex flex-wrap gap-2">
{record.relatedUsers.slice(0, 3).map(({ field, user }) => (
<Badge key={`${field}-${user._id}`} variant="muted">
{field.replace("Id", "")}: {user.stageName || user.name || user.username || user.email}
</Badge>
))}
</div>
) : null}
<dl className="mt-4 grid grid-cols-2 gap-3">
{config.fields.slice(0, 4).map((field) => (
<div key={field.key} className="min-w-0 rounded-lg bg-background/45 p-2.5">
<dt className="text-[10px] uppercase tracking-wider text-muted-foreground">
{field.label}
</dt>
<dd className="mt-1 truncate text-xs font-semibold text-foreground">
{formatValue(record[field.key])}
</dd>
</div>
))}
</dl>
<div className="mt-4 flex items-center justify-between border-t border-border/60 pt-3 text-xs text-muted-foreground">
<span>{formatDateTime(record.createdAt)}</span>
<span className="text-primary transition-transform group-hover:-translate-x-1">Inspect →</span>
</div>
</button>
))}
</div>
) : (
<EmptyState
title={`No ${config.label.toLowerCase()} found`}
description="Try another search or state filter. The live API returned no matching records."
/>
)}
</section>
{pagination ? (
<PaginationControls pagination={pagination} onPageChange={setPage} loading={loading} />
) : null}
<Drawer
open={Boolean(selectedRecord)}
onClose={() => setSelectedRecord(null)}
title={selectedRecord ? String(getRecordTitle(selectedRecord, activeType)) : "Record details"}
description={`${config.label} relationship inspection`}
side="right"
>
{selectedRecord ? (
<div className="space-y-5">
<div className={cn("rounded-2xl bg-gradient-to-br p-5", config.accent)}>
<div className="flex items-center gap-3">
<span className="domain-icon bg-background/60">
<config.icon className="h-5 w-5" />
</span>
<div>
<p className="font-heading font-bold">{config.label}</p>
<p className="font-mono text-[11px] text-muted-foreground">{selectedRecord._id}</p>
</div>
</div>
</div>
{selectedRecord.relatedUsers?.length ? (
<section>
<h3 className="mb-3 text-sm font-bold">Connected identities</h3>
<div className="space-y-2">
{selectedRecord.relatedUsers.map(({ field, user }) => (
<div key={`${field}-${user._id}`} className="detail-row">
<div>
<p className="text-xs text-muted-foreground">{field}</p>
<p className="mt-1 text-sm font-semibold">
{user.stageName || user.name || user.username || user.email}
</p>
</div>
<Badge variant={user.isDisabled ? "danger" : user.isVerified ? "success" : "muted"}>
{user.isDisabled ? "disabled" : user.role ?? "user"}
</Badge>
</div>
))}
</div>
</section>
) : null}
{selectedRecord.relatedPosts?.length ? (
<section>
<h3 className="mb-3 text-sm font-bold">Connected content</h3>
{selectedRecord.relatedPosts.map(({ field, post }) => (
<div key={`${field}-${post._id}`} className="detail-row block">
<p className="text-xs text-muted-foreground">{field} · {post.postType}</p>
<p className="mt-2 line-clamp-3 text-sm">{post.content || "Media-only post"}</p>
</div>
))}
</section>
) : null}
<section>
<h3 className="mb-3 text-sm font-bold">Record fields</h3>
<div className="grid gap-2">
{Object.entries(selectedRecord)
.filter(([key]) => !["_id", "relatedUsers", "relatedPosts", "__v"].includes(key))
.map(([key, value]) => (
<div key={key} className="detail-row">
<span className="text-xs text-muted-foreground">{key}</span>
<span className="max-w-[65%] break-words text-end text-xs font-semibold">
{key.endsWith("At") ? formatDateTime(String(value)) : formatValue(value)}
</span>
</div>
))}
</div>
</section>
</div>
) : null}
</Drawer>
</div>
);
}