From 4f129fc59ac9ddb62dffc4d2aaea9c52373e9227 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Thu, 15 Oct 2026 10:01:02 -0400 Subject: [PATCH] feat(approval): reset reviewed documents to in progress on non-superuser edits Add resetApprovalStatusOnEdit(), a collection beforeChange hook factory: when a non-superuser updates a document whose stored approvalStatus is approved or revision_requested, the status is rewritten to in_progress so the edit goes through review again. Creates, superusers (system:admin-access), and system writes with no user (catalog imports, seeds) are exempt, and an explicit in_progress/ready_for_review in the edit is honored. Wired into Technologies, Assets, Resources, Vehicles, and Structures. Structures also moves from the legacy isDeveloper filterOptions gate to approvalStatusFieldAccess("structures"), matching the other four collections and removing the hard ValidationError when saving an already-approved structure. Tests: 12 cases in tests/int/division-admin-access.int.spec.ts. --- src/collections/intelligence/Technologies.ts | 4 + src/collections/logistics/Assets.ts | 4 + src/collections/logistics/Resources.ts | 4 + src/collections/logistics/Structures.ts | 17 +- src/collections/logistics/Vehicles.ts | 4 + src/utils/access-control/divisionAccess.ts | 57 +++- tests/int/division-admin-access.int.spec.ts | 301 ++++++++++++++++++- 7 files changed, 378 insertions(+), 13 deletions(-) diff --git a/src/collections/intelligence/Technologies.ts b/src/collections/intelligence/Technologies.ts index 8bc6eb3c..4d8fab32 100644 --- a/src/collections/intelligence/Technologies.ts +++ b/src/collections/intelligence/Technologies.ts @@ -4,6 +4,7 @@ import { approvalStatusFieldAccess, requireApprovalPermission, requireIntelligencePermission, + resetApprovalStatusOnEdit, } from "@/utils/access-control/divisionAccess"; const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("technologies"); @@ -20,6 +21,9 @@ export const Technologies: CollectionConfig = { delete: requireIntelligencePermission("technologies:delete"), read: requirePermission("technologies:read"), }, + hooks: { + beforeChange: [resetApprovalStatusOnEdit()], + }, fields: [ { name: "name", diff --git a/src/collections/logistics/Assets.ts b/src/collections/logistics/Assets.ts index 5741ef0e..18f53858 100644 --- a/src/collections/logistics/Assets.ts +++ b/src/collections/logistics/Assets.ts @@ -3,6 +3,7 @@ import { approvalStatusFieldAccess, requireApprovalPermission, requireLogisticsPermission, + resetApprovalStatusOnEdit, } from "@/utils/access-control/divisionAccess"; const approvalFieldAccess = { @@ -23,6 +24,9 @@ export const Assets: CollectionConfig = { update: requireLogisticsPermission("assets:update"), delete: requireLogisticsPermission("assets:delete"), }, + hooks: { + beforeChange: [resetApprovalStatusOnEdit()], + }, fields: [ { name: "name", diff --git a/src/collections/logistics/Resources.ts b/src/collections/logistics/Resources.ts index 678eb1d6..8896949d 100644 --- a/src/collections/logistics/Resources.ts +++ b/src/collections/logistics/Resources.ts @@ -5,6 +5,7 @@ import { approvalStatusFieldAccess, requireApprovalPermission, requireLogisticsPermission, + resetApprovalStatusOnEdit, } from "@/utils/access-control/divisionAccess"; const onlyIfNotPrimaryCurrency = async ({ req }: { req: PayloadRequest }) => { @@ -61,6 +62,9 @@ export const Resources: CollectionConfig = { update: logisticsWriteWithCurrencyGuard("resources:update"), delete: logisticsWriteWithCurrencyGuard("resources:delete"), }, + hooks: { + beforeChange: [resetApprovalStatusOnEdit()], + }, fields: [ { name: "NoEditWarning", diff --git a/src/collections/logistics/Structures.ts b/src/collections/logistics/Structures.ts index 4834266e..343b99c5 100644 --- a/src/collections/logistics/Structures.ts +++ b/src/collections/logistics/Structures.ts @@ -1,5 +1,5 @@ import { CollectionConfig } from "payload"; -import { isDeveloper } from "@/utils/access-control/isRole"; +import { approvalStatusFieldAccess, resetApprovalStatusOnEdit } from "@/utils/access-control/divisionAccess"; import type { Resource } from "@/payload-types"; import { emitGameEvent } from "@/utils/event-log/emit"; import { createStaffingFields } from "@/collections/game/staffingFields"; @@ -7,6 +7,8 @@ import { createProductionFields } from "@/collections/game/productionFields"; import { createModuleFields } from "@/collections/game/moduleFields"; import { createAuraFields } from "@/collections/game/auraFields"; +const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("structures"); + export const Structures: CollectionConfig = { slug: "structures", admin: { @@ -240,6 +242,9 @@ export const Structures: CollectionConfig = { return data; }, + // Editing a structure that is already approved / revision-requested + // resets it to in_progress unless the writer is a superuser. + resetApprovalStatusOnEdit(), ], }, fields: [ @@ -275,15 +280,7 @@ export const Structures: CollectionConfig = { { label: "Revision Requested", value: "revision_requested" }, ], defaultValue: "in_progress", - filterOptions: ({ options, data: _data, req }) => { - return !isDeveloper({ req }) - ? options.filter((option) => - typeof option === "string" - ? options - : ["in_progress", "ready_for_review"].includes(option.value), - ) - : options; - }, + access: approvalStatusFieldAccessConfig, required: true, admin: { description: diff --git a/src/collections/logistics/Vehicles.ts b/src/collections/logistics/Vehicles.ts index 1a367917..efccd660 100644 --- a/src/collections/logistics/Vehicles.ts +++ b/src/collections/logistics/Vehicles.ts @@ -3,6 +3,7 @@ import { approvalStatusFieldAccess, requireApprovalPermission, requireLogisticsPermission, + resetApprovalStatusOnEdit, } from "@/utils/access-control/divisionAccess"; const approvalStatusFieldAccessConfig = approvalStatusFieldAccess("vehicles"); @@ -18,6 +19,9 @@ export const Vehicles: CollectionConfig = { update: requireLogisticsPermission("vehicles:update"), delete: requireLogisticsPermission("vehicles:delete"), }, + hooks: { + beforeChange: [resetApprovalStatusOnEdit()], + }, fields: [ { // D11b: searchable imported-library picker (name, classname, thumbnail) diff --git a/src/utils/access-control/divisionAccess.ts b/src/utils/access-control/divisionAccess.ts index a701e680..1d9b0631 100644 --- a/src/utils/access-control/divisionAccess.ts +++ b/src/utils/access-control/divisionAccess.ts @@ -1,4 +1,11 @@ -import type { Access, AccessArgs, AccessResult, Payload, PayloadRequest } from "payload"; +import type { + Access, + AccessArgs, + AccessResult, + CollectionBeforeChangeHook, + Payload, + PayloadRequest, +} from "payload"; import type { Permission } from "@/permissions"; import { canAccessAdminPanel as canAccessAdminPanelByPermissions, @@ -110,6 +117,54 @@ export function approvalStatusFieldAccess(collectionSlug: string) { }; } +/** + * Approval statuses that a non-superuser edit invalidates: + * - `approved` the document is live/implemented, so an edit must be + * reviewed again before it stays live + * - `revision_requested` the author has changes to make, which is exactly the + * edit happening now + */ +const EDIT_INVALIDATED_APPROVAL_STATUSES = ["approved", "revision_requested"]; + +/** Statuses a non-superuser may legitimately land on while editing. */ +const EDITABLE_APPROVAL_STATUSES = ["in_progress", "ready_for_review"]; + +/** + * Collection `beforeChange` hook factory: when a NON-superuser updates a + * document whose stored `approvalStatus` is Approved or Revision Requested, + * rewrite the status back to "In Progress" so the edit is reviewed again. + * + * A hook is required rather than field-level access for two reasons: + * - Payload field access can only *strip* a field, never rewrite its value. + * - It only sees the incoming payload, so it cannot react to a partial update + * that omits `approvalStatus` entirely (the normal case for the tech tree + * lite editor and PATCH-style edits). + * + * Rules: + * - Update only; creates keep the existing default/access behavior. + * - Superusers (holders of `system:admin-access`) are exempt. + * - System writes with no `req.user` (catalog imports, seeds, scripts using + * `overrideAccess: true`) are exempt, so automation never resets a reviewed + * document. + * - If the edit explicitly sets an editable status (In Progress, Ready for + * Review), that choice is honored instead of forcing In Progress. + */ +export function resetApprovalStatusOnEdit(): CollectionBeforeChangeHook { + return async ({ req, data, originalDoc, operation }) => { + if (operation !== "update" || !req.user || !data) return data; + + const current = (originalDoc as { approvalStatus?: string } | null | undefined)?.approvalStatus; + if (!current || !EDIT_INVALIDATED_APPROVAL_STATUSES.includes(current)) return data; + + if (await hasPermission(req.payload, req.user, "system:admin-access")) return data; + + const incoming = data.approvalStatus as string | undefined; + if (incoming && EDITABLE_APPROVAL_STATUSES.includes(incoming)) return data; + + return { ...data, approvalStatus: "in_progress" }; + }; +} + /** * Same contract as `requireAdminPageAccess`, with one addition: for the four * division-scoped collections an admin-panel request also passes when the user diff --git a/tests/int/division-admin-access.int.spec.ts b/tests/int/division-admin-access.int.spec.ts index 0a08613b..f181b899 100644 --- a/tests/int/division-admin-access.int.spec.ts +++ b/tests/int/division-admin-access.int.spec.ts @@ -4,7 +4,7 @@ import config from "@/payload.config"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import type { Role, User } from "@/payload-types"; +import type { Role, Structure, User } from "@/payload-types"; import { approvalStatusFieldAccess, canAccessAdminPanel, @@ -20,6 +20,17 @@ let payload: Payload; const RUN = `div-${Date.now().toString(36)}`; const TIMEOUT = 30_000; +const LEXICAL_EMPTY = { + root: { + children: [{ text: "" }], + direction: null, + format: "" as const, + indent: 0, + type: "text", + version: 1, + }, +}; + describe("Division-scoped admin access (intelligence / logistics)", () => { const roleIds: number[] = []; const userIds: number[] = []; @@ -27,6 +38,7 @@ describe("Division-scoped admin access (intelligence / logistics)", () => { const resourceIds: number[] = []; const vehicleIds: number[] = []; const technologyIds: number[] = []; + const structureIds: number[] = []; const createdQualificationIds: number[] = []; let intelUser: User; @@ -165,8 +177,10 @@ describe("Division-scoped admin access (intelligence / logistics)", () => { afterAll(async () => { if (!payload) return; - type TestSlug = "assets" | "resources" | "vehicles" | "technologies"; + type TestSlug = "assets" | "resources" | "vehicles" | "technologies" | "structures"; const docs: Array<[TestSlug, number]> = [ + // Structures first: they may reference the resources deleted below. + ...structureIds.map((id) => ["structures", id] as [TestSlug, number]), ...assetIds.map((id) => ["assets", id] as [TestSlug, number]), ...resourceIds.map((id) => ["resources", id] as [TestSlug, number]), ...vehicleIds.map((id) => ["vehicles", id] as [TestSlug, number]), @@ -502,4 +516,287 @@ describe("Division-scoped admin access (intelligence / logistics)", () => { expect(await accessFnDecision(approvalStatusUpdate, plainUser, data("approved"))).toBe(false); }, TIMEOUT); }); + + describe("approval status reset on non-superuser edit", () => { + let seq = 0; + + type ApprovalStatus = "in_progress" | "ready_for_review" | "approved" | "rejected" | "revision_requested"; + + // A final/held status can only be seeded by a superuser. + const createAsset = async (approvalStatus: ApprovalStatus): Promise<{ id: number }> => { + seq += 1; + const doc = (await payload.create({ + collection: "assets", + data: { + name: `${RUN} Reset ${approvalStatus} ${seq}`, + className: `reset-${approvalStatus}-${seq}-${RUN}`, + assetType: "weapon", + approvalStatus, + crafting: { craftingData: { craftingTimePerUnit: 1, batchSize: 1 } }, + storageDimensions: { gridWidth: 1, gridHeight: 1 }, + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + assetIds.push(doc.id); + return doc; + }; + + it("resets an approved document to in_progress when a non-superuser edits it", async () => { + const asset = await createAsset("approved"); + // editorUser holds assets:update but is not a member of the super-user tier. + // The payload mirrors the tech tree editor, which submits the document's + // current (final) status: field access strips "approved", then the hook + // rewrites the status to in_progress. + const updated = (await payload.update({ + collection: "assets", + id: asset.id, + data: { name: `${RUN} Reset renamed`, approvalStatus: "approved" }, + user: editorUser, + overrideAccess: false, + })) as unknown as { name: string; approvalStatus: string }; + expect(updated.name).toBe(`${RUN} Reset renamed`); + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("resets a revision-requested technology when a non-superuser edits it", async () => { + const tech = (await payload.create({ + collection: "technologies", + data: { + name: `${RUN} Revision Tech`, + summary: "needs rework", + type: "upgrade", + approvalStatus: "revision_requested", + researchCosts: { minimumResearchDuration: 1 }, + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + technologyIds.push(tech.id); + + const updated = (await payload.update({ + collection: "technologies", + id: tech.id, + data: { name: `${RUN} Revision Tech v2` }, + user: intelUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("resets a revision-requested resource when a non-superuser edits it", async () => { + const resource = (await payload.create({ + collection: "resources", + data: { + name: `${RUN} Revision Fuel`, + codeName: `res_revision_${RUN}`, + unitOfMeasure: "liter", + massPerUnit: 0, + gridWidth: 1, + gridHeight: 1, + type: "fluid", + baseValue: 1, + rarity: "common", + approvalStatus: "revision_requested", + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + resourceIds.push(resource.id); + + const updated = (await payload.update({ + collection: "resources", + id: resource.id, + data: { name: `${RUN} Revision Fuel v2` }, + user: logiUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("resets an approved vehicle when a non-superuser edits it", async () => { + const resource = (await payload.create({ + collection: "resources", + data: { + name: `${RUN} Vehicle Fuel`, + codeName: `res_vehicle_fuel_${RUN}`, + unitOfMeasure: "liter", + massPerUnit: 0, + gridWidth: 1, + gridHeight: 1, + type: "fluid", + baseValue: 1, + rarity: "common", + approvalStatus: "approved", + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + resourceIds.push(resource.id); + + const vehicle = (await payload.create({ + collection: "vehicles", + data: { + name: `${RUN} Approved Truck`, + transportMode: "ground", + approvalStatus: "approved", + fuel: { fuelType: resource.id, fuelCapacity: 100, fuelConsumptionRate: 1 }, + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + vehicleIds.push(vehicle.id); + + const updated = (await payload.update({ + collection: "vehicles", + id: vehicle.id, + data: { name: `${RUN} Approved Truck v2` }, + user: logiUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("does not reset when a superuser edits an approved document", async () => { + const asset = await createAsset("approved"); + const updated = (await payload.update({ + collection: "assets", + id: asset.id, + data: { name: `${RUN} Super edit` }, + user: superUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("approved"); + }, TIMEOUT); + + it("does not reset on system writes with no user (catalog imports, seeds)", async () => { + const asset = await createAsset("approved"); + const updated = (await payload.update({ + collection: "assets", + id: asset.id, + data: { name: `${RUN} Import edit` }, + overrideAccess: true, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("approved"); + }, TIMEOUT); + + it("honors an explicit editable status instead of forcing in_progress", async () => { + const asset = await createAsset("approved"); + const updated = (await payload.update({ + collection: "assets", + id: asset.id, + data: { approvalStatus: "ready_for_review" }, + user: editorUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("ready_for_review"); + }, TIMEOUT); + + it("leaves statuses outside the invalidated set untouched", async () => { + const asset = await createAsset("rejected"); + const updated = (await payload.update({ + collection: "assets", + id: asset.id, + data: { name: `${RUN} Rejected edit` }, + user: editorUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("rejected"); + }, TIMEOUT); + }); + + describe("approval status reset on structures (parity with the four approval collections)", () => { + let seq = 0; + + type ApprovalStatus = "in_progress" | "ready_for_review" | "approved" | "rejected" | "revision_requested"; + + const createStructure = async (approvalStatus: ApprovalStatus): Promise<{ id: number }> => { + seq += 1; + const resource = (await payload.create({ + collection: "resources", + data: { + name: `${RUN} Structure Material ${seq}`, + codeName: `res_structure_${seq}_${RUN}`, + unitOfMeasure: "unit", + massPerUnit: 0, + gridWidth: 1, + gridHeight: 1, + type: "physical", + baseValue: 1, + rarity: "common", + approvalStatus: "approved", + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + resourceIds.push(resource.id); + + const structure = (await payload.create({ + collection: "structures", + data: { + name: `${RUN} Structure ${approvalStatus} ${seq}`, + codeName: `${RUN}-structure-${seq}-${approvalStatus}`, + approvalStatus, + category: "logistics", + materials: [{ resource: resource.id, amount: 1 }], + constructionDurationMinutes: 1, + terrainType: "land", + maxHealth: 100, + description: LEXICAL_EMPTY as unknown as Structure["description"], + }, + user: superUser, + overrideAccess: false, + })) as unknown as { id: number }; + structureIds.push(structure.id); + return structure; + }; + + it("resets an approved structure when a non-superuser edits it", async () => { + const structure = await createStructure("approved"); + const updated = (await payload.update({ + collection: "structures", + id: structure.id, + data: { name: `${RUN} Structure renamed` }, + user: editorUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("resets a revision-requested structure when a non-superuser edits it", async () => { + const structure = await createStructure("revision_requested"); + const updated = (await payload.update({ + collection: "structures", + id: structure.id, + data: { name: `${RUN} Structure rework` }, + user: logiUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + + it("lets a superuser edit an approved structure (no filterOptions validation error)", async () => { + const structure = await createStructure("approved"); + const updated = (await payload.update({ + collection: "structures", + id: structure.id, + data: { name: `${RUN} Structure super edit` }, + user: superUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("approved"); + }, TIMEOUT); + + it("strips a final status submitted by a non-superuser", async () => { + const structure = await createStructure("in_progress"); + const updated = (await payload.update({ + collection: "structures", + id: structure.id, + data: { name: `${RUN} Structure self-approve attempt`, approvalStatus: "approved" }, + user: editorUser, + overrideAccess: false, + })) as unknown as { approvalStatus: string }; + expect(updated.approvalStatus).toBe("in_progress"); + }, TIMEOUT); + }); });