Authors can no longer rate a mission they ran or planned. The rating action, the availability check and the server submit all enforce it, and the UI explains why. The mission-ratings fixtures now use a dedicated author so the rater accounts stay non-authors.
683 lines
25 KiB
TypeScript
683 lines
25 KiB
TypeScript
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import type { Payload } from "payload";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import type { Campaign, Map as MissionMap, Mission, Role, User } from "@/payload-types";
|
|
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
|
import {
|
|
isRatingAvailable,
|
|
isRatingWindowOpen,
|
|
getMissionRatingAggregate,
|
|
getMissionRatingState,
|
|
submitMissionRating,
|
|
} from "@/lib/missionRatings";
|
|
import {
|
|
MISSION_RATING_CORE_FACTORS,
|
|
RATING_ANONYMITY_THRESHOLD,
|
|
RATING_VALUE_OPTIONS,
|
|
} from "@/lib/missionRatings/factors";
|
|
import { CONTRIBUTION_TYPE_MISSION_RATING, MISSION_RATING_XP } from "@/lib/missionRatings/xp";
|
|
import { recordContribution } from "@/lib/contributions";
|
|
|
|
type TestPayload = Awaited<ReturnType<typeof getTestPayload>>;
|
|
|
|
describe("Mission ratings (post-op survey)", () => {
|
|
let payload: TestPayload;
|
|
const RUN = `mrat-${Date.now().toString(36)}`;
|
|
|
|
let mapId: number;
|
|
let campaignId: number;
|
|
const missionIds: number[] = [];
|
|
const userIds: number[] = [];
|
|
|
|
// Raters shared across scenarios.
|
|
let author: User;
|
|
let rater1: User;
|
|
let rater2: User;
|
|
let rater3: User;
|
|
let noRsvp: User;
|
|
let outsider: User;
|
|
|
|
// Missions, each created in `beforeAll`.
|
|
let aggMissionId: number; // Completed, unit: aggregate math + per-factor + state
|
|
let belowMissionId: number; // Completed, unit: below-then-at threshold + comments
|
|
let closedMissionId: number; // Scheduled future: window closed
|
|
let eligMissionId: number; // Completed, unit: eligibility gate
|
|
let customMissionId: number; // Completed, unit, custom factor "Comms"
|
|
let xpMissionId: number; // Completed, unit: XP grant + idempotency
|
|
|
|
const past = new Date();
|
|
past.setHours(past.getHours() - 1); // within the 14-day window
|
|
const future = new Date();
|
|
future.setDate(future.getDate() + 20);
|
|
|
|
const makeUser = async (label: string): 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",
|
|
roles: ["user"],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User;
|
|
userIds.push(user.id);
|
|
return user;
|
|
};
|
|
|
|
const rsvp = async (userId: number, missionId: number): Promise<void> => {
|
|
await payload.create({
|
|
collection: "mission-attendances",
|
|
data: { mission: missionId, user: userId, response: "yes" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
};
|
|
|
|
const makeCompletedMission = async (
|
|
label: string,
|
|
opts?: { customFactors?: { label: string }[] },
|
|
): Promise<Mission> => {
|
|
const mission = (await payload.create({
|
|
collection: "missions",
|
|
data: {
|
|
name: `${RUN} ${label}`,
|
|
codeName: `${RUN}-${label}`,
|
|
summary: "Mission rating test mission",
|
|
operationType: "main",
|
|
classification: {
|
|
map: mapId,
|
|
missionType: "PvE",
|
|
campaign: campaignId,
|
|
startDateTime: past.toISOString(),
|
|
estimatedDuration: 60,
|
|
},
|
|
ownershipAndStatus: {
|
|
status: "Completed",
|
|
completedAt: past.toISOString(),
|
|
visibility: "unit",
|
|
authors: [author.id],
|
|
},
|
|
...(opts?.customFactors ? { missionRating: { customFactors: opts.customFactors } } : {}),
|
|
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 as number);
|
|
return mission;
|
|
};
|
|
|
|
const makeFutureMission = async (label: string): Promise<Mission> => {
|
|
const mission = (await payload.create({
|
|
collection: "missions",
|
|
data: {
|
|
name: `${RUN} ${label}`,
|
|
codeName: `${RUN}-${label}`,
|
|
summary: "Future mission",
|
|
operationType: "main",
|
|
classification: {
|
|
map: mapId,
|
|
missionType: "PvE",
|
|
campaign: campaignId,
|
|
startDateTime: future.toISOString(),
|
|
estimatedDuration: 60,
|
|
},
|
|
ownershipAndStatus: {
|
|
status: "Scheduled",
|
|
visibility: "unit",
|
|
authors: [author.id],
|
|
},
|
|
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 as number);
|
|
return mission;
|
|
};
|
|
|
|
const bucketFor = async (userId: number): Promise<number> => {
|
|
const res = await payload.find({
|
|
collection: "profiles",
|
|
where: { user: { equals: userId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
select: { progression: { contributions: { xpEarned: true } } },
|
|
});
|
|
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
|
|
};
|
|
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
|
|
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: "Rating test campaign", status: "concept", campaignMode: "custom" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Campaign;
|
|
campaignId = campaign.id;
|
|
|
|
author = await makeUser("author");
|
|
rater1 = await makeUser("rater1");
|
|
rater2 = await makeUser("rater2");
|
|
rater3 = await makeUser("rater3");
|
|
noRsvp = await makeUser("no-rsvp");
|
|
outsider = await makeUser("outsider");
|
|
|
|
aggMissionId = (await makeCompletedMission("agg")).id as number;
|
|
belowMissionId = (await makeCompletedMission("below")).id as number;
|
|
closedMissionId = (await makeFutureMission("closed")).id as number;
|
|
eligMissionId = (await makeCompletedMission("elig")).id as number;
|
|
customMissionId = (await makeCompletedMission("custom", { customFactors: [{ label: "Comms" }] })).id as number;
|
|
xpMissionId = (await makeCompletedMission("xp")).id as number;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await payload
|
|
.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {})
|
|
.catch(() => {});
|
|
|
|
// Drop everything created for this run.
|
|
await payload
|
|
.delete({
|
|
collection: "mission-ratings",
|
|
where: { mission: { in: missionIds } },
|
|
overrideAccess: true,
|
|
})
|
|
.catch(() => {});
|
|
await payload
|
|
.delete({
|
|
collection: "mission-attendances",
|
|
where: { mission: { in: missionIds } },
|
|
overrideAccess: true,
|
|
})
|
|
.catch(() => {});
|
|
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: "contribution-entries", where: { user: { in: userIds } }, overrideAccess: true })
|
|
.catch(() => {});
|
|
for (const userId of userIds) {
|
|
const profiles = await payload
|
|
.find({ collection: "profiles", where: { user: { equals: userId } }, depth: 0, overrideAccess: true })
|
|
.catch(() => ({ docs: [] }));
|
|
for (const doc of profiles.docs) {
|
|
await payload.delete({ collection: "profiles", id: doc.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
await payload.delete({ collection: "users", id: userId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Window classification (pure)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("classifies the rating window (pure)", () => {
|
|
const now = new Date();
|
|
const inWindow = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
|
|
|
|
expect(isRatingWindowOpen("Completed", inWindow, now)).toBe(true);
|
|
// Exactly 14 days after completion: the window's end equals `now`, which
|
|
// is inclusive.
|
|
const boundary = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString();
|
|
expect(isRatingWindowOpen("Completed", boundary, now)).toBe(true);
|
|
// One second past the 14-day mark: closed.
|
|
const justPast = new Date(now.getTime() - (14 * 24 * 60 * 60 * 1000 + 1000)).toISOString();
|
|
expect(isRatingWindowOpen("Completed", justPast, now)).toBe(false);
|
|
// Not completed, or no completion timestamp.
|
|
expect(isRatingWindowOpen("Scheduled", inWindow, now)).toBe(false);
|
|
expect(isRatingWindowOpen("Completed", null, now)).toBe(false);
|
|
expect(isRatingWindowOpen("Completed", "not-a-date", now)).toBe(false);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Eligibility
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("gates availability on window, yes-RSVP, and prior rating", async () => {
|
|
// rater1: window open + yes-RSVP + not rated -> eligible.
|
|
await rsvp(rater1.id, eligMissionId);
|
|
expect(
|
|
await isRatingAvailable(payload, { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, rater1.id),
|
|
).toBe(true);
|
|
|
|
// noRsvp: no attendance -> ineligible.
|
|
expect(
|
|
await isRatingAvailable(payload, { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, noRsvp.id),
|
|
).toBe(false);
|
|
|
|
// Window closed for a different mission -> ineligible.
|
|
expect(
|
|
await isRatingAvailable(payload, { id: closedMissionId, ownershipAndStatus: { status: "Scheduled", completedAt: null } }, rater1.id),
|
|
).toBe(false);
|
|
});
|
|
|
|
it("rejects a second rating from the same user (idempotent write)", async () => {
|
|
await rsvp(rater1.id, aggMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater1.id,
|
|
values: { Briefing: 5, Pacing: 4, Map: 3, Host: 2, Balance: 5 },
|
|
});
|
|
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater1.id,
|
|
values: { Briefing: 3, Pacing: 3, Map: 3, Host: 4, Balance: 4 },
|
|
}),
|
|
).rejects.toThrow(/already submitted/i);
|
|
|
|
// A different user can still rate the same mission.
|
|
await rsvp(rater2.id, aggMissionId);
|
|
const second = await submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater2.id,
|
|
values: { Briefing: 4, Pacing: 4, Map: 3, Host: 3, Balance: 3 },
|
|
});
|
|
expect(second).toHaveLength(5);
|
|
});
|
|
|
|
it("blocks a mission author from rating their own mission", async () => {
|
|
// author authored aggMission and has a yes-RSVP, so only the author rule can block them.
|
|
await rsvp(author.id, aggMissionId);
|
|
|
|
expect(
|
|
await isRatingAvailable(
|
|
payload,
|
|
{ id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } },
|
|
author.id,
|
|
),
|
|
).toBe(false);
|
|
|
|
const state = await getMissionRatingState(
|
|
payload,
|
|
{ id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } },
|
|
author.id,
|
|
);
|
|
expect(state.isAuthor).toBe(true);
|
|
expect(state.isEligible).toBe(false);
|
|
expect(state.canRate).toBe(false);
|
|
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: author.id,
|
|
values: { Briefing: 5 },
|
|
}),
|
|
).rejects.toThrow(/cannot rate their own mission/i);
|
|
});
|
|
|
|
it("still lets a non-author with a yes-RSVP rate an authored mission", async () => {
|
|
// rater2 is not an author of eligMission (authored by author) and has a yes-RSVP.
|
|
await rsvp(rater2.id, eligMissionId);
|
|
const mission = { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } };
|
|
|
|
expect(await isRatingAvailable(payload, mission, rater2.id)).toBe(true);
|
|
const state = await getMissionRatingState(payload, mission, rater2.id);
|
|
expect(state.isAuthor).toBe(false);
|
|
expect(state.isEligible).toBe(true);
|
|
});
|
|
|
|
it("validates factor values before writing (unknown / out-of-range / closed)", async () => {
|
|
await rsvp(rater3.id, aggMissionId);
|
|
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 5, NotAFactor: 4 },
|
|
}),
|
|
).rejects.toThrow(/unknown factor/i);
|
|
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 6 },
|
|
}),
|
|
).rejects.toThrow(/between 1 and 5/i);
|
|
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 0 },
|
|
}),
|
|
).rejects.toThrow(/between 1 and 5/i);
|
|
|
|
// A closed-window mission rejects the write outright.
|
|
await rsvp(rater3.id, closedMissionId);
|
|
await expect(
|
|
submitMissionRating(payload, {
|
|
missionId: closedMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 5 },
|
|
}),
|
|
).rejects.toThrow(/window.*closed/i);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Aggregate math + per-factor breakdown (at threshold)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("aggregates the overall average and per-factor breakdown once visible", async () => {
|
|
// rater1 and rater2 have already rated (idempotent-write test). rater3 rates now.
|
|
await rsvp(rater3.id, aggMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: aggMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 3, Pacing: 3, Map: 3, Host: 4, Balance: 4 },
|
|
});
|
|
|
|
const agg = await getMissionRatingAggregate(payload, aggMissionId);
|
|
|
|
// 3 distinct raters, each rating 5 core factors -> 15 values.
|
|
expect(agg.raterCount).toBe(3);
|
|
expect(agg.visible).toBe(true);
|
|
expect(agg.factors).not.toBeNull();
|
|
// Overall: (19 + 17 + 17) / 15 = 53 / 15 = 3.5333...
|
|
expect(agg.overallAverage).toBeCloseTo(3.53, 0.01);
|
|
|
|
const byFactor = new Map((agg.factors as Array<{ factor: string; average: number; count: number; distribution: { value: number; count: number }[] }>).map((f) => [f.factor, f]));
|
|
|
|
// Canonical core order.
|
|
expect((agg.factors as Array<{ factor: string }>).map((f) => f.factor)).toEqual([...MISSION_RATING_CORE_FACTORS]);
|
|
|
|
// Briefing = (5 + 4 + 3) / 3 = 4.0.
|
|
expect(byFactor.get("Briefing")?.average).toBeCloseTo(4.0, 6);
|
|
expect(byFactor.get("Briefing")?.count).toBe(3);
|
|
expect(byFactor.get("Briefing")?.distribution).toEqual([
|
|
{ value: 1, count: 0 },
|
|
{ value: 2, count: 0 },
|
|
{ value: 3, count: 1 },
|
|
{ value: 4, count: 1 },
|
|
{ value: 5, count: 1 },
|
|
]);
|
|
|
|
// Map is unanimous at 3.
|
|
expect(byFactor.get("Map")?.average).toBeCloseTo(3.0, 6);
|
|
|
|
// Every distribution sums to the factor count and only uses valid options.
|
|
for (const factor of agg.factors as Array<{ factor: string; count: number; distribution: { value: number; count: number }[]}>) {
|
|
const total = factor.distribution.reduce((sum, d) => sum + d.count, 0);
|
|
expect(total).toBe(factor.count);
|
|
for (const d of factor.distribution) {
|
|
expect(RATING_VALUE_OPTIONS).toContain(d.value);
|
|
}
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Anonymity threshold
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("withholds the breakdown below the anonymity threshold and reveals it at threshold", async () => {
|
|
const state = (r: User) => ({ id: belowMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } });
|
|
|
|
await rsvp(rater1.id, belowMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: belowMissionId,
|
|
userId: rater1.id,
|
|
values: { Briefing: 5, Pacing: 5 },
|
|
comment: "Great op",
|
|
});
|
|
await rsvp(rater2.id, belowMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: belowMissionId,
|
|
userId: rater2.id,
|
|
values: { Briefing: 3, Pacing: 1 },
|
|
comment: "Could be better",
|
|
});
|
|
|
|
// 2 distinct raters < RATING_ANONYMITY_THRESHOLD.
|
|
expect(RATING_ANONYMITY_THRESHOLD).toBe(3);
|
|
const hidden = await getMissionRatingAggregate(payload, belowMissionId);
|
|
expect(hidden.raterCount).toBe(2);
|
|
expect(hidden.visible).toBe(false);
|
|
expect(hidden.factors).toBeNull();
|
|
expect(hidden.comments).toBeNull();
|
|
// The overall average and rater count are always available.
|
|
expect(hidden.overallAverage).toBeCloseTo(3.5, 0.01);
|
|
|
|
// Add a third rater -> now visible.
|
|
await rsvp(rater3.id, belowMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: belowMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 4, Pacing: 4 },
|
|
});
|
|
const revealed = await getMissionRatingAggregate(payload, belowMissionId);
|
|
expect(revealed.raterCount).toBe(3);
|
|
expect(revealed.visible).toBe(true);
|
|
expect(revealed.factors).not.toBeNull();
|
|
expect(revealed.comments).not.toBeNull();
|
|
expect(revealed.comments?.some((c) => c.text === "Great op")).toBe(true);
|
|
expect(revealed.overallAverage).toBeCloseTo(22 / 6, 0.01);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Custom factors
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("aggregates authored custom factors alongside core factors", async () => {
|
|
// Three raters so the breakdown is visible (threshold = 3). Each rates the
|
|
// authored custom factor "Comms" plus one core factor.
|
|
await rsvp(rater1.id, customMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: customMissionId,
|
|
userId: rater1.id,
|
|
values: { Comms: 5, Briefing: 5 },
|
|
});
|
|
await rsvp(rater2.id, customMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: customMissionId,
|
|
userId: rater2.id,
|
|
values: { Comms: 4, Briefing: 3 },
|
|
});
|
|
await rsvp(rater3.id, customMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: customMissionId,
|
|
userId: rater3.id,
|
|
values: { Comms: 3, Briefing: 4 },
|
|
});
|
|
|
|
const agg = await getMissionRatingAggregate(payload, customMissionId);
|
|
expect(agg.visible).toBe(true);
|
|
const factor = (agg.factors ?? []).find((f) => f.factor === "Comms");
|
|
// (5 + 4 + 3) / 3 = 4.0
|
|
expect(factor?.average).toBeCloseTo(4.0, 6);
|
|
expect(factor?.count).toBe(3);
|
|
expect(factor?.distribution).toEqual([
|
|
{ value: 1, count: 0 },
|
|
{ value: 2, count: 0 },
|
|
{ value: 3, count: 1 },
|
|
{ value: 4, count: 1 },
|
|
{ value: 5, count: 1 },
|
|
]);
|
|
// Custom factors sort after core factors.
|
|
const labels = (agg.factors ?? []).map((f) => f.factor);
|
|
expect(labels.indexOf("Briefing")).toBeLessThan(labels.indexOf("Comms"));
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Read state (myValues coercion)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("returns the current user's own ratings with numeric values", async () => {
|
|
// rater2 already rated aggMission.
|
|
const state = await getMissionRatingState(payload, { id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, rater2.id);
|
|
expect(state.windowOpen).toBe(true);
|
|
expect(state.canRate).toBe(false); // already rated
|
|
expect(state.myValues).not.toBeNull();
|
|
for (const entry of state.myValues ?? []) {
|
|
expect(typeof entry.value).toBe("number");
|
|
expect(Number.isInteger(entry.value)).toBe(true);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Contribution XP
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("grants the rating XP and bumps the profile bucket", async () => {
|
|
await rsvp(rater1.id, xpMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: xpMissionId,
|
|
userId: rater1.id,
|
|
values: { Briefing: 5 },
|
|
});
|
|
|
|
const before = await bucketFor(rater1.id);
|
|
const result = await recordContribution(payload, {
|
|
userId: rater1.id,
|
|
type: CONTRIBUTION_TYPE_MISSION_RATING,
|
|
sourceCollection: "missions",
|
|
sourceId: xpMissionId,
|
|
summary: `Rated mission "xp"`,
|
|
pointsOverride: MISSION_RATING_XP,
|
|
dedupeSuffix: `user:${rater1.id}`,
|
|
actorId: rater1.id,
|
|
});
|
|
|
|
expect(result.status).toBe("granted");
|
|
expect(result.points).toBe(MISSION_RATING_XP);
|
|
expect(MISSION_RATING_XP).toBe(50);
|
|
expect(await bucketFor(rater1.id)).toBe(before + MISSION_RATING_XP);
|
|
});
|
|
|
|
it("is idempotent: the same rating contribution cannot be counted twice", async () => {
|
|
await rsvp(rater2.id, xpMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: xpMissionId,
|
|
userId: rater2.id,
|
|
values: { Briefing: 4 },
|
|
});
|
|
|
|
const input = {
|
|
userId: rater2.id,
|
|
type: CONTRIBUTION_TYPE_MISSION_RATING,
|
|
sourceCollection: "missions" as const,
|
|
sourceId: xpMissionId,
|
|
summary: "Duplicate guard",
|
|
pointsOverride: MISSION_RATING_XP,
|
|
dedupeSuffix: `user:${rater2.id}`,
|
|
};
|
|
const first = await recordContribution(payload, input);
|
|
const second = await recordContribution(payload, input);
|
|
expect(second.entryId).toBe(first.entryId);
|
|
|
|
const count = await payload.count({
|
|
collection: "contribution-entries",
|
|
where: { idempotencyKey: { equals: `mission-rating-completion:missions:${xpMissionId}:user:${rater2.id}` } },
|
|
overrideAccess: true,
|
|
});
|
|
expect(count.totalDocs).toBe(1);
|
|
});
|
|
|
|
it("grants XP to each distinct rater of the same mission (per-user, not per-mission)", async () => {
|
|
// xpMission already carries rater1 and rater2 ratings; rater3 is a third,
|
|
// distinct rater on the same mission. Without per-user idempotency the
|
|
// shared sourceId would collide and rater3 would earn nothing.
|
|
await rsvp(rater3.id, xpMissionId);
|
|
await submitMissionRating(payload, {
|
|
missionId: xpMissionId,
|
|
userId: rater3.id,
|
|
values: { Briefing: 5 },
|
|
});
|
|
const before = await bucketFor(rater3.id);
|
|
await recordContribution(payload, {
|
|
userId: rater3.id,
|
|
type: CONTRIBUTION_TYPE_MISSION_RATING,
|
|
sourceCollection: "missions",
|
|
sourceId: xpMissionId,
|
|
summary: "Cross-user grant",
|
|
pointsOverride: MISSION_RATING_XP,
|
|
dedupeSuffix: `user:${rater3.id}`,
|
|
});
|
|
expect(await bucketFor(rater3.id)).toBe(before + MISSION_RATING_XP);
|
|
});
|
|
// ---------------------------------------------------------------------------
|
|
|
|
it("hides raw mission-ratings from users without the permission", async () => {
|
|
await expect(
|
|
payload.find({
|
|
collection: "mission-ratings",
|
|
limit: 50,
|
|
depth: 0,
|
|
user: outsider,
|
|
overrideAccess: false,
|
|
}),
|
|
).rejects.toThrow(/not allowed/);
|
|
});
|
|
|
|
it("exposes raw mission-ratings to users holding mission-ratings:read", async () => {
|
|
const role = (await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN} Rating Reader`, slug: `${RUN}-rating-reader`, permissions: ["mission-ratings:read"] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Role;
|
|
|
|
const reader = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-rating-reader`,
|
|
discordUsername: `${RUN}-rating-reader`,
|
|
displayName: "RATING READER",
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roles: ["user"],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User;
|
|
userIds.push(reader.id);
|
|
|
|
await payload.update({
|
|
collection: "users",
|
|
id: reader.id,
|
|
data: { roleDocs: [role.id] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
invalidatePermissionCache();
|
|
|
|
try {
|
|
const result = await payload.find({
|
|
collection: "mission-ratings",
|
|
limit: 50,
|
|
depth: 0,
|
|
user: reader,
|
|
overrideAccess: false,
|
|
});
|
|
expect(result.docs.length).toBeGreaterThan(0);
|
|
const doc = result.docs[0] as unknown as Record<string, unknown>;
|
|
// Staff-only fields are present on the raw doc.
|
|
expect(typeof doc.user).toBe("number");
|
|
expect(Array.isArray(doc.ratings)).toBe(true);
|
|
} finally {
|
|
await payload.delete({ collection: "roles", id: role.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
});
|
|
});
|