1
0
Fork 0

Compare commits

...

5 commits

Author SHA1 Message Date
adbfcb0fd7 v0.13.0 - add rank-based leadership evaluations 2026-10-25 21:39:49 -04:00
c5bd74f297 chore(locker): commit pending stock handling refinements 2026-10-25 21:23:40 -04:00
70b484ad31 docs: add v0.13.0 changelog entry 2026-10-25 21:22:01 -04:00
977f841056 feat(evaluations): gate leadership ratings by rank instead of squad assignments
Eligibility now requires a strict rank gap plus a yes-RSVP from at least
one side of the pair on an evaluable mission. Junior rates senior writes
leader-direct (feeds the anonymous aggregate); senior rates junior writes
subordinate; leader-indirect stays readable for legacy rows only.

- New src/lib/evaluations/ranks.ts ladder helpers shared by all call sites
- Profile page: eligible missions union viewer+subject attendance, dialog
  hidden without a rank gap, subordinate line visible to higher ranks
- Bot and in-app reminder planners pair co-attendees by rank, not squads
- isDirectLeaderOf/isAnyLeader removed; no schema change or migration
2026-10-25 02:53:49 -04:00
633853589f feat(arma): dedupe vehicle templates by name and mod with cleanup CLI 2026-10-22 13:18:11 -04:00
36 changed files with 45929 additions and 258 deletions

View file

@ -1,5 +1,15 @@
# Changelog
# v0.13.0
Leadership ratings now follow the unit's rank structure instead of squad assignments.
### Features
- **Leadership evaluations.** Rating eligibility is now based on strict rank gaps instead of squad assignments: junior operators rate their seniors upward, seniors rate juniors downward, and post-mission reminder plans pair co-attendees by rank. Same-rank peers and rankless members are never paired.
---
# v0.12.19
Bomperator matches stay in step again, without the arena snapping your fighter around after a lag spike.

View file

@ -126,7 +126,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
### D. Evaluation reminders (post-mission)
- **Trigger**: a mission becomes evaluable (status `Completed`, or `Scheduled`/`Active` whose scheduled window (`classification.startDateTime` + `classification.estimatedDuration`, default 240 min) has fully passed — same rule as `isMissionEvaluable` in `src/lib/evaluations`). Poll loop every `DISCORD_EVALUATION_POLL_MS` (default 60s) queries evaluable missions with no `evaluationRemindersSentAt` marker (one-shot, same pattern as `discordAttendanceSentAt`).
- **Recipients** (`computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`): participants = users with a "yes" RSVP. Each participant is reminded to rate their direct leader(s); each leader of an assignment containing a participant is reminded to rate that participant (subordinate kind needs no RSVP). Self-pairs skipped; a user who is both gets one merged DM.
- **Recipients** (`computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`): participants = users with a "yes" RSVP. Pairing follows rank, not assignments: every pair of participants with a strict rank gap is reminded both ways (the junior to rate the senior as `leader-direct`, the senior to rate the junior as `subordinate`). Same-rank participants and participants without a profile rank form no pairs; self-pairs skipped; a user with both lists gets one merged DM.
- **DM**: embed with "Rate your leadership" / "Rate your subordinates" sections, each line linking to the ratee's profile page (`APP_URL + /profile/<username>`) where the rating dialog lives. Best-effort: DM failures are logged and skipped, marker is set after the pass (cap 40 DMs/tick, 300ms between sends; overflow retries next tick before the marker is set).
- **Deliberate exception**: these DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in the web UI — honoring it would DM nobody). Dedicated unit-admin flow, not notification-stream forwarding.
- **Manual trigger**: `/remind-evaluations` (staff only, guild-only). Optional `mission` option (mission ID, name, or code name — ambiguous matches list candidates) sends reminders for that one mission even if the marker is already set (as long as it's evaluable); omitted, it runs the reconcile sweep over all pending missions immediately and reports `{processed, sent}`. Replies are ephemeral; the interaction is deferred because DM sending takes minutes at scale.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.12.19",
"version": "0.13.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",
@ -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

@ -1206,11 +1206,17 @@ export async function attachItemFromGrid(
if (!weapon || typeof weapon === "number" || weapon.assetType !== "weapon") {
return { success: false, error: "Attachments can only be installed on weapons." };
}
if (items[weaponIdx].quantity < 1) {
return { success: false, error: "That weapon is out of stock." };
}
const attachment = items[attIdx].asset as Asset;
if (!attachment || typeof attachment === "number") {
return { success: false, error: "Invalid item." };
}
if (items[attIdx].quantity < 1) {
return { success: false, error: "That attachment is out of stock." };
}
const category = ATTACHMENT_CATEGORIES.find((c) => c.assetType === attachment.assetType);
if (!category) {

View file

@ -65,9 +65,9 @@ async function findUserByUsername(
/**
* Submit (or re-submit) a leadership evaluation for the given profile. The kind
* is derived server-side from the rater/ratee/mission relationship — it is never
* accepted from the client. Eligibility is the permission gate here; any logged-in
* user with a qualifying relationship may evaluate.
* is derived server-side from the rater/ratee rank relationship and attendance;
* it is never accepted from the client. Eligibility is the permission gate here;
* any logged-in user with a strict rank difference may evaluate.
*/
export async function submitEvaluation(input: {
username: string;

View file

@ -8,7 +8,8 @@ import { ClientDate } from "@/components/frontend/ClientDate";
import { resolveLevel } from "@/utils/xp/resolveLevel";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { isSuperuser, hasPermission } from "@/utils/access-control/hasPermission";
import { isDirectLeaderOf, isMissionEvaluable } from "@/lib/evaluations";
import { isMissionEvaluable } from "@/lib/evaluations";
import { rankDirection, type RankDirection } from "@/lib/evaluations/ranks";
import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
import { getEvaluationSummary } from "./actions";
import { getContributionSummary } from "@/lib/contributions";
@ -158,24 +159,43 @@ async function findUpgradedFromNames(
return upgradedFromNames;
}
/**
* Missions the viewer could anchor an evaluation on: evaluable missions where
* the viewer OR the profile subject has a yes-RSVP (rank-based rule: at least
* one side of the pair attended). Callers must additionally verify a strict
* rank gap exists before showing this list.
*/
async function findEligibleEvaluationMissions(
payload: Payload,
viewerId: number,
subjectId: number,
now: Date,
): Promise<readonly EvaluationMissionOption[]> {
const attendanceRes = await payload.find({
collection: "mission-attendances",
where: {
and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }],
},
limit: 100,
depth: 0,
select: { mission: true },
overrideAccess: true,
});
const [viewerAttendanceRes, subjectAttendanceRes] = await Promise.all([
payload.find({
collection: "mission-attendances",
where: {
and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }],
},
limit: 100,
depth: 0,
select: { mission: true },
overrideAccess: true,
}),
payload.find({
collection: "mission-attendances",
where: {
and: [{ user: { equals: subjectId } }, { response: { equals: "yes" } }],
},
limit: 100,
depth: 0,
select: { mission: true },
overrideAccess: true,
}),
]);
const missionIds = [
...new Set(
attendanceRes.docs.map((attendance) =>
[...viewerAttendanceRes.docs, ...subjectAttendanceRes.docs].map((attendance) =>
typeof attendance.mission === "number" ? attendance.mission : attendance.mission.id,
),
),
@ -301,33 +321,37 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
viewer?.roles?.some((role) => role === "admin" || role === "developer") === true;
const evaluationSummaryPromise = viewer ? getEvaluationSummary(username) : Promise.resolve(null);
const eligibleMissionsPromise: Promise<readonly EvaluationMissionOption[]> = viewer
? findEligibleEvaluationMissions(payload, viewer.id, new Date())
? findEligibleEvaluationMissions(payload, viewer.id, user.id, new Date())
: Promise.resolve([]);
const privilegedViewerPromise: Promise<boolean> = viewer
? isSuperuser(payload, viewer)
: Promise.resolve(false);
const directLeaderPromise: Promise<boolean> =
const rankGapPromise: Promise<RankDirection | null> =
viewer && !isProfileOwner
? isDirectLeaderOf(payload, viewer.id, user.id)
: Promise.resolve(false);
? rankDirection(payload, viewer.id, user.id)
: Promise.resolve(null);
const canEditIntelPromise: Promise<boolean> = viewer
? hasPermission(payload, viewer, "profiles:intel_excerpt:update")
: Promise.resolve(false);
const [
evaluationSummaryResult,
eligibleMissions,
eligibleMissionsRaw,
isSuperuserViewer,
isDirectLeader,
rankGap,
canEditIntel,
] = await Promise.all([
evaluationSummaryPromise,
eligibleMissionsPromise,
privilegedViewerPromise,
directLeaderPromise,
rankGapPromise,
canEditIntelPromise,
]);
// Without a strict rank gap there is no direction to rate in, so the dialog
// gets no mission list at all.
const eligibleMissions = rankGap ? eligibleMissionsRaw : [];
// Seniors may see the subordinate-rating line on their juniors' profiles.
const canViewSubordinate =
isProfileOwner || isLegacyPrivileged || isSuperuserViewer || isDirectLeader;
isProfileOwner || isLegacyPrivileged || isSuperuserViewer || rankGap === "downward";
const latestMissionRows =
evaluationSummaryResult?.success && evaluationSummaryResult.data.leader.visible
? await findLatestLeaderMissionRows(payload, user.id)
@ -367,7 +391,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
evaluationSummaryResult && !evaluationSummaryResult.success
? evaluationSummaryResult.error
: null;
const canSubmitEvaluation = viewer !== null && !isProfileOwner;
const canSubmitEvaluation = viewer !== null && !isProfileOwner && rankGap !== null;
const rank = profile.rank as Rank;
const promotionResult = viewer ? await resolvePromotionAuthority(payload, viewer) : null;
const allowedTargetRanks = promotionResult

View file

@ -11,9 +11,9 @@ export const runtime = "nodejs";
* GET /api/mission-reminder
*
* Returns recently completed main operations (within 72h of completion) where the
* authenticated user RSVP'd "yes" and at least one of their assignment-based
* direct leaders also RSVP'd "yes". The client uses this to prompt mission
* feedback. Leader entries carry identity only — no rater/comment data.
* authenticated user RSVP'd "yes" and at least one strictly higher-ranked
* co-attendee also RSVP'd "yes". The client uses this to prompt mission
* feedback. Leader entries carry identity only, no rater/comment data.
*/
export async function GET(req: NextRequest) {
const payload = await getPayload({ config: await config });

View file

@ -75,7 +75,7 @@ Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit
## Feature flow: evaluation reminders
Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start), sends a one-shot DM per linked user asking them to rate their leadership (leaders also get a "rate your subordinates" section). Recipient plan: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker `evaluationRemindersSentAt` on Missions (withheld if the 40-DM/tick cap is hit — retries next tick). DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in web UI). Staff can re-send manually via `/remind-evaluations`.
Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start), sends a one-shot DM per linked user asking them to rate their leadership (juniors get a "rate your seniors" list; seniors get a "rate your subordinates" section). Pairing is rank-based among the mission's yes-RSVP participants: every strict-rank-gap attendee pair is reminded in both directions; same-rank peers and rankless participants form no pairs. Recipient plan: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker `evaluationRemindersSentAt` on Missions (withheld if the 40-DM/tick cap is hit - retries next tick). DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in web UI). Staff can re-send manually via `/remind-evaluations`.
## Feature flow: imminent op reminder

View file

@ -8,10 +8,10 @@ import { isMissionEvaluable } from "@/lib/evaluations";
/**
* Evaluation reminder service: after a mission becomes evaluable (completed, or
* its scheduled start has passed), every participant with a linked Discord
* account gets a one-shot DM asking them to rate their leadership — and every
* leader additionally gets a section asking them to rate the subordinates who
* participated. Each DM links to the relevant profile pages, where the rating
* dialog lives.
* account gets a one-shot DM listing the co-attendees they may rate under the
* rank-based rules: juniors are prompted to rate their higher-ranked attendees,
* seniors are prompted to rate their lower-ranked ones. Each DM links to the
* relevant profile pages, where the rating dialog lives.
*
* The DM deliberately ignores `preferences.discord.enabled` (the notification
* bridge opt-in): that toggle defaults to false and is not yet exposed in the

View file

@ -473,7 +473,7 @@ export const GameStructures: CollectionConfig = {
name: "quantity",
type: "number",
required: true,
min: 1,
min: 0,
defaultValue: 1,
},
{

View file

@ -77,7 +77,7 @@ export const LockerStorages: CollectionConfig = {
name: "quantity",
type: "number",
required: true,
min: 1,
min: 0,
defaultValue: 1,
},
{

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

@ -7,6 +7,7 @@ import { processLockerEvent } from "@/lib/arma-bridge/lockers";
import { processGarageEvent } from "@/lib/arma-bridge/garages";
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
import { processOperationEvent } from "@/lib/operations/process";
import { toRawSyncEvent } from "@/lib/operations/reconcile";
export const ArmaSyncEvents: CollectionConfig = {
slug: "arma-sync-events",
@ -16,55 +17,60 @@ export const ArmaSyncEvents: CollectionConfig = {
afterChange: [
async ({ doc, req, operation }) => {
if (operation !== "create") return;
// Payload hands afterChange a doc whose relationship fields are
// populated at defaultDepth (an object, not the numeric FK). Every
// downstream processor expects `server` to be a number, so normalize
// once here; without this they all bail as "malformed".
const raw = toRawSyncEvent(doc as unknown as Record<string, unknown>);
// Ledger first: every raw event is consumed into the operation ledger
// before any downstream projection runs. Evidence is always stored;
// only derived effects are gated by the kill switch.
if (isOperationLedgerEnabled()) {
await processOperationEvent(req.payload, doc, req);
await processOperationEvent(req.payload, raw, req);
}
if (doc.type === "player.kill") {
processPlayerKill(req.payload, doc).catch((err) => {
req.payload.logger.error(`[KillTracker] Failed to process kill event ${doc.eventId}: ${err}`);
if (raw.type === "player.kill") {
processPlayerKill(req.payload, raw).catch((err) => {
req.payload.logger.error(`[KillTracker] Failed to process kill event ${raw.eventId}: ${err}`);
});
}
if (doc.type.startsWith("box.")) {
if (raw.type.startsWith("box.")) {
// Awaited (not fire-and-forget) so the crate writes join the raw-event
// transaction; processBoxEvent never throws, so ingestion cannot be
// rolled back by crate sync.
try {
await processBoxEvent(req.payload, doc, req);
await processBoxEvent(req.payload, raw, req);
} catch (err) {
req.payload.logger.error(`[CrateSync] Failed to process box event ${doc.eventId}: ${err}`);
req.payload.logger.error(`[CrateSync] Failed to process box event ${raw.eventId}: ${err}`);
}
}
if (doc.type === "money.delta") {
if (raw.type === "money.delta") {
// Awaited so that by the time the game's flush returns, the bank
// balance already reflects it (the game pulls balances right after
// flushing). processMoneyEvent never throws.
await processMoneyEvent(req.payload, doc);
await processMoneyEvent(req.payload, raw);
}
if (doc.type.startsWith("reinforcement.")) {
if (raw.type.startsWith("reinforcement.")) {
// Awaited (same posture as money.delta): the pool balance must be
// current before the game's next reinforcement pull, and
// processReinforcementEvent never throws.
await processReinforcementEvent(req.payload, doc, req);
await processReinforcementEvent(req.payload, raw, req);
}
if (doc.type.startsWith("locker.")) {
if (raw.type.startsWith("locker.")) {
// Awaited (same posture as box.*): locker writes join the raw-event
// transaction; processLockerEvent never throws.
try {
await processLockerEvent(req.payload, doc, req);
await processLockerEvent(req.payload, raw, req);
} catch (err) {
req.payload.logger.error(`[LockerSync] Failed to process locker event ${doc.eventId}: ${err}`);
req.payload.logger.error(`[LockerSync] Failed to process locker event ${raw.eventId}: ${err}`);
}
}
if (doc.type.startsWith("garage.")) {
if (raw.type.startsWith("garage.")) {
// Awaited (same posture as locker.*): garage writes join the
// raw-event transaction; processGarageEvent never throws.
try {
await processGarageEvent(req.payload, doc, req);
await processGarageEvent(req.payload, raw, req);
} catch (err) {
req.payload.logger.error(`[GarageSync] Failed to process garage event ${doc.eventId}: ${err}`);
req.payload.logger.error(`[GarageSync] Failed to process garage event ${raw.eventId}: ${err}`);
}
}
},

View file

@ -9,6 +9,13 @@ import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
* service layer (`upsertEvaluation` in `src/lib/evaluations`), not by a DB
* constraint.
*
* Eligibility (rank-based, see `evaluateEligibility` in `src/lib/evaluations`):
* a strict rank gap between rater and ratee plus a yes-RSVP from at least one
* of them on the mission. Upward ratings (junior rates senior) are stored as
* `leader-direct`; downward ratings (senior rates junior) as `subordinate`.
* `leader-indirect` only exists on legacy rows written while eligibility was
* assignment-based.
*
* Privacy model: raw documents are only readable/writable by users holding the
* `evaluations:*` permissions (admin/developer via role docs). Normal users never
* receive raw rows over REST — the profile UI consumes pre-aggregated, rater-free
@ -56,15 +63,15 @@ export const Evaluations: CollectionConfig = {
type: "select",
options: [
{
label: "Leader (direct)",
label: "Leader (junior rates senior)",
value: "leader-direct",
},
{
label: "Leader (indirect)",
label: "Leader (legacy indirect)",
value: "leader-indirect",
},
{
label: "Subordinate",
label: "Subordinate (senior rates junior)",
value: "subordinate",
},
],

View file

@ -595,7 +595,7 @@ export function LockerGrid({
}),
)}
{items.map((item) => (
{items.filter((item) => item.quantity >= 1).map((item) => (
<DraggableLockerItem
key={item.id}
item={item}

View file

@ -280,7 +280,7 @@ export function LockerView({
>
<ItemContent className="gap-0 p-1.5">
<div className="flex flex-col">
{items.map((entry, index) => (
{items.filter((entry) => entry.quantity >= 1).map((entry, index) => (
<div key={entry.id}>
<button
type="button"

View file

@ -64,6 +64,7 @@ export function CreateListingDialog({
for (const entry of locker.items) {
const asset = entry.asset as Asset;
if (!asset || typeof asset === "number") continue;
if ((entry.quantity ?? 0) < 1) continue;
const attachments = entry.equipment?.attachments ?? [];
const skinId = resolveAssetId(entry.equipment?.skin);
if (attachments.length > 0 || skinId != null) continue;

View file

@ -127,8 +127,9 @@ export function LeadershipEvaluationDialog({
<DialogHeader>
<DialogTitle>Rate leadership</DialogTitle>
<DialogDescription>
Submit a new rating or update your existing rating for one completed mission. Your
rating is included anonymously in the leadership aggregate.
Submit a new rating or update your existing rating for one completed mission. Ratings
follow rank: only operators strictly above or below your own rank can be rated here.
Your rating is included anonymously.
</DialogDescription>
</DialogHeader>

View file

@ -78,7 +78,7 @@ export function LeadershipEvaluationSection({
)}
</CardTitle>
<CardDescription>
Anonymous feedback from operators who have served alongside this leader.
Anonymous ratings from unit members ranked above or below this operator.
</CardDescription>
</CardHeader>

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,
},
};
}

View file

@ -6,10 +6,18 @@ import {
type PerformanceLevelId,
} from "./levels";
import { missionEndTime } from "@/lib/intelligence/missionLifecycle";
import { rankDirection } from "./ranks";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
/** The three evaluation kinds, per the leadership-evaluations feature. */
/**
* The evaluation kinds. Since the rank-based rework only two kinds are ever
* written: `leader-direct` for an upward rating (junior rates senior, feeds
* the leader aggregate) and `subordinate` for a downward rating (senior rates
* junior). `leader-indirect` is legacy: rows written while eligibility was
* assignment-based keep it so their aggregates stay intact, but nothing new
* produces it.
*/
export type EvaluationKind = "leader-direct" | "leader-indirect" | "subordinate";
/** Shape of an evaluations doc as consumed by this service (depth 0). */
@ -58,9 +66,9 @@ export function isMissionEvaluable(
/**
* Documented participation proxy: this codebase has no actual participant list or
* mission-leader field on missions. A "yes" RSVP in `mission-attendances` is the
* evidence we treat as "this user took part in the mission". Used for leader
* ratings (direct and indirect). Subordinate ratings do not require it — the
* command relationship itself is the basis.
* evidence we treat as "this user took part in the mission". Under the rank-based
* rules at least one side of the pair must have a yes-RSVP for the mission, so
* every rating is anchored to an op one of them actually attended.
*/
export async function hasYesAttendance(
payload: PayloadType,
@ -83,45 +91,6 @@ export async function hasYesAttendance(
return res.docs.length > 0;
}
function extractIds(value: unknown): number[] {
if (!Array.isArray(value)) return [];
const ids: number[] = [];
for (const v of value) {
if (typeof v === "number") ids.push(v);
else if (v && typeof v === "object" && typeof (v as { id?: unknown }).id === "number") {
ids.push((v as { id: number }).id);
}
}
return ids;
}
/** True when `leaderId` leads an assignment whose members include `subordinateId`. */
export async function isDirectLeaderOf(
payload: PayloadType,
leaderId: number,
subordinateId: number,
): Promise<boolean> {
const assignments = await payload.find({
collection: "assignments",
where: { leader: { equals: leaderId } },
depth: 0,
overrideAccess: true,
});
return assignments.docs.some((a) => extractIds(a.members).includes(subordinateId));
}
/** True when `userId` leads at least one assignment. */
export async function isAnyLeader(payload: PayloadType, userId: number): Promise<boolean> {
const res = await payload.find({
collection: "assignments",
where: { leader: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return res.docs.length > 0;
}
export interface EligibilityResult {
eligible: boolean;
kind?: EvaluationKind;
@ -130,16 +99,18 @@ export interface EligibilityResult {
/**
* Determines whether `raterId` may evaluate `rateeId` for `missionId`, and under
* which kind. Rules (leadership-evaluations feature):
* which kind. Rules (leadership-evaluations feature, rank-based):
*
* - You cannot evaluate yourself.
* - The mission must be completed/past (see {@link isMissionEvaluable}).
* - `leader-direct`: the ratee directly leads the rater's assignment AND the rater
* participated in the mission (yes-RSVP proxy).
* - `subordinate`: the rater directly leads the ratee's assignment. No RSVP
* required — the command relationship itself is the basis.
* - `leader-indirect`: the rater participated in the mission and the ratee leads at
* least one assignment, but did not directly lead the rater.
* - Strict rank gap: the rater must hold a strictly lower or strictly higher
* rank than the ratee (per the ranks ladder). Equal ranks, or either side
* without a resolvable profile rank, are never eligible. Squad/division or
* assignment membership plays no role.
* - Rater strictly below ratee -> `leader-direct` (upward rating of a senior).
* - Rater strictly above ratee -> `subordinate` (downward rating of a junior).
* - At least one of rater/ratee must have a yes-RSVP for the mission, so every
* rating is anchored to an op one of them attended.
*/
export async function evaluateEligibility(
payload: PayloadType,
@ -173,25 +144,22 @@ export async function evaluateEligibility(
return { eligible: false, reason: "This mission is not completed or past yet." };
}
const participated = await hasYesAttendance(payload, raterId, missionId);
const rateeLeadsRater = await isDirectLeaderOf(payload, rateeId, raterId);
if (rateeLeadsRater) {
if (!participated) {
return { eligible: false, reason: "No attendance recorded for this mission." };
}
return { eligible: true, kind: "leader-direct" };
const direction = await rankDirection(payload, raterId, rateeId);
if (!direction) {
return {
eligible: false,
reason: "Evaluations require a strict rank difference (rate those above or below you).",
};
}
const raterLeadsRatee = await isDirectLeaderOf(payload, raterId, rateeId);
if (raterLeadsRatee) {
return { eligible: true, kind: "subordinate" };
const attended =
(await hasYesAttendance(payload, raterId, missionId)) ||
(await hasYesAttendance(payload, rateeId, missionId));
if (!attended) {
return { eligible: false, reason: "No attendance recorded for this mission." };
}
if (participated && (await isAnyLeader(payload, rateeId))) {
return { eligible: true, kind: "leader-indirect" };
}
return { eligible: false, reason: "No leadership relationship for this mission." };
return { eligible: true, kind: direction === "upward" ? "leader-direct" : "subordinate" };
}
export interface UpsertEvaluationInput {

View file

@ -0,0 +1,74 @@
import type { Payload } from "payload";
import { loadRankLadder, rankIndex, resolveRankFromLadder } from "@/lib/promotions/authority";
/**
* Rank seniority helpers for the leadership-evaluations feature.
*
* Eligibility is rank-based: a strictly junior member may rate a senior
* (upward), a strictly senior member may rate a junior (downward). Equal
* ranks, users without a profile, and users whose profile has no rank (or a
* rank that is not on the ladder) never form an eligible pair.
*/
type PayloadType = Payload;
/**
* Direction of a rating relative to the rater: "upward" means the rater holds
* a strictly lower rank than the ratee; "downward" means strictly higher.
*/
export type RankDirection = "upward" | "downward";
/**
* Ladder index (0 = lowest rank) for each user that has a profile carrying a
* rank found on the ladder. Users without a profile, with a null rank, or with
* an off-ladder rank are simply absent from the map. Bulk helper shared by the
* reminder planners so they can load seniority for everyone in one pass.
*/
export async function getUserRankIndexes(
payload: PayloadType,
userIds: readonly number[],
): Promise<Map<number, number>> {
const uniqueIds = [...new Set(userIds)];
if (uniqueIds.length === 0) return new Map();
const ladder = await loadRankLadder(payload);
if (ladder.length === 0) return new Map();
const res = await payload.find({
collection: "profiles",
where: { user: { in: uniqueIds } },
limit: 1000,
depth: 0,
select: { user: true, rank: true },
overrideAccess: true,
});
const wanted = new Set(uniqueIds.map((id) => String(id)));
const indexes = new Map<number, number>();
for (const profile of res.docs) {
const userId = typeof profile.user === "number" ? profile.user : profile.user?.id;
if (userId == null || !wanted.has(String(userId))) continue;
const rank = resolveRankFromLadder(ladder, profile.rank as number | undefined | null);
if (!rank) continue;
indexes.set(userId, rankIndex(ladder, rank.id));
}
return indexes;
}
/**
* Rank relationship between rater and ratee, or null when no strict gap
* exists (equal ranks, or either side without a resolvable rank).
*/
export async function rankDirection(
payload: PayloadType,
raterId: number,
rateeId: number,
): Promise<RankDirection | null> {
const indexes = await getUserRankIndexes(payload, [raterId, rateeId]);
const raterIndex = indexes.get(raterId);
const rateeIndex = indexes.get(rateeId);
if (raterIndex === undefined || rateeIndex === undefined) return null;
if (raterIndex < rateeIndex) return "upward";
if (raterIndex > rateeIndex) return "downward";
return null;
}

View file

@ -6,17 +6,19 @@ import type { Payload } from "payload";
* Rules (aligned with `evaluateEligibility` in ./index.ts):
* - Participants = users with a "yes" RSVP for the mission (the documented
* participation proxy — same as the profile-page rating dialog).
* - Every participant is reminded to rate their direct leader(s) — eligible as
* `leader-direct` (and, for any other leader, `leader-indirect`).
* - Every leader of an assignment containing a participant is reminded to rate
* that participant — eligible as `subordinate` (no RSVP required for leaders).
* - Self-pairs are skipped; a user who is both a participant and a leader gets a
* single merged DM.
* - Pairing follows rank, not assignments: every pair of participants with a
* strict rank gap is reminded in both directions. The junior is prompted to
* rate the senior (`leader-direct`); the senior is prompted to rate the
* junior (`subordinate`).
* - Same-rank participants and participants without a profile rank form no
* pairs; self-pairs are skipped; a user with both lists gets one merged DM.
*
* This module is payload-only (no Discord imports) so the recipient plan is
* testable independently of the bot service.
*/
import { getUserRankIndexes } from "./ranks";
type PayloadType = Payload;
export interface ReminderLink {
@ -42,18 +44,6 @@ export interface EvaluationReminderPlan {
recipients: ReminderRecipient[];
}
function extractIds(value: unknown): number[] {
if (!Array.isArray(value)) return [];
const ids: number[] = [];
for (const v of value) {
if (typeof v === "number") ids.push(v);
else if (v && typeof v === "object" && typeof (v as { id?: unknown }).id === "number") {
ids.push((v as { id: number }).id);
}
}
return ids;
}
function extractId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "number") {
@ -98,30 +88,13 @@ export async function computeEvaluationReminderPlan(
return { missionId, recipients: [] };
}
// 2. Command graph from assignments: leader -> members, member -> leaders.
const assignments = await payload.find({
collection: "assignments",
where: { leader: { not_equals: null } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
const leadersOf = new Map<number, Set<number>>();
const membersLedBy = new Map<number, Set<number>>();
for (const a of assignments.docs) {
const leaderId = extractId(a.leader);
if (leaderId === null) continue;
for (const memberId of extractIds(a.members)) {
if (memberId === leaderId) continue; // a leader is not their own leader
if (!leadersOf.has(memberId)) leadersOf.set(memberId, new Set());
leadersOf.get(memberId)!.add(leaderId);
if (!membersLedBy.has(leaderId)) membersLedBy.set(leaderId, new Set());
membersLedBy.get(leaderId)!.add(memberId);
}
}
// 2. Rank ladder index per participant. Participants without a profile rank
// are left out: eligibility needs a strict rank gap on both sides.
const rankIndexes = await getUserRankIndexes(payload, participantIds);
const ranked = participantIds.filter((id) => rankIndexes.has(id));
// 3. Merge both roles per user: participant -> rate leaders; leader of a
// participant -> rate that participant.
// 3. Pair every strict-rank-gap combination among the ranked participants:
// the junior rates the senior upward, the senior rates the junior downward.
const plan = new Map<number, { rateLeaders: Map<number, number>; rateSubordinates: Map<number, number> }>();
const ensure = (userId: number) => {
let entry = plan.get(userId);
@ -132,11 +105,17 @@ export async function computeEvaluationReminderPlan(
return entry;
};
for (const participantId of participantIds) {
ensure(participantId); // even with no direct leader they may still be rated by theirs
for (const leaderId of leadersOf.get(participantId) ?? []) {
ensure(participantId).rateLeaders.set(leaderId, participantId);
ensure(leaderId).rateSubordinates.set(participantId, leaderId);
for (let i = 0; i < ranked.length; i += 1) {
for (let j = i + 1; j < ranked.length; j += 1) {
const a = ranked[i];
const b = ranked[j];
const indexA = rankIndexes.get(a)!;
const indexB = rankIndexes.get(b)!;
if (indexA === indexB) continue; // equal ranks never rate each other
const junior = indexA < indexB ? a : b;
const senior = indexA < indexB ? b : a;
ensure(junior).rateLeaders.set(senior, junior);
ensure(senior).rateSubordinates.set(junior, senior);
}
}

View file

@ -1,4 +1,5 @@
import type { Payload } from "payload";
import { getUserRankIndexes } from "@/lib/evaluations/ranks";
/**
* Mission feedback reminder window: a completed main operation only prompts for
@ -13,7 +14,7 @@ export interface ReminderLeader {
displayName: string;
}
/** One eligible mission with the direct leaders who RSVP'd "yes". */
/** One eligible mission with the strictly higher-ranked attendees who RSVP'd "yes". */
export interface MissionReminder {
missionId: number;
missionName: string;
@ -28,35 +29,16 @@ function refId(value: number | { id: number } | null | undefined): number | null
return null;
}
/**
* The user's direct leaders, using the same assignment model as
* `isDirectLeaderOf` in `@/lib/evaluations`: a leader is anyone who leads an
* assignment whose members include this user.
*/
async function findDirectLeaderIds(payload: Payload, userId: number): Promise<number[]> {
const res = await payload.find({
collection: "assignments",
where: { members: { contains: userId } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const ids = new Set<number>();
for (const assignment of res.docs) {
const leaderId = refId(assignment.leader);
if (leaderId !== null) ids.add(leaderId);
}
return [...ids];
}
/**
* Recently completed main operations that need feedback from `user`: the mission
* is a main operation, transitioned to Completed within the last 72 hours
* (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one of
* the user's assignment-based direct leaders also RSVP'd "yes".
* (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one
* strictly higher-ranked co-attendee also RSVP'd "yes" (rank-based feedback
* model: you rate those above you; same-rank peers are never listed).
*
* Fail-closed: missions with a missing or unparseable completion timestamp are
* never eligible, and `updatedAt` is never used as a completion proxy.
* never eligible, and `updatedAt` is never used as a completion proxy. A user
* without a profile rank gets no reminders because they cannot rate anyone.
*/
export async function getMissionReminders(
payload: Payload,
@ -125,9 +107,14 @@ export async function getMissionReminders(
yesUsers.add(userId);
}
const leaderIds = await findDirectLeaderIds(payload, user.id);
if (leaderIds.length === 0) return [];
const leaderSet = new Set(leaderIds);
// Rank model: the people the user is prompted to rate are the co-attendees
// holding a strictly higher rank. No profile rank means nothing rateable.
const attendeeIds = [
...new Set([...yesByMission.values()].flatMap((yesUsers) => [...yesUsers])),
];
const rankIndexes = await getUserRankIndexes(payload, attendeeIds);
const userRankIndex = rankIndexes.get(user.id);
if (userRankIndex === undefined) return [];
const eligible: Array<{
mission: (typeof missionsRes.docs)[number];
@ -137,8 +124,12 @@ export async function getMissionReminders(
for (const { mission, completedAt } of candidates) {
const yesUsers = yesByMission.get(mission.id) ?? new Set<number>();
if (!yesUsers.has(user.id)) continue; // the user must have RSVP'd "yes"
const leaders = [...yesUsers].filter((id) => leaderSet.has(id));
if (leaders.length === 0) continue; // at least one direct leader must have RSVP'd "yes"
const leaders = [...yesUsers].filter((id) => {
if (id === user.id) return false;
const index = rankIndexes.get(id);
return index !== undefined && index > userRankIndex;
});
if (leaders.length === 0) continue; // at least one higher-ranked co-attendee required
eligible.push({ mission, completedAt, leaderIds: leaders });
}

View file

@ -29,6 +29,9 @@ export type LockerGridItem = {
/** Normalize raw locker `items` into populated grid items. */
export function toLockerGridItems(items: LockerStorage["items"]): LockerGridItem[] {
// Depleted rows (quantity 0) are kept: they still reserve their grid cell, so
// a restock cannot land on top of a live item, and their equipment resolves.
// Views that show stock on hand filter them out at the render boundary.
return (items ?? [])
.filter((e) => e.asset && typeof e.asset === "object" && "id" in e.asset)
.map((e) => {

View file

@ -142,7 +142,10 @@ export function buildSearchEntries(
for (const item of items) {
if (!item.asset) continue;
const displayName = item.equipment?.customName?.trim() || item.asset.name;
upsert(item.asset, item.quantity, { kind: "locker", text: "In locker" }, displayName);
// Quantity 0 is an explicit depletion from locker sync, not stock on hand.
if (item.quantity >= 1) {
upsert(item.asset, item.quantity, { kind: "locker", text: "In locker" }, displayName);
}
for (const attachment of item.equipment?.attachments ?? []) {
const asset = resolveAssetRef(attachment.asset, items);

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();
}
});
});

View file

@ -27,11 +27,14 @@ describe("Leadership evaluations", () => {
let participantE: User;
let noRsvpF: User;
let outsiderD: User;
let assignmentId: number;
let juniorRankId: number;
let midRankId: number;
let seniorRankId: number;
let missionCompletedId: number;
let missionFutureId: number;
const userIds: number[] = [];
const rankIds: number[] = [];
const attendanceIds: number[] = [];
const evaluationIds: number[] = [];
@ -53,6 +56,41 @@ describe("Leadership evaluations", () => {
return user;
};
// Self-contained ladder slice: creation order ascends in seniority, matching
// the pattern in promotions.int.spec.ts.
const makeRank = async (name: string): Promise<number> => {
const rank = await payload.create({
collection: "ranks",
data: {
name: `${RUN} ${name}`,
abbreviation: `${RUN}-${name.toLowerCase()}`,
description: `${RUN} test rank`,
},
overrideAccess: true,
depth: 0,
});
rankIds.push(rank.id);
return rank.id;
};
const setProfileRank = async (userId: number, rankId: number): Promise<void> => {
const profiles = (await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
expect(profiles.docs.length).toBe(1); // hook-provisioned profile
await payload.update({
collection: "profiles",
id: profiles.docs[0].id,
data: { rank: rankId },
overrideAccess: true,
depth: 0,
});
};
const makeMission = async (
label: string,
status: Mission["ownershipAndStatus"]["status"],
@ -123,6 +161,10 @@ describe("Leadership evaluations", () => {
})) as unknown as Campaign;
campaignId = campaign.id;
juniorRankId = await makeRank("Jr");
midRankId = await makeRank("Mid");
seniorRankId = await makeRank("Sr");
leaderA = await makeUser("leader-a");
subordinateB = await makeUser("subordinate-b");
participantC = await makeUser("participant-c");
@ -130,18 +172,24 @@ describe("Leadership evaluations", () => {
noRsvpF = await makeUser("no-rsvp-f");
outsiderD = await makeUser("outsider-d");
const assignment = await payload.create({
collection: "assignments",
data: {
name: `${RUN} Squad`,
type: "squad",
leader: leaderA.id,
members: [subordinateB.id, noRsvpF.id],
},
overrideAccess: true,
// Rank ladder: leaderA (Sr) > C/E (Mid) > B/F (Jr). The Users hook gives
// every new profile a default bottom rank, and profiles require one, so D's
// profile is deleted outright to exercise the no-rank path.
await setProfileRank(leaderA.id, seniorRankId);
await setProfileRank(subordinateB.id, juniorRankId);
await setProfileRank(participantC.id, midRankId);
await setProfileRank(participantE.id, midRankId);
await setProfileRank(noRsvpF.id, juniorRankId);
const dProfiles = await payload.find({
collection: "profiles",
where: { user: { equals: outsiderD.id } },
limit: 5,
depth: 0,
overrideAccess: true,
});
assignmentId = assignment.id;
for (const doc of dProfiles.docs) {
await payload.delete({ collection: "profiles", id: doc.id, overrideAccess: true });
}
const past = new Date();
past.setDate(past.getDate() - 7);
@ -181,9 +229,9 @@ describe("Leadership evaluations", () => {
.delete({ collection: "mission-attendances", id, overrideAccess: true })
.catch(() => {});
}
await payload.delete({ collection: "assignments", id: assignmentId, overrideAccess: true }).catch(
() => {},
);
for (const id of rankIds) {
await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
}
for (const id of [missionCompletedId, missionFutureId]) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
@ -248,11 +296,16 @@ describe("Leadership evaluations", () => {
expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false);
});
it("derives the evaluation kind from the rater/ratee/mission relationship", async () => {
it("derives the evaluation kind from rank relation and shared attendance", async () => {
const cases = [
// Junior rates a senior (rater attended) -> upward leader rating.
{ input: { raterId: subordinateB.id, rateeId: leaderA.id }, expectKind: "leader-direct" },
{ input: { raterId: participantC.id, rateeId: leaderA.id }, expectKind: "leader-indirect" },
// Mid rates the senior (rater attended) -> also upward, no assignment needed.
{ input: { raterId: participantC.id, rateeId: leaderA.id }, expectKind: "leader-direct" },
// Senior rates a junior -> downward subordinate rating.
{ input: { raterId: leaderA.id, rateeId: subordinateB.id }, expectKind: "subordinate" },
// F never RSVPed, but E did: one side attending anchors the mission.
{ input: { raterId: noRsvpF.id, rateeId: participantE.id }, expectKind: "leader-direct" },
];
for (const { input, expectKind } of cases) {
const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId });
@ -260,22 +313,32 @@ describe("Leadership evaluations", () => {
expect(result.kind).toBe(expectKind);
}
// In A's assignment but never RSVPed yes — the participation proxy fails.
const noRsvp = await evaluateEligibility(payload, {
raterId: noRsvpF.id,
rateeId: leaderA.id,
// Equal ranks can never rate each other, even with both on the roster.
const peer = await evaluateEligibility(payload, {
raterId: participantE.id,
rateeId: participantC.id,
missionId: missionCompletedId,
});
expect(noRsvp.eligible).toBe(false);
expect(noRsvp.reason).toBe("No attendance recorded for this mission.");
expect(peer.eligible).toBe(false);
expect(peer.reason).toContain("strict rank");
// No leadership relationship at all.
const outsider = await evaluateEligibility(payload, {
// Rankless raters are ineligible regardless of attendance.
const rankless = await evaluateEligibility(payload, {
raterId: outsiderD.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
});
expect(outsider.eligible).toBe(false);
expect(rankless.eligible).toBe(false);
expect(rankless.reason).toContain("strict rank");
// Strict rank gap but neither side attended this mission.
const noAttendance = await evaluateEligibility(payload, {
raterId: noRsvpF.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
});
expect(noAttendance.eligible).toBe(false);
expect(noAttendance.reason).toBe("No attendance recorded for this mission.");
// Self-rating is always rejected.
const selfRating = await evaluateEligibility(payload, {

View file

@ -8,7 +8,7 @@ import { randomUUID } from "node:crypto";
import { NextRequest } from "next/server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Assignment, Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import { GET } from "@/app/api/mission-reminder/route";
import { getMissionReminders } from "@/lib/intelligence/missionReminder";
@ -73,7 +73,7 @@ describe("Mission feedback reminder", () => {
const userIds: number[] = [];
const missionIds: number[] = [];
const attendanceIds: number[] = [];
const assignmentIds: number[] = [];
const rankIds: number[] = [];
let memberId: number;
let leaderAId: number;
@ -92,7 +92,7 @@ describe("Mission feedback reminder", () => {
let staleMainId: number; // main, 73h ago (past the window)
let noStampId: number; // main, completion stamp cleared -> fail closed
let userNoId: number; // member RSVP'd "no"
let leaderNoId: number; // only a non-leader (stranger) RSVP'd yes
let leaderNoId: number; // only a same-rank peer (stranger) RSVP'd yes
// Boundary fixtures relative to fixedNow.
let boundaryExactId: number; // exactly fixedNow - 72h -> included at fixedNow
@ -148,21 +148,50 @@ describe("Mission feedback reminder", () => {
strangerId = stranger.id;
lonerId = loner.id;
// The member belongs to two squads, so their direct leaders are both
// leaders (same model as isDirectLeaderOf in @/lib/evaluations).
const makeAssignment = async (label: string, leaderId: number): Promise<Assignment> => {
const assignment = (await payload.create({
collection: "assignments",
data: { name: `${RUN} ${label}`, type: "squad", leader: leaderId, members: [memberId] },
// Rank-based pairing (same model as @/lib/evaluations/ranks): leaderA and
// leaderB strictly outrank member/stranger/loner, who share one junior rank.
// Creation order ascends in seniority, matching the promotions specs.
const makeRank = async (label: string): Promise<number> => {
const rank = await payload.create({
collection: "ranks",
data: {
name: `${RUN} ${label}`,
abbreviation: `${RUN}-${label.toLowerCase()}`,
description: `${RUN} test rank`,
},
overrideAccess: true,
depth: 0,
})) as unknown as Assignment;
assignmentIds.push(assignment.id);
return assignment;
});
rankIds.push(rank.id);
return rank.id;
};
await makeAssignment("Squad A", leaderAId);
await makeAssignment("Squad B", leaderBId);
const setProfileRank = async (userId: number, rankId: number): Promise<void> => {
const profiles = (await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
expect(profiles.docs.length).toBe(1); // hook-provisioned profile
await payload.update({
collection: "profiles",
id: profiles.docs[0].id,
data: { rank: rankId },
overrideAccess: true,
depth: 0,
});
};
const jrRankId = await makeRank("Jr");
const sr1RankId = await makeRank("Sr1");
const sr2RankId = await makeRank("Sr2");
await setProfileRank(memberId, jrRankId);
await setProfileRank(strangerId, jrRankId); // same rank as the member
await setProfileRank(lonerId, jrRankId);
await setProfileRank(leaderAId, sr1RankId);
await setProfileRank(leaderBId, sr2RankId);
const makeMission = async (
label: string,
@ -272,7 +301,7 @@ describe("Mission feedback reminder", () => {
await makeMission("leader-no", "main", new Date(fixedNow.getTime() - DAY).toISOString())
).id;
await addAttendance(leaderNoId, memberId, "yes");
await addAttendance(leaderNoId, strangerId, "yes"); // a non-leader "yes" must not count
await addAttendance(leaderNoId, strangerId, "yes"); // a same-rank peer "yes" must not count
// Boundary fixtures relative to fixedNow.
boundaryExactId = (
@ -308,8 +337,8 @@ describe("Mission feedback reminder", () => {
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
for (const id of assignmentIds) {
await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {});
for (const id of rankIds) {
await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
}
// User deletion trips FK constraints unless the hook-provisioned personal
// bank account and profile are removed first.
@ -355,7 +384,7 @@ describe("Mission feedback reminder", () => {
expect(res.status).toBe(401);
});
it("returns only eligible missions with the yes-RSVP direct leaders", async () => {
it("returns only eligible missions with the yes-RSVP higher-ranked attendees", async () => {
const res = await GET(request(memberToken));
expect(res.status).toBe(200);
const body = (await res.json()) as { reminders: Array<Record<string, unknown>> };
@ -387,13 +416,13 @@ describe("Mission feedback reminder", () => {
expect(leaders[0].username).toBe(`${RUN}-leader-a`);
expect(leaders[0].displayName).toBe("LEADER A");
// Both direct leaders who RSVP'd yes are reported.
// Both higher-ranked yes-RSVPers are reported.
const multi = byMissionId.get(multiLeaderId)!;
const multiLeaderIds = (multi.leaders as Array<{ id: number }>).map((leader) => leader.id);
expect([...multiLeaderIds].sort()).toEqual([leaderAId, leaderBId].sort());
});
it("returns nothing for a user without direct leaders", async () => {
it("returns nothing for a user without higher-ranked co-attendees", async () => {
const res = await GET(request(lonerToken));
expect(res.status).toBe(200);
const body = (await res.json()) as { reminders: unknown[] };