From 5d4dbab36b8198c0d69b7e04d1e9e83f4eb717c1 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Mon, 2 Nov 2026 10:00:25 -0500 Subject: [PATCH] feat(dev): add seed-attendance bin for random mission attendance New Payload bin seeds a random subset of users with weighted attendance (75% yes / 15% no / 10% tentative) for a given mission, clearing prior records first so each run produces a fresh sample. Written through the single attendance write path so events and slot-holder notifications fire normally. --- src/payload.config.ts | 4 + src/scripts/seedMissionAttendance.ts | 121 +++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 src/scripts/seedMissionAttendance.ts diff --git a/src/payload.config.ts b/src/payload.config.ts index 8c41cc27..aef470ba 100644 --- a/src/payload.config.ts +++ b/src/payload.config.ts @@ -657,6 +657,10 @@ export default buildConfig({ scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"), key: "generate-mission", }, + { + scriptPath: path.resolve(dirname, "scripts/seedMissionAttendance.ts"), + key: "seed-attendance", + }, { scriptPath: path.resolve(dirname, "scripts/analyticsRollup.ts"), key: "analytics-rollup", diff --git a/src/scripts/seedMissionAttendance.ts b/src/scripts/seedMissionAttendance.ts new file mode 100644 index 00000000..962184a5 --- /dev/null +++ b/src/scripts/seedMissionAttendance.ts @@ -0,0 +1,121 @@ +import type { SanitizedConfig } from "payload"; +import { getPayload } from "payload"; +import { + getMissionAttendance, + setMissionAttendance, + type AttendanceResponse, +} from "@/lib/attendance"; +import { createBinLogger, errorMessage } from "./lib/binFileLogger"; + +/** + * Test helper: seeds random attendance for a mission. Picks a random subset of + * users and assigns each a response weighted 75% yes / 15% no / 10% tentative. + * + * Existing attendance for the mission is cleared first so every run produces a + * fresh, predictable sample rather than accumulating stale rows. + * + * Usage: + * bun run payload seed-attendance [count] + * required — the mission to seed + * [count] optional — how many random users to sample (default 25) + */ + +const YES_WEIGHT = 0.75; +const NO_WEIGHT = 0.15; +const DEFAULT_SAMPLE_SIZE = 25; + +function drawResponse(): AttendanceResponse { + const roll = Math.random(); + if (roll < YES_WEIGHT) return "yes"; + if (roll < YES_WEIGHT + NO_WEIGHT) return "no"; + return "tentative"; +} + +function shuffle(items: T[]): T[] { + const result = [...items]; + for (let i = result.length - 1; i > 0; i -= 1) { + const j = Math.floor(Math.random() * (i + 1)); + [result[i], result[j]] = [result[j], result[i]]; + } + return result; +} + +export const script = async (config: SanitizedConfig) => { + const payload = await getPayload({ config }); + const log = createBinLogger("seed-attendance", payload.logger); + + try { + // Payload's bin runner calls `script(config)` and leaves the CLI args in + // process.argv as [node, bin.js, , ...positionals], so the first + // positional is the bin key and the mission id is the second token. + const tokens = process.argv.slice(2).filter((arg) => !arg.startsWith("-")); + const rawMissionId = tokens[1]; + const rawCount = tokens[2]; + const missionId = Number(rawMissionId); + if (!rawMissionId || Number.isNaN(missionId)) { + log.error( + "[Seed Attendance] Usage: bun run payload seed-attendance [count]", + ); + process.exit(1); + } + + const mission = await payload + .findByID({ collection: "missions", id: missionId, depth: 0, overrideAccess: true }) + .catch(() => null); + if (!mission) { + log.error(`[Seed Attendance] Mission #${missionId} not found.`); + process.exit(1); + } + + // Existing attendance for this mission is wiped so re-runs stay idempotent + // in size (fresh random set, never stacking on prior runs). + const cleared = (await payload.delete({ + collection: "mission-attendances", + where: { mission: { equals: missionId } }, + overrideAccess: true, + })) as unknown as { totalDocs: number; docs: { id: number }[] }; + const clearedCount = cleared.totalDocs ?? (cleared.docs?.length ?? 0); + + const users = (await payload.find({ + collection: "users", + limit: 1000, + depth: 0, + overrideAccess: true, + })) as unknown as { docs: { id: number }[] }; + const candidates = shuffle(users.docs); + + const sampleSize = Math.min( + rawCount ? Number(rawCount) : DEFAULT_SAMPLE_SIZE, + candidates.length, + ); + if (candidates.length === 0) { + log.info("[Seed Attendance] No users found; nothing to seed."); + process.exit(0); + } + + let yes = 0; + let no = 0; + let tentative = 0; + for (let i = 0; i < sampleSize; i += 1) { + const userId = candidates[i].id; + const response = drawResponse(); + await setMissionAttendance(payload, { missionId, userId, response }); + if (response === "yes") yes += 1; + else if (response === "no") no += 1; + else tentative += 1; + } + + const summary = await getMissionAttendance(payload, missionId); + log.info( + `[Seed Attendance] Seeded ${sampleSize} attendance record(s) for Mission #${missionId} ` + + `(cleared ${clearedCount} prior). Yes: ${summary.counts.yes}, No: ${summary.counts.no}, ` + + `Tentative: ${summary.counts.tentative}.`, + ); + process.exit(0); + } catch (error) { + log.error( + `[Seed Attendance] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`, + ); + process.exit(1); + } +};