Vitest 4 orders serial test files by cached durations, so adding the interior suite reshuffled the schedule and exposed two order-dependent specs. - arma-locker-sync: floor the apply-command scan at a beforeAll id baseline and assert the two enqueue tests via per-test id deltas (the pattern the echo-guard describe already used) instead of absolute totals that accumulate rows when foreign online game-servers change enqueue fan-out - award-automation: scope every evaluateAwardRules call to this file's ruleIds, and track veteran/rookie USER ids separately from PROFILE ids because plans key on userId while makeUser returned profile ids; equality only held while both sequences stayed aligned
495 lines
17 KiB
TypeScript
495 lines
17 KiB
TypeScript
import { getPayload, Payload } from "payload";
|
|
import config from "@/payload.config";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
formatInstanceRef,
|
|
mergeStockIntoItems,
|
|
parseInstanceRef,
|
|
parseStockSnapshot,
|
|
processLockerEvent,
|
|
} from "@/lib/arma-bridge/lockers";
|
|
|
|
let payload: Payload;
|
|
const RUN = `locker-${Date.now().toString(36)}`;
|
|
const STEAM_ID = `${RUN}-steam-001`;
|
|
const UNLINKED = `${RUN}-steam-unlinked`;
|
|
const SLUG = `${RUN}-superstructure`;
|
|
const CLASS_A = "arifle_MX_F";
|
|
const CLASS_B = "ACE_bandage";
|
|
|
|
const LEXICAL_EMPTY = {
|
|
root: {
|
|
children: [{ text: "" }],
|
|
direction: null,
|
|
format: "" as const,
|
|
indent: 0,
|
|
type: "text",
|
|
version: 1,
|
|
},
|
|
};
|
|
|
|
let userId: number;
|
|
let assetAId: number;
|
|
let assetBId: number;
|
|
let resourceId: number;
|
|
let blueprintId: number;
|
|
let structureId: number;
|
|
let lockerId: number;
|
|
let serverId: number;
|
|
// Highest arma-commands id when this file starts (set in beforeAll). Rows at or
|
|
// below it belong to earlier spec files and must never affect total counts here.
|
|
let cmdBaseline = 0;
|
|
const commandIds: number[] = [];
|
|
|
|
let eventSeq = 0;
|
|
function lockerEvent(type: string, eventPayload: unknown[], server: number) {
|
|
eventSeq += 1;
|
|
return {
|
|
id: eventSeq,
|
|
eventId: `${RUN}:${eventSeq}`,
|
|
server,
|
|
type,
|
|
occurredAt: new Date().toISOString(),
|
|
payload: eventPayload,
|
|
};
|
|
}
|
|
|
|
async function findLockerApplyCommands(): Promise<{ id: number; payload: unknown }[]> {
|
|
const found = await payload.find({
|
|
collection: "arma-commands",
|
|
where: { type: { equals: "locker.apply" } },
|
|
sort: "-id",
|
|
limit: 200,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
// Scope to this run's instances: other spec files leave game-servers online,
|
|
// so their web-originated locker edits also enqueue locker.apply commands.
|
|
// An unscoped count made this file order-dependent (25 foreign rows once
|
|
// vitest's timing-based file order put those files first).
|
|
return found.docs
|
|
.filter((doc) => {
|
|
if (doc.id <= cmdBaseline) return false;
|
|
const commandPayload = (doc as { payload?: unknown }).payload;
|
|
const instanceRef = Array.isArray(commandPayload) ? commandPayload[0] : undefined;
|
|
return (
|
|
typeof instanceRef === "string" &&
|
|
(instanceRef.includes(STEAM_ID) || instanceRef.includes(SLUG))
|
|
);
|
|
})
|
|
.map((doc) => ({ id: doc.id, payload: (doc as { payload?: unknown }).payload }));
|
|
}
|
|
|
|
async function lockerDoc() {
|
|
return (await payload.findByID({
|
|
collection: "locker-storages",
|
|
id: lockerId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { items: Record<string, unknown>[]; itemCount: number };
|
|
}
|
|
|
|
describe("Arma locker sync", () => {
|
|
beforeAll(async () => {
|
|
const payloadConfig = await config;
|
|
payload = await getPayload({ config: payloadConfig });
|
|
|
|
const user = await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-player`,
|
|
discordUsername: `${RUN}-player-discord`,
|
|
displayName: `${RUN} Player`,
|
|
steamId: STEAM_ID,
|
|
password: "Test1234",
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
userId = user.id;
|
|
|
|
for (const [className, name] of [
|
|
[CLASS_A, `${RUN} MX Rifle`],
|
|
[CLASS_B, `${RUN} Bandage`],
|
|
] as const) {
|
|
const asset = await payload.create({
|
|
collection: "assets",
|
|
data: {
|
|
name,
|
|
className,
|
|
assetType: className === CLASS_A ? "weapon" : "medical",
|
|
approvalStatus: "approved",
|
|
} as never,
|
|
draft: false,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
if (className === CLASS_A) assetAId = asset.id;
|
|
else assetBId = asset.id;
|
|
}
|
|
|
|
const resource = await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: `${RUN} Steel`,
|
|
codeName: `${RUN}-steel`,
|
|
approvalStatus: "in_progress",
|
|
type: "physical",
|
|
baseValue: 1,
|
|
rarity: "common",
|
|
unitOfMeasure: "kg",
|
|
massPerUnit: 1,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
resourceId = resource.id;
|
|
|
|
const blueprint = await payload.create({
|
|
collection: "structures",
|
|
data: {
|
|
name: `${RUN} Superstructure`,
|
|
codeName: `${RUN}-superstructure`,
|
|
approvalStatus: "in_progress",
|
|
description: LEXICAL_EMPTY,
|
|
category: "logistics",
|
|
materials: [{ resource: resourceId, amount: 1 }],
|
|
constructionDurationMinutes: 1,
|
|
terrainType: "land",
|
|
maxHealth: 100,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
blueprintId = blueprint.id;
|
|
|
|
const structure = await payload.create({
|
|
collection: "game-structures",
|
|
data: {
|
|
name: `${RUN} Superstructure`,
|
|
type: blueprintId,
|
|
constructionStatus: "complete",
|
|
storageSlug: SLUG,
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
structureId = structure.id;
|
|
|
|
// Isolate from arma-commands rows left by earlier spec files (foreign online
|
|
// servers change locker fan-out and pollute the total-count assertions).
|
|
const latest = await payload.find({
|
|
collection: "arma-commands",
|
|
where: { id: { greater_than: 0 } },
|
|
sort: "-id",
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
cmdBaseline = (latest.docs[0]?.id as number | undefined) ?? 0;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
for (const id of commandIds) {
|
|
await payload.delete({ collection: "arma-commands", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (lockerId) {
|
|
await payload.delete({ collection: "locker-storages", id: lockerId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (structureId) {
|
|
await payload.delete({ collection: "game-structures", id: structureId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (blueprintId) {
|
|
await payload.delete({ collection: "structures", id: blueprintId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (resourceId) {
|
|
await payload.delete({ collection: "resources", id: resourceId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
for (const id of [assetAId, assetBId]) {
|
|
if (id) await payload.delete({ collection: "assets", id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (serverId) {
|
|
await payload.delete({ collection: "game-servers", id: serverId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
if (userId) {
|
|
const profiles = await payload.find({
|
|
collection: "profiles",
|
|
where: { user: { equals: userId } },
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
for (const profile of profiles.docs) {
|
|
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
await payload.delete({ collection: "users", id: userId, overrideAccess: true }).catch(() => {});
|
|
}
|
|
});
|
|
|
|
describe("parseInstanceRef", () => {
|
|
it("parses personal and structure refs", () => {
|
|
expect(parseInstanceRef(`personal:${STEAM_ID}`)).toEqual({ kind: "personal", steamId: STEAM_ID });
|
|
expect(parseInstanceRef("structure:superstructure")).toEqual({
|
|
kind: "structure",
|
|
slug: "superstructure",
|
|
});
|
|
expect(formatInstanceRef({ kind: "personal", steamId: "abc" })).toBe("personal:abc");
|
|
});
|
|
|
|
it("rejects malformed refs", () => {
|
|
expect(parseInstanceRef(null)).toBeNull();
|
|
expect(parseInstanceRef("nope")).toBeNull();
|
|
expect(parseInstanceRef("personal:")).toBeNull();
|
|
expect(parseInstanceRef("structure:Bad Slug!")).toBeNull();
|
|
expect(parseInstanceRef("other:x")).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("parseStockSnapshot", () => {
|
|
it("parses [[class, count], ...] and clamps counts", () => {
|
|
expect(
|
|
parseStockSnapshot([
|
|
[CLASS_A, 3],
|
|
[CLASS_B, 2.6],
|
|
]),
|
|
).toEqual([
|
|
{ className: CLASS_A, count: 3 },
|
|
{ className: CLASS_B, count: 3 },
|
|
]);
|
|
});
|
|
|
|
it("returns null for non-arrays and drops bad lines", () => {
|
|
expect(parseStockSnapshot("nope")).toBeNull();
|
|
expect(parseStockSnapshot([[CLASS_A, "x"], ["", 1], [CLASS_B, 2]])).toEqual([
|
|
{ className: CLASS_B, count: 2 },
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe("mergeStockIntoItems", () => {
|
|
it("preserves grid metadata, appends new classes, leaves unknown entries", () => {
|
|
const existing = [
|
|
{ asset: 1, quantity: 2, gridX: 3, gridY: 4, rotated: true, className: CLASS_A, equipment: { customName: "Frank's Karma" } },
|
|
{ asset: 9, quantity: 1, gridX: 0, gridY: 0, rotated: false, className: "other_class" },
|
|
];
|
|
const assetIds = new Map<string, number>([
|
|
[CLASS_A, 1],
|
|
[CLASS_B, 2],
|
|
]);
|
|
const merged = mergeStockIntoItems(
|
|
existing,
|
|
[
|
|
{ className: CLASS_A, count: 7 },
|
|
{ className: CLASS_B, count: 10 },
|
|
{ className: "no_such_asset", count: 1 },
|
|
],
|
|
assetIds,
|
|
);
|
|
expect(merged).toHaveLength(3);
|
|
expect(merged[0]).toMatchObject({ quantity: 7, gridX: 3, gridY: 4, rotated: true });
|
|
expect((merged[0].equipment as { customName: string }).customName).toBe("Frank's Karma");
|
|
expect(merged[1]).toMatchObject({ className: "other_class", quantity: 1 });
|
|
expect(merged[2]).toMatchObject({ asset: 2, quantity: 10, gridX: 0, gridY: 5, rotated: false });
|
|
});
|
|
});
|
|
|
|
describe("locker.sync (personal)", () => {
|
|
it("creates the linked user's locker from the first snapshot", async () => {
|
|
await expect(
|
|
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 2]]], 1)),
|
|
).resolves.toBeUndefined();
|
|
|
|
const lockers = await payload.find({
|
|
collection: "locker-storages",
|
|
where: { ownerUser: { equals: userId } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
expect(lockers.docs).toHaveLength(1);
|
|
lockerId = lockers.docs[0].id;
|
|
const doc = await lockerDoc();
|
|
expect(doc.itemCount).toBe(1);
|
|
expect(doc.items[0]).toMatchObject({ asset: assetAId, quantity: 2, gridX: 0, gridY: 0, rotated: false });
|
|
});
|
|
|
|
it("preserves web-managed grid metadata on later syncs", async () => {
|
|
await payload.update({
|
|
collection: "locker-storages",
|
|
id: lockerId,
|
|
data: {
|
|
items: [
|
|
{
|
|
asset: assetAId,
|
|
quantity: 2,
|
|
gridX: 3,
|
|
gridY: 4,
|
|
rotated: true,
|
|
equipment: { customName: "Frank's Karma" },
|
|
},
|
|
],
|
|
} as never,
|
|
// Fixture write, not an echo-guard test: suppress the locker.apply
|
|
// enqueue so this file's absolute command counts stay stable even
|
|
// when other spec files leave a game-server online.
|
|
context: { lockerSyncOrigin: true },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
|
|
await processLockerEvent(
|
|
payload,
|
|
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 7], [CLASS_B, 10]]], 1),
|
|
);
|
|
|
|
const doc = await lockerDoc();
|
|
expect(doc.itemCount).toBe(2);
|
|
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
|
|
expect(byAsset.get(assetAId)).toMatchObject({
|
|
quantity: 7,
|
|
gridX: 3,
|
|
gridY: 4,
|
|
rotated: true,
|
|
equipment: { customName: "Frank's Karma" },
|
|
});
|
|
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10, gridX: 0, gridY: 5, rotated: false });
|
|
});
|
|
|
|
it("treats absence as not-deletion and skips unknown classes", async () => {
|
|
await processLockerEvent(
|
|
payload,
|
|
lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1], ["no_such_class", 3]]], 1),
|
|
);
|
|
const doc = await lockerDoc();
|
|
expect(doc.itemCount).toBe(2);
|
|
const byAsset = new Map(doc.items.map((item) => [item.asset, item]));
|
|
expect(byAsset.get(assetAId)).toMatchObject({ quantity: 1 });
|
|
expect(byAsset.get(assetBId)).toMatchObject({ quantity: 10 });
|
|
});
|
|
|
|
it("skips unlinked Steam IDs without creating anything", async () => {
|
|
const before = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
|
|
await expect(
|
|
processLockerEvent(payload, lockerEvent("locker.sync", [`personal:${UNLINKED}`, [[CLASS_A, 5]]], 1)),
|
|
).resolves.toBeUndefined();
|
|
const after = await payload.find({ collection: "locker-storages", limit: 100, depth: 0, overrideAccess: true });
|
|
expect(after.totalDocs).toBe(before.totalDocs);
|
|
});
|
|
|
|
it("is idempotent for repeated snapshots", async () => {
|
|
const event = lockerEvent("locker.sync", [`personal:${STEAM_ID}`, [[CLASS_A, 1]]], 1);
|
|
await processLockerEvent(payload, event);
|
|
await processLockerEvent(payload, { ...event });
|
|
const doc = await lockerDoc();
|
|
expect(doc.itemCount).toBe(2);
|
|
});
|
|
});
|
|
|
|
describe("locker.sync (structure)", () => {
|
|
it("merges into game-structures storedAssets by storageSlug", async () => {
|
|
await processLockerEvent(
|
|
payload,
|
|
lockerEvent("locker.sync", [`structure:${SLUG}`, [[CLASS_A, 4]]], 1),
|
|
);
|
|
const structure = (await payload.findByID({
|
|
collection: "game-structures",
|
|
id: structureId,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as { storedAssets: Record<string, unknown>[]; storedAssetCount: number };
|
|
expect(structure.storedAssetCount).toBe(1);
|
|
expect(structure.storedAssets[0]).toMatchObject({ asset: assetAId, quantity: 4 });
|
|
});
|
|
|
|
it("skips unknown slugs without throwing", async () => {
|
|
await expect(
|
|
processLockerEvent(payload, lockerEvent("locker.sync", [`structure:${RUN}-missing`, [[CLASS_A, 4]]], 1)),
|
|
).resolves.toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("locker.request + locker.apply enqueue", () => {
|
|
it("enqueues exactly one locker.apply for the requesting server with current stock", async () => {
|
|
const server = await payload.create({
|
|
collection: "game-servers",
|
|
data: {
|
|
serverId: `${RUN}-srv`,
|
|
name: `${RUN} Test Server`,
|
|
status: "online",
|
|
lastSeenAt: new Date().toISOString(),
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
serverId = server.id;
|
|
|
|
// Delta-scoped, not absolute: earlier sections of this file enqueue their
|
|
// own applies once any game-server (ours or a foreign leftover) is online,
|
|
// so only rows created by THIS event may be counted.
|
|
const beforeIds = new Set((await findLockerApplyCommands()).map((command) => command.id));
|
|
|
|
await processLockerEvent(payload, lockerEvent("locker.request", [`personal:${STEAM_ID}`], serverId));
|
|
|
|
const commands = (await findLockerApplyCommands()).filter(
|
|
(command) => !beforeIds.has(command.id),
|
|
);
|
|
commandIds.push(...commands.map((command) => command.id));
|
|
expect(commands).toHaveLength(1);
|
|
const [instanceRef, stock] = commands[0].payload as [string, [string, number][]];
|
|
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
|
|
expect(stock).toContainEqual([CLASS_A, 1]);
|
|
expect(stock).toContainEqual([CLASS_B, 10]);
|
|
});
|
|
|
|
it("enqueues nothing for unknown instances", async () => {
|
|
const beforeIds = new Set((await findLockerApplyCommands()).map((command) => command.id));
|
|
await processLockerEvent(payload, lockerEvent("locker.request", [`structure:${RUN}-missing`], serverId));
|
|
const fresh = (await findLockerApplyCommands()).filter((command) => !beforeIds.has(command.id));
|
|
expect(fresh).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe("echo guard", () => {
|
|
it("web-originated locker edits enqueue locker.apply; sync-origin writes do not", async () => {
|
|
const beforeCommands = await findLockerApplyCommands();
|
|
const beforeIds = new Set(beforeCommands.map((command) => command.id));
|
|
|
|
const doc = await lockerDoc();
|
|
await payload.update({
|
|
collection: "locker-storages",
|
|
id: lockerId,
|
|
data: {
|
|
items: doc.items.map((item) =>
|
|
item.asset === assetAId ? { ...item, quantity: 42 } : item,
|
|
),
|
|
} as never,
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
const afterEdit = await findLockerApplyCommands();
|
|
const newCommands = afterEdit.filter((command) => !beforeIds.has(command.id));
|
|
commandIds.push(...newCommands.map((command) => command.id));
|
|
expect(newCommands).toHaveLength(1);
|
|
const [instanceRef, stock] = newCommands[0].payload as [string, [string, number][]];
|
|
expect(instanceRef).toBe(`personal:${STEAM_ID}`);
|
|
expect(stock).toContainEqual([CLASS_A, 42]);
|
|
|
|
const docAgain = await lockerDoc();
|
|
await payload.update({
|
|
collection: "locker-storages",
|
|
id: lockerId,
|
|
data: {
|
|
items: docAgain.items.map((item) =>
|
|
item.asset === assetAId ? { ...item, quantity: 43 } : item,
|
|
),
|
|
} as never,
|
|
context: { lockerSyncOrigin: true },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
const afterSyncWrite = await findLockerApplyCommands();
|
|
expect(afterSyncWrite.filter((command) => !beforeIds.has(command.id))).toHaveLength(1);
|
|
});
|
|
});
|
|
});
|