Wire the previously orphaned LaborCrewPanel into the game-structures editor so staff can set actual headcount and per-worker wage for a labor classification. Adds a laborCrewPanel ui field on the edit view, a POST route under /api/game-structures that authenticates and gates on game-structures:update, delegates to the canonical setLaborHeadcount service (enforcing caps and wage logic), and an integration test covering auth, validation, and cap enforcement.
318 lines
10 KiB
TypeScript
318 lines
10 KiB
TypeScript
// @vitest-environment node
|
|
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
|
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
|
|
|
import { getFieldsToSign, getPayload, jwtSign, type CollectionSlug, type Payload, type Where } from "payload";
|
|
import config from "@/payload.config";
|
|
import { randomUUID } from "node:crypto";
|
|
import { NextRequest } from "next/server";
|
|
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import type { Role, Structure, User } from "@/payload-types";
|
|
import { POST } from "@/app/api/game-structures/set-labor-headcount/route";
|
|
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
|
|
|
let payload: Payload;
|
|
|
|
const RUN = `lcr-${Date.now().toString(36)}`;
|
|
const LEXICAL_EMPTY = {
|
|
root: {
|
|
children: [{ text: "", format: "", type: "text", version: 1 }],
|
|
direction: null,
|
|
format: "",
|
|
indent: 0,
|
|
version: 1,
|
|
},
|
|
};
|
|
const TIMEOUT = 30_000;
|
|
|
|
/** Build a NextRequest against the admin route, optionally authenticated + bodied. */
|
|
function request(token?: string, body?: unknown): NextRequest {
|
|
const headers = new Headers();
|
|
if (token) headers.set("cookie", `payload-token=${token}`);
|
|
return new NextRequest(
|
|
"http://localhost/api/game-structures/set-labor-headcount",
|
|
{
|
|
headers,
|
|
method: "POST",
|
|
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
},
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Mint a payload-token JWT for a user, mirroring the impersonation route:
|
|
* persist a session on the user doc, then sign with that session's sid.
|
|
*/
|
|
async function mintToken(userId: number): Promise<string> {
|
|
const collection = payload.collections.users.config;
|
|
const user = await payload.findByID({
|
|
collection: "users",
|
|
id: userId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
|
|
const sid = randomUUID();
|
|
const now = new Date();
|
|
const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000);
|
|
const sessions = (user.sessions ?? []).filter(
|
|
(session) => new Date(session.expiresAt).getTime() > now.getTime(),
|
|
);
|
|
sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() });
|
|
await payload.update({
|
|
collection: "users",
|
|
id: userId,
|
|
data: { sessions },
|
|
overrideAccess: true,
|
|
});
|
|
|
|
const { token } = await jwtSign({
|
|
fieldsToSign: getFieldsToSign({
|
|
collectionConfig: collection,
|
|
email: user.email ?? "",
|
|
sid,
|
|
user,
|
|
}),
|
|
secret: payload.secret,
|
|
tokenExpiration: collection.auth.tokenExpiration,
|
|
});
|
|
return token;
|
|
}
|
|
|
|
async function sweep(collection: CollectionSlug, where: Where) {
|
|
const found = await payload.find({
|
|
collection,
|
|
where,
|
|
limit: 200,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
await Promise.allSettled(
|
|
found.docs.map((doc) =>
|
|
payload.delete({ collection, id: doc.id as number, overrideAccess: true }),
|
|
),
|
|
);
|
|
}
|
|
|
|
describe("game-structures set-labor-headcount admin route", () => {
|
|
const roleIds: number[] = [];
|
|
const userIds: number[] = [];
|
|
const blueprintIds: number[] = [];
|
|
const classificationIds: number[] = [];
|
|
const mapIds: number[] = [];
|
|
|
|
let superUserId: number;
|
|
let plainUserId: number;
|
|
let superUserToken: string;
|
|
let plainUserToken: string;
|
|
let siteId: number;
|
|
let classificationId: number;
|
|
let hiringWasEnabled = false;
|
|
|
|
beforeAll(async () => {
|
|
payload = await getPayload({ config: await config });
|
|
invalidatePermissionCache();
|
|
|
|
// enable staffing so setLaborHeadcount does not fail closed.
|
|
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
|
|
hiringWasEnabled = Boolean(rules.staffHiringEnabled);
|
|
await payload.updateGlobal({
|
|
slug: "game-rules",
|
|
data: { staffHiringEnabled: true },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
|
|
// A map to seat the structure on (not required, but mirrors real placement).
|
|
const map = (await payload.create({
|
|
collection: "maps",
|
|
data: { name: `${RUN} map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
mapIds.push(map.id);
|
|
|
|
// A classification with plenty of available workers.
|
|
const classification = (await payload.create({
|
|
collection: "labor-classifications",
|
|
data: { name: `${RUN} Labor`, key: `${RUN}-labor`, defaultUnitSalary: 5, availableHeadcount: 50 },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
classificationIds.push(classification.id);
|
|
classificationId = classification.id;
|
|
|
|
// A resource so the blueprint can carry required materials.
|
|
const materialResource = (await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: `${RUN} Material`,
|
|
codeName: `${RUN}-material`,
|
|
approvalStatus: "in_progress",
|
|
type: "physical",
|
|
baseValue: 1,
|
|
rarity: "common",
|
|
unitOfMeasure: "kg",
|
|
massPerUnit: 1,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
|
|
// A blueprint that requires the classification (laborRequirements is copied into
|
|
// the game-structure on create by the beforeChange hook).
|
|
const blueprint = (await payload.create({
|
|
collection: "structures",
|
|
data: {
|
|
name: `${RUN} Site`,
|
|
codeName: `${RUN}-site`,
|
|
approvalStatus: "in_progress",
|
|
category: "logistics",
|
|
materials: [{ resource: materialResource.id, amount: 1 }],
|
|
constructionDurationMinutes: 10,
|
|
constructionCrewRequired: 1,
|
|
terrainType: "land",
|
|
maxHealth: 100,
|
|
description: LEXICAL_EMPTY as unknown as Structure["description"],
|
|
laborRequirements: [
|
|
{ classification: classification.id, requiredHeadcount: 2, maxHeadcount: 6 },
|
|
],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
blueprintIds.push(blueprint.id);
|
|
|
|
const site = (await payload.create({
|
|
collection: "game-structures",
|
|
data: { name: `${RUN} Site`, type: blueprint.id, map: map.id, coordinates: [500, 500] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
siteId = site.id;
|
|
|
|
// Superuser role + user (passes game-structures:update via the superuser bypass).
|
|
const superRole = (await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN} Labor Admin`, slug: `${RUN}-labor-admin`, isSuperuser: true },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
roleIds.push(superRole.id);
|
|
const superUser = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-su`,
|
|
discordUsername: `${RUN}-su`,
|
|
displayName: "SU",
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
// Permission resolution reads roleDocs (dynamic RBAC), not the legacy enum.
|
|
roleDocs: [superRole.id],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as User;
|
|
userIds.push(superUser.id);
|
|
superUserId = superUser.id;
|
|
|
|
// Plain (no-permission) role + user.
|
|
const plainRole = (await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN} Plain`, slug: `${RUN}-plain`, permissions: [] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as { id: number };
|
|
roleIds.push(plainRole.id);
|
|
const plainUser = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-plain`,
|
|
discordUsername: `${RUN}-plain`,
|
|
displayName: "Plain",
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roleDocs: [plainRole.id],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as User;
|
|
userIds.push(plainUser.id);
|
|
plainUserId = plainUser.id;
|
|
|
|
superUserToken = await mintToken(superUserId);
|
|
plainUserToken = await mintToken(plainUserId);
|
|
}, TIMEOUT);
|
|
|
|
afterAll(async () => {
|
|
if (!payload) return;
|
|
// FK-safe order, best-effort (the test DB is truncated between runs regardless).
|
|
if (typeof siteId === "number") {
|
|
await sweep("npc-staffing", { structure: { equals: siteId } });
|
|
}
|
|
await sweep("game-structures", { name: { like: `${RUN}%` } });
|
|
await sweep("structures", { name: { like: `${RUN}%` } });
|
|
await sweep("labor-classifications", { name: { like: `${RUN}%` } });
|
|
await sweep("maps", { name: { like: `${RUN}%` } });
|
|
for (const id of userIds) {
|
|
await sweep("profiles", { user: { equals: id } });
|
|
await Promise.allSettled([payload.delete({ collection: "users", id, overrideAccess: true })]);
|
|
}
|
|
for (const id of roleIds) {
|
|
await Promise.allSettled([payload.delete({ collection: "roles", id, overrideAccess: true })]);
|
|
}
|
|
await payload.updateGlobal({
|
|
slug: "game-rules",
|
|
data: { staffHiringEnabled: hiringWasEnabled },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
}, TIMEOUT);
|
|
|
|
it("rejects unauthenticated requests with 401", async () => {
|
|
const res = await POST(request());
|
|
expect(res.status).toBe(401);
|
|
}, TIMEOUT);
|
|
|
|
it("rejects an authenticated non-staff user with 403", async () => {
|
|
const res = await POST(request(plainUserToken));
|
|
expect(res.status).toBe(403);
|
|
}, TIMEOUT);
|
|
|
|
it("rejects a malformed body with 400", async () => {
|
|
const res = await POST(request(superUserToken, { classificationId }));
|
|
expect(res.status).toBe(400);
|
|
}, TIMEOUT);
|
|
|
|
it("sets the crew headcount for a valid request", async () => {
|
|
const res = await POST(
|
|
request(superUserToken, { structureId: siteId, classificationId, headcount: 3, unitSalary: 5 }),
|
|
);
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toMatchObject({ success: true });
|
|
|
|
const staffing = await payload.find({
|
|
collection: "npc-staffing",
|
|
where: {
|
|
structure: { equals: siteId },
|
|
laborClassification: { equals: classificationId },
|
|
positionType: { equals: "labor" },
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
const active = staffing.docs.find((doc) => doc.status === "active");
|
|
expect(active?.headcount).toBe(3);
|
|
}, TIMEOUT);
|
|
|
|
it("rejects a headcount over the blueprint cap with 400", async () => {
|
|
const res = await POST(
|
|
request(superUserToken, { structureId: siteId, classificationId, headcount: 999, unitSalary: 5 }),
|
|
);
|
|
expect(res.status).toBe(400);
|
|
expect(await res.json()).toMatchObject({ success: false });
|
|
}, TIMEOUT);
|
|
});
|