1
0
Fork 0
polaris-task-force/src/lib/respawn-tickets/index.ts
Z8MB1E 7ad9320c02 feat(respawn-tickets): settle attendance-based respawn tickets per mission
Tickets collection, settlement service, arma-bridge API route, one-shot ticketsSettledAt marker on missions, migration, and tests.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-09-14 15:37:05 -04:00

258 lines
8.2 KiB
TypeScript

import { getMissionAttendance } from "@/lib/attendance";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { emitGameEvent } from "@/utils/event-log/emit";
import type { Mission, User } from "@/payload-types";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
// Award per actual attendee, keyed by RSVP response (TODO.md: respawn
// tickets based on attendance). Attending without an RSVP awards nothing.
const AWARD_BY_RESPONSE = { yes: 1, tentative: 0.5, no: 0.25 } as const;
type AwardResponse = keyof typeof AWARD_BY_RESPONSE;
// Attendance is measured inside a window around the mission start: connections
// after the next mission begins belong to that operation, and 24h is the
// absolute cutoff for a mission that is never followed by another one.
const WINDOW_BEFORE_MS = 60 * 60 * 1000;
const WINDOW_AFTER_MS = 24 * 60 * 60 * 1000;
// Draft statuses never settle: Concept/Planning/Ready ops may still be
// scrapped, and Cancelled is terminal without attendance.
const SETTLEABLE_STATUSES = ["Scheduled", "Active", "Completed"] as const;
export interface SettleOptions {
/** Restrict settlement to these mission ids (tests scope runs this way). */
missionIds?: number[];
/** Time source for window gating (defaults to now). */
now?: Date;
}
export interface SettleResult {
/** Mission ids settled in this run (ticketsSettledAt stamped). */
settled: number[];
/** Points added this run, per user id. */
awardedByUser: Record<number, number>;
}
interface SyncEventDoc {
id: number | string;
type: string;
occurredAt: string;
payload?: unknown;
}
function steamIdFromSyncEvent(event: SyncEventDoc): string | null {
const payload = event.payload;
if (!Array.isArray(payload) || payload.length < 2) return null;
const raw = payload[1];
if (typeof raw === "string" && raw.length > 0) return raw.trim();
if (typeof raw === "number") return String(raw);
return null;
}
async function fetchAttendeeSteamIds(
payload: PayloadType,
serverIds: number[],
windowStart: Date,
windowEnd: Date,
): Promise<Set<string>> {
const attendees = new Set<string>();
for (const serverId of serverIds) {
const res = await payload.find({
collection: "arma-sync-events",
where: {
and: [
{ server: { equals: serverId } },
{ type: { equals: "player.connected" } },
{ occurredAt: { greater_than_equal: windowStart.toISOString() } },
{ occurredAt: { less_than_equal: windowEnd.toISOString() } },
],
},
depth: 0,
limit: 5000,
sort: "occurredAt",
overrideAccess: true,
});
for (const doc of res.docs as unknown as SyncEventDoc[]) {
const steamId = steamIdFromSyncEvent(doc);
if (steamId) attendees.add(steamId);
}
}
return attendees;
}
async function awardTickets(
payload: PayloadType,
userId: number,
points: number,
awardedByUser: Record<number, number>,
): Promise<void> {
const res = await payload.find({
collection: "respawn-tickets",
where: { user: { equals: userId } },
depth: 0,
limit: 1,
overrideAccess: true,
});
const doc = res.docs[0];
const previous = awardedByUser[userId] ?? 0;
awardedByUser[userId] = previous + points;
if (doc) {
const balance = Math.round(((doc.balance ?? 0) + points) * 100) / 100;
await payload.update({
collection: "respawn-tickets",
id: doc.id,
data: { balance },
overrideAccess: true,
});
} else {
await payload.create({
collection: "respawn-tickets",
data: { user: userId, balance: Math.round(points * 100) / 100 },
overrideAccess: true,
});
}
}
async function settleMission(
payload: PayloadType,
mission: Mission,
windowStart: Date,
windowEnd: Date,
result: SettleResult,
): Promise<void> {
const servers = await payload.find({
collection: "game-servers",
depth: 0,
limit: 1000,
overrideAccess: true,
});
const serverIds = servers.docs.map((server) => server.id);
const attendees = await fetchAttendeeSteamIds(payload, serverIds, windowStart, windowEnd);
const awardedByUser: Record<number, number> = {};
let awardedCount = 0;
if (attendees.size > 0) {
const attendance = await getMissionAttendance(payload, mission.id);
for (const response of Object.keys(AWARD_BY_RESPONSE) as AwardResponse[]) {
for (const user of attendance[response] as User[]) {
if (!user.steamId || !attendees.has(user.steamId.trim())) continue;
await awardTickets(payload, user.id, AWARD_BY_RESPONSE[response], awardedByUser);
awardedCount++;
}
}
}
await payload.update({
collection: "missions",
id: mission.id,
data: { ticketsSettledAt: new Date().toISOString() },
overrideAccess: true,
});
result.settled.push(mission.id);
for (const [userId, points] of Object.entries(awardedByUser)) {
const existing = result.awardedByUser[Number(userId)] ?? 0;
result.awardedByUser[Number(userId)] = Math.round((existing + points) * 100) / 100;
}
if (awardedCount > 0) {
emitGameEvent(payload, {
type: EventTypes.RespawnTicketsSettled,
message: `${mission.name ?? `Mission #${mission.id}`}: respawn tickets settled (${awardedCount} attendee${awardedCount === 1 ? "" : "s"} awarded).`,
targetCollection: "missions",
targetId: mission.id,
data: { awardedByUser },
});
}
}
/**
* Settles respawn tickets for every mission whose attendance window has
* closed: RSVP responses are matched against actual attendance (player
* connections on the arma-sync-events feed) and the awards are accumulated
* into per-player respawn-tickets balances. Idempotent via the mission's
* ticketsSettledAt marker.
*/
export async function settleDueMissions(
payload: PayloadType,
options: SettleOptions = {},
): Promise<SettleResult> {
const now = options.now ?? new Date();
const result: SettleResult = { settled: [], awardedByUser: {} };
const missions = await payload.find({
collection: "missions",
where: {
and: [
{ "ownershipAndStatus.status": { in: [...SETTLEABLE_STATUSES] } },
...(options.missionIds?.length ? [{ id: { in: options.missionIds } }] : []),
],
},
depth: 0,
limit: 1000,
overrideAccess: true,
});
const all = await payload.find({
collection: "missions",
...(options.missionIds?.length ? { where: { id: { in: options.missionIds } } } : {}),
depth: 0,
limit: 1000,
overrideAccess: true,
});
const startMs = (mission: Mission): number | null => {
const start = mission.classification?.startDateTime;
if (!start) return null;
return new Date(start).getTime();
};
const candidates = (missions.docs as unknown as Mission[])
.filter((mission) => !mission.ticketsSettledAt && startMs(mission) !== null)
.sort((a, b) => (startMs(a) as number) - (startMs(b) as number));
for (const mission of candidates) {
const missionStart = startMs(mission) as number;
const laterStarts = (all.docs as unknown as Mission[])
.map((other) => (other.id === mission.id ? null : startMs(other)))
.filter((value): value is number => value !== null && value > missionStart);
const nextMissionStart = laterStarts.length ? Math.min(...laterStarts) : null;
const windowStart = new Date(missionStart - WINDOW_BEFORE_MS);
const windowEnd = new Date(
Math.min(missionStart + WINDOW_AFTER_MS, nextMissionStart ?? Infinity),
);
if (now.getTime() < windowEnd.getTime()) continue;
await settleMission(payload, mission, windowStart, windowEnd, result);
}
return result;
}
/**
* Resolved ticket balances keyed by the player's steam id (only balances
* above zero), in the shape the Arma 3 mod expects.
*/
export async function getTicketBalances(
payload: PayloadType,
): Promise<Record<string, number>> {
const res = await payload.find({
collection: "respawn-tickets",
where: { balance: { greater_than: 0 } },
depth: 1,
limit: 10000,
overrideAccess: true,
});
const tickets: Record<string, number> = {};
for (const doc of res.docs) {
const user = doc.user as User;
if (!user || typeof user === "number" || !user.steamId) continue;
tickets[user.steamId] = Math.round((doc.balance ?? 0) * 100) / 100;
}
return tickets;
}