1
0
Fork 0

feat(vehicles): add per-vehicle disallowed-cargo blacklist enforced at shipment

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.
This commit is contained in:
Jason Fraley 2026-10-26 22:17:21 -04:00
parent 02ef9f4954
commit 40b074a693
8 changed files with 45421 additions and 1 deletions

View file

@ -8,6 +8,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { calculateDistance } from "@/lib/distance";
import { calculateFuelCost, calculateTransitTime, getVehicleEffectiveSpeed } from "@/lib/shipping";
import { findDisallowedCargo } from "@/lib/shipping/cargo";
import { checkStorageDeposit, storageViolationMessage } from "@/lib/storageRules";
import { effectiveMaxMass } from "@/lib/base/modules";
import { buildRoadGraph, findRoute } from "@/lib/map/routing";
@ -213,6 +214,18 @@ export async function createShipment(params: {
};
}
// Reject cargo the vehicle template is not permitted to carry. Checked
// before any origin stock is deducted so a blacklisted manifest never
// mutates state. `disallowedCargo` lives on the Vehicle template; amount 0
// forbids an item entirely, a positive amount caps it.
const disallowed = findDisallowedCargo(vehicleType.disallowedCargo, cargo);
if (disallowed) {
return {
success: false,
error: `Vehicle "${vehicleType.name}" may not carry ${disallowed.relationTo} #${disallowed.itemId}${disallowed.cap > 0 ? ` (over its ${disallowed.cap} cap)` : ""}.`,
};
}
// Validate cargo exists at origin
const storedResources = origin.storedResources ?? [];
for (const cargoItem of cargo) {

View file

@ -365,6 +365,32 @@ export const Vehicles: CollectionConfig = {
},
],
},
{
name: "disallowedCargo",
label: "Disallowed Virtual Cargo",
type: "array",
admin: {
description:
"Items this vehicle may NOT carry when used virtually (e.g., during deliveries, moving troops). A shipment using this vehicle is rejected before its cargo is deducted if any cargo line matches.",
},
fields: [
{
name: "item",
type: "relationship",
relationTo: ["assets", "vehicles", "resources"],
required: true,
},
{
name: "amount",
type: "number",
defaultValue: 0,
admin: {
description:
"Optional cap. Leave at 0 to forbid the item entirely; set a positive number to allow up to that amount only.",
},
},
],
},
],
},
],

75
src/lib/shipping/cargo.ts Normal file
View file

@ -0,0 +1,75 @@
/**
* Pure helpers for vehicle virtual-cargo rules.
*
* Kept free of Payload/DB access so the enforcement seam in
* `createShipment` can be reasoned about (and unit-tested) in isolation.
*/
/** A shipment cargo line, as passed to `createShipment`. */
export interface CargoLine {
relationTo: string;
value: number | { id: number } | null;
amount: number;
}
/** A single entry on a vehicle template's `disallowedCargo` array. */
export interface DisallowedCargoEntry {
item: { relationTo: string; value: number | { id: number } } | number | null;
amount?: number | null;
}
/**
* Resolve a disallowed-cargo entry's item to a comparable `(relationTo, id)`
* pair, tolerating the raw relationship shape stored on the vehicle template.
*/
function normalizedItem(entry: DisallowedCargoEntry): { relationTo: string; id: number } | null {
const item = entry.item;
if (!item || typeof item !== "object") return null;
const relationTo = item.relationTo;
const raw = (item as { value?: number | { id?: number } | null }).value;
const id = typeof raw === "number" ? raw : raw?.id;
if (relationTo == null || id == null) return null;
return { relationTo, id };
}
export interface DisallowedMatch {
relationTo: string;
itemId: number;
/** Amount the entry permits (0 = full ban). */
cap: number;
}
/**
* Return the first cargo line that a vehicle template forbids, or `null` when
* the cargo is permitted.
*
* A line matches a `disallowedCargo` entry when the `(relationTo, itemId)` pair
* is equal. An entry with `amount === 0` (the default) forbids the item
* entirely; an entry with `amount > 0` only forbids quantities above that cap.
*/
export function findDisallowedCargo(
disallowedCargo: DisallowedCargoEntry[] | null | undefined,
cargo: CargoLine[],
): DisallowedMatch | null {
if (!disallowedCargo || disallowedCargo.length === 0 || !cargo.length) return null;
for (const line of cargo) {
const itemId =
typeof line.value === "number" ? line.value : (line.value as { id: number } | null)?.id;
if (itemId == null) continue;
const match = disallowedCargo.find((entry) => {
const resolved = normalizedItem(entry);
return resolved && resolved.relationTo === line.relationTo && resolved.id === itemId;
});
if (!match) continue;
const cap = match.amount ?? 0;
if (cap === 0 || line.amount > cap) {
return { relationTo: line.relationTo, itemId, cap };
}
}
return null;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,20 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TABLE "vehicles_disallowed_cargo" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"amount" numeric DEFAULT 0
);
ALTER TABLE "vehicles_disallowed_cargo" ADD CONSTRAINT "vehicles_disallowed_cargo_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."vehicles"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "vehicles_disallowed_cargo_order_idx" ON "vehicles_disallowed_cargo" USING btree ("_order");
CREATE INDEX "vehicles_disallowed_cargo_parent_id_idx" ON "vehicles_disallowed_cargo" USING btree ("_parent_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP TABLE "vehicles_disallowed_cargo" CASCADE;`)
}

View file

@ -149,6 +149,7 @@ import * as migration_20261020_200000_add_interior_asset_outputs_flag from './20
import * as migration_20261020_201242_add_room_fixture_blocks_station from './20261020_201242_add_room_fixture_blocks_station';
import * as migration_20261022_170228_add_vehicle_mod_field from './20261022_170228_add_vehicle_mod_field';
import * as migration_20261026_073228_add_vehicle_category_static_and_drone from './20261026_073228_add_vehicle_category_static_and_drone';
import * as migration_20261026_195910_add_vehicle_disallowed_cargo_field from './20261026_195910_add_vehicle_disallowed_cargo_field';
export const migrations = [
{
@ -904,6 +905,11 @@ export const migrations = [
{
up: migration_20261026_073228_add_vehicle_category_static_and_drone.up,
down: migration_20261026_073228_add_vehicle_category_static_and_drone.down,
name: '20261026_073228_add_vehicle_category_static_and_drone'
name: '20261026_073228_add_vehicle_category_static_and_drone',
},
{
up: migration_20261026_195910_add_vehicle_disallowed_cargo_field.up,
down: migration_20261026_195910_add_vehicle_disallowed_cargo_field.down,
name: '20261026_195910_add_vehicle_disallowed_cargo_field',
},
];

View file

@ -2518,6 +2518,31 @@ export interface Vehicle {
id?: string | null;
}[]
| null;
/**
* Items this vehicle may NOT carry when used virtually (e.g., during deliveries, moving troops). A shipment using this vehicle is rejected before its cargo is deducted if any cargo line matches.
*/
disallowedCargo?:
| {
item:
| {
relationTo: 'assets';
value: number | Asset;
}
| {
relationTo: 'vehicles';
value: number | Vehicle;
}
| {
relationTo: 'resources';
value: number | Resource;
};
/**
* Optional cap. Leave at 0 to forbid the item entirely; set a positive number to allow up to that amount only.
*/
amount?: number | null;
id?: string | null;
}[]
| null;
maxHealth?: number | null;
armorRating?: ('none' | 'light' | 'medium' | 'heavy' | 'composite') | null;
maxSpeedOnRoad?: number | null;
@ -10930,6 +10955,13 @@ export interface VehiclesSelect<T extends boolean = true> {
amount?: T;
id?: T;
};
disallowedCargo?:
| T
| {
item?: T;
amount?: T;
id?: T;
};
maxHealth?: T;
armorRating?: T;
maxSpeedOnRoad?: T;

View file

@ -0,0 +1,362 @@
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");
});
});