1
0
Fork 0

Compare commits

..

No commits in common. "a696a864ca7f176097f33b5ae3cf91ea79a5c71d" and "e57633c57542ad611d4238b75fc8bd131b08841e" have entirely different histories.

27 changed files with 129 additions and 39107 deletions

View file

@ -1,19 +1,5 @@
# Changelog
# v0.7.3
Campaigns learn to pause this time, and the list keeps finished campaigns out of the way by default.
### Features
- **Pause your campaign.** When your campaign is between operations or you simply need a break, set it to On Hold from its own page. It stays exactly where you left it and goes right back to active whenever you are ready to run it again.
### Improvements
- The campaigns list now shows active campaigns by default, so finished ones stay out of the way. Turn on "Show completed" whenever you want to look back at campaigns that have concluded.
---
# v0.7.2
A small but important patch: uploading a mod list with a side op was broken for everyone, and now it works.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.7.3",
"version": "0.7.2",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -17,8 +17,6 @@ import {
import { Item, ItemContent, ItemDescription, ItemHeader, ItemTitle } from "@/components/ui/item";
import { MissionCard } from "@/components/frontend/intelligence/MissionCard";
import { statusColors as missionStatusColors } from "@/lib/intelligence/missionColors";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { CampaignStatusEditor } from "@/components/frontend/intelligence/CampaignStatusEditor";
interface CampaignDetailPageProps {
params: Promise<{ id: string }>;
@ -27,17 +25,9 @@ interface CampaignDetailPageProps {
const statusColors: Record<string, string> = {
concept: "bg-muted text-muted-foreground",
inProgress: "bg-blue-500/20 text-blue-400",
onHold: "bg-amber-500/20 text-amber-400",
completed: "bg-emerald-500/20 text-emerald-400",
};
const statusLabels: Record<string, string> = {
concept: "Concept",
inProgress: "In Progress",
onHold: "On Hold",
completed: "Completed",
};
const factionTypeColors: Record<string, string> = {
majorFaction: "bg-blue-500/20 text-blue-400",
minorFaction: "bg-muted text-muted-foreground",
@ -82,15 +72,6 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
notFound();
}
// Who can change the status: the campaign owner or anyone holding
// campaigns:update (mirrors the collection's requireCampaignOwnership gate).
let canEditCampaign = await hasPermission(payload, user, "campaigns:update");
if (!canEditCampaign && campaign.owner) {
const ownerId =
typeof campaign.owner === "object" ? (campaign.owner as { id: number }).id : campaign.owner;
canEditCampaign = Number(ownerId) === Number(user?.id);
}
const coverImage =
typeof campaign.coverImage === "object" && campaign.coverImage !== null
? (campaign.coverImage as Media)
@ -167,8 +148,9 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${statusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{statusLabels[campaign.status] ??
campaign.status.charAt(0).toUpperCase() + campaign.status.slice(1)}
{campaign.status === "inProgress"
? "In Progress"
: campaign.status.charAt(0).toUpperCase() + campaign.status.slice(1)}
</span>
</div>
@ -256,20 +238,6 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
<div className="flex flex-col gap-4">
{canEditCampaign && (
<Item variant="outline">
<ItemHeader>
<ItemTitle>Campaign Status</ItemTitle>
</ItemHeader>
<ItemContent>
<CampaignStatusEditor
campaignId={campaign.id}
initialStatus={campaign.status}
/>
</ItemContent>
</Item>
)}
{/* Campaign Stats */}
<Item variant="outline">
<ItemHeader>

View file

@ -418,10 +418,8 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status.charAt(0).toUpperCase() +
campaign.status.slice(1)}
: campaign.status.charAt(0).toUpperCase() +
campaign.status.slice(1)}
</span>
)}
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />

View file

@ -577,13 +577,9 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
<div>
<h3 className="text-sm font-semibold">{campaign.name}</h3>
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded mt-1 inline-block ${campaign.status === "inProgress" ? "bg-blue-500/20 text-blue-400" : campaign.status === "onHold" ? "bg-amber-500/20 text-amber-400" : "bg-muted text-muted-foreground"}`}
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded mt-1 inline-block ${campaign.status === "inProgress" ? "bg-blue-500/20 text-blue-400" : "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status}
{campaign.status === "inProgress" ? "In Progress" : campaign.status}
</span>
</div>
<p className="text-xs text-muted-foreground line-clamp-3">{campaign.summary}</p>

View file

@ -3,11 +3,6 @@
import config from "@payload-config";
import { getPayload } from "payload";
import {
markAllNotificationsReadForUser,
markNotificationsReadForUser,
} from "@/lib/notifications";
export interface NotificationActionResult {
success: boolean;
error?: string;
@ -23,9 +18,29 @@ export async function markNotificationsRead(ids: number[]): Promise<Notification
if (!user) return { success: false, error: "You must be logged in." };
// Read-state is personal to the recipient: this only ever flips the acting
// user's own notifications, never another user's (staff oversight included).
await markNotificationsReadForUser(payload, Number(user.id), ids);
const cleanIds = [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))];
if (cleanIds.length === 0) return { success: true };
// Query with access control so users can only touch their own notifications.
const found = await payload.find({
collection: "user-notifications",
where: { id: { in: cleanIds } },
limit: Math.min(cleanIds.length, 100),
depth: 0,
});
for (const doc of found.docs) {
if (!doc.read) {
await payload.update({
collection: "user-notifications",
id: doc.id,
data: { read: true },
overrideAccess: true,
depth: 0,
});
}
}
return { success: true };
} catch {
return { success: false, error: "Failed to update notifications." };
@ -42,8 +57,23 @@ export async function markAllNotificationsRead(): Promise<NotificationActionResu
if (!user) return { success: false, error: "You must be logged in." };
// Only the acting user's own unread notifications are marked read.
await markAllNotificationsReadForUser(payload, Number(user.id));
const unread = await payload.find({
collection: "user-notifications",
where: { read: { equals: false } },
limit: 100,
depth: 0,
});
for (const doc of unread.docs) {
await payload.update({
collection: "user-notifications",
id: doc.id,
data: { read: true },
overrideAccess: true,
depth: 0,
});
}
return { success: true };
} catch {
return { success: false, error: "Failed to update notifications." };

View file

@ -24,7 +24,6 @@ import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997e
import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { ComposeField as ComposeField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_5b78ffdfa54ff25f104b8b2d7d755857 } from '@/components/admin/game/LaborCrewField'
import { default as default_163cd5fa19b83af73532cccaf34704fb } from '@/components/admin/npc-dialogue/NpcDialogueEditor'
import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/components/admin/groups/CollapsibleGroupField'
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
@ -76,7 +75,6 @@ export const importMap = {
"@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@ai-stack/payloadcms/client#ComposeField": ComposeField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/game/LaborCrewField#default": default_5b78ffdfa54ff25f104b8b2d7d755857,
"@/components/admin/npc-dialogue/NpcDialogueEditor#default": default_163cd5fa19b83af73532cccaf34704fb,
"@/components/admin/groups/CollapsibleGroupField#default": default_513af5ed43d616d133e530d8c94232f8,
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,

View file

@ -1,72 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* GET /api/notifications/inbox
*
* Bell inbox for the current user. Mirrors the shape the REST endpoint
* (/api/user-notifications) returns, but enriches every row with WHO it is
* meant for (`ownerId` + `ownerName`) and whether it belongs to the caller
* (`isMine`). Staff with read-all oversight see everyone's notifications, so
* this is what lets the bell label "meant for someone else" rows. Read access
* is still scoped by the collection's own access control (own notifications for
* regular users, all for staff).
*/
interface NotificationRow {
id: number;
title: string;
message: string | null;
link: string | null;
type: string | null;
read: boolean;
createdAt: string;
ownerId: number;
ownerName: string;
isMine: boolean;
}
export async function GET(req: NextRequest) {
const payload = await getPayload({ config: await config });
const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false });
if (!isPayloadUser(user)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
try {
const userId = Number(user.id);
const res = await payload.find({
collection: "user-notifications",
sort: "-createdAt",
limit: 12,
depth: 1,
overrideAccess: false,
user,
});
const notifications = res.docs.map((doc) => {
const owner = doc.user;
const ownerId = typeof owner === "object" && owner !== null ? owner.id : (owner as number);
const isMine = Number(ownerId) === userId;
return {
id: doc.id,
title: doc.title,
message: doc.message ?? null,
link: doc.link ?? null,
type: doc.type ?? null,
read: Boolean(doc.read),
createdAt: doc.createdAt,
ownerId: Number(ownerId),
ownerName: typeof owner === "object" && owner !== null ? (owner.username ?? "") : "",
isMine,
};
});
return NextResponse.json({ notifications });
} catch (error) {
console.error("notifications/inbox: failed to load", error);
return NextResponse.json({ error: "Failed to load notifications." }, { status: 500 });
}
}

View file

@ -69,7 +69,7 @@ Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start
## Feature flow: Friday open-slot notice
At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. The slot window is Friday 00:00–23:59:59.999 **America/New_York** computed from the Eastern calendar date, never the server clock (the UTC deploy container once treated Wed 8 PM ET as Thursday and missed Friday-evening ops entirely); when it is already Friday Eastern, that day itself is the slot, so the dedup token stays stable from Wednesday through the op day and late claims still credit. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by \<user\>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday `<t:epoch:D>` token and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Drafts (Concept) count as the slot being taken.
At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in `src/lib/intelligence/fridayOpsNotice.ts`; catch-up until ET midnight, a fully missed Wednesday skips to next week), if no non-cancelled mission starts on that week's upcoming Friday, `fridayOpsNotice` posts once in #side-ops pinging the Community Zeus role: the slot is open, hosting is welcome, and if nobody picks it up the slot stays empty or Jason hosts it himself. When a non-superuser creator later claims the slot (`getFridayClaimant`, earliest-created mission wins; superuser/staff-created missions never claim), the notice is edited to append "This slot was claimed by \<user\>. Thank you for hosting for our community!"; if that op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a between-polls claim swap re-credits the new claimant). Role: `DISCORD_COMMUNITY_ZEUS_ROLE_ID` or resolved by name in the guild; channel: `DISCORD_SIDE_OPS_CHANNEL_ID`. Dedup without DB state: the message embeds a stable per-Friday `<t:epoch:D>` token and the service scans recent channel messages for it (claim idempotency via a marker in the message content). Drafts (Concept) count as the slot being taken.
## Feature flow: assignment transfers

View file

@ -40,10 +40,6 @@ export const Campaigns: CollectionConfig = {
label: "In Progress",
value: "inProgress",
},
{
label: "On Hold",
value: "onHold",
},
{
label: "Completed",
value: "completed",

View file

@ -16,7 +16,6 @@ interface ActiveCampaignsProps {
const statusColors: Record<string, string> = {
inProgress: "bg-blue-500/20 text-blue-400",
concept: "bg-muted text-muted-foreground",
onHold: "bg-amber-500/20 text-amber-400",
};
export function ActiveCampaigns({ campaigns }: ActiveCampaignsProps) {
@ -67,11 +66,7 @@ export function ActiveCampaigns({ campaigns }: ActiveCampaignsProps) {
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded shrink-0 ${statusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "Active"
: campaign.status === "onHold"
? "On Hold"
: campaign.status}
{campaign.status === "inProgress" ? "Active" : campaign.status}
</span>
</div>
<span className="text-xs text-muted-foreground truncate">{campaign.summary}</span>

View file

@ -26,28 +26,24 @@ interface CampaignCardProps {
const statusColors: Record<Campaign["status"], string> = {
concept: "bg-muted text-muted-foreground",
inProgress: "bg-blue-500/20 text-blue-400",
onHold: "bg-amber-500/20 text-amber-400",
completed: "bg-emerald-500/20 text-emerald-400",
};
const statusLabels: Record<Campaign["status"], string> = {
concept: "Concept",
inProgress: "In Progress",
onHold: "On Hold",
completed: "Completed",
};
const officialStatusLabels: Record<Campaign["status"], string> = {
concept: "Planning",
inProgress: "Active Deployment",
onHold: "On Hold",
completed: "Concluded",
};
const statusTextColors: Record<Campaign["status"], string> = {
concept: "text-muted-foreground",
inProgress: "text-emerald-400",
onHold: "text-amber-400",
completed: "text-blue-400",
};

View file

@ -1,64 +0,0 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { updateCampaignStatus } from "./create";
const STATUS_OPTIONS: { value: "concept" | "inProgress" | "onHold" | "completed"; label: string }[] = [
{ value: "concept", label: "Concept" },
{ value: "inProgress", label: "In Progress" },
{ value: "onHold", label: "On Hold" },
{ value: "completed", label: "Completed" },
];
export function CampaignStatusEditor({
campaignId,
initialStatus,
}: {
campaignId: number;
initialStatus: string;
}) {
const router = useRouter();
const [status, setStatus] = useState(initialStatus);
const [committedStatus, setCommittedStatus] = useState(initialStatus);
const [saving, setSaving] = useState(false);
const handleChange = async (newValue: string) => {
// Optimistic UI: reflect the pick immediately, then confirm with the server.
setStatus(newValue);
setSaving(true);
const result = await updateCampaignStatus(
campaignId,
newValue as "concept" | "inProgress" | "onHold" | "completed",
);
setSaving(false);
if (result.success) {
setCommittedStatus(newValue);
toast.success("Campaign status updated.");
router.refresh();
return;
}
toast.error(result.error ?? "Failed to update campaign status.");
// Revert to the last known-good status on failure.
setStatus(committedStatus);
};
return (
<select
value={status}
disabled={saving}
onChange={(e) => void handleChange(e.target.value)}
className="w-full rounded-md border border-border/50 bg-background px-2 py-1.5 text-sm font-medium text-primary ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-70"
>
{STATUS_OPTIONS.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
);
}

View file

@ -8,7 +8,7 @@ export interface CampaignListEntry {
readonly id: number;
readonly name: string;
readonly summary: string;
readonly status: "concept" | "inProgress" | "onHold" | "completed";
readonly status: "concept" | "inProgress" | "completed";
readonly campaignMode: "official" | "custom";
readonly startDate?: string | null;
readonly endDate?: string | null;
@ -25,11 +25,11 @@ interface CampaignsListProps {
}
export function CampaignsList({ campaigns }: CampaignsListProps) {
const [showCompleted, setShowCompleted] = useState(false);
const [hideCompleted, setHideCompleted] = useState(false);
const visible = showCompleted
? campaigns
: campaigns.filter((campaign) => campaign.status !== "completed");
const visible = hideCompleted
? campaigns.filter((campaign) => campaign.status !== "completed")
: campaigns;
const officialCampaigns = visible.filter(
(campaign) => campaign.campaignMode === "official",
);
@ -41,16 +41,16 @@ export function CampaignsList({ campaigns }: CampaignsListProps) {
<>
<div className="flex items-center justify-end gap-2">
<Switch
id="show-completed-campaigns"
checked={showCompleted}
onCheckedChange={setShowCompleted}
aria-label="Show completed campaigns"
id="hide-completed-campaigns"
checked={hideCompleted}
onCheckedChange={setHideCompleted}
aria-label="Hide completed campaigns"
/>
<label
htmlFor="show-completed-campaigns"
htmlFor="hide-completed-campaigns"
className="cursor-pointer select-none text-sm text-muted-foreground"
>
Show completed
Hide completed
</label>
</div>
{visible.length > 0 ? (
@ -101,7 +101,7 @@ export function CampaignsList({ campaigns }: CampaignsListProps) {
<div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground">
<p className="text-sm">No campaigns match the current filter.</p>
<button
onClick={() => setShowCompleted(true)}
onClick={() => setHideCompleted(false)}
className="text-sm text-primary hover:underline"
>
Show completed

View file

@ -17,7 +17,7 @@ export function CreateCampaignDialog() {
const [formData, setFormData] = useState({
name: "",
summary: "An Arma 3 campaign.",
status: "concept" as "concept" | "inProgress" | "onHold" | "completed",
status: "concept" as "concept" | "inProgress" | "completed",
description: "",
startDate: "",
endDate: "",
@ -119,7 +119,6 @@ export function CreateCampaignDialog() {
>
<option value="concept">Concept</option>
<option value="inProgress">In Progress</option>
<option value="onHold">On Hold</option>
<option value="completed">Completed</option>
</select>
</div>

View file

@ -3,12 +3,11 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { hasPermission } from "@/utils/access-control/hasPermission";
interface CreateCampaignData {
name: string;
summary: string;
status: "concept" | "inProgress" | "onHold" | "completed";
status: "concept" | "inProgress" | "completed";
startDate?: string;
endDate?: string;
description?: string;
@ -77,55 +76,6 @@ export async function createCampaign(data: CreateCampaignData) {
}
}
export async function updateCampaignStatus(
campaignId: number,
status: "concept" | "inProgress" | "onHold" | "completed",
) {
try {
const { payload, user } = await authenticate();
// Gate: campaign owner OR campaigns:update permission (mirrors the
// requireCampaignOwnership access on the campaigns collection).
const canManage = await hasPermission(payload, user, "campaigns:update");
if (!canManage) {
const campaign = await payload.findByID({
collection: "campaigns",
id: campaignId,
depth: 0,
overrideAccess: true,
select: { owner: true },
});
const ownerId =
campaign && campaign.owner && typeof campaign.owner === "object"
? campaign.owner.id
: campaign?.owner;
if (ownerId == null || Number(ownerId) !== Number(user.id)) {
return {
success: false,
error: "You don't have permission to change this campaign's status.",
};
}
}
const campaign = await payload.update({
collection: "campaigns",
id: campaignId,
data: { status },
depth: 1,
});
return {
success: true,
data: campaign,
};
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Failed to update campaign status",
};
}
}
export async function uploadUgcImage(
formData: FormData,
): Promise<{ success: boolean; error?: string; data?: { id: number; url: string; filename: string } }> {

View file

@ -29,14 +29,6 @@ interface NotificationItem {
link?: string | null;
read: boolean;
createdAt: string;
/**
* Whether this notification belongs to the current user. When false the
* current user (staff with read-all) is viewing someone else's notification;
* it can be shown and opened but its read-state must never be changed.
*/
isMine?: boolean;
/** Display name of the user this notification is actually meant for. Only set when `!isMine`. */
ownerName?: string | null;
}
function timeAgo(iso: string): string {
@ -66,12 +58,12 @@ export function NotificationsBell() {
const fetchNotifications = useCallback(async () => {
try {
const res = await fetch("/api/notifications/inbox?limit=12&sort=-createdAt", {
const res = await fetch("/api/user-notifications?limit=12&sort=-createdAt", {
cache: "no-store",
});
if (!res.ok) throw new Error("Failed to fetch");
const data = (await res.json()) as { notifications?: NotificationItem[] };
setNotifications(data.notifications ?? []);
const data = (await res.json()) as { docs?: NotificationItem[] };
setNotifications(data.docs ?? []);
setError(false);
} catch {
setError(true);
@ -91,11 +83,8 @@ export function NotificationsBell() {
};
}, [fetchNotifications]);
// Read-state is personal to the recipient. Never let marking one change
// another user's read flag — staff are viewing it as an oversight, not as
// that user, so flipping it would hide the notification from them.
async function handleMarkOne(item: NotificationItem) {
if (item.read || marking || item.isMine === false) return;
if (item.read || marking) return;
setMarking(true);
setActionError(null);
try {
@ -115,9 +104,7 @@ export function NotificationsBell() {
}
async function handleItemClick(item: NotificationItem) {
// Own notifications are marked read on open; others' are only opened, never
// marked, so the real owner still sees them as unread.
if (!item.read && item.isMine !== false) await handleMarkOne(item);
if (!item.read) await handleMarkOne(item);
if (item.link) {
router.push(item.link);
setOpen(false);
@ -131,11 +118,7 @@ export function NotificationsBell() {
try {
const result = await markAllNotificationsRead();
if (result.success) {
// Only own rows are guaranteed to have been flipped, so only optimistic-
// update those. Staff viewing others' rows must not see them flip to read.
setNotifications((prev) =>
prev.map((n) => (n.isMine === false ? n : { ...n, read: true })),
);
setNotifications((prev) => prev.map((n) => (n.read ? n : { ...n, read: true })));
} else {
setActionError(result.error ?? "Failed to update notifications.");
}
@ -170,7 +153,7 @@ export function NotificationsBell() {
<button
onClick={() => void handleMarkAll()}
disabled={marking}
aria-label="Mark all of my notifications as read"
aria-label="Mark all notifications as read"
className="text-xs text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
>
{marking ? "Marking..." : "Mark all read"}
@ -196,28 +179,25 @@ export function NotificationsBell() {
{actionError}
</p>
)}
{notifications.map((item) => {
const isUnread = !item.read;
const isForeign = item.isMine === false;
return (
<DropdownMenuItem
key={item.id}
className={cn(
"flex flex-col items-start gap-1 py-2.5",
isUnread && "bg-accent/50",
isForeign && "opacity-80",
)}
disabled={marking}
onClick={() => void handleItemClick(item)}
>
<span className="flex w-full items-center justify-between gap-2">
<span className="min-w-0 truncate text-sm font-medium">
{!isForeign && isUnread && (
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
)}
{item.title}
</span>
{!isForeign && item.read && (
{notifications.map((item) => (
<DropdownMenuItem
key={item.id}
className={cn(
"flex flex-col items-start gap-1 py-2.5",
!item.read && "bg-accent/50",
)}
disabled={marking}
onClick={() => void handleItemClick(item)}
>
<span className="flex w-full items-center justify-between gap-2">
<span className="min-w-0 truncate text-sm font-medium">
{!item.read && (
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
)}
{item.title}
</span>
<span className="flex shrink-0 items-center gap-1.5">
{!item.read && (
<button
type="button"
title="Mark as read"
@ -231,28 +211,21 @@ export function NotificationsBell() {
<CheckIcon className="size-3.5" />
</button>
)}
<span className="flex shrink-0 items-center gap-1.5">
<span className="text-[10px] text-muted-foreground">
{timeAgo(item.createdAt)}
</span>
<span className="text-[10px] text-muted-foreground">
{timeAgo(item.createdAt)}
</span>
</span>
{isForeign && item.ownerName && (
<span className="text-[10px] font-medium text-amber-400/90">
meant for {item.ownerName}
</span>
)}
{item.message && (
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
{item.message}
</span>
)}
<span className="text-[10px] text-muted-foreground/70">
{notificationLabel(item.type)}
</span>
{item.message && (
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
{item.message}
</span>
</DropdownMenuItem>
);
})}
)}
<span className="text-[10px] text-muted-foreground/70">
{notificationLabel(item.type)}
</span>
</DropdownMenuItem>
))}
</>
)}
</div>

View file

@ -46,97 +46,19 @@ export const isNoticeDue = (now: Date): boolean => {
return weekday === "Wed" && hour >= NOTICE_HOUR_ET;
};
/** en-US short weekday names in JS getDay() numbering. */
const WEEKDAY_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
interface EtCalendarDate {
year: number;
/** 1-12 */
month: number;
day: number;
/** 0 = Sunday, matching getDay() numbering. */
weekday: number;
}
/** The calendar date and weekday of `now` as seen in America/New_York. */
const etDate = (now: Date): EtCalendarDate => {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: ET_TIME_ZONE,
weekday: "short",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(now);
const get = (type: string): string => parts.find((part) => part.type === type)?.value ?? "";
return {
year: Number.parseInt(get("year"), 10),
month: Number.parseInt(get("month"), 10),
day: Number.parseInt(get("day"), 10),
weekday: WEEKDAY_SHORT.indexOf(get("weekday")),
};
};
/** The offset (Eastern wall clock minus UTC) in ms at an instant. */
const etOffsetMs = (instant: Date): number => {
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: ET_TIME_ZONE,
hourCycle: "h23",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
}).formatToParts(instant);
const get = (type: string): string => parts.find((part) => part.type === type)?.value ?? "0";
const wallClockAsUtc = Date.UTC(
Number.parseInt(get("year"), 10),
Number.parseInt(get("month"), 10) - 1,
Number.parseInt(get("day"), 10),
Number.parseInt(get("hour"), 10),
Number.parseInt(get("minute"), 10),
Number.parseInt(get("second"), 10),
);
return wallClockAsUtc - Math.floor(instant.getTime() / 1000) * 1000;
};
/**
* The UTC instant of midnight Eastern on a calendar date. Two offset passes
* converge for zones whose DST transitions never straddle midnight
* (America/New_York switches at 2 AM local).
*/
const etMidnightUtc = (year: number, month: number, day: number): number => {
const midnightUtc = Date.UTC(year, month - 1, day);
let ts = midnightUtc - etOffsetMs(new Date(midnightUtc));
ts = midnightUtc - etOffsetMs(new Date(ts));
return ts;
};
/**
* Start/end/epoch of the unit's Friday slot: Friday 00:00:00.000 through
* 23:59:59.999 America/New_York, computed from the Eastern calendar date so
* the window is identical on any server timezone (the deploy container runs
* UTC, where Wednesday 8 PM ET is already Thursday and an op starting Friday
* evening Eastern once fell outside the old server-local window). When `now`
* is already Friday Eastern, that day itself is the slot, keeping the dedup
* token stable from Wednesday through the op day so late claims still credit.
* Used both for the mission-existence query and for the per-Friday token.
* Start/end/epoch of the upcoming Friday (server-local), strictly after
* `now`. Used both for the mission-existence query and for the stable
* per-Friday dedup token.
*/
export const upcomingFridayRange = (now: Date): { start: Date; end: Date; epoch: number } => {
const et = etDate(now);
const daysUntilFriday = (5 - et.weekday + 7) % 7;
const friday = new Date(Date.UTC(et.year, et.month - 1, et.day + daysUntilFriday));
const saturday = new Date(
Date.UTC(friday.getUTCFullYear(), friday.getUTCMonth(), friday.getUTCDate() + 1),
);
const startMs = etMidnightUtc(
friday.getUTCFullYear(),
friday.getUTCMonth() + 1,
friday.getUTCDate(),
);
const endMs =
etMidnightUtc(saturday.getUTCFullYear(), saturday.getUTCMonth() + 1, saturday.getUTCDate()) - 1;
return { start: new Date(startMs), end: new Date(endMs), epoch: Math.floor(startMs / 1000) };
const start = new Date(now);
const daysUntilFriday = (5 - start.getDay() + 7) % 7 || 7;
start.setDate(start.getDate() + daysUntilFriday);
start.setHours(0, 0, 0, 0);
const end = new Date(start);
end.setHours(23, 59, 59, 999);
return { start, end, epoch: Math.floor(start.getTime() / 1000) };
};
/**

View file

@ -52,87 +52,6 @@ export async function notifyUser(payload: PayloadType, input: NotifyInput): Prom
}
}
/**
* Mark the given notifications read, scoped so an actor can only change the
* read-state of notifications that belong to THEM.
*
* Read-state is personal to the recipient. Staff with read-all oversight can
* *view* anyone's notifications, but they must never flip another user's read
* flag — doing so would hide that notification from its real owner. The ownership
* guard (`doc.user === actorUserId`) is what enforces this; `overrideAccess` on
* the reads/updates just fetches and writes the rows.
*
* @returns the ids that were actually flipped from unread to read.
*/
export async function markNotificationsReadForUser(
payload: PayloadType,
actorUserId: number,
ids: number[],
): Promise<number[]> {
const cleanIds = [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))];
if (cleanIds.length === 0) return [];
const found = await payload.find({
collection: "user-notifications",
where: { id: { in: cleanIds } },
limit: cleanIds.length,
depth: 0,
overrideAccess: true,
});
const updated: number[] = [];
for (const doc of found.docs) {
if (Number(doc.user) !== actorUserId) continue;
if (!doc.read) {
await payload.update({
collection: "user-notifications",
id: doc.id,
data: { read: true },
overrideAccess: true,
depth: 0,
});
updated.push(doc.id);
}
}
return updated;
}
/**
* Mark every unread notification that belongs to the actor as read. Never
* touches another user's notifications — unlike the old inline "mark all read"
* which swept unread rows across every user.
*
* @returns the ids that were actually flipped from unread to read.
*/
export async function markAllNotificationsReadForUser(
payload: PayloadType,
actorUserId: number,
): Promise<number[]> {
const found = await payload.find({
collection: "user-notifications",
where: { read: { equals: false } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const updated: number[] = [];
for (const doc of found.docs) {
if (Number(doc.user) !== actorUserId) continue;
if (!doc.read) {
await payload.update({
collection: "user-notifications",
id: doc.id,
data: { read: true },
overrideAccess: true,
depth: 0,
});
updated.push(doc.id);
}
}
return updated;
}
/** Short display label for a notification type, or the raw type when unknown. */
export function notificationLabel(type?: string | null): string {
switch (type) {

View file

@ -58,11 +58,6 @@ function buildScriptView(
let otherSubmissionCount = 0;
for (const submission of submissions) {
// depth: 0 — `script` is a numeric id here. Scope every count to this
// script so a submission on one script never bleeds onto another's card.
// `listScriptsForUser` passes ALL submissions at once, so without this a
// single take surfaces under every script (a prod display bug).
if (submission.script !== script.id) continue;
if (submission.user === userId) {
mySubmissions.push(toSubmissionSummary(submission));
} else {

File diff suppressed because it is too large Load diff

View file

@ -1,16 +0,0 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_campaigns_status" ADD VALUE 'onHold' BEFORE 'completed';`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "campaigns" ALTER COLUMN "status" SET DATA TYPE text;
ALTER TABLE "campaigns" ALTER COLUMN "status" SET DEFAULT 'concept'::text;
DROP TYPE "public"."enum_campaigns_status";
CREATE TYPE "public"."enum_campaigns_status" AS ENUM('concept', 'inProgress', 'completed');
ALTER TABLE "campaigns" ALTER COLUMN "status" SET DEFAULT 'concept'::"public"."enum_campaigns_status";
ALTER TABLE "campaigns" ALTER COLUMN "status" SET DATA TYPE "public"."enum_campaigns_status" USING "status"::"public"."enum_campaigns_status";`)
}

View file

@ -116,7 +116,6 @@ import * as migration_20261007_025942_add_event_log_visibility from './20261007_
import * as migration_20261007_040914_add_reinforcement_pools from './20261007_040914_add_reinforcement_pools';
import * as migration_20261007_044017_add_ticket_archival from './20261007_044017_add_ticket_archival';
import * as migration_20261007_183000_add_missing_mcp_key_capabilities from './20261007_183000_add_missing_mcp_key_capabilities';
import * as migration_20261009_160740_add_campaign_on_hold_status from './20261009_160740_add_campaign_on_hold_status';
export const migrations = [
{
@ -702,16 +701,11 @@ export const migrations = [
{
up: migration_20261007_044017_add_ticket_archival.up,
down: migration_20261007_044017_add_ticket_archival.down,
name: '20261007_044017_add_ticket_archival',
name: '20261007_044017_add_ticket_archival'
},
{
up: migration_20261007_183000_add_missing_mcp_key_capabilities.up,
down: migration_20261007_183000_add_missing_mcp_key_capabilities.down,
name: '20261007_183000_add_missing_mcp_key_capabilities',
},
{
up: migration_20261009_160740_add_campaign_on_hold_status.up,
down: migration_20261009_160740_add_campaign_on_hold_status.down,
name: '20261009_160740_add_campaign_on_hold_status'
},
];

View file

@ -2176,7 +2176,7 @@ export interface Campaign {
id: number;
name: string;
summary: string;
status: 'concept' | 'inProgress' | 'onHold' | 'completed';
status: 'concept' | 'inProgress' | 'completed';
/**
* Only developers can designate a campaign as official or custom.
*/

View file

@ -16,19 +16,12 @@ let payload: Payload;
const RUN = `fon-${Date.now().toString(36)}`;
// Hermetic window: 2027-01-13 is a Wednesday far enough out that the shared
// dev database holds no real missions on its Friday (2027-01-15). All fixtures
// are explicit UTC instants so the suite behaves identically on any machine
// timezone (January 2027 is EST, UTC-5: Eastern midnight = 05:00Z).
const WEDNESDAY = new Date("2027-01-13T17:00:00Z"); // Wed 12:00 PM ET
// Wed 8:00 PM ET — already Thursday 01:00 UTC, the instant that broke the
// old server-local window math on the UTC deploy container.
const WEDNESDAY_EVENING = new Date("2027-01-14T01:00:00Z");
const TUESDAY = new Date("2027-01-12T17:00:00Z"); // Tue 12:00 PM ET
const FRIDAY = new Date("2027-01-15T17:00:00Z"); // Fri 12:00 PM ET
const FRIDAY_EVENING = new Date("2027-01-16T01:00:00Z"); // Fri 8:00 PM ET
const SATURDAY = new Date("2027-01-17T01:00:00Z"); // Sat 8:00 PM ET
const FRIDAY_SLOT_START = "2027-01-15T05:00:00.000Z"; // Fri 00:00 EST
const FRIDAY_SLOT_END = "2027-01-16T04:59:59.999Z"; // Fri 23:59:59.999 EST
// dev database holds no real missions on its Friday (2027-01-15).
const WEDNESDAY = new Date(2027, 0, 13, 12, 0, 0, 0);
const TUESDAY = new Date(2027, 0, 12, 12, 0, 0, 0);
const FRIDAY = new Date(2027, 0, 15, 12, 0, 0, 0);
const FRIDAY_EVENING = new Date(2027, 0, 15, 20, 0, 0, 0);
const SATURDAY = new Date(2027, 0, 16, 20, 0, 0, 0);
describe("Friday open-slot notice", () => {
let mapId: number;
@ -233,37 +226,24 @@ describe("Friday open-slot notice", () => {
expect(isNoticeDue(new Date("2026-01-15T01:00:00Z"))).toBe(true); // Wed 20:00 ET (EST)
});
it("targets Friday 00:00-23:59:59.999 Eastern regardless of server timezone", () => {
it("targets the upcoming Friday, strictly in the future", () => {
const fromWednesday = upcomingFridayRange(WEDNESDAY);
expect(fromWednesday.start.toISOString()).toBe(FRIDAY_SLOT_START);
expect(fromWednesday.end.toISOString()).toBe(FRIDAY_SLOT_END);
expect(fromWednesday.start).toEqual(new Date(2027, 0, 15, 0, 0, 0, 0));
expect(fromWednesday.end).toEqual(new Date(2027, 0, 15, 23, 59, 59, 999));
expect(fromWednesday.epoch).toBe(Math.floor(fromWednesday.start.getTime() / 1000));
// Earlier in the week still lands on the same Friday.
expect(upcomingFridayRange(TUESDAY).start).toEqual(fromWednesday.start);
// Regression (prod incident 2026-10-07): Wed 8 PM ET is Thursday UTC on
// the UTC deploy container; the slot must stay THIS week's Eastern Friday,
// and an op starting Friday 8 PM ET — the exact instant that fell outside
// the old server-local window — must count as inside it.
const fromWednesdayEvening = upcomingFridayRange(WEDNESDAY_EVENING);
expect(fromWednesdayEvening.start).toEqual(fromWednesday.start);
expect(FRIDAY_EVENING >= fromWednesdayEvening.start).toBe(true);
expect(FRIDAY_EVENING <= fromWednesdayEvening.end).toBe(true);
// On the Friday itself (Eastern) that day is still the slot, so the
// notice keeps tracking late claims; Saturday rolls to the next Friday.
expect(upcomingFridayRange(FRIDAY).start).toEqual(fromWednesday.start);
expect(upcomingFridayRange(SATURDAY).start.toISOString()).toBe("2027-01-22T05:00:00.000Z");
expect(upcomingFridayRange(new Date(2027, 0, 11, 8, 0, 0, 0)).start).toEqual(
fromWednesday.start,
);
// On a Friday itself, the next Friday is targeted instead.
expect(upcomingFridayRange(FRIDAY).start).toEqual(new Date(2027, 0, 22, 0, 0, 0, 0));
});
it("builds a stable per-Friday dedup token", () => {
expect(noticeToken(WEDNESDAY)).toBe(noticeToken(TUESDAY));
expect(noticeToken(WEDNESDAY)).toBe(`<t:${upcomingFridayRange(WEDNESDAY).epoch}:D>`);
// Stable through the op day, so claims made after Thursday ET midnight
// still match the notice posted on Wednesday.
expect(noticeToken(FRIDAY)).toBe(noticeToken(WEDNESDAY));
expect(noticeToken(SATURDAY)).not.toBe(noticeToken(WEDNESDAY));
expect(noticeToken(FRIDAY)).not.toBe(noticeToken(WEDNESDAY));
});
it("treats the Friday slot as open only when a non-cancelled mission starts that Friday", async () => {
@ -271,9 +251,6 @@ describe("Friday open-slot notice", () => {
const concept = await makeMission("concept-friday", FRIDAY_EVENING, "Concept");
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(true);
// Same answer when asked at Wed 8 PM ET (= Thursday UTC): a Friday-evening
// op holds the slot on any server timezone.
await expect(hasMissionOnFriday(payload, WEDNESDAY_EVENING)).resolves.toBe(true);
await makeMission("cancelled-friday", FRIDAY_EVENING, "Cancelled");
await expect(hasMissionOnFriday(payload, WEDNESDAY)).resolves.toBe(true);
@ -292,11 +269,6 @@ describe("Friday open-slot notice", () => {
const zeusMission = await makeMission("zeus-claim", FRIDAY_EVENING, "Scheduled", zeusId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });
// A Friday-evening claim is still credited when checked at Wed 8 PM ET
// (= Thursday UTC on the deploy container).
await expect(getFridayClaimant(payload, WEDNESDAY_EVENING)).resolves.toEqual({
userName: "ZEUS",
});
await makeMission("su-claim", FRIDAY_EVENING, "Scheduled", superuserId);
await expect(getFridayClaimant(payload, WEDNESDAY)).resolves.toEqual({ userName: "ZEUS" });

View file

@ -1,140 +0,0 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, User } from "@/payload-types";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
import {
markAllNotificationsReadForUser,
markNotificationsReadForUser,
} from "@/lib/notifications";
let payload: Payload;
const RUN = `ntfread-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
describe("notification read-state is personal to the recipient", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const notifIds: number[] = [];
let alice: User;
let bob: User;
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const createNotification = async (userId: number): Promise<number> => {
const doc = await payload.create({
collection: "user-notifications",
data: {
user: userId,
type: "test:scope",
title: `${RUN} ${userId}`,
message: "test",
read: false,
},
overrideAccess: true,
depth: 0,
});
notifIds.push(doc.id as number);
return doc.id as number;
};
const isRead = async (id: number): Promise<boolean> => {
const res = await payload.find({
collection: "user-notifications",
where: { id: { equals: id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return Boolean(res.docs[0]?.read);
};
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
invalidatePermissionCache();
const plainRole = await makeRole("plain", { permissions: [] });
alice = await makeUser("alice", plainRole.id);
bob = await makeUser("bob", plainRole.id);
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
for (const id of notifIds) {
await payload.delete({ collection: "user-notifications", id, overrideAccess: true }).catch(
() => {},
);
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
});
it("markNotificationsReadForUser only flips the actor's own notifications", async () => {
const aliceId = await createNotification(alice.id);
const bobId = await createNotification(bob.id);
// Alice attempts to mark BOTH reads. The bug: with overrideAccess the
// original code flipped bob's row too, hiding it from bob.
await markNotificationsReadForUser(payload, alice.id, [aliceId, bobId]);
expect(await isRead(aliceId)).toBe(true);
expect(await isRead(bobId)).toBe(false);
}, TIMEOUT);
it("markAllNotificationsReadForUser never touches another user's unread rows", async () => {
const aliceId = await createNotification(alice.id);
const bobId = await createNotification(bob.id);
await markAllNotificationsReadForUser(payload, alice.id);
expect(await isRead(aliceId)).toBe(true);
expect(await isRead(bobId)).toBe(false);
}, TIMEOUT);
it("marks an actor's own notifications read when called for themselves", async () => {
const aliceId = await createNotification(alice.id);
const bobId = await createNotification(bob.id);
const updated = await markAllNotificationsReadForUser(payload, alice.id);
expect(updated).toEqual([aliceId]);
expect(await isRead(aliceId)).toBe(true);
expect(await isRead(bobId)).toBe(false);
}, TIMEOUT);
});

View file

@ -1,174 +0,0 @@
import { getPayload, Payload, type Where } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, User, VoiceScript, VoiceSubmission } from "@/payload-types";
import { listScriptsForUser } from "@/lib/voiceover";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
const RUN = `vo-list-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
describe("voiceover listing scopes submissions to their script", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const scriptIds: number[] = [];
const submissionIds: number[] = [];
let plainUser: User;
let otherUser: User;
let scriptA: VoiceScript;
let scriptB: VoiceScript;
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const createScript = async (label: string): Promise<VoiceScript> => {
const script = (await payload.create({
collection: "voice-scripts",
data: {
title: `${RUN}-${label}`,
script: `${RUN} ${label} script text`,
xpAmount: 100,
status: "open",
},
overrideAccess: true,
depth: 0,
})) as unknown as VoiceScript;
scriptIds.push(script.id);
return script;
};
const createSubmission = async (
scriptId: number,
userId: number,
status: VoiceSubmission["status"],
): Promise<VoiceSubmission> => {
// voice-submissions is an upload collection, so create requires a file
// payload; a tiny buffer with an audio mimetype is enough to seed a row.
const submission = (await payload.create({
collection: "voice-submissions",
data: { script: scriptId, user: userId, status },
file: {
data: Buffer.from("test-audio-payload"),
mimetype: "audio/mpeg",
name: `${RUN}-take.mp3`,
size: 20,
},
overrideAccess: true,
depth: 0,
})) as unknown as VoiceSubmission;
submissionIds.push(submission.id);
return submission;
};
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
const plainRole = await makeRole("plain", { permissions: [] });
const otherRole = await makeRole("other", { permissions: [] });
plainUser = await makeUser("plain", plainRole.id);
otherUser = await makeUser("other", otherRole.id);
scriptA = await createScript("script-a");
scriptB = await createScript("script-b");
// The prod bug: a single take on script A was rendered under EVERY script
// card because the listing attributed submissions by submitter only.
await createSubmission(scriptA.id, plainUser.id, "rejected");
// A different user's take on script B, so the "other" count is per-script.
await createSubmission(scriptB.id, otherUser.id, "pending");
invalidatePermissionCache();
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
for (const id of submissionIds) {
await payload.delete({ collection: "voice-submissions", id, overrideAccess: true }).catch(
() => {},
);
}
for (const id of scriptIds) {
await payload.delete({ collection: "voice-scripts", id, overrideAccess: true }).catch(
() => {},
);
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
});
it("shows a user's take only on the script they submitted it to", async () => {
const views = await listScriptsForUser(payload, plainUser);
const viewA = views.find((s) => s.id === scriptA.id);
const viewB = views.find((s) => s.id === scriptB.id);
expect(viewA).toBeDefined();
expect(viewB).toBeDefined();
// The take lives on script A.
expect(viewA?.mySubmissions).toHaveLength(1);
expect(viewA?.mySubmissions[0]?.status).toBe("rejected");
// THE BUG FIX: script B must not inherit script A's take.
expect(viewB?.mySubmissions).toHaveLength(0);
});
it("counts other submissions per script, not across all scripts", async () => {
const views = await listScriptsForUser(payload, plainUser);
const viewA = views.find((s) => s.id === scriptA.id);
const viewB = views.find((s) => s.id === scriptB.id);
// Script A: only plainUser's own take exists -> no other submissions.
expect(viewA?.otherSubmissionCount).toBe(0);
// Script B: one take by the other user -> counted here, not on A.
expect(viewB?.otherSubmissionCount).toBe(1);
});
it("exposes the VoiceSubmissions read access as an owner scope for members", async () => {
const read = (await import("@/collections/voiceover/VoiceSubmissions")).VoiceSubmissions
.access?.read;
expect(typeof read).toBe("function");
const fn = read as (args: { req: unknown }) => Promise<Where | boolean>;
const memberClause = await fn({ req: { user: plainUser, payload } });
expect(typeof memberClause).toBe("object");
expect((memberClause as Where).user).toEqual({ equals: plainUser.id });
expect(await fn({ req: { user: null, payload } })).toBe(false);
}, TIMEOUT);
});