/** * Vehicle template dedupe (plan D2): one template per (name, mod). * Pure rule tests + upsert-time skip behavior + the cleanup CLI planner. */ import { getTestPayload } from "../helpers/get-test-payload"; import type { Payload } from "payload"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { DEFAULT_MOD, findDuplicateVehicle, filterSameRunDuplicateVehicles, inferModFromClassname, normalizeRowMod, planVehicleDedupe, type DedupeVehicleRow, } from "@/lib/arma-import/dedupe"; import { upsertPlan, type ImportPlan } from "@/lib/arma-import/catalog"; import { runVehicleDedupe } from "@/tools/import/dedupeVehicleTemplates"; // --------------------------------------------------------------------------- // Pure: classname prefix -> mod mapping (mirrors the migration SQL CASE) // --------------------------------------------------------------------------- describe("inferModFromClassname", () => { it("maps known prefixes case-insensitively", () => { expect(inferModFromClassname("cup_barracks_prop")).toBe("CUP"); expect(inferModFromClassname("CUP_O_ZU23_TK")).toBe("CUP"); expect(inferModFromClassname("RHS_ZU23_MSV")).toBe("RHS"); expect(inferModFromClassname("rhsgref_tla_g_ZU23")).toBe("RHS"); expect(inferModFromClassname("rhssaf_army_o_m1152_tcv_olive")).toBe("RHS"); expect(inferModFromClassname("twwk_remnants_v_hemtt_transport")).toBe("TWWK Remnants"); }); it("falls back to the default mod for vanilla and empty classnames", () => { expect(inferModFromClassname("B_Truck_01_transport_F")).toBe(DEFAULT_MOD); expect(inferModFromClassname("")).toBe(DEFAULT_MOD); expect(inferModFromClassname(null)).toBe(DEFAULT_MOD); }); it("prefers a stored mod and infers only when missing", () => { expect(normalizeRowMod("My Mod", "cup_x")).toBe("My Mod"); expect(normalizeRowMod(" ", "rhs_x")).toBe("RHS"); expect(normalizeRowMod(null, "B_Car_F")).toBe(DEFAULT_MOD); }); }); // --------------------------------------------------------------------------- // Pure: same-run plan filter // --------------------------------------------------------------------------- type FakePlan = { kind: string; displayName: string; mod: string; className: string }; const vplan = (className: string, displayName: string, mod: string): FakePlan => ({ kind: "vehicle", className, displayName, mod, }); describe("filterSameRunDuplicateVehicles", () => { it("keeps the first vehicle per name+mod and skips later siblings", () => { const { kept, skipped } = filterSameRunDuplicateVehicles([ vplan("B_Truck_01_transport_F", "HEMTT Transport", "Arma 3"), vplan("B_T_Truck_01_transport_F", "hemtt transport ", "ARMA 3"), vplan("twwk_v_hemtt", "HEMTT Transport", "TWWK Remnants"), ]); expect(kept.map((p) => p.className)).toEqual(["B_Truck_01_transport_F", "twwk_v_hemtt"]); expect(skipped.map((p) => p.className)).toEqual(["B_T_Truck_01_transport_F"]); }); it("passes asset plans through even when names collide", () => { const a = { kind: "asset", displayName: "Same", mod: "M", className: "a_1" }; const b = { kind: "asset", displayName: "Same", mod: "M", className: "a_2" }; const { kept, skipped } = filterSameRunDuplicateVehicles([a, b]); expect(kept).toEqual([a, b]); expect(skipped).toEqual([]); }); }); // --------------------------------------------------------------------------- // Pure: existing-row duplicate lookup + cleanup planning // --------------------------------------------------------------------------- const row = (over: Partial & { id: number }): DedupeVehicleRow => ({ name: "HEMTT Transport", classname: "B_Truck_01_transport_F", createdAt: "2026-10-03T00:00:00.000Z", ...over, }); describe("findDuplicateVehicle", () => { const want = { displayName: "HEMTT Transport", mod: "Arma 3", className: "B_T_Truck_01_transport_F" }; it("matches on name+mod with a different classname and returns the oldest", () => { const older = row({ id: 2, createdAt: "2026-09-01T00:00:00.000Z" }); const newer = row({ id: 5, classname: "B_Truck_01_transport_F" }); const otherMod = row({ id: 7, classname: "twwk_v_hemtt", mod: "TWWK Remnants" }); expect(findDuplicateVehicle([newer, otherMod, older], want)?.id).toBe(2); }); it("never matches the same classname (that is an update, not a duplicate)", () => { const same = row({ id: 3, classname: "b_t_truck_01_transport_f" }); expect(findDuplicateVehicle([same], want)).toBeUndefined(); }); it("treats un-backfilled rows by classname inference", () => { const legacyCup = row({ id: 4, name: "ZU-23-2", classname: "CUP_O_ZU23_TK", mod: null }); expect( findDuplicateVehicle([legacyCup], { displayName: "ZU-23-2", mod: "CUP", className: "rhs_zu23_x" })?.id, ).toBe(4); }); }); describe("planVehicleDedupe", () => { const group = [ row({ id: 10, createdAt: "2026-10-01T00:00:00.000Z" }), row({ id: 11, classname: "B_T_Truck_01_transport_F", createdAt: "2026-10-02T00:00:00.000Z" }), row({ id: 12, classname: "B_Truck_01_transport_v2_F", approvalStatus: "approved", createdAt: "2026-10-03T00:00:00.000Z" }), ]; it("keeps the oldest row and protects approved/referenced siblings", () => { const plan = planVehicleDedupe(group, new Set([11])); expect(plan.stats).toEqual({ totalVehicles: 3, duplicateGroups: 1, removable: 0, protectedCount: 2 }); const g = plan.groups[0]; expect(g.keeperId).toBe(10); expect(g.removableIds).toEqual([]); expect(g.protectedIds).toEqual([ { id: 11, reason: "referenced by game-vehicles" }, { id: 12, reason: "approvalStatus=approved" }, ]); }); it("marks plain in-progress duplicates removable", () => { const plan = planVehicleDedupe( group.map((r) => (r.id === 12 ? { ...r, approvalStatus: "rejected" } : r)), new Set([11]), ); expect(plan.groups[0].removableIds).toEqual([12]); }); it("ignores singleton groups and separates mods", () => { const plan = planVehicleDedupe([row({ id: 20 }), row({ id: 21, mod: "TWWK Remnants" })]); expect(plan.groups).toEqual([]); expect(plan.stats.duplicateGroups).toBe(0); }); }); // --------------------------------------------------------------------------- // Database: upsert-time skip + cleanup run // --------------------------------------------------------------------------- const RUN = `arma-dedupe-${Date.now().toString(36)}`; const NAME = `${RUN} HEMTT Transport`; /** Separate name for the cleanup-run group so the upsert block's rows * (same NAME, older createdAt) cannot join this group and steal keeper. */ const NAME2 = `${RUN} Kanu Covered`; let payload: Payload; let fuelId: number; const vehicleIds: number[] = []; const instanceIds: number[] = []; function makePlan(className: string, displayName = NAME, mod = DEFAULT_MOD): ImportPlan { return { kind: "vehicle", className, displayName, description: "", assetType: "vehicle", transportMode: "ground", mod, pictureRef: "", media: { paaPath: "", pngPath: "", screenshotPath: "" }, }; } async function createTemplate(data: Record): Promise { const doc = await payload.create({ collection: "vehicles", data: { name: `${RUN} plain`, approvalStatus: "in_progress", fuel: { fuelType: fuelId, fuelCapacity: 100, fuelConsumptionRate: 1 }, ...data, } as never, draft: false, overrideAccess: true, depth: 0, }); vehicleIds.push(doc.id); return doc.id; } beforeAll(async () => { payload = await getTestPayload(); const resource = await payload.create({ collection: "resources", data: { name: `${RUN} Fuel`, codeName: `${RUN}-fuel`, approvalStatus: "in_progress", type: "physical", baseValue: 1, rarity: "common", unitOfMeasure: "L", } as never, overrideAccess: true, depth: 0, }); fuelId = resource.id; }); afterAll(async () => { for (const id of instanceIds) { await payload.delete({ collection: "game-vehicles", id, overrideAccess: true }).catch(() => {}); } for (const id of vehicleIds) { await payload.delete({ collection: "vehicles", id, overrideAccess: true }).catch(() => {}); } await payload.delete({ collection: "resources", id: fuelId, overrideAccess: true }).catch(() => {}); }); describe("upsertVehicle dedupe (database)", () => { it("creates the first template, skips alias classnames, allows other mods", async () => { const created = await upsertPlan(payload, makePlan(`${RUN}_base_F`), fuelId); expect(created.action).toBe("created"); // Exact re-import still updates. const again = await upsertPlan(payload, makePlan(`${RUN}_base_F`), fuelId); expect(again.action).toBe("updated"); expect(again.id).toBe(created.id); // Same name + mod, different classname -> skipped against the existing row. const alias = await upsertPlan(payload, makePlan(`${RUN}_alias_F`), fuelId); expect(alias.action).toBe("skipped"); expect(alias.duplicateOfId).toBe(created.id); // Same name, different mod -> its own template. const crossMod = await upsertPlan(payload, makePlan(`${RUN}_twwk_F`, NAME, "TWWK Remnants"), fuelId); expect(crossMod.action).toBe("created"); // Case-insensitive on both sides. const ciAlias = await upsertPlan(payload, makePlan(`${RUN}_ci_F`, NAME.toLowerCase(), "arma 3"), fuelId); expect(ciAlias.action).toBe("skipped"); vehicleIds.push(created.id, crossMod.id); }); }); describe("runVehicleDedupe (database)", () => { it("dry run deletes nothing; approve removes only unprotected duplicates", async () => { // Oldest row in the group becomes keeper for both runs. await createTemplate({ name: NAME2, classname: `${RUN}_k1` }); const dup = await createTemplate({ name: NAME2.toUpperCase(), classname: `${RUN}_k2` }); const approved = await createTemplate({ name: ` ${NAME2} `, classname: `${RUN}_k3`, approvalStatus: "approved", }); // dup survives every run because a game-vehicle instance references it. const instance = await payload.create({ collection: "game-vehicles", data: { name: `${RUN} inst`, type: dup, status: "idle", currentFuel: 100, currentHealth: 100 } as never, overrideAccess: true, depth: 0, }); instanceIds.push(instance.id); const dry = await runVehicleDedupe(payload, { log: () => {} }); expect(dry.deleted).toBe(0); expect(dry.duplicateGroups).toBeGreaterThanOrEqual(1); const otherDup = await createTemplate({ name: NAME2, classname: `${RUN}_k4` }); const applied = await runVehicleDedupe(payload, { approve: true, log: () => {} }); expect(applied.deleted).toBe(1); expect(applied.errors).toBe(0); // The plain duplicate is gone; keeper, referenced dup and approved survive. await expect( payload.findByID({ collection: "vehicles", id: otherDup, depth: 0, overrideAccess: true }), ).rejects.toThrow(); for (const id of [dup, approved]) { await expect( payload.findByID({ collection: "vehicles", id, depth: 0, overrideAccess: true }), ).resolves.toBeTruthy(); } }); });