brackt/app/services/standings-sync/index.ts
chrisp 273742f02e
Some checks failed
🚀 Deploy / 🧪 Test (push) Failing after 2m45s
🚀 Deploy / ʦ🔍 Typecheck & Lint (push) Successful in 1m27s
🚀 Deploy / 🐳 Build (push) Has been skipped
🚀 Deploy / 🚀 Deploy (push) Has been skipped
Phase A: external HTTP cron jobs for snapshots, standings sync, and simulation (#79)
## Summary

- Removes the last in-process \`setInterval\` (\`server/snapshots.ts\` 24h loop) and replaces it with an external HTTP cron job via Forgejo Actions
- Adds automated standings sync + conditional simulation: syncs every 2h, only simulates when standings actually changed (detected by comparing \`gamesPlayed\`/\`leagueRank\` before upsert)
- Adds \`GET /healthz\` for Docker healthcheck (Phase B prerequisite)

## What's new

| Endpoint | Triggered by | What it does |
|---|---|---|
| \`POST /admin/jobs/run-daily-snapshots\` | Forgejo schedule \`5 0 * * *\` | Creates daily fantasy standings snapshots for all active/draft seasons |
| \`POST /admin/jobs/sync-and-simulate\` | Forgejo schedule \`0 */2 * * *\` | Syncs standings from external APIs; runs simulation only if standings changed |
| \`GET /healthz\` | Docker / Traefik | Returns 200 \`{ok:true}\` when DB reachable, 503 otherwise |

Both cron endpoints are protected by \`X-Cron-Secret\` header (set \`CRON_SECRET\` in Forgejo repo secrets + production env).

## Schema changes (migration 0118)

Two new nullable columns on \`sports_seasons\`:
- \`standings_last_changed_at\` — written by \`syncStandings()\` when data actually changes
- \`last_simulated_at\` — written by the cron job after a successful simulation run

## Deployment notes

1. Add \`CRON_SECRET\` to Forgejo repo secrets (generate with \`openssl rand -hex 32\`)
2. Add same value to production environment
3. Migration runs automatically via the \`migrate\` container on deploy

## Test plan

- [ ] \`curl -X POST https://brackt.com/admin/jobs/run-daily-snapshots -H "X-Cron-Secret: ..."\` → 200 \`{total, succeeded, errors}\`
- [ ] \`curl -X POST https://brackt.com/admin/jobs/sync-and-simulate -H "X-Cron-Secret: ..."\` → 200 with \`synced\`/\`unchanged\`/\`simulated\` breakdown
- [ ] \`curl https://brackt.com/healthz\` → 200 \`{ok:true}\`
- [ ] Verify Forgejo workflow runs appear in Actions tab after merge
- [ ] Kill web process mid-day; confirm external cron still fires (no in-process dependency)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Chris Parsons <chrisparsons1127@gmail.com>
Reviewed-on: #79
2026-06-08 07:42:14 +00:00

190 lines
7 KiB
TypeScript

import { database } from "~/database/context";
import { eq, inArray } from "drizzle-orm";
import * as schema from "~/database/schema";
import { findParticipantsBySportsSeasonId, updateParticipant } from "~/models/season-participant";
import { upsertRegularSeasonStandings } from "~/models/regular-season-standings";
import { upsertPendingStandingsMappings } from "~/models/pending-standings-mappings";
import { findMatchingTeamName } from "~/lib/normalize-team-name";
import { NhlStandingsAdapter } from "./nhl";
import { NbaStandingsAdapter } from "./nba";
import { AflStandingsAdapter } from "./afl";
import { MlbStandingsAdapter } from "./mlb";
import { WnbaStandingsAdapter } from "./wnba";
import { EplStandingsAdapter } from "./epl";
import { MlsStandingsAdapter } from "./mls";
import type { StandingsSyncAdapter, SyncResult, UnmatchedTeam } from "./types";
/**
* Map a simulator type to its standings sync adapter.
* Returns null for sports that don't use regularSeasonStandings
* (e.g. season_standings sports like F1 will use a different path when implemented).
*/
function getAdapter(simulatorType: string): StandingsSyncAdapter {
switch (simulatorType) {
case "nba_bracket":
return new NbaStandingsAdapter();
case "nhl_bracket":
return new NhlStandingsAdapter();
case "afl_bracket":
return new AflStandingsAdapter();
case "epl_standings":
return new EplStandingsAdapter();
case "mls_bracket":
return new MlsStandingsAdapter();
case "mlb_bracket":
return new MlbStandingsAdapter();
case "wnba_bracket":
return new WnbaStandingsAdapter();
case "f1_standings":
throw new Error(
"F1 standings sync is not yet implemented. Use the manual standings page."
);
case "indycar_standings":
throw new Error(
"IndyCar standings sync is not yet implemented. Use the manual standings page."
);
default:
throw new Error(
`No standings sync adapter available for simulator type "${simulatorType}". ` +
"NBA, NHL, AFL, MLB, WNBA, EPL, and MLS are currently supported."
);
}
}
/**
* Sync current standings from the appropriate external API for a sports season.
* Matches API team names to participants by name and bulk-upserts the results.
*
* Returns the count of synced teams and any API team names that couldn't be matched.
*/
export async function syncStandings(sportsSeasonId: string): Promise<SyncResult> {
const db = database();
// Load sports season with sport relation
const sportsSeason = await db.query.sportsSeasons.findFirst({
where: eq(schema.sportsSeasons.id, sportsSeasonId),
with: { sport: true },
});
if (!sportsSeason) {
throw new Error(`Sports season ${sportsSeasonId} not found`);
}
const simulatorType = sportsSeason.sport?.simulatorType;
if (!simulatorType) {
const sportName = sportsSeason.sport?.name ?? "(no sport linked)";
throw new Error(`Sport "${sportName}" has no simulator type configured`);
}
const adapter = getAdapter(simulatorType);
const fetchedRecords = await adapter.fetchStandings();
// Load all participants for this season
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
const participantNames = participants.map((p) => p.name);
const participantByName = new Map(participants.map((p) => [p.name, p]));
// Build a map of externalId → participant for ID-first matching
const participantByExternalId = new Map(
participants.filter((p) => p.externalId).map((p) => [p.externalId ?? "", p])
);
const toUpsert: Parameters<typeof upsertRegularSeasonStandings>[0] = [];
const unmatchedRecords: typeof fetchedRecords = [];
const matchedParticipantIds: string[] = [];
for (const record of fetchedRecords) {
// Strategy A: try externalId-first (bypasses name matching entirely after first sync)
let participant = participantByExternalId.get(record.externalTeamId) ?? null;
if (!participant) {
// Fall back to name matching
const matchedName = findMatchingTeamName(record.teamName, participantNames);
if (matchedName) {
participant = participantByName.get(matchedName) ?? null;
// Write-back: persist externalId so future syncs skip name matching for this team
if (participant && !participant.externalId) {
await updateParticipant(participant.id, { externalId: record.externalTeamId });
}
}
}
if (!participant) {
unmatchedRecords.push(record);
continue;
}
matchedParticipantIds.push(participant.id);
toUpsert.push({
participantId: participant.id,
sportsSeasonId,
wins: record.wins,
losses: record.losses,
otLosses: record.otLosses ?? null,
ties: record.ties ?? null,
tablePoints: record.tablePoints ?? null,
goalsFor: record.goalsFor ?? null,
goalsAgainst: record.goalsAgainst ?? null,
goalDifference: record.goalDifference ?? null,
winPct: record.winPct,
gamesPlayed: record.gamesPlayed,
gamesBack: record.gamesBack ?? null,
conference: record.conference ?? null,
division: record.division ?? null,
conferenceRank: record.conferenceRank ?? null,
divisionRank: record.divisionRank ?? null,
leagueRank: record.leagueRank,
streak: record.streak ?? null,
lastTen: record.lastTen ?? null,
homeRecord: record.homeRecord ?? null,
awayRecord: record.awayRecord ?? null,
externalTeamId: record.externalTeamId,
srs: record.srs ?? null,
syncedAt: new Date(),
});
}
// Detect whether standings actually changed by comparing gamesPlayed + leagueRank
// against current DB values before upserting.
let changed = false;
if (toUpsert.length > 0) {
const currentRows = await db
.select({
participantId: schema.regularSeasonStandings.participantId,
gamesPlayed: schema.regularSeasonStandings.gamesPlayed,
leagueRank: schema.regularSeasonStandings.leagueRank,
})
.from(schema.regularSeasonStandings)
.where(inArray(schema.regularSeasonStandings.participantId, matchedParticipantIds));
const currentByParticipant = new Map(
currentRows.map((r) => [r.participantId, r])
);
changed = toUpsert.some((row) => {
const current = currentByParticipant.get(row.participantId);
if (!current) return true; // new row
return current.gamesPlayed !== row.gamesPlayed || current.leagueRank !== row.leagueRank;
});
await upsertRegularSeasonStandings(toUpsert);
if (changed) {
await db
.update(schema.sportsSeasons)
.set({ standingsLastChangedAt: new Date() })
.where(eq(schema.sportsSeasons.id, sportsSeasonId));
}
}
// Persist unmatched records so admin can resolve them without losing data on page reload
if (unmatchedRecords.length > 0) {
await upsertPendingStandingsMappings(sportsSeasonId, unmatchedRecords);
}
const unmatched: UnmatchedTeam[] = unmatchedRecords.map((r) => ({
teamName: r.teamName,
externalTeamId: r.externalTeamId,
}));
return { synced: toUpsert.length, unmatched, changed };
}