Vehicles gain a virtual-block disallowedCargo array (asset/vehicle/resource item + optional amount cap, 0 forbids outright). createShipment consults findDisallowedCargo() before deducting any origin stock and rejects matching cargo lines cleanly. Includes Payload migration + 7 integration tests.
362 lines
12 KiB
TypeScript
362 lines
12 KiB
TypeScript
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
|
|
import type { Payload } from "payload";
|
|
import type {
|
|
GameStructure,
|
|
GameVehicle,
|
|
Resource,
|
|
Role,
|
|
User,
|
|
Vehicle,
|
|
} from "@/payload-types";
|
|
import { createShipment } from "@/app/(frontend)/logistics/shipments/actions";
|
|
import { findDisallowedCargo, type CargoLine } from "@/lib/shipping/cargo";
|
|
|
|
// Mock next/headers so createShipment's authenticate() can run outside a request.
|
|
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
|
|
|
|
const RUN = `cargo-blacklist-${Date.now().toString(36)}`;
|
|
|
|
let payload: Payload;
|
|
let authSpy: MockInstance;
|
|
|
|
const mapIds: number[] = [];
|
|
const resourceIds: number[] = [];
|
|
const structureIds: number[] = [];
|
|
const vehicleTypeIds: number[] = [];
|
|
const userIds: number[] = [];
|
|
|
|
let mapId: number;
|
|
let resourceId: number;
|
|
let originId: number;
|
|
let destinationId: number;
|
|
let blacklistTypeId: number;
|
|
let cleanTypeId: number;
|
|
let commandUser: User;
|
|
|
|
const LEXICAL_EMPTY = {
|
|
root: {
|
|
children: [{ text: "" }],
|
|
direction: null,
|
|
format: "" as const,
|
|
indent: 0,
|
|
type: "text",
|
|
version: 1,
|
|
},
|
|
};
|
|
|
|
function relId(value: unknown): number {
|
|
return typeof value === "object" && value !== null
|
|
? (value as { id: number }).id
|
|
: (value as number);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Pure unit tests for the matching logic (no DB required)
|
|
// ---------------------------------------------------------------------------
|
|
describe("findDisallowedCargo (pure)", () => {
|
|
const cargo = (value: number, amount = 5): CargoLine[] => [
|
|
{ relationTo: "resources", value, amount },
|
|
];
|
|
|
|
it("returns null when there is no blacklist", () => {
|
|
expect(findDisallowedCargo(null, cargo(1))).toBeNull();
|
|
expect(findDisallowedCargo([], cargo(1))).toBeNull();
|
|
});
|
|
|
|
it("forbids an item entirely when the cap is 0", () => {
|
|
expect(
|
|
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 0 }], cargo(7)),
|
|
).toEqual({ relationTo: "resources", itemId: 7, cap: 0 });
|
|
});
|
|
|
|
it("allows quantity at or below the cap and forbids the excess", () => {
|
|
const atCap: CargoLine[] = [{ relationTo: "resources", value: 7, amount: 3 }];
|
|
expect(
|
|
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 3 }], atCap),
|
|
).toBeNull();
|
|
|
|
const overCap: CargoLine[] = [{ relationTo: "resources", value: 7, amount: 4 }];
|
|
expect(
|
|
findDisallowedCargo([{ item: { relationTo: "resources", value: 7 }, amount: 3 }], overCap),
|
|
).toEqual({ relationTo: "resources", itemId: 7, cap: 3 });
|
|
});
|
|
|
|
it("matches by relationTo and id, ignoring unrelated entries", () => {
|
|
const twoLines: CargoLine[] = [
|
|
{ relationTo: "resources", value: 7, amount: 5 },
|
|
{ relationTo: "assets", value: 9, amount: 5 },
|
|
];
|
|
|
|
// Same id, wrong relationTo -> no match.
|
|
expect(
|
|
findDisallowedCargo([{ item: { relationTo: "vehicles", value: 7 }, amount: 0 }], twoLines),
|
|
).toBeNull();
|
|
|
|
// The asset line is blacklisted -> matches only that line.
|
|
expect(
|
|
findDisallowedCargo([{ item: { relationTo: "assets", value: 9 }, amount: 0 }], twoLines),
|
|
).toEqual({ relationTo: "assets", itemId: 9, cap: 0 });
|
|
});
|
|
|
|
it("tolerates a stored relationship shape (item.value as { id })", () => {
|
|
expect(
|
|
findDisallowedCargo(
|
|
[{ item: { relationTo: "resources", value: { id: 12 } }, amount: 0 }],
|
|
cargo(12),
|
|
),
|
|
).toEqual({ relationTo: "resources", itemId: 12, cap: 0 });
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// createShipment enforcement (integration)
|
|
// ---------------------------------------------------------------------------
|
|
describe("createShipment vehicle cargo blacklist", () => {
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
authSpy = vi.spyOn(payload, "auth");
|
|
|
|
const role = (await payload.create({
|
|
collection: "roles",
|
|
data: { name: `${RUN} Cmd`, slug: `${RUN}-cmd`, isSuperuser: true },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Role;
|
|
userIds.push(role.id);
|
|
|
|
commandUser = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-cmd`,
|
|
displayName: `${RUN} Cmd`,
|
|
discordUsername: `${RUN}-cmd`,
|
|
steamId: `${RUN}-steam`,
|
|
password: "Test1234",
|
|
roles: ["user"],
|
|
roleDocs: [role.id],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User;
|
|
userIds.push(commandUser.id);
|
|
|
|
authSpy.mockResolvedValue({ user: commandUser });
|
|
|
|
const map = (await payload.create({
|
|
collection: "maps",
|
|
data: {
|
|
name: `${RUN} Map`,
|
|
worldSizeWidth: 20480,
|
|
worldSizeHeight: 20480,
|
|
basemapMode: "tiles",
|
|
tileUrlTemplate: "http://localhost/{z}/{x}/{y}.png",
|
|
isActive: false,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as { id: number };
|
|
mapId = map.id;
|
|
mapIds.push(mapId);
|
|
|
|
const fuel = (await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: `${RUN} Diesel`,
|
|
codeName: `${RUN}-diesel`,
|
|
approvalStatus: "in_progress",
|
|
type: "physical",
|
|
baseValue: 1,
|
|
rarity: "common",
|
|
unitOfMeasure: "kg",
|
|
massPerUnit: 1,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Resource;
|
|
resourceId = fuel.id;
|
|
resourceIds.push(resourceId);
|
|
|
|
// A second resource, used to prove the clean vehicle blacklist targets a
|
|
// specific item (FK requires the referenced resource to exist).
|
|
const otherResource = (await payload.create({
|
|
collection: "resources",
|
|
data: {
|
|
name: `${RUN} Gravel`,
|
|
codeName: `${RUN}-gravel`,
|
|
approvalStatus: "in_progress",
|
|
type: "physical",
|
|
baseValue: 1,
|
|
rarity: "common",
|
|
unitOfMeasure: "kg",
|
|
massPerUnit: 1,
|
|
gridWidth: 1,
|
|
gridHeight: 1,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Resource;
|
|
const otherResourceId = otherResource.id;
|
|
resourceIds.push(otherResourceId);
|
|
|
|
const blueprint = (await payload.create({
|
|
collection: "structures",
|
|
data: {
|
|
name: `${RUN} Depot`,
|
|
codeName: `${RUN}-depot`,
|
|
approvalStatus: "in_progress",
|
|
description: LEXICAL_EMPTY as unknown as never,
|
|
category: "logistics",
|
|
materials: [{ resource: resourceId, amount: 1 }],
|
|
constructionDurationMinutes: 60,
|
|
terrainType: "land",
|
|
maxHealth: 100,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as { id: number };
|
|
|
|
const origin = (await payload.create({
|
|
collection: "game-structures",
|
|
data: { name: `${RUN} Origin`, type: blueprint.id, map: mapId, coordinates: [2000, 2000] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as GameStructure;
|
|
originId = origin.id;
|
|
structureIds.push(originId);
|
|
|
|
const destination = (await payload.create({
|
|
collection: "game-structures",
|
|
data: { name: `${RUN} Destination`, type: blueprint.id, map: mapId, coordinates: [18000, 18000] },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as GameStructure;
|
|
destinationId = destination.id;
|
|
structureIds.push(destinationId);
|
|
|
|
// Vehicle template that forbids the fuel resource entirely.
|
|
const blacklistType = (await payload.create({
|
|
collection: "vehicles",
|
|
data: {
|
|
name: `${RUN} Banned`,
|
|
approvalStatus: "in_progress",
|
|
transportMode: "air",
|
|
maxSpeedOnRoad: 60,
|
|
fuel: { fuelType: resourceId, fuelCapacity: 100000, fuelConsumptionRate: 0.01 },
|
|
disallowedCargo: [{ item: { relationTo: "resources", value: resourceId }, amount: 0 }],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Vehicle;
|
|
blacklistTypeId = blacklistType.id;
|
|
vehicleTypeIds.push(blacklistTypeId);
|
|
|
|
// Vehicle template that forbids a *different* resource, so the fuel is allowed.
|
|
const cleanType = (await payload.create({
|
|
collection: "vehicles",
|
|
data: {
|
|
name: `${RUN} Clean`,
|
|
approvalStatus: "in_progress",
|
|
transportMode: "air",
|
|
maxSpeedOnRoad: 60,
|
|
fuel: { fuelType: resourceId, fuelCapacity: 100000, fuelConsumptionRate: 0.01 },
|
|
disallowedCargo: [{ item: { relationTo: "resources", value: otherResourceId }, amount: 0 }],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Vehicle;
|
|
cleanTypeId = cleanType.id;
|
|
vehicleTypeIds.push(cleanTypeId);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
for (const id of vehicleTypeIds)
|
|
await payload.delete({ collection: "vehicles", id, overrideAccess: true }).catch(() => {});
|
|
for (const id of structureIds)
|
|
await payload.delete({ collection: "game-structures", id, overrideAccess: true }).catch(() => {});
|
|
for (const id of resourceIds)
|
|
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
|
|
for (const id of mapIds)
|
|
await payload.delete({ collection: "maps", id, overrideAccess: true }).catch(() => {});
|
|
for (const id of userIds)
|
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
|
});
|
|
|
|
const makeGameVehicle = async (typeId: number, atOriginId: number): Promise<GameVehicle> =>
|
|
(await payload.create({
|
|
collection: "game-vehicles",
|
|
data: {
|
|
name: `GV ${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
type: typeId,
|
|
deployedAt: atOriginId,
|
|
status: "idle",
|
|
currentFuel: 100000,
|
|
currentHealth: 100,
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as GameVehicle;
|
|
|
|
const resourceCargo = (value: number, amount = 10) =>
|
|
[{ relationTo: "resources" as const, value, amount }];
|
|
|
|
it("rejects a shipment whose vehicle may not carry the cargo (before anything is deducted)", async () => {
|
|
const vehicle = await makeGameVehicle(blacklistTypeId, originId);
|
|
|
|
const result = await createShipment({
|
|
originId,
|
|
destinationId,
|
|
vehicleId: vehicle.id,
|
|
cargo: resourceCargo(resourceId, 10),
|
|
});
|
|
|
|
expect(result.success).toBe(false);
|
|
expect(result.error).toMatch(/may not carry/i);
|
|
expect(result.error).toContain(String(resourceId));
|
|
|
|
// Nothing was deducted and no shipment was created: the vehicle is untouched.
|
|
const after = (await payload.findByID({
|
|
collection: "game-vehicles",
|
|
id: vehicle.id,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as GameVehicle;
|
|
expect(after.status).toBe("idle");
|
|
expect(relId(after.deployedAt)).toBe(originId);
|
|
});
|
|
|
|
it("allows a shipment when the cargo is not blacklisted", async () => {
|
|
const vehicle = await makeGameVehicle(cleanTypeId, originId);
|
|
|
|
// Seed the origin with the cargo so the origin-stock and destination checks pass.
|
|
await payload.update({
|
|
collection: "game-structures",
|
|
id: originId,
|
|
data: {
|
|
storedResources: [
|
|
{ resource: resourceId, amount: 100, gridX: 0, gridY: 0, rotated: false },
|
|
],
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
|
|
const result = await createShipment({
|
|
originId,
|
|
destinationId,
|
|
vehicleId: vehicle.id,
|
|
cargo: resourceCargo(resourceId, 10),
|
|
});
|
|
|
|
expect(result.success).toBe(true);
|
|
|
|
const after = (await payload.findByID({
|
|
collection: "game-vehicles",
|
|
id: vehicle.id,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as GameVehicle;
|
|
expect(after.status).toBe("in_transit");
|
|
});
|
|
});
|