Archived tickets disappear from every front-end surface for all users (staff included): helpdesk list, detail page 404s, dashboard widget, and project board/sprints/releases/search views. They remain fully visible in the Payload admin panel, where un-archiving restores them. The collection hook stamps archivedAt and appends an activity entry on each toggle; the archiveTicket server action is tickets:staff gated and emits a ticket:archive event. Edits and votes on archived tickets are rejected.
408 lines
13 KiB
TypeScript
408 lines
13 KiB
TypeScript
import config from "@payload-config";
|
|
import type { ReactNode } from "react";
|
|
import { getPayload } from "payload";
|
|
import { headers as nextHeaders } from "next/headers";
|
|
import type { Assignment, Campaign, GameStructure, Map, Media, Rank, User } from "@/payload-types";
|
|
import { resolveLevel } from "@/utils/xp/resolveLevel";
|
|
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|
import { canViewIntelligence } from "@/utils/access-control/canViewIntelligence";
|
|
import { getCurrencyConfig } from "@/lib/banking";
|
|
import { CLOSING_STATUSES, NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
|
import { ProfileSummary } from "@/components/frontend/dashboard/ProfileSummary";
|
|
import { MissionBriefing } from "@/components/frontend/dashboard/MissionBriefing";
|
|
import { RecentEvents } from "@/components/frontend/dashboard/RecentEvents";
|
|
import { QuickStats } from "@/components/frontend/dashboard/QuickStats";
|
|
import { UpcomingMissions } from "@/components/frontend/dashboard/UpcomingMissions";
|
|
import { ActiveCampaigns } from "@/components/frontend/dashboard/ActiveCampaigns";
|
|
import { WalletWidget } from "@/components/frontend/dashboard/WalletWidget";
|
|
import { OpenNegotiations } from "@/components/frontend/dashboard/OpenNegotiations";
|
|
import { MyTickets } from "@/components/frontend/dashboard/MyTickets";
|
|
import { RecentNotifications } from "@/components/frontend/dashboard/RecentNotifications";
|
|
import {
|
|
DashboardGrid,
|
|
type DashboardGridWidget,
|
|
} from "@/components/frontend/dashboard/DashboardGrid";
|
|
import {
|
|
normalizeDashboardLayout,
|
|
widgetSpan,
|
|
type DashboardLayout,
|
|
type DashboardWidgetId,
|
|
} from "@/lib/dashboard/layout";
|
|
|
|
export default async function HomePage() {
|
|
const payload = await getPayload({ config });
|
|
const headers = await nextHeaders();
|
|
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
|
|
|
if (!user || !isPayloadUser(user)) return null;
|
|
|
|
const userId = user.id;
|
|
|
|
const hasIntelligence = await canViewIntelligence(payload, user).catch(() => false);
|
|
|
|
const [profileRes, experienceRes, assignmentRes] = await Promise.all([
|
|
payload.find({
|
|
collection: "profiles",
|
|
where: { user: { equals: userId } },
|
|
depth: 2,
|
|
select: {
|
|
user: true,
|
|
rank: true,
|
|
progression: { xp: true, awards: true, scoreboard: true, minigames: true },
|
|
createdAt: true,
|
|
},
|
|
}),
|
|
payload.find({
|
|
collection: "experience",
|
|
sort: "requiredPoints",
|
|
limit: 100,
|
|
select: { name: true, description: true, requiredPoints: true },
|
|
}),
|
|
payload.find({
|
|
collection: "assignments",
|
|
where: { members: { equals: userId } },
|
|
limit: 10,
|
|
select: { name: true, type: true, callsign: true },
|
|
}),
|
|
]);
|
|
|
|
const profile = profileRes.docs[0];
|
|
const xp = profile?.progression?.xp ?? 0;
|
|
const xpLevel = resolveLevel(xp, experienceRes.docs);
|
|
const profileUser = profile?.user as User | undefined;
|
|
const rank = profile?.rank as Rank | undefined;
|
|
const assignments = assignmentRes.docs as Pick<Assignment, "name" | "type" | "callsign">[];
|
|
|
|
const rankData = rank
|
|
? {
|
|
name: rank.name,
|
|
abbreviation: rank.abbreviation,
|
|
insigniaUrl:
|
|
rank.insignia && typeof rank.insignia === "object" ? (rank.insignia as Media).url : null,
|
|
}
|
|
: { name: "Unknown", abbreviation: "?" };
|
|
|
|
// Fetch upcoming missions (Scheduled or Ready) — up to 5 for the sidebar
|
|
const upcomingRes = await payload
|
|
.find({
|
|
collection: "missions",
|
|
where: {
|
|
"ownershipAndStatus.status": { in: ["Scheduled", "Ready"] },
|
|
},
|
|
sort: "classification.startDateTime",
|
|
limit: 5,
|
|
depth: 2,
|
|
user,
|
|
overrideAccess: false,
|
|
})
|
|
.catch(() => ({ docs: [] }));
|
|
|
|
// If no upcoming, get most recently completed for the briefing card
|
|
let briefingMission = upcomingRes.docs[0] ?? null;
|
|
if (!briefingMission) {
|
|
const completedRes = await payload
|
|
.find({
|
|
collection: "missions",
|
|
where: {
|
|
"ownershipAndStatus.status": { equals: "Completed" },
|
|
},
|
|
sort: "-classification.startDateTime",
|
|
limit: 1,
|
|
depth: 2,
|
|
user,
|
|
overrideAccess: false,
|
|
})
|
|
.catch(() => ({ docs: [] }));
|
|
briefingMission = completedRes.docs[0] ?? null;
|
|
}
|
|
|
|
const mission = briefingMission
|
|
? {
|
|
id: briefingMission.id,
|
|
name: briefingMission.name,
|
|
codeName: briefingMission.codeName,
|
|
summary: briefingMission.summary,
|
|
operationType: briefingMission.operationType,
|
|
classification: {
|
|
missionType: briefingMission.classification.missionType,
|
|
startDateTime: briefingMission.classification.startDateTime,
|
|
estimatedDuration: briefingMission.classification.estimatedDuration,
|
|
map: briefingMission.classification.map as number | Map,
|
|
campaign: briefingMission.classification.campaign as number | Campaign,
|
|
},
|
|
ownershipAndStatus: {
|
|
status: briefingMission.ownershipAndStatus.status,
|
|
},
|
|
missionRoles: briefingMission.missionRoles
|
|
? { maxPlayers: briefingMission.missionRoles.maxPlayers }
|
|
: null,
|
|
coverImage: briefingMission.coverImage,
|
|
}
|
|
: null;
|
|
|
|
const upcomingMissions = upcomingRes.docs.map((m) => ({
|
|
id: m.id,
|
|
name: m.name,
|
|
codeName: m.codeName,
|
|
summary: m.summary,
|
|
operationType: m.operationType,
|
|
classification: {
|
|
missionType: m.classification.missionType,
|
|
startDateTime: m.classification.startDateTime,
|
|
estimatedDuration: m.classification.estimatedDuration,
|
|
map: m.classification.map as number | Map,
|
|
campaign: m.classification.campaign as number | Campaign,
|
|
},
|
|
ownershipAndStatus: {
|
|
status: m.ownershipAndStatus.status,
|
|
},
|
|
missionRoles: m.missionRoles ? { maxPlayers: m.missionRoles.maxPlayers } : null,
|
|
coverImage: m.coverImage,
|
|
}));
|
|
|
|
// Fetch recent events. Runs as the viewer with access control applied so
|
|
// restricted events (dialogue effects, flag changes) stay hidden from
|
|
// members who lack the required permissions.
|
|
const eventsRes = await payload.find({
|
|
collection: "game-event-logs",
|
|
sort: "-timestamp",
|
|
limit: 8,
|
|
depth: 1,
|
|
user,
|
|
overrideAccess: false,
|
|
});
|
|
|
|
const events = eventsRes.docs.map((e) => ({
|
|
id: e.id,
|
|
timestamp: e.timestamp,
|
|
type: e.type,
|
|
message: e.message,
|
|
system: e.system ?? true,
|
|
actor: e.actor as number | User | null | undefined,
|
|
structure: e.structure as number | GameStructure | null | undefined,
|
|
}));
|
|
|
|
// Fetch active campaigns for the sidebar
|
|
const activeCampaignsRes = await payload
|
|
.find({
|
|
collection: "campaigns",
|
|
where: { status: { equals: "inProgress" } },
|
|
limit: 5,
|
|
sort: "-createdAt",
|
|
})
|
|
.catch(() => ({ docs: [] }));
|
|
|
|
const activeCampaigns = activeCampaignsRes.docs.map((c) => ({
|
|
id: c.id,
|
|
name: c.name,
|
|
summary: c.summary,
|
|
status: c.status,
|
|
}));
|
|
|
|
// Fetch counts
|
|
const [campaignsRes, missionsCountRes, structuresRes, factionsRes, profilesRes] =
|
|
await Promise.all([
|
|
payload.find({
|
|
collection: "campaigns",
|
|
where: { status: { equals: "inProgress" } },
|
|
limit: 0,
|
|
}),
|
|
payload
|
|
.find({
|
|
collection: "missions",
|
|
limit: 0,
|
|
user,
|
|
overrideAccess: false,
|
|
})
|
|
.catch(() => ({ totalDocs: 0 })),
|
|
payload.find({
|
|
collection: "game-structures",
|
|
limit: 0,
|
|
}),
|
|
payload.find({
|
|
collection: "factions",
|
|
limit: 0,
|
|
}),
|
|
payload.find({
|
|
collection: "profiles",
|
|
limit: 0,
|
|
}),
|
|
]);
|
|
|
|
// Personal widgets: wallet, open negotiations, tickets, notifications.
|
|
// Negotiations are fetched in a second step so seller-side threads can be
|
|
// matched against the user's own active listing ids (same filter approach as
|
|
// the market page, which avoids deep `listing.seller` relationship queries).
|
|
const [walletRes, activeListingsRes, ticketsRes, notificationsRes, currencyConfig] =
|
|
await Promise.all([
|
|
payload
|
|
.find({
|
|
collection: "bank-accounts",
|
|
where: {
|
|
and: [{ accountType: { equals: "personal" } }, { ownerUser: { equals: userId } }],
|
|
},
|
|
limit: 1,
|
|
depth: 0,
|
|
})
|
|
.catch(() => null),
|
|
payload
|
|
.find({
|
|
collection: "market-listings",
|
|
where: {
|
|
and: [{ status: { equals: "active" } }, { seller: { equals: userId } }],
|
|
},
|
|
limit: 100,
|
|
depth: 0,
|
|
})
|
|
.catch(() => null),
|
|
payload
|
|
.find({
|
|
collection: "tickets",
|
|
where: { and: [{ reporter: { equals: userId } }, NON_ARCHIVED_WHERE] },
|
|
sort: "-updatedAt",
|
|
limit: 10,
|
|
depth: 0,
|
|
})
|
|
.catch(() => ({ docs: [] })),
|
|
payload
|
|
.find({
|
|
collection: "user-notifications",
|
|
where: { user: { equals: userId } },
|
|
sort: "-createdAt",
|
|
limit: 8,
|
|
depth: 0,
|
|
})
|
|
.catch(() => ({ docs: [] })),
|
|
getCurrencyConfig(payload),
|
|
]);
|
|
|
|
const walletAccount = walletRes?.docs[0] ?? null;
|
|
const myActiveListingIds = (activeListingsRes?.docs ?? []).map((listing) => listing.id);
|
|
|
|
const negotiationsRes = await payload
|
|
.find({
|
|
collection: "market-negotiations",
|
|
where: {
|
|
and: [
|
|
{ status: { equals: "open" } },
|
|
{
|
|
or: [{ buyer: { equals: userId } }, { listing: { in: myActiveListingIds } }],
|
|
},
|
|
],
|
|
},
|
|
sort: "-updatedAt",
|
|
limit: 6,
|
|
depth: 2,
|
|
})
|
|
.catch(() => ({ docs: [] }));
|
|
const negotiations = negotiationsRes.docs.slice(0, 5);
|
|
|
|
const openTickets = ticketsRes.docs.filter((t) => !CLOSING_STATUSES.includes(t.status));
|
|
const recentTickets = [
|
|
...openTickets,
|
|
...ticketsRes.docs.filter((t) => CLOSING_STATUSES.includes(t.status)),
|
|
].slice(0, 5);
|
|
|
|
const unreadNotifications = notificationsRes.docs.filter((n) => !n.read);
|
|
const recentNotifications = [
|
|
...unreadNotifications,
|
|
...notificationsRes.docs.filter((n) => n.read),
|
|
].slice(0, 5);
|
|
|
|
// Build the dashboard widgets for the customizable grid. Widgets whose data
|
|
// is empty (negotiations, notifications) or that the viewer cannot see
|
|
// (intel-gated) are omitted so they never render as empty drag targets.
|
|
const widgetNodes = new Map<DashboardWidgetId, ReactNode>();
|
|
if (profile && profileUser) {
|
|
widgetNodes.set(
|
|
"profile-summary",
|
|
<ProfileSummary
|
|
displayName={profileUser.displayName}
|
|
username={profileUser.username}
|
|
rank={rankData}
|
|
xpLevel={xpLevel}
|
|
assignments={assignments}
|
|
/>,
|
|
);
|
|
}
|
|
widgetNodes.set(
|
|
"mission-briefing",
|
|
<MissionBriefing
|
|
mission={mission}
|
|
heading={upcomingRes.docs[0] ? "Next Mission" : "Last Mission"}
|
|
/>,
|
|
);
|
|
widgetNodes.set("recent-events", <RecentEvents events={events} currentUserId={userId} />);
|
|
widgetNodes.set(
|
|
"quick-stats",
|
|
<div data-tour="dashboard-quick-stats">
|
|
<QuickStats
|
|
activeCampaigns={campaignsRes.totalDocs}
|
|
totalMissions={missionsCountRes.totalDocs}
|
|
totalStructures={structuresRes.totalDocs}
|
|
totalFactions={factionsRes.totalDocs}
|
|
totalMembers={profilesRes.totalDocs}
|
|
/>
|
|
</div>,
|
|
);
|
|
widgetNodes.set(
|
|
"wallet",
|
|
<div data-tour="dashboard-wallet">
|
|
<WalletWidget account={walletAccount} currencyConfig={currencyConfig} />
|
|
</div>,
|
|
);
|
|
if (negotiations.length > 0) {
|
|
widgetNodes.set(
|
|
"negotiations",
|
|
<OpenNegotiations
|
|
negotiations={negotiations}
|
|
currentUserId={userId}
|
|
currencyConfig={currencyConfig}
|
|
/>,
|
|
);
|
|
}
|
|
widgetNodes.set(
|
|
"my-tickets",
|
|
<MyTickets tickets={recentTickets} openCount={openTickets.length} />,
|
|
);
|
|
if (recentNotifications.length > 0) {
|
|
widgetNodes.set(
|
|
"notifications",
|
|
<RecentNotifications
|
|
notifications={recentNotifications}
|
|
unreadCount={unreadNotifications.length}
|
|
/>,
|
|
);
|
|
}
|
|
if (hasIntelligence) {
|
|
widgetNodes.set("upcoming-missions", <UpcomingMissions missions={upcomingMissions} />);
|
|
widgetNodes.set("active-campaigns", <ActiveCampaigns campaigns={activeCampaigns} />);
|
|
}
|
|
|
|
const savedLayout = normalizeDashboardLayout(user.preferences?.dashboard?.layout);
|
|
const availableIds = new Set(widgetNodes.keys());
|
|
const dashboardLayout: DashboardLayout = {
|
|
main: savedLayout.main.filter((id) => availableIds.has(id)),
|
|
sidebar: savedLayout.sidebar.filter((id) => availableIds.has(id)),
|
|
spans: savedLayout.spans,
|
|
};
|
|
const widgets = dashboardLayout.main
|
|
.concat(dashboardLayout.sidebar)
|
|
.flatMap<DashboardGridWidget>((id) => {
|
|
const node = widgetNodes.get(id);
|
|
return node ? [{ id, span: widgetSpan(id), node }] : [];
|
|
});
|
|
|
|
return (
|
|
<div className="p-5 flex flex-col gap-6">
|
|
<div className="flex flex-col gap-1" data-tour="page-header">
|
|
<h1 className="text-lg font-semibold">
|
|
Welcome back, {rankData.name}. {/*{profileUser?.displayName ?? user.username}*/}
|
|
</h1>
|
|
<p className="text-sm text-muted-foreground">Here's your operations dashboard.</p>
|
|
</div>
|
|
|
|
<DashboardGrid layout={dashboardLayout} widgets={widgets} />
|
|
</div>
|
|
);
|
|
}
|