1
0
Fork 0

feat(arma): dedupe vehicle templates by name and mod with cleanup CLI

This commit is contained in:
Jason Fraley 2026-10-22 13:18:11 -04:00
parent 59460111fd
commit 633853589f
11 changed files with 45516 additions and 10 deletions

View file

@ -15,6 +15,7 @@
"generate:types": "cross-env NODE_OPTIONS=--no-deprecation payload generate:types",
"generate:version-info": "bun run src/scripts/generateVersionInfo.ts",
"import:arma": "bun run src/tools/import/importArmaLibrary.ts",
"arma:dedupe": "bun run src/tools/import/dedupeVehicleTemplates.ts",
"icons:arma": "bun run src/tools/import/extractArmaIcons.ts",
"markers:arma": "bun run src/tools/arma/extractMarkers.ts",
"version:bump": "bun run src/scripts/bumpVersion.ts",

View file

@ -51,6 +51,15 @@ export const Vehicles: CollectionConfig = {
"If not provided, this vehicle will ONLY be available as a virtual asset (i.e., cannot be used in Arma.)",
},
},
{
name: "mod",
type: "text",
defaultValue: "Arma 3",
admin: {
description:
"Mod package this template belongs to (imported from the game catalog; backfilled from the classname prefix for older rows). Dedupe keeps one template per name + mod.",
},
},
{
name: "approvalStatus",
type: "select",

View file

@ -24,12 +24,17 @@
* in-game data (name, assetType/transportMode, mod, description) and attach a
* new thumbnail/image only when a fresh media doc was produced, so
* approvalStatus and human-edited "Virtual Data" are never reset.
* Vehicle creates additionally dedupe: a plan whose (display name, mod)
* already exists under a different classname is SKIPPED rather than creating
* another template (rules live in ./dedupe.ts), which stops the export's
* faction/retexture classname spam from each becoming its own row.
*/
import { spawnSync } from "child_process";
import { existsSync, mkdirSync, readFileSync, statSync } from "fs";
import { join } from "path";
import type { Payload } from "payload";
import { plaintextToLexical } from "@/lib/tickets/lexical";
import { findDuplicateVehicle } from "./dedupe";
/** Mirrors the Assets collection's assetType enum (src/collections/logistics/Assets.ts). */
export const ASSET_TYPES = [
@ -348,9 +353,12 @@ export async function resolveFuelConfig(payload: Payload, codeName = "res_fuel")
}
export interface UpsertResult {
action: "created" | "updated";
/** "skipped": a vehicle with this (name, mod) already exists under another
* classname; `id` is the existing template's id (same as duplicateOfId). */
action: "created" | "updated" | "skipped";
collection: "assets" | "vehicles";
id: number;
duplicateOfId?: number;
}
/**
@ -500,6 +508,9 @@ async function upsertVehicle(payload: Payload, plan: ImportPlan, fuelId: number
const data: Record<string, unknown> = {
name: plan.displayName,
transportMode: plan.transportMode,
// Mod is pure game data like mass: refresh it on every import so rows
// predating the mod field converge to the export's value.
mod: plan.mod,
};
if (plan.description) data.description = plaintextToLexical(plan.description);
// Physical mass is pure game data: refresh it on every import.
@ -519,11 +530,30 @@ async function upsertVehicle(payload: Payload, plan: ImportPlan, fuelId: number
return { action: "updated", collection: "vehicles", id };
}
// Dedupe before create (plan D2): CUP/RHS retextures share one display
// name across dozens of classnames, and only the oldest template per
// (name, mod) survives. Exact-classname re-imports updated above and never
// reach here. Rows without a stored mod compare by classname inference
// (./dedupe.ts) so pre-backfill databases dedupe identically.
const candidates = await payload.find({
collection: "vehicles",
where: { name: { like: plan.displayName } },
depth: 0,
pagination: false,
overrideAccess: true,
});
const duplicate = findDuplicateVehicle(candidates.docs, plan);
if (duplicate) {
const id = Number(duplicate.id);
return { action: "skipped", collection: "vehicles", id, duplicateOfId: id };
}
const imagePath = planImagePath(plan);
const mediaId = imagePath ? (await resolveMedia(payload, imagePath))?.id : undefined;
const data: Record<string, unknown> = {
name: plan.displayName,
classname: plan.className,
mod: plan.mod,
fuel: { fuelType: fuelId, fuelCapacity: 100, fuelConsumptionRate: 1 },
transportMode: plan.transportMode,
category: [defaultCategoryForTransport(plan.transportMode)],

View file

@ -0,0 +1,208 @@
/**
* Vehicle template dedupe rules (plan D2: one template per name+mod).
*
* The Arma export catalog carries one record per classname, and CUP/RHS
* publish every faction/camo retexture as its own classname under an
* identical display name (e.g. 23x "Search light"). That let the Oct 2026
* import land 1,686 duplicate-name vehicle templates. These helpers encode
* the collapse rule used by BOTH the importer (skip creating another row for
* a name+mod that already exists) and the cleanup CLI (delete extras, keep
* one per group), so the two never diverge and a post-cleanup re-import stays
* stable.
*
* Keeper rule shared by both sides: OLDEST wins (then lowest id as tiebreak).
* Within one import run, FIRST-WINS in catalog order, matching the same
* "nothing newer replaces it" intent.
*/
export const DEFAULT_MOD = "Arma 3";
/**
* Classname-prefix -> mod mapping used when a row has no stored mod yet.
* Mirrors the SQL CASE in migration 20261022_*_add_vehicle_mod_field; change
* one, change the other (covered by tests/int/arma-import-dedupe.int.spec.ts).
* Matched against the lowercased classname as a prefix, so `rhs` also covers
* rhsgref_/rhssaf_ and `cup` covers CUP_* case variants.
*/
export const MOD_PREFIX_RULES: ReadonlyArray<{ prefix: string; mod: string }> = [
{ prefix: "cup", mod: "CUP" },
{ prefix: "rhs", mod: "RHS" },
{ prefix: "twwk", mod: "TWWK Remnants" },
];
/** Prefix mapping from MOD_PREFIX_RULES; anything else is stock content. */
export function inferModFromClassname(classname?: string | null): string {
const c = String(classname ?? "").trim().toLowerCase();
for (const rule of MOD_PREFIX_RULES) {
if (c.startsWith(rule.prefix)) return rule.mod;
}
return DEFAULT_MOD;
}
/**
* Mod used when GROUPING an existing vehicles row: its stored mod when set,
* otherwise the classname inference so un-backfilled rows still collapse
* with their retexture siblings instead of pairing with vanilla.
*/
export function normalizeRowMod(mod?: string | null, classname?: string | null): string {
const m = String(mod ?? "").trim();
return m || inferModFromClassname(classname);
}
/** Display-name comparison key: trim + lowercase (matches the picker search). */
export function normalizeName(name?: string | null): string {
return String(name ?? "").trim().toLowerCase();
}
/** Group/lookup key: lowercased mod and name joined so they never collide. */
export function dedupeKey(name: string | null | undefined, mod: string): string {
return `${mod.trim().toLowerCase()}::${normalizeName(name)}`;
}
/** Minimal shape of a vehicles row that dedupe decisions need. */
export interface DedupeVehicleRow {
id: number;
name?: string | null;
classname?: string | null;
mod?: string | null;
createdAt?: string | null;
approvalStatus?: string | null;
}
/**
* Approval states the cleanup CLI refuses to delete. Anything in flight
* through the review workflow (or already shipped in game) must be retired
* by a human, not by a dedupe sweep.
*/
export const PROTECTED_APPROVAL_STATES: ReadonlyArray<string> = ["approved", "ready_for_review"];
/**
* The row this plan would duplicate: same normalized name AND mod, but a
* DIFFERENT classname (an exact classname match is a normal update, handled
* before this lookup). Oldest wins, matching the keeper rule; createdAt is an
* ISO string so lexical ordering is chronological.
*/
export function findDuplicateVehicle<T extends DedupeVehicleRow>(
rows: T[],
want: { displayName: string; mod: string; className: string },
): T | undefined {
const targetName = normalizeName(want.displayName);
const targetMod = want.mod.trim().toLowerCase();
const wantedClass = String(want.className ?? "").trim().toLowerCase();
return [...rows]
.filter(
(row) =>
normalizeName(row.name) === targetName &&
normalizeRowMod(row.mod, row.classname).trim().toLowerCase() === targetMod &&
String(row.classname ?? "").trim().toLowerCase() !== wantedClass,
)
.sort((a, b) =>
String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")) || a.id - b.id,
)[0];
}
/**
* Collapse duplicate vehicle plans WITHIN one import run: first record for a
* (name, mod) wins, later faction/retexture siblings are skipped before any
* DB write. Asset plans pass through untouched (arsenal skins stay distinct).
* Pure; used by the import CLI.
*/
export function filterSameRunDuplicateVehicles<T extends { kind: string; displayName: string; mod: string }>(
plans: T[],
): { kept: T[]; skipped: T[] } {
const seen = new Set<string>();
const kept: T[] = [];
const skipped: T[] = [];
for (const plan of plans) {
if (plan.kind !== "vehicle") {
kept.push(plan);
continue;
}
const key = dedupeKey(plan.displayName, plan.mod);
if (seen.has(key)) skipped.push(plan);
else {
seen.add(key);
kept.push(plan);
}
}
return { kept, skipped };
}
/* -------------------------------------------------------------------------
* Cleanup planning
* ----------------------------------------------------------------------- */
export interface DedupeGroup {
key: string;
keeperId: number;
/** Rows safe to delete now. */
removableIds: number[];
/** Rows that would go but are protected, with the reason. */
protectedIds: Array<{ id: number; reason: string }>;
}
export interface DedupePlan {
groups: DedupeGroup[];
stats: {
totalVehicles: number;
duplicateGroups: number;
removable: number;
protectedCount: number;
};
}
/**
* Plan a full-collection dedupe: group by (name, mod), keep the oldest row,
* and classify every other row as removable or protected. A row is protected
* when its approvalStatus is in PROTECTED_APPROVAL_STATES or a game-vehicle
* instance references it (referencedTemplateIds). Pure; the CLI owns I/O.
*/
export function planVehicleDedupe(
vehicles: DedupeVehicleRow[],
referencedTemplateIds: Set<number> = new Set(),
): DedupePlan {
const byKey = new Map<string, DedupeVehicleRow[]>();
for (const row of vehicles) {
const key = dedupeKey(row.name, normalizeRowMod(row.mod, row.classname));
const group = byKey.get(key);
if (group) group.push(row);
else byKey.set(key, [row]);
}
const groups: DedupeGroup[] = [];
let removable = 0;
let protectedCount = 0;
for (const [key, rows] of byKey) {
if (rows.length < 2) continue;
const sorted = [...rows].sort((a, b) =>
String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")) || a.id - b.id,
);
const keeper = sorted[0];
const group: DedupeGroup = { key, keeperId: keeper.id, removableIds: [], protectedIds: [] };
for (const row of sorted.slice(1)) {
const approval = String(row.approvalStatus ?? "").trim();
if (PROTECTED_APPROVAL_STATES.includes(approval)) {
group.protectedIds.push({ id: row.id, reason: `approvalStatus=${approval || "unset"}` });
protectedCount++;
} else if (referencedTemplateIds.has(row.id)) {
group.protectedIds.push({ id: row.id, reason: "referenced by game-vehicles" });
protectedCount++;
} else {
group.removableIds.push(row.id);
removable++;
}
}
groups.push(group);
}
groups.sort((a, b) => b.removableIds.length + b.protectedIds.length - (a.removableIds.length + a.protectedIds.length));
return {
groups,
stats: {
totalVehicles: vehicles.length,
duplicateGroups: groups.length,
removable,
protectedCount,
},
};
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,22 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "vehicles" ADD COLUMN "mod" varchar DEFAULT 'Arma 3';`)
// Backfill mods from classname prefixes (mirrors MOD_PREFIX_RULES in
// src/lib/arma-import/dedupe.ts; change one, change the other). The ADD
// COLUMN default already placed every row on 'Arma 3', so mod-less rows
// and unknown prefixes intentionally keep it.
await db.execute(sql`
UPDATE "vehicles" SET "mod" = CASE
WHEN lower("classname") LIKE 'cup%' THEN 'CUP'
WHEN lower("classname") LIKE 'rhs%' THEN 'RHS'
WHEN lower("classname") LIKE 'twwk%' THEN 'TWWK Remnants'
ELSE "mod" END
WHERE "classname" IS NOT NULL;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "vehicles" DROP COLUMN "mod";`)
}

View file

@ -147,6 +147,7 @@ import * as migration_20261020_171725_add_superstructure_interior from './202610
import * as migration_20261020_191433_add_interior_module_effect_types from './20261020_191433_add_interior_module_effect_types';
import * as migration_20261020_200000_add_interior_asset_outputs_flag from './20261020_200000_add_interior_asset_outputs_flag';
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';
export const migrations = [
{
@ -892,6 +893,11 @@ export const migrations = [
{
up: migration_20261020_201242_add_room_fixture_blocks_station.up,
down: migration_20261020_201242_add_room_fixture_blocks_station.down,
name: '20261020_201242_add_room_fixture_blocks_station'
name: '20261020_201242_add_room_fixture_blocks_station',
},
{
up: migration_20261022_170228_add_vehicle_mod_field.up,
down: migration_20261022_170228_add_vehicle_mod_field.down,
name: '20261022_170228_add_vehicle_mod_field'
},
];

View file

@ -2394,6 +2394,10 @@ export interface Vehicle {
* If not provided, this vehicle will ONLY be available as a virtual asset (i.e., cannot be used in Arma.)
*/
classname?: string | null;
/**
* Mod package this template belongs to (imported from the game catalog; backfilled from the classname prefix for older rows). Dedupe keeps one template per name + mod.
*/
mod?: string | null;
/**
* Mark whether this vehicle is ready for developer approval and implementation into the live environment.
*/
@ -10875,6 +10879,7 @@ export interface ResourcesSelect<T extends boolean = true> {
export interface VehiclesSelect<T extends boolean = true> {
name?: T;
classname?: T;
mod?: T;
approvalStatus?: T;
description?: T;
image?: T;

View file

@ -0,0 +1,122 @@
#!/usr/bin/env bun
/**
* dedupeVehicleTemplates.ts - collapse duplicate vehicle templates (plan D2).
*
* The Oct 2026 catalog import created one template per faction/retexture
* classname under an identical display name (446 names, 1,686 rows in prod).
* This CLI groups `vehicles` by (name, mod), keeps the OLDEST row per group,
* and deletes the rest. Rows are protected (never deleted) when their
* approvalStatus is approved/ready_for_review or a game-vehicles instance
* references them. Media docs of deleted rows are left alone; admins can
* prune orphans separately.
*
* Usage (targets the DATABASE_URI from .env, same as other local tooling):
* bun run arma:dedupe # dry-run report only (default)
* bun run arma:dedupe --approve # apply deletions
* Grouping/mod rules live in src/lib/arma-import/dedupe.ts and match what
* the importer now skips, so a re-import after cleanup stays stable.
*/
import type { Payload } from "payload";
import { planVehicleDedupe, type DedupeVehicleRow } from "@/lib/arma-import/dedupe";
export interface DedupeRunResult {
removable: number;
deleted: number;
errors: number;
protectedCount: number;
duplicateGroups: number;
}
/**
* One dedupe pass: read every template + reference, plan with
* planVehicleDedupe, log the report, and delete when `approve` is set.
* Exported for integration tests; the CLI wrapper below only parses flags.
*/
export async function runVehicleDedupe(
payload: Payload,
opts: { approve?: boolean; log?: (msg: string) => void } = {},
): Promise<DedupeRunResult> {
const log = opts.log ?? ((msg: string) => console.log(`[vehicle-dedupe] ${msg}`));
const { docs } = await payload.find({
collection: "vehicles",
depth: 0,
pagination: false,
sort: "createdAt",
overrideAccess: true,
select: { name: true, classname: true, mod: true, approvalStatus: true, createdAt: true },
});
const vehicles = docs as unknown as DedupeVehicleRow[];
const referencedTemplateIds = new Set<number>();
const instances = await payload.find({
collection: "game-vehicles",
depth: 0,
pagination: false,
overrideAccess: true,
select: { type: true },
});
for (const instance of instances.docs) {
const templateId = typeof instance.type === "number" ? instance.type : Number(instance.type);
if (Number.isFinite(templateId)) referencedTemplateIds.add(templateId);
}
const plan = planVehicleDedupe(vehicles, referencedTemplateIds);
const byId = new Map(vehicles.map((v) => [v.id, v]));
const describe = (id: number) => {
const row = byId.get(id);
return `${id} "${row?.name ?? "?"}" [${row?.classname ?? "no classname"}]`;
};
log(
`${plan.stats.totalVehicles} templates, ${plan.stats.duplicateGroups} duplicate groups, ` +
`${plan.stats.removable} removable, ${plan.stats.protectedCount} protected.`,
);
for (const group of plan.groups) {
if (group.removableIds.length === 0 && group.protectedIds.length === 0) continue;
log(`Group ${group.key}: keep ${describe(group.keeperId)}`);
for (const id of group.removableIds) log(` delete ${describe(id)}`);
for (const p of group.protectedIds) log(` PROTECTED ${describe(p.id)} (${p.reason})`);
}
if (!opts.approve) {
log("Dry run complete. Re-run with --approve to delete the rows above.");
return { ...plan.stats, deleted: 0, errors: 0 };
}
let deleted = 0;
let errors = 0;
for (const group of plan.groups) {
for (const id of group.removableIds) {
try {
await payload.delete({ collection: "vehicles", id, overrideAccess: true });
deleted++;
} catch (e) {
errors++;
log(`ERR deleting ${id}: ${(e as Error).message}`);
}
}
}
log(`Done: deleted ${deleted} templates, ${errors} errors, kept ${plan.stats.duplicateGroups} group leaders.`);
return { ...plan.stats, deleted, errors };
}
async function main() {
const approve = process.argv.includes("--approve");
const payloadConfig = await (await import("@payload-config")).default;
const { getPayload } = await import("payload");
const payload: Payload = await getPayload({ config: payloadConfig });
await runVehicleDedupe(payload, { approve });
}
if (process.argv[1] && process.argv[1].includes("dedupeVehicleTemplates")) {
main()
// Explicit exit: plugin event loops keep handles open and would hang the
// CLI forever after the work is done (same as garage:backfill).
.then(() => process.exit(0))
.catch((e) => {
console.error(e);
process.exit(1);
});
}

View file

@ -36,6 +36,7 @@ import {
type CatalogRecord,
type ImportPlan,
} from "@/lib/arma-import/catalog";
import { filterSameRunDuplicateVehicles } from "@/lib/arma-import/dedupe";
interface CliOpts {
catalog?: string[];
@ -108,10 +109,18 @@ async function main() {
console.log(` -> ${plan.kind}\t${plan.className}\t${plan.displayName}\t${img}`);
}
// Same-run name+mod collapse BEFORE any write: later retexture siblings of
// an already-planned vehicle never reach the DB (upsertPlan additionally
// checks the database itself for pre-existing duplicates).
const { kept, skipped } = filterSameRunDuplicateVehicles(plans);
for (const s of skipped) {
console.log(` SKIP ${s.className} (same name+mod as an earlier record: ${s.displayName} / ${s.mod})`);
}
if (dryRun) {
const withCompat = plans.filter((p) => p.compat);
const refs = withCompat.reduce((n, p) => n + p.compat!.magazines.length + p.compat!.attachments.length, 0);
console.log(`\nDry run: ${plans.length} would import, 0 applied.`);
console.log(`\nDry run: ${kept.length} would import, ${skipped.length} same-run duplicate vehicles skipped, 0 applied.`);
console.log(`Compatibility: ${withCompat.length} weapons carry ${refs} magazine/attachment references.`);
return;
}
@ -119,20 +128,25 @@ async function main() {
const payload = await getPayload({ config });
// Fuel is only needed for vehicle records; resolve lazily so asset-only
// catalogs import even without a Fuel resource.
const fuelId = plans.some((p) => p.kind === "vehicle") ? await resolveFuelConfig(payload, opts.fuel?.[0] ?? "res_fuel") : undefined;
const fuelId = kept.some((p) => p.kind === "vehicle") ? await resolveFuelConfig(payload, opts.fuel?.[0] ?? "res_fuel") : undefined;
let created = 0, updated = 0, errors = 0;
for (const plan of plans) {
let created = 0, updated = 0, dbSkipped = 0, errors = 0;
for (const plan of kept) {
try {
const res = await upsertPlan(payload, plan, fuelId);
console.log(`Applied ${res.action} ${res.collection}:${res.id}`);
if (res.action === "created") created++; else updated++;
if (res.action === "skipped") {
dbSkipped++;
console.log(`Skipped duplicate ${plan.className}: name+mod already exists as vehicles:${res.duplicateOfId}`);
} else {
console.log(`Applied ${res.action} ${res.collection}:${res.id}`);
if (res.action === "created") created++; else updated++;
}
} catch (e) {
console.error(`ERR ${plan.className}: ${(e as Error).message}`);
errors++;
}
}
console.log(`Done: ${created} created, ${updated} updated, ${errors} errors.`);
console.log(`Done: ${created} created, ${updated} updated, ${dbSkipped} existing duplicates skipped, ${errors} errors.`);
// Second pass: link weapons to their magazines/attachments (references to
// the rows imported above, never copies).
@ -144,4 +158,8 @@ async function main() {
);
}
main().catch((e) => { console.error(e); process.exit(1); });
main()
// Explicit exit for the same reason as dedupeVehicleTemplates: plugin
// handles keep the event loop alive after work completes.
.then(() => process.exit(0))
.catch((e) => { console.error(e); process.exit(1); });

View file

@ -0,0 +1,284 @@
/**
* 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<DedupeVehicleRow> & { 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<string, unknown>): Promise<number> {
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();
}
});
});