- The mission tick now runs two idempotent sweeps: auto-start flips Scheduled missions whose start time has arrived to Active, and auto-complete sets missions whose scheduled window (start plus duration) has fully passed to Completed with a stamped completedAt. - Side ops are created as quiet Ready drafts and committed with a "Mark as Scheduled" control, which is what posts the Discord roll-call and hands the op to the lifecycle above. - Daily schedule reminders nudge the creator to set a draft live (web notification plus Discord DM). - Adds the mission lifecycle/commit event types and the matching notification labels, and updates the bot docs.
146 lines
5.7 KiB
TypeScript
146 lines
5.7 KiB
TypeScript
import type { Payload } from "payload";
|
|
import type { Mission } from "@/payload-types";
|
|
import { notifyUser } from "@/lib/notifications";
|
|
|
|
/**
|
|
* Ready-reminder system for player-scheduled side ops.
|
|
*
|
|
* Starting READY_REMINDER_LEAD_DAYS days before an op's scheduled start, the
|
|
* creator gets a once-per-day reminder (web notification + Discord DM) to
|
|
* finish the op and commit it to "Scheduled" (markSideOpScheduled): the status
|
|
* that triggers the roll-call embed, locks in details, and delivers the mission
|
|
* hooks. Reminders stop the moment the op is Scheduled (or
|
|
* cancelled/completed/active), and a marker field records the last server-local
|
|
* day each channel was sent so the cadence is exactly one reminder per day per
|
|
* channel.
|
|
*
|
|
* Side ops are created as a quiet "Ready" draft (createFridaySideOp), so a
|
|
* reminder is due while the op is still Concept/Planning/Ready.
|
|
*
|
|
* Scope: only ops with a `createdBy` (player-scheduled via the Friday Ops
|
|
* calendar, always `operationType: "side"`). Staff/admin-created missions are
|
|
* never reminded.
|
|
*
|
|
* Shared by the mission-tick bin (web notifications) and the Discord bot's
|
|
* readyReminders service (DMs): keep this module free of discord.js imports.
|
|
*
|
|
* Note: the module name, notification type ("mission:ready-reminder"), and
|
|
* marker fields keep their legacy "ready" spelling to avoid a data migration;
|
|
* only the user-facing copy talks about scheduling.
|
|
*/
|
|
|
|
/** How many days before the op the daily reminders begin. */
|
|
export const READY_REMINDER_LEAD_DAYS = 5;
|
|
|
|
/** Notification type used for the web-app reminder (labels + bridge exclusion). */
|
|
export const READY_REMINDER_NOTIFICATION_TYPE = "mission:ready-reminder";
|
|
|
|
/**
|
|
* Statuses that still need the creator's attention. "Scheduled" is the
|
|
* committed state the reminders push toward; Active/Completed/Cancelled are
|
|
* terminal or already underway.
|
|
*/
|
|
export const READY_REMINDER_ELIGIBLE_STATUSES = ["Concept", "Planning", "Ready"] as const;
|
|
|
|
export const missionTitle = (mission: Mission): string =>
|
|
mission.codeName ? `${mission.name} (${mission.codeName})` : mission.name;
|
|
|
|
/** Server-local YYYY-MM-DD key used for the once-per-day cadence. */
|
|
export const dayKey = (date: Date): string =>
|
|
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(
|
|
date.getDate(),
|
|
).padStart(2, "0")}`;
|
|
|
|
/**
|
|
* A channel is due when it has never sent, or last sent on a previous
|
|
* server-local day. Day-based (not 24h-based) so retries within the same day
|
|
* stay deduped, and a status flapping Scheduled back to Ready resumes reminders
|
|
* the next day instead of being suppressed forever.
|
|
*/
|
|
export const isReminderDue = (marker: string | null | undefined, now: Date): boolean => {
|
|
if (!marker) return true;
|
|
const markerDate = new Date(marker);
|
|
if (Number.isNaN(markerDate.getTime())) return true;
|
|
return dayKey(markerDate) !== dayKey(now);
|
|
};
|
|
|
|
export const daysUntil = (startIso: string, now: Date): number =>
|
|
Math.max(0, Math.ceil((new Date(startIso).getTime() - now.getTime()) / 86_400_000));
|
|
|
|
/**
|
|
* Ops due for reminders: player-created (createdBy set), still not Scheduled /
|
|
* terminal, and starting within the lead window (future start, at most
|
|
* READY_REMINDER_LEAD_DAYS days out). Marker filtering is done per-channel by
|
|
* the caller via isReminderDue: the "not sent today" condition can't be
|
|
* expressed in a single where clause.
|
|
*/
|
|
export const getReadyReminderMissions = async (payload: Payload, now = new Date()): Promise<Mission[]> => {
|
|
const nowIso = now.toISOString();
|
|
const windowEndIso = new Date(
|
|
now.getTime() + READY_REMINDER_LEAD_DAYS * 86_400_000,
|
|
).toISOString();
|
|
const res = await payload.find({
|
|
collection: "missions",
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
sort: "classification.startDateTime",
|
|
limit: 50,
|
|
where: {
|
|
and: [
|
|
{ createdBy: { exists: true } },
|
|
{ "ownershipAndStatus.status": { in: [...READY_REMINDER_ELIGIBLE_STATUSES] } },
|
|
{ "classification.startDateTime": { greater_than: nowIso } },
|
|
{ "classification.startDateTime": { less_than_equal: windowEndIso } },
|
|
],
|
|
},
|
|
});
|
|
return res.docs as unknown as Mission[];
|
|
};
|
|
|
|
export interface ReadyReminderSummary {
|
|
missions: number;
|
|
notified: number;
|
|
}
|
|
|
|
/**
|
|
* Web sweep: one in-app notification per due mission per server-local day.
|
|
* Called from the mission-tick bin. Respects each user's notification mutes
|
|
* (notifyUser handles suppression) and stamps the per-day marker.
|
|
*/
|
|
export const sendWebReadyReminders = async (
|
|
payload: Payload,
|
|
now = new Date(),
|
|
): Promise<ReadyReminderSummary> => {
|
|
const missions = await getReadyReminderMissions(payload, now);
|
|
let notified = 0;
|
|
for (const mission of missions) {
|
|
if (!isReminderDue(mission.readyReminderWebSentAt, now)) continue;
|
|
if (mission.createdBy == null) continue;
|
|
const creatorId =
|
|
typeof mission.createdBy === "object" ? mission.createdBy.id : mission.createdBy;
|
|
if (!creatorId) continue;
|
|
|
|
const days = daysUntil(mission.classification.startDateTime, now);
|
|
const when =
|
|
days === 0
|
|
? "today"
|
|
: days === 1
|
|
? "tomorrow"
|
|
: `in ${days} days`;
|
|
await notifyUser(payload, {
|
|
userId: creatorId,
|
|
type: READY_REMINDER_NOTIFICATION_TYPE,
|
|
title: `Schedule check: ${missionTitle(mission)}`,
|
|
message: `Your op starts ${when}. Finish up the details and set the mission status to Scheduled so the roll-call can be posted and the mission hooks delivered.`,
|
|
link: `/intelligence/missions/${mission.id}`,
|
|
});
|
|
await payload.update({
|
|
collection: "missions",
|
|
id: mission.id,
|
|
data: { readyReminderWebSentAt: now.toISOString() },
|
|
overrideAccess: true,
|
|
});
|
|
notified += 1;
|
|
}
|
|
return { missions: missions.length, notified };
|
|
};
|