From 74b116b9cf8a439a721bb246906fb13941d879da Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 24 Nov 2026 08:03:30 -0500 Subject: [PATCH] fix(awards): save awards without an advancement tier The beforeChange hook compared advancement values against undefined, but the admin form always submits the group, so an award outside a lineup arrived as { seriesKey: null, tier: null }. Null counted as set, which tripped the duplicate tier check for standalone ribbons and the ribbons-only guard for medals and commendations. Normalize null, empty, and non-finite values to "not set" before validating. Non-ribbon awards clear leftover lineup values on a type change instead of throwing on a hidden field, and partial API updates that omit advancement keep the stored lineup. --- src/collections/users/Awards.ts | 82 ++++++++------- tests/int/award-advancement.int.spec.ts | 134 ++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 37 deletions(-) diff --git a/src/collections/users/Awards.ts b/src/collections/users/Awards.ts index 815227fe..8e5f9862 100644 --- a/src/collections/users/Awards.ts +++ b/src/collections/users/Awards.ts @@ -184,51 +184,59 @@ export const Awards: CollectionConfig = { hooks: { beforeChange: [ async ({ req, data, operation, originalDoc }) => { - const advancement = data.advancement; - if ( - advancement && - typeof advancement.seriesKey === "string" && - advancement.seriesKey.trim() !== "" - ) { - advancement.seriesKey = advancement.seriesKey.trim().toLowerCase().replace(/\s+/g, "-"); + const effectiveType = data.type ?? originalDoc?.type; + const advancementProvided = data.advancement !== undefined; + const rawAdvancement = data.advancement; + + // Normalize before validating: the admin form submits the advancement group even + // when it is hidden or empty, so a standalone award arrives as + // `{ seriesKey: null, tier: null }` and a cleared text input as "". Treat all of + // those as "not set" instead of as real values (the old `!== undefined` checks + // treated null as set, which rejected saving any award without a tier). + const rawSeriesKey = + typeof rawAdvancement?.seriesKey === "string" ? rawAdvancement.seriesKey.trim() : ""; + const seriesKey = + rawSeriesKey === "" ? null : rawSeriesKey.toLowerCase().replace(/\s+/g, "-"); + const rawTier = rawAdvancement?.tier; + const tier = typeof rawTier === "number" && Number.isFinite(rawTier) ? rawTier : null; + + // Partial API updates that omit the field leave the stored lineup untouched. + if (!advancementProvided) { + return data; } - const seriesKey = advancement?.seriesKey; - const tier = advancement?.tier; - if (operation === "create" || operation === "update") { - const effectiveType = data.type ?? originalDoc?.type; - if ( - (seriesKey !== undefined && tier === undefined) || - (seriesKey === undefined && tier !== undefined) - ) { - throw new Error("Advancement requires both a series key and a tier."); - } + if (effectiveType !== "ribbon") { + // Advancement lineups only exist for ribbons. Clear leftovers when an award is + // switched to another type, since the field is hidden and cannot be cleared there. + data.advancement = { seriesKey: null, tier: null }; + return data; + } - if ((seriesKey !== undefined || tier !== undefined) && effectiveType !== "ribbon") { - throw new Error("Advancement lineups are only supported for ribbons."); - } + if ((seriesKey === null) !== (tier === null)) { + throw new Error("Advancement requires both a series key and a tier."); + } - if (seriesKey !== undefined && tier !== undefined) { - const result = await req.payload.count({ - collection: "awards", - where: { - and: [ - { "advancement.seriesKey": { equals: seriesKey } }, - { "advancement.tier": { equals: tier } }, - ...(operation === "update" && originalDoc?.id - ? [{ id: { not_equals: originalDoc.id } }] - : []), - ], - }, - overrideAccess: true, - }); + if (seriesKey !== null && tier !== null) { + const result = await req.payload.count({ + collection: "awards", + where: { + and: [ + { "advancement.seriesKey": { equals: seriesKey } }, + { "advancement.tier": { equals: tier } }, + ...(operation === "update" && originalDoc?.id + ? [{ id: { not_equals: originalDoc.id } }] + : []), + ], + }, + overrideAccess: true, + }); - if (result.totalDocs > 0) { - throw new Error(`Tier ${tier} of this series already exists.`); - } + if (result.totalDocs > 0) { + throw new Error(`Tier ${tier} of this series already exists.`); } } + data.advancement = { seriesKey, tier }; return data; }, ], diff --git a/tests/int/award-advancement.int.spec.ts b/tests/int/award-advancement.int.spec.ts index 5ce42772..78b8d741 100644 --- a/tests/int/award-advancement.int.spec.ts +++ b/tests/int/award-advancement.int.spec.ts @@ -16,6 +16,40 @@ let authSpy: MockInstance; const RUN = `award-${Date.now().toString(36)}`; +function simpleRichText(text: string): Award["description"] { + return { + root: { + type: "root", + children: [ + { + type: "paragraph", + children: [ + { + type: "text", + text, + format: 0, + style: "", + mode: "normal", + detail: 0, + version: 1, + }, + ], + direction: "ltr", + format: "", + indent: 0, + textFormat: 0, + textStyle: "", + version: 1, + }, + ], + direction: "ltr", + format: "", + indent: 0, + version: 1, + }, + }; +} + describe("Award Advancement Series", () => { let adminUser: User; let adminUserId: number; @@ -733,4 +767,104 @@ describe("Award Advancement Series", () => { }), ).rejects.toThrow("Tier 1 of this series already exists."); }); + + describe("saving awards without an advancement tier", () => { + // The admin form submits every field in form state, including the hidden + // "Advancement Series" group, so untouched awards arrive with explicit nulls + // (and a cleared text input as an empty string). + async function createAward(type: "ribbon" | "commendation" | "medal", label: string) { + return (await payload.create({ + collection: "awards", + data: { + name: `${label}-${RUN}`, + description: simpleRichText(label), + type, + }, + overrideAccess: true, + depth: 0, + })) as unknown as Award; + } + + it("saves a standalone ribbon when advancement is submitted as nulls", async () => { + const award = await createAward("ribbon", "Null Advancement Ribbon"); + + const updated = (await payload.update({ + collection: "awards", + id: award.id, + data: { advancement: { seriesKey: null, tier: null } }, + overrideAccess: true, + depth: 0, + })) as unknown as Award; + + expect(updated.advancement?.seriesKey ?? null).toBeNull(); + expect(updated.advancement?.tier ?? null).toBeNull(); + }); + + it("saves a standalone ribbon when the series key is submitted as an empty string", async () => { + const award = await createAward("ribbon", "Empty Series Key Ribbon"); + + const updated = (await payload.update({ + collection: "awards", + id: award.id, + data: { advancement: { seriesKey: "", tier: null } }, + overrideAccess: true, + depth: 0, + })) as unknown as Award; + + expect(updated.advancement?.seriesKey ?? null).toBeNull(); + expect(updated.advancement?.tier ?? null).toBeNull(); + }); + + it("saves a medal whose hidden advancement group arrives as nulls", async () => { + const award = await createAward("medal", "Null Advancement Medal"); + + await expect( + payload.update({ + collection: "awards", + id: award.id, + data: { advancement: { seriesKey: null, tier: null } }, + overrideAccess: true, + depth: 0, + }), + ).resolves.toBeTruthy(); + }); + + it("clears a leftover lineup when an award is switched off the ribbon type", async () => { + const award = await createAward("ribbon", "Type Switch Ribbon"); + const seriesKey = `${RUN}-type-switch`; + + await payload.update({ + collection: "awards", + id: award.id, + data: { advancement: { seriesKey, tier: 1 } }, + overrideAccess: true, + depth: 0, + }); + + const updated = (await payload.update({ + collection: "awards", + id: award.id, + data: { type: "commendation", advancement: { seriesKey, tier: 1 } }, + overrideAccess: true, + depth: 0, + })) as unknown as Award; + + expect(updated.advancement?.seriesKey ?? null).toBeNull(); + expect(updated.advancement?.tier ?? null).toBeNull(); + }); + + it("still rejects a lineup with only one of the two fields", async () => { + const award = await createAward("ribbon", "One Sided Ribbon"); + + await expect( + payload.update({ + collection: "awards", + id: award.id, + data: { advancement: { seriesKey: null, tier: 2 } }, + overrideAccess: true, + depth: 0, + }), + ).rejects.toThrow("Advancement requires both a series key and a tier."); + }); + }); });