1
0
Fork 0

feat(game-structures): add item storage model with per-structure access control

New item storage (limited-arsenal stock) on game-structures: a unique
storageSlug identifying the structure to the game bridge, an Item Storage
Access group (anyone / specific roles / specific users) backed by
canAccessStructureStorage, a storedAssets array (asset, quantity, grid
position, rotation, per-instance attachments/skin/custom name) with a
storedAssetCount rollup, and a beforeChange hook that pushes a locker.apply
command to the game whenever web-originated stock changes. Migration
20261005_051452_add_game_structure_item_storage.
This commit is contained in:
Jason Fraley 2026-10-05 03:19:32 -04:00
parent 5963082f9d
commit 4755cb681a
3 changed files with 37132 additions and 2 deletions

View file

@ -1,11 +1,63 @@
import type { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import type { CollectionConfig, PayloadRequest } from "payload";
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
import { emitGameEvent } from "@/utils/event-log/emit";
import { staffingDefaultsFromBlueprint } from "@/lib/base/staffingDefaults";
import { createStaffingFields } from "./staffingFields";
import { createProductionFields } from "./productionFields";
import { createModuleFields } from "./moduleFields";
import { productionDefaultsFromBlueprint } from "@/lib/base/productionDefaults";
import { enqueueLockerApplyForStructureDoc, isLockerSyncOrigin } from "@/lib/arma-bridge/lockers";
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Field-level gate for storedAssets (web UI only — bridge sync writes use
* overrideAccess and are unaffected). Admins with game-structures:update
* always pass; otherwise the structure's storageAccess mode decides:
* anyone / specific roles (matched against the user's roleDocs) / specific
* users. A "faction" mode is deliberately not offered yet: members have no
* faction linkage in the users/profiles model, so it could not be evaluated.
*/
async function canAccessStructureStorage({
req,
doc,
}: {
req: PayloadRequest;
doc?: Record<string, unknown> | null;
}): Promise<boolean> {
const user = req.user;
if (!user) return false;
if (await hasPermission(req.payload, user, "game-structures:update")) return true;
const access = (doc?.storageAccess ?? undefined) as
| { mode?: string; roles?: unknown; users?: unknown }
| undefined;
const mode = access?.mode ?? "anyone";
if (mode === "anyone") return true;
if (mode === "roles") {
const allowed = (Array.isArray(access?.roles) ? (access.roles as unknown[]) : [])
.map(relId)
.filter((v): v is number => v != null);
const userRoles = (Array.isArray((user as { roleDocs?: unknown }).roleDocs)
? ((user as { roleDocs: unknown[] }).roleDocs as unknown[])
: []
)
.map(relId)
.filter((v): v is number => v != null);
return allowed.length > 0 && userRoles.some((role) => allowed.includes(role));
}
if (mode === "users") {
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
return allowed.includes(user.id);
}
return false;
}
export const GameStructures: CollectionConfig = {
slug: "game-structures",
@ -80,6 +132,17 @@ export const GameStructures: CollectionConfig = {
},
});
},
// Locker sync (docs/arma-bridge/locker-sync.md): web-originated
// storedAssets edits push a locker.apply command to the game. Writes
// that came from a locker.sync merge are marked in req.context and
// skipped so they never echo back.
async ({ doc, previousDoc, req }) => {
if (isLockerSyncOrigin(req)) return;
const d = doc as Record<string, unknown>;
const prev = (previousDoc ?? {}) as Record<string, unknown>;
if (JSON.stringify(prev.storedAssets ?? []) === JSON.stringify(d.storedAssets ?? [])) return;
await enqueueLockerApplyForStructureDoc(req.payload, doc);
},
],
},
fields: [
@ -302,5 +365,176 @@ export const GameStructures: CollectionConfig = {
},
],
},
{
name: "storageSlug",
type: "text",
unique: true,
index: true,
validate: (value: unknown) =>
value == null ||
value === "" ||
(typeof value === "string" && /^[a-z0-9][a-z0-9-_]{1,63}$/.test(value)) ||
"2-64 chars: lowercase letters, digits, '-' and '_', starting with a letter or digit.",
admin: {
description:
"Slug identifying this structure's item storage to the game bridge (e.g. 'superstructure'). The in-game arsenal module binds to structure:<slug>. Empty = no item storage.",
},
},
{
name: "storageAccess",
type: "group",
label: "Item Storage Access",
admin: {
description:
"Who can see and edit this structure's item storage in the member UI. Bridge (game) sync is unaffected by these rules.",
},
fields: [
{
name: "mode",
type: "select",
// NOT required and no required parent: a required mode makes the
// whole storageAccess group required in generated create-data types,
// which breaks every existing game-structures create call site
// (Payload 3.88 draft-overload gotcha). Runtime treats empty as
// "anyone" (see canAccessStructureStorage).
defaultValue: "anyone",
options: [
{ label: "Anyone (all members)", value: "anyone" },
{ label: "Specific roles", value: "roles" },
{ label: "Specific users", value: "users" },
],
},
{
name: "roles",
type: "relationship",
relationTo: "roles",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "roles",
description: "Members holding any of these roles (Role Assignments) can access the storage.",
},
},
{
name: "users",
type: "relationship",
relationTo: "users",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "users",
description: "Only these members can access the storage.",
},
},
],
},
{
name: "storedAssets",
type: "array",
access: {
read: canAccessStructureStorage,
create: canAccessStructureStorage,
update: canAccessStructureStorage,
},
admin: {
description:
"Arma item storage (limited-arsenal stock). Synced with the game via locker.sync / locker.apply; grid position and equipment are managed from the member UI and preserved by sync merges.",
},
fields: [
{
name: "asset",
type: "relationship",
relationTo: "assets",
required: true,
},
{
name: "quantity",
type: "number",
required: true,
min: 1,
defaultValue: 1,
},
{
name: "gridX",
type: "number",
required: true,
min: 0,
defaultValue: 0,
admin: {
description: "Column position in the storage grid (0-indexed).",
},
},
{
name: "gridY",
type: "number",
required: true,
min: 0,
defaultValue: 0,
admin: {
description: "Row position in the storage grid (0-indexed).",
},
},
{
name: "rotated",
type: "checkbox",
defaultValue: false,
admin: {
description: "Whether this item is rotated 90 degrees (swaps width and height).",
},
},
{
name: "equipment",
type: "group",
label: "Equipment Customization",
admin: {
description:
"Per-instance customization for this item: installed attachments, applied skin, and a custom name. Managed from the member storage UI.",
},
fields: [
{
name: "attachments",
type: "array",
label: "Installed Attachments",
fields: [
{
name: "asset",
type: "relationship",
relationTo: "assets",
required: true,
},
],
},
{
name: "skin",
type: "relationship",
relationTo: "assets",
filterOptions: {
assetType: {
equals: "skin",
},
},
},
{
name: "customName",
type: "text",
},
],
},
],
},
{
name: "storedAssetCount",
type: "number",
admin: {
readOnly: true,
description: "Total number of distinct entries currently in item storage.",
},
hooks: {
beforeChange: [
({ data }) => {
const items = (data as { storedAssets?: unknown[] } | undefined)?.storedAssets;
return Array.isArray(items) ? items.length : 0;
},
],
},
},
],
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,74 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_game_structures_storage_access_mode" AS ENUM('anyone', 'roles', 'users');
CREATE TABLE "game_structures_stored_assets_equipment_attachments" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"asset_id" integer NOT NULL
);
CREATE TABLE "game_structures_stored_assets" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"asset_id" integer NOT NULL,
"quantity" numeric DEFAULT 1 NOT NULL,
"grid_x" numeric DEFAULT 0 NOT NULL,
"grid_y" numeric DEFAULT 0 NOT NULL,
"rotated" boolean DEFAULT false,
"equipment_skin_id" integer,
"equipment_custom_name" varchar
);
CREATE TABLE "game_structures_rels" (
"id" serial PRIMARY KEY NOT NULL,
"order" integer,
"parent_id" integer NOT NULL,
"path" varchar NOT NULL,
"roles_id" integer,
"users_id" integer
);
ALTER TABLE "game_structures" ADD COLUMN "storage_slug" varchar;
ALTER TABLE "game_structures" ADD COLUMN "storage_access_mode" "enum_game_structures_storage_access_mode" DEFAULT 'anyone';
ALTER TABLE "game_structures" ADD COLUMN "stored_asset_count" numeric;
ALTER TABLE "game_structures_stored_assets_equipment_attachments" ADD CONSTRAINT "game_structures_stored_assets_equipment_attachments_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets_equipment_attachments" ADD CONSTRAINT "game_structures_stored_assets_equipment_attachments_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."game_structures_stored_assets"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_equipment_skin_id_assets_id_fk" FOREIGN KEY ("equipment_skin_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "game_structures_stored_assets" ADD CONSTRAINT "game_structures_stored_assets_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."game_structures"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_parent_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."game_structures"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_roles_fk" FOREIGN KEY ("roles_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "game_structures_rels" ADD CONSTRAINT "game_structures_rels_users_fk" FOREIGN KEY ("users_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "game_structures_stored_assets_equipment_attachments_order_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("_order");
CREATE INDEX "game_structures_stored_assets_equipment_attachments_parent_id_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("_parent_id");
CREATE INDEX "game_structures_stored_assets_equipment_attachments_asse_idx" ON "game_structures_stored_assets_equipment_attachments" USING btree ("asset_id");
CREATE INDEX "game_structures_stored_assets_order_idx" ON "game_structures_stored_assets" USING btree ("_order");
CREATE INDEX "game_structures_stored_assets_parent_id_idx" ON "game_structures_stored_assets" USING btree ("_parent_id");
CREATE INDEX "game_structures_stored_assets_asset_idx" ON "game_structures_stored_assets" USING btree ("asset_id");
CREATE INDEX "game_structures_stored_assets_equipment_equipment_skin_idx" ON "game_structures_stored_assets" USING btree ("equipment_skin_id");
CREATE INDEX "game_structures_rels_order_idx" ON "game_structures_rels" USING btree ("order");
CREATE INDEX "game_structures_rels_parent_idx" ON "game_structures_rels" USING btree ("parent_id");
CREATE INDEX "game_structures_rels_path_idx" ON "game_structures_rels" USING btree ("path");
CREATE INDEX "game_structures_rels_roles_id_idx" ON "game_structures_rels" USING btree ("roles_id");
CREATE INDEX "game_structures_rels_users_id_idx" ON "game_structures_rels" USING btree ("users_id");
CREATE UNIQUE INDEX "game_structures_storage_slug_idx" ON "game_structures" USING btree ("storage_slug");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_structures_stored_assets_equipment_attachments" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "game_structures_stored_assets" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "game_structures_rels" DISABLE ROW LEVEL SECURITY;
DROP TABLE "game_structures_stored_assets_equipment_attachments" CASCADE;
DROP TABLE "game_structures_stored_assets" CASCADE;
DROP TABLE "game_structures_rels" CASCADE;
DROP INDEX "game_structures_storage_slug_idx";
ALTER TABLE "game_structures" DROP COLUMN "storage_slug";
ALTER TABLE "game_structures" DROP COLUMN "storage_access_mode";
ALTER TABLE "game_structures" DROP COLUMN "stored_asset_count";
DROP TYPE "public"."enum_game_structures_storage_access_mode";`)
}