import { getPayload, Payload } from "payload"; import config from "@/payload.config"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types"; import { getNextUpcomingScheduledMission, resolveMissionByRef, validateRollCallTarget, } from "@/lib/intelligence/rollCall"; let payload: Payload; const RUN = `rc-${Date.now().toString(36)}`; describe("Forced roll-call target helpers", () => { let mapId: number; let campaignId: number; let authorId: number; const missionIds: number[] = []; beforeAll(async () => { const payloadConfig = await config; payload = await getPayload({ config: payloadConfig }); const map = (await payload.create({ collection: "maps", data: { name: `${RUN} Map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" }, overrideAccess: true, depth: 0, })) as unknown as MissionMap; mapId = map.id; const campaign = (await payload.create({ collection: "campaigns", data: { name: `${RUN} Campaign`, summary: "Roll-call force test campaign", status: "concept", campaignMode: "custom" }, overrideAccess: true, depth: 0, })) as unknown as Campaign; campaignId = campaign.id; const author = (await payload.create({ collection: "users", data: { username: `${RUN}-author`, discordUsername: `${RUN}-author`, displayName: "RC AUTHOR", steamId: `7656119${Math.floor(Math.random() * 1e9)}`, password: "Test123", roles: ["user"], }, overrideAccess: true, depth: 0, })) as unknown as User; authorId = author.id; }); afterAll(async () => { for (const id of missionIds) { await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {}); } await payload .delete({ collection: "campaigns", id: campaignId, overrideAccess: true }) .catch(() => {}); await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {}); // User deletion trips FK constraints unless the hook-provisioned // personal bank account and profile are removed first. const accounts = await payload .find({ collection: "bank-accounts", where: { ownerUser: { equals: authorId } }, limit: 5, depth: 0, overrideAccess: true, }) .catch(() => null); for (const account of accounts?.docs ?? []) { await payload .delete({ collection: "bank-accounts", id: account.id, overrideAccess: true }) .catch(() => {}); } const profiles = await payload .find({ collection: "profiles", where: { user: { equals: authorId } }, limit: 5, depth: 0, overrideAccess: true, }) .catch(() => null); for (const profile of profiles?.docs ?? []) { await payload .delete({ collection: "profiles", id: profile.id, overrideAccess: true }) .catch(() => {}); } await payload .delete({ collection: "users", id: authorId, overrideAccess: true }) .catch(() => {}); }); const makeMission = async ( label: string, overrides: { name?: string; status?: Mission["ownershipAndStatus"]["status"]; visibility?: Mission["ownershipAndStatus"]["visibility"]; start: Date; }, ): Promise => { const mission = (await payload.create({ collection: "missions", data: { name: overrides.name ?? `${RUN} ${label}`, codeName: `${RUN}-${label}`, summary: "Forced roll-call test mission", operationType: "main", classification: { map: mapId, missionType: "PvE", campaign: campaignId, startDateTime: overrides.start.toISOString(), estimatedDuration: 60, }, ownershipAndStatus: { authors: [authorId], status: overrides.status ?? "Scheduled", visibility: overrides.visibility ?? "unit", }, missionRoles: { maxPlayers: 16, }, gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302, }, }, briefing: [], }, overrideAccess: true, depth: 0, })) as unknown as Mission; missionIds.push(mission.id); return mission; }; describe("getNextUpcomingScheduledMission", () => { it("picks the soonest future Scheduled unit op and skips past, draft, and leadership ops", async () => { const now = new Date(); await makeMission("far", { start: new Date(now.getTime() + 4 * 86_400_000) }); const soon = await makeMission("soon", { start: new Date(now.getTime() + 2 * 86_400_000) }); const past = await makeMission("past", { start: new Date(now.getTime() - 3_600_000) }); const draft = await makeMission("draft", { status: "Ready", start: new Date(now.getTime() + 600_000), }); const leadership = await makeMission("leadership", { visibility: "leadership", start: new Date(now.getTime() + 600_000), }); const next = await getNextUpcomingScheduledMission(payload, now); expect(next).not.toBeNull(); // Other suites may leave missions in the shared test DB, so assert // ordering/exclusion rather than exact identity: the pick must never be // one of the excluded rows and must start no later than our soonest. expect([past.id, draft.id, leadership.id]).not.toContain(next!.id); expect(new Date(next!.classification.startDateTime).getTime()).toBeLessThanOrEqual( new Date(soon.classification.startDateTime).getTime(), ); }); }); describe("resolveMissionByRef", () => { it("resolves by ID, name, and code name", async () => { const now = new Date(); const mission = await makeMission("solo", { start: new Date(now.getTime() + 86_400_000) }); const byId = await resolveMissionByRef(payload, String(mission.id)); expect(byId.mission?.id).toBe(mission.id); const byCodeName = await resolveMissionByRef(payload, `${RUN}-solo`); expect(byCodeName.mission?.id).toBe(mission.id); const byName = await resolveMissionByRef(payload, `${RUN} solo`); expect(byName.mission?.id).toBe(mission.id); }); it("reports no-match and ambiguity instead of guessing", async () => { const now = new Date(); const twinStart = new Date(now.getTime() + 86_400_000); await makeMission("twin-a", { name: `${RUN} twins`, start: twinStart }); await makeMission("twin-b", { name: `${RUN} twins`, start: twinStart }); const missing = await resolveMissionByRef(payload, `${RUN} definitely-not-here`); expect(missing.mission).toBeUndefined(); expect(missing.error).toContain("No mission matches"); const ambiguous = await resolveMissionByRef(payload, `${RUN} twins`); expect(ambiguous.mission).toBeUndefined(); expect(ambiguous.error).toContain("Multiple missions match"); }); }); describe("validateRollCallTarget", () => { const base = (overrides: { status?: Mission["ownershipAndStatus"]["status"]; visibility?: Mission["ownershipAndStatus"]["visibility"]; start?: Date; }): Mission => ({ id: 1, name: "Validation Probe", ownershipAndStatus: { status: overrides.status ?? "Scheduled", visibility: overrides.visibility ?? "unit", }, classification: { startDateTime: (overrides.start ?? new Date(Date.now() + 86_400_000)).toISOString(), }, }) as unknown as Mission; it("accepts a future Scheduled unit op", () => { expect(validateRollCallTarget(base({}))).toBeNull(); }); it("rejects drafts, leadership visibility, and started ops with explanations", () => { expect(validateRollCallTarget(base({ status: "Ready" }))).toContain("not Scheduled"); expect(validateRollCallTarget(base({ visibility: "leadership" }))).toContain( "not unit-visible", ); expect( validateRollCallTarget(base({ start: new Date(Date.now() - 60_000) })), ).toContain("already started"); }); }); });