diff --git a/src/services/ledgerService.js b/src/services/ledgerService.js index f12f8fa..d0d63de 100644 --- a/src/services/ledgerService.js +++ b/src/services/ledgerService.js @@ -28,7 +28,7 @@ */ const { nameKey, normalizeName } = require('../utils/playerName'); -const { settleResult, statValue } = require('./outcomeService'); +const { settleResult, statValue, logRowOnDate } = require('./outcomeService'); const CONFLICT = 'user_id,player_key,stat,line,side,game_id'; const UPSERT_CHUNK = 200; @@ -330,9 +330,12 @@ async function settleLedger(sport, opts = {}) { let pending = 0; for (const row of rows || []) { const log = logByPlayer[row.player_name] || []; - const gameRow = log.find((r) => r && r.date === row.game_date); + // Sport-aware date match: MLB rows are YYYY-MM-DD, NBA/WNBA ESPN rows are + // ISO timestamps normalized to their ET date. game_date is already < today + // (the .lt('game_date', cutoff) fetch), so an unplayed game never settles. + const gameRow = log.find((r) => logRowOnDate(r, row.game_date, sp)); if (!gameRow) { pending += 1; continue; } - const actual = statValue(gameRow.stat, row.stat); + const actual = statValue(gameRow.stat, row.stat, sp); if (actual == null) { pending += 1; continue; } const outcome = settleResult(row.side, actual, row.line); if (!outcome) { pending += 1; continue; } @@ -386,10 +389,15 @@ async function settleAllLedgers(opts = {}) { } async function defaultGetPlayerStats(name, sport) { - if (String(sport).toLowerCase() === 'mlb') { + const sp = String(sport || '').toLowerCase(); + if (sp === 'mlb') { return require('./adapters/mlbStatsAdapter').getPlayerStats(name); } - return { found: false }; // no free settled-result feed yet → pending + // Wave 1 — NBA/WNBA settle against the FREE ESPN per-game log. + if (sp === 'nba' || sp === 'wnba') { + return require('./adapters/espnStatsAdapter').getPlayerGameLog(name, sp); + } + return { found: false }; // soccer — no free settled-result feed yet → pending } /** diff --git a/src/services/opsWatch.js b/src/services/opsWatch.js index 1af2298..949ed56 100644 --- a/src/services/opsWatch.js +++ b/src/services/opsWatch.js @@ -28,9 +28,16 @@ * Everything here is pure or fully injectable — no requires of redis/ntfy. */ -/** Sports with a real settled-result feed (mlb game logs). Keep in sync with - * outcomeService/ledgerService's MLB-only settlement until Phase 4.5. */ -const SETTLEABLE_SPORTS = ['mlb']; +/** Sports with a real settled-result feed. MLB = statsapi game logs; NBA/WNBA = + * ESPN per-game logs (Wave 1). Keep in sync with outcomeService/ledgerService's + * defaultGetPlayerStats. Soccer stays out until it has a settled-result feed. */ +const SETTLEABLE_SPORTS = ['mlb', 'nba', 'wnba']; + +/** Sports whose zero-settle alarm requires a real-finals probe before paging: + * their slates go dark for months (offseason) and a stale pending row must not + * false-page on a genuine off-day. MLB is exempt (proven daily feed in-season; + * a dark day fetches 0 rows and never alarms). */ +const FINALS_GATED_SPORTS = ['nba', 'wnba']; const PAGE_THRESHOLD = 3; @@ -79,10 +86,28 @@ function morningHourUtc(hoursUtc) { * Evaluate the zero-settle signal from settleAllLedgers results. * alarm === true only when settleable-sport rows EXISTED for settlement * (fetched from Postgres: settled + pending > 0) and none settled. + * + * Wave 1 — a finals-gated sport (NBA/WNBA) only contributes to the alarm when + * yesterday actually had games: `opts.finalsBySport[sport]` truthy (the caller + * counts ESPN `state==='post'` events). Without that signal its stale pendings + * are excluded, so an offseason/off-day never false-pages "settled 0". MLB is + * always counted (a dark MLB day fetches 0 rows → settled 0 / pending 0 → no + * alarm on its own). + * opts: { settleable, finalsBySport }. A bare array 2nd arg (legacy call: + * `zeroSettleAlarm(results, settleableArray)`) is still honored. */ -function zeroSettleAlarm(ledgerResults, settleable = SETTLEABLE_SPORTS) { +function zeroSettleAlarm(ledgerResults, opts = {}) { + const o = Array.isArray(opts) ? { settleable: opts } : (opts || {}); + const settleable = o.settleable || SETTLEABLE_SPORTS; + const finalsBySport = o.finalsBySport || {}; const rows = (Array.isArray(ledgerResults) ? ledgerResults : []) - .filter((r) => r && settleable.includes(String(r.sport || '').toLowerCase())); + .filter((r) => r && settleable.includes(String(r.sport || '').toLowerCase())) + .filter((r) => { + const sp = String(r.sport || '').toLowerCase(); + // Finals-gated sports need a "yesterday had games" signal to count. + if (FINALS_GATED_SPORTS.includes(sp)) return Boolean(finalsBySport[sp]); + return true; + }); const settled = rows.reduce((n, r) => n + (r.settled || 0), 0); const pending = rows.reduce((n, r) => n + (r.pending || 0), 0); return { alarm: settled === 0 && pending > 0, settled, pending }; @@ -177,5 +202,6 @@ module.exports = { buildPulseMessage, dateET, SETTLEABLE_SPORTS, + FINALS_GATED_SPORTS, PAGE_THRESHOLD, }; diff --git a/src/services/outcomeService.js b/src/services/outcomeService.js index ea3a733..928ba4f 100644 --- a/src/services/outcomeService.js +++ b/src/services/outcomeService.js @@ -45,7 +45,53 @@ const MLB_LOG_FIELD = { doubles: 'doubles', triples: 'triples', outs: 'outs', }; -function statValue(statObj, statType) { +// Wave 1 — NBA/WNBA settlement box-field map. A SEPARATE local map from +// MLB_LOG_FIELD (the S11 three-map-split rule — settlement, features, and live +// tracking each own their own map; never merge). The ESPN gamelog row's `stat` +// object (espnStatsAdapter.getPlayerGameLog) is already keyed by VYNDR stat +// names, so simple stats map 1:1; combo stat_types (pts_reb_ast, …) sum their +// components at read time — mirroring featureCache.statFromGameLog. A stat_type +// absent here does NOT settle (absent beats a fabricated outcome); add a new +// NBA/WNBA stat here (and to featureCache + liveTrackingService) to unlock it. +const NBA_BOX_KEY = { + points: 'points', rebounds: 'rebounds', assists: 'assists', threes: 'threes', + steals: 'steals', blocks: 'blocks', turnovers: 'turnovers', pra: 'pra', +}; +const NBA_COMBO = { + pts_reb_ast: ['points', 'rebounds', 'assists'], + pts_reb: ['points', 'rebounds'], + pts_ast: ['points', 'assists'], + reb_ast: ['rebounds', 'assists'], + stl_blk: ['steals', 'blocks'], +}; + +// Resolve one NBA/WNBA per-game stat value. Combos require EVERY component to +// be present (a played game reports 0, not absent) — a partial box never +// fabricates a combo total. +function nbaStatValue(statObj, statType) { + if (!statObj) return null; + const st = String(statType || '').toLowerCase(); + const combo = NBA_COMBO[st]; + if (combo) { + let sum = 0; + for (const c of combo) { + const n = parseFloat(statObj[c]); + if (!Number.isFinite(n)) return null; + sum += n; + } + return sum; + } + const f = NBA_BOX_KEY[st]; + if (!f) return null; + const n = parseFloat(statObj[f]); + return Number.isFinite(n) ? n : null; +} + +// Sport-aware actual-value resolver. Default (unspecified/mlb) reads the +// statsapi.mlb.com game-log field; nba/wnba read the ESPN gamelog box object. +function statValue(statObj, statType, sport) { + const sp = String(sport || 'mlb').toLowerCase(); + if (sp === 'nba' || sp === 'wnba') return nbaStatValue(statObj, statType); const f = MLB_LOG_FIELD[String(statType || '').toLowerCase()]; if (!f || !statObj) return null; const n = parseFloat(statObj[f]); @@ -66,6 +112,32 @@ function dateStrings(ts) { return [...new Set([utc, et])]; } +// The America/New_York calendar date (YYYY-MM-DD) of an ISO timestamp. +function etDate(ts) { + if (!ts) return null; + const d = new Date(ts); + if (isNaN(d.getTime())) return null; + try { + return new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York' }).format(d); + } catch { + return d.toISOString().slice(0, 10); + } +} + +/** + * Does a game-log row fall on `targetDate` (YYYY-MM-DD)? + * MLB rows are already plain YYYY-MM-DD → exact compare (unchanged behavior). + * NBA/WNBA rows carry a FULL ISO timestamp from ESPN (e.g. a late tip is + * 00:30Z the next calendar day) → match on either its UTC or ET date so a + * game whose UTC date rolled past midnight still matches its ET slate date. + */ +function logRowOnDate(logRow, targetDate, sport) { + if (!logRow || !logRow.date || !targetDate) return false; + const sp = String(sport || 'mlb').toLowerCase(); + if (sp === 'nba' || sp === 'wnba') return dateStrings(logRow.date).includes(targetDate); + return logRow.date === targetDate; +} + const sideOver = (side) => { const s = String(side || 'over').toLowerCase(); return s === 'over' || s === 'o'; @@ -130,6 +202,8 @@ async function settleSnapshot(sport, opts = {}) { } catch { logByPlayer[player] = []; } } + const todayEt = etDate(nowIso); + const isBasketball = sp === 'nba' || sp === 'wnba'; const fresh = []; let pending = 0; for (const g of grades) { @@ -140,16 +214,29 @@ async function settleSnapshot(sport, opts = {}) { const gradedTs = (g.gradedAt && g.gradedAt.timestamp) || snap.updated_at || nowIso; const dates = dateStrings(gradedTs); const log = logByPlayer[player] || []; - // Find the game played on the graded date. - const row = log.find((r) => r && r.date && dates.includes(r.date)); + // Find the game played on the graded date (sport-aware date normalization). + const row = log.find((r) => dates.some((d) => logRowOnDate(r, d, sp))); if (!row) { pending += 1; continue; } - const actual = statValue(row.stat, stat); + // Detect FINAL honestly: a game-log row is a COMPLETED game, but never + // settle a game whose ET date is today (could be an in-progress partial + // row for NBA/WNBA). MLB game logs are final-only + settle same-day, so + // this guard is scoped to basketball — it must not stall MLB afternoons. + if (isBasketball) { + const rowEt = etDate(row.date); + if (!rowEt || rowEt >= todayEt) { pending += 1; continue; } + } + const actual = statValue(row.stat, stat, sp); if (actual == null) { pending += 1; continue; } const result = settleResult(side, actual, line); if (!result) { pending += 1; continue; } + // Store the game's ET calendar date (YYYY-MM-DD). MLB rows are already in + // that form; basketball rows carry a full ISO timestamp → normalize so the + // accuracy 30-day window filter + the idempotency key (both key off `date`) + // behave identically across sports. + const outcomeDate = isBasketball ? (etDate(row.date) || row.date) : row.date; const outcome = { player, stat, line, side: sideOver(side) ? 'O' : 'U', - grade: g.grade, actual, result, date: row.date, + grade: g.grade, actual, result, date: outcomeDate, gradedAt: gradedTs, settledAt: nowIso, }; const key = outcomeKey(outcome); @@ -215,10 +302,16 @@ function normalizeLog(raw) { } async function defaultGetPlayerStats(name, sport) { - if (String(sport).toLowerCase() === 'mlb') { + const sp = String(sport || '').toLowerCase(); + if (sp === 'mlb') { return require('./adapters/mlbStatsAdapter').getPlayerStats(name); } - // NBA/WNBA/soccer: no free settled-result feed here → pending. + // Wave 1 — NBA/WNBA settle against the FREE ESPN per-game log (Wave 0's + // getPlayerGameLog returns the same { found, last10:[{date, stat}] } shape). + if (sp === 'nba' || sp === 'wnba') { + return require('./adapters/espnStatsAdapter').getPlayerGameLog(name, sp); + } + // soccer: no free settled-result feed yet → pending. return { found: false }; } @@ -293,10 +386,15 @@ module.exports = { computeAccuracy, accuracyBuckets, // Session 58 — settlement primitives shared with ledgerService (single - // source of truth for hit/miss/push + MLB log-field resolution). + // source of truth for hit/miss/push + log-field resolution). Wave 1 — + // logRowOnDate normalizes the ESPN ISO game-log date for NBA/WNBA. settleResult, statValue, + logRowOnDate, SPORTS, MIN_SAMPLE, - __internals: { settleResult, gradeBucket, dateStrings, statValue, outcomeKey, MLB_LOG_FIELD, TIERS }, + __internals: { + settleResult, gradeBucket, dateStrings, etDate, statValue, nbaStatValue, + logRowOnDate, outcomeKey, MLB_LOG_FIELD, NBA_BOX_KEY, NBA_COMBO, TIERS, + }, }; diff --git a/src/snapshotScheduler.js b/src/snapshotScheduler.js index 85edd6f..1674c53 100644 --- a/src/snapshotScheduler.js +++ b/src/snapshotScheduler.js @@ -69,6 +69,9 @@ function startSnapshotScheduler(opts = {}) { const healthIssues = opts.healthIssues || require('./services/systemHealth').healthIssues; const getQuotaStatus = opts.getQuotaStatus || require('./services/quotaTracker').getQuotaStatus; const countLedgerRows = opts.countLedgerRows || require('./services/ledgerService').countRowsForDate; + // Wave 1 — real-finals probe for the zero-settle alarm (NBA/WNBA only page + // when yesterday actually had games). Reuses the free, cached ESPN scoreboard. + const getSchedule = opts.getSchedule || require('./services/scheduleService').getSchedule; const failureTracker = opts.failureTracker || opsWatch.createFailureTracker(); let lastFiredSlot = null; let lastOverdueSlot = null; @@ -178,7 +181,17 @@ function startSnapshotScheduler(opts = {}) { // once per ET date; a genuinely empty yesterday (0 rows fetched) never fires. try { if (h === opsWatch.morningHourUtc(HOURS_UTC) && ledgerResults) { - const z = opsWatch.zeroSettleAlarm(ledgerResults); + // Wave 1 — probe yesterday's ESPN scoreboard so an NBA/WNBA off-day + // (0 finals) never false-pages "settled 0" on stale pending rows. + const yEt = opsWatch.dateET(new Date(d.getTime() - 24 * 3600 * 1000)); + const finalsBySport = {}; + for (const fsp of opsWatch.FINALS_GATED_SPORTS) { + try { + const games = await getSchedule(fsp, yEt); + finalsBySport[fsp] = Array.isArray(games) && games.some((g) => g && g.status === 'post'); + } catch { finalsBySport[fsp] = false; } + } + const z = opsWatch.zeroSettleAlarm(ledgerResults, { finalsBySport }); if (z.alarm) { const dk = `ops:settle_zero:${opsWatch.dateET(d)}`; if (!(await cacheGet(dk))) { @@ -254,7 +267,10 @@ function startSnapshotScheduler(opts = {}) { // settleAllLedgers run FIRST at every snapshot slot, before grading). It // was invisible at boot, which made "is settlement scheduled?" unanswerable // from logs. This line makes it verifiable forever. - console.log(`[settlement] armed — outcomes + ledger settle pass runs FIRST at each snapshot slot (${HOURS_UTC.join(',')} UTC), idempotent re-runs`); + // Wave 1 — announce settlement PER settleable sport so "does NBA settle?" is + // answerable from boot logs (mlb=statsapi, nba/wnba=ESPN game logs). + const settleTags = require('./services/opsWatch').SETTLEABLE_SPORTS.map((s) => `[settle:${s}]`).join(' '); + console.log(`[settlement] armed — ${settleTags} outcomes + ledger settle pass runs FIRST at each snapshot slot (${HOURS_UTC.join(',')} UTC), idempotent re-runs`); // Session 8 — same verifiability rule: every watchdog states itself at boot. console.log(`[opsWatch] armed — settle alarms (throw + morning zero-settle), failure pager (${failureTracker.threshold} consecutive), quota daily check, pulse ${PULSE_HOUR_UTC}:00 UTC`); return { interval, tick, refreshTick, pulseTick }; diff --git a/tests/unit/nbaSettlement.test.js b/tests/unit/nbaSettlement.test.js new file mode 100644 index 0000000..2a39c54 --- /dev/null +++ b/tests/unit/nbaSettlement.test.js @@ -0,0 +1,203 @@ +// Wave 1 (truth-everywhere-train) — NBA/WNBA settlement. +// Locks that once a basketball grade exists, it settles against the FREE ESPN +// per-game log (espnStatsAdapter.getPlayerGameLog), records populate, the run +// is idempotent, and an unplayed/in-progress game NEVER settles. Zero network. + +const svc = require('../../src/services/outcomeService'); +const ledger = require('../../src/services/ledgerService'); +const { statValue, nbaStatValue, logRowOnDate } = svc.__internals; + +// ---- in-memory Redis (same helper shape as outcomeService.test.js) -------- +function memCache(seed = {}) { + const store = { ...seed }; + return { + store, + cacheGet: async (k) => (k in store ? store[k] : null), + cacheSet: async (k, v) => { store[k] = v; return true; }, + }; +} + +// ESPN gamelog rows carry a FULL ISO timestamp (a late tip is 00:xxZ the next +// UTC day) — the exact shape Wave 0's getPlayerGameLog returns. +const NOW = '2026-07-13T15:00:00.000Z'; // 11am ET Jul 13 = "today" +const GRADED_TS = '2026-07-12T23:30:00.000Z'; // 7:30pm ET Jul 12 (locked pre-game) +const GAME_ISO = '2026-07-13T01:00:00.000+00:00'; // 9pm ET Jul 12 → ET date Jul 12 + +function snapshot(sport, grades) { return { sport, updated_at: GRADED_TS, grades }; } +function grade(over = {}) { + return { + player: over.player || "A'ja Wilson", + stat_type: over.stat || 'points', + line: over.line != null ? over.line : 19.5, + direction: over.side || 'over', + grade: over.grade || 'A', + gradedAt: { line: over.line != null ? over.line : 19.5, odds: -115, timestamp: GRADED_TS }, + }; +} +// espnStatsAdapter.getPlayerGameLog fixture: { found, id, last10:[{date, stat}] } +function espnLog(statObj, dateIso = GAME_ISO) { + return { found: true, id: '3149391', last10: [{ date: dateIso, opponent: 'IND', isHome: true, stat: statObj }] }; +} + +describe('statValue — sport-aware (NBA/WNBA box keys, S11 three-map-split kept)', () => { + test('MLB path unchanged when sport unspecified/mlb', () => { + expect(statValue({ homeRuns: 1 }, 'home_runs')).toBe(1); + expect(statValue({ homeRuns: 1 }, 'home_runs', 'mlb')).toBe(1); + }); + test('NBA/WNBA simple stats read the ESPN box object', () => { + const box = { points: 24, rebounds: 12, assists: 3, threes: 2, steals: 1, blocks: 1, turnovers: 4 }; + expect(statValue(box, 'points', 'wnba')).toBe(24); + expect(statValue(box, 'rebounds', 'nba')).toBe(12); + expect(statValue(box, 'threes', 'wnba')).toBe(2); + expect(statValue(box, 'turnovers', 'nba')).toBe(4); + }); + test('combo stat_types sum their components (pts_reb_ast, reb_ast, stl_blk)', () => { + const box = { points: 20, rebounds: 12, assists: 2, steals: 1, blocks: 3 }; + expect(nbaStatValue(box, 'pts_reb_ast')).toBe(34); + expect(nbaStatValue(box, 'pts_reb')).toBe(32); + expect(nbaStatValue(box, 'reb_ast')).toBe(14); + expect(nbaStatValue(box, 'stl_blk')).toBe(4); + }); + test('a combo with a missing component never fabricates a total', () => { + expect(nbaStatValue({ points: 20, rebounds: 12 }, 'pts_reb_ast')).toBeNull(); + }); + test('an unmapped NBA stat is unsettleable (absent beats a fabricated outcome)', () => { + expect(statValue({ points: 20 }, 'double_doubles', 'wnba')).toBeNull(); + }); +}); + +describe('logRowOnDate — ESPN ISO date normalized to UTC+ET', () => { + test('MLB rows exact-compare YYYY-MM-DD (unchanged)', () => { + expect(logRowOnDate({ date: '2026-07-09' }, '2026-07-09', 'mlb')).toBe(true); + expect(logRowOnDate({ date: '2026-07-09' }, '2026-07-08', 'mlb')).toBe(false); + }); + test('NBA/WNBA ISO row matches its ET date (late tip rolled past UTC midnight)', () => { + expect(logRowOnDate({ date: GAME_ISO }, '2026-07-12', 'wnba')).toBe(true); // ET + expect(logRowOnDate({ date: GAME_ISO }, '2026-07-13', 'nba')).toBe(true); // UTC + expect(logRowOnDate({ date: GAME_ISO }, '2026-07-11', 'wnba')).toBe(false); + }); +}); + +describe('settleSnapshot — WNBA grades settle vs the real ESPN game log', () => { + test('a locked WNBA over settles to a hit and populates accuracy:wnba + byGrade', async () => { + const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 19.5, side: 'over', grade: 'A' })]) }); + const getPlayerStats = async () => espnLog({ points: 24, rebounds: 12, assists: 3 }); + const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW }); + expect(res.settled).toBe(1); + expect(res.log[0]).toMatchObject({ result: 'hit', actual: 24, grade: 'A', side: 'O' }); + expect(cache.store['accuracy:wnba'].byGrade['A'].hits).toBe(1); + expect(cache.store['accuracy:wnba'].overall.pct).toBe(100); + }); + + test('settles a miss (under, actual above line)', async () => { + const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 19.5, side: 'under', grade: 'B' })]) }); + const getPlayerStats = async () => espnLog({ points: 24 }); + const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW }); + expect(res.log[0].result).toBe('miss'); + expect(cache.store['accuracy:wnba'].byGrade['B'].misses).toBe(1); + }); + + test('settles a push (actual equals line)', async () => { + const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'points', line: 24, side: 'over', grade: 'C' })]) }); + const getPlayerStats = async () => espnLog({ points: 24 }); + const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW }); + expect(res.log[0].result).toBe('push'); + }); + + test('a combo prop (pts_reb_ast) settles', async () => { + const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ stat: 'pts_reb_ast', line: 29.5, side: 'over', grade: 'A' })]) }); + const getPlayerStats = async () => espnLog({ points: 20, rebounds: 12, assists: 2 }); // 34 + const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW }); + expect(res.settled).toBe(1); + expect(res.log[0]).toMatchObject({ result: 'hit', actual: 34, stat: 'pts_reb_ast' }); + }); + + test('idempotent — a second run does not double-count', async () => { + const cache = memCache({ 'snapshot:wnba:latest': snapshot('wnba', [grade({ grade: 'A' })]) }); + const deps = { ...cache, getPlayerStats: async () => espnLog({ points: 24 }), now: () => NOW }; + await svc.settleSnapshot('wnba', deps); + const res2 = await svc.settleSnapshot('wnba', deps); + expect(res2.settled).toBe(0); + expect(res2.log.length).toBe(1); + expect(cache.store['accuracy:wnba'].overall.total).toBe(1); + }); + + test('an in-progress / today game does NOT settle (final-honesty guard)', async () => { + // Graded today, ESPN returns a row whose ET date is TODAY → never settle it. + const gradedToday = '2026-07-13T14:00:00.000Z'; // 10am ET Jul 13 + const todaysGame = '2026-07-13T23:00:00.000+00:00'; // 7pm ET Jul 13 (in progress) + const g = grade({ stat: 'points', line: 19.5, side: 'over', grade: 'A' }); + g.gradedAt.timestamp = gradedToday; + const cache = memCache({ 'snapshot:wnba:latest': { sport: 'wnba', updated_at: gradedToday, grades: [g] } }); + const getPlayerStats = async () => espnLog({ points: 30 }, todaysGame); + const res = await svc.settleSnapshot('wnba', { ...cache, getPlayerStats, now: () => NOW }); + expect(res.settled).toBe(0); + expect(res.pending).toBe(1); + }); + + test('offline ESPN (found:false) → pending, never throws', async () => { + const cache = memCache({ 'snapshot:nba:latest': snapshot('nba', [grade()]) }); + const res = await svc.settleSnapshot('nba', { ...cache, getPlayerStats: async () => ({ found: false }), now: () => NOW }); + expect(res.settled).toBe(0); + expect(res.pending).toBe(1); + }); +}); + +describe('ledgerService.settleLedger — WNBA settles vs the ESPN game log', () => { + // Minimal chainable Supabase stub (same shape as ledgerService.test.js). + function fakeSb() { + const calls = { updates: [] }; + const state = { selectResults: [], selectCursor: 0, countResult: 0 }; + function builder() { + const b = { + _update: null, + upsert() { return Promise.resolve({ error: null }); }, + update(v) { b._update = v; return b; }, + select() { return b; }, eq() { return b; }, is() { return b; }, + not() { return b; }, lt() { return b; }, gte() { return b; }, order() { return b; }, + in(col, ids) { + if (b._update) { calls.updates.push({ values: b._update, ids }); return Promise.resolve({ error: null }); } + return terminal(); + }, + limit() { return terminal(); }, + then(res, rej) { return terminal().then(res, rej); }, + }; + function terminal() { + if (b._update) { calls.updates.push({ values: b._update }); return Promise.resolve({ error: null }); } + const data = state.selectResults[state.selectCursor] ?? []; + state.selectCursor += 1; + return Promise.resolve({ data, error: null, count: state.countResult }); + } + return b; + } + return { from: () => builder(), _calls: calls, _state: state }; + } + + test('settles a WNBA row (points) via the ESPN gamelog ET-date match', async () => { + const sb = fakeSb(); + sb._state.selectResults = [ + [{ id: 'r1' }], + [{ id: 'r1', player_name: "A'ja Wilson", stat: 'points', line: 19.5, side: 'over', closing_line: 19.5, game_date: '2026-07-12' }], + ]; + // ESPN ISO date normalizes to ET 2026-07-12 → matches game_date. + const getPlayerStats = async () => espnLog({ points: 24 }); + const res = await ledger.settleLedger('wnba', { sb, getPlayerStats, now: () => NOW, beforeDate: '2026-07-13' }); + expect(res.settled).toBe(1); + expect(sb._calls.updates[0].values).toMatchObject({ outcome: 'hit', actual_value: 24, clv: 0, clv_result: 'flat' }); + }); + + test('by_tier populates for WNBA settled rows (records need no new plumbing)', async () => { + const sb = fakeSb(); + const rows = [ + ...Array.from({ length: 14 }, () => ({ outcome: 'hit', clv_result: null, grade: 'A' })), + ...Array.from({ length: 6 }, () => ({ outcome: 'miss', clv_result: null, grade: 'A-' })), + ]; + sb._state.selectResults = [rows]; + sb._state.countResult = 0; + // by_tier is sport-agnostic: once WNBA rows carry an outcome + grade they + // flow into the SAME calibration buckets the MLB path uses (no new plumbing). + const agg = await ledger.getModelAggregate({ sb }); + expect(agg.by_tier.A.settled).toBe(20); + expect(agg.by_tier.A.hit_pct).toBe(70); + }); +}); diff --git a/tests/unit/opsWatch.test.js b/tests/unit/opsWatch.test.js index 9095823..6a0076f 100644 --- a/tests/unit/opsWatch.test.js +++ b/tests/unit/opsWatch.test.js @@ -80,13 +80,45 @@ describe('zeroSettleAlarm', () => { expect(zeroSettleAlarm([{ sport: 'mlb', settled: 3, pending: 9 }]).alarm).toBe(false); }); - test('ignores sports without a settled-result feed (WNBA pendings are honest)', () => { + test('WNBA pendings without a finals signal never page (off-day / stale rows)', () => { + // Wave 1 — wnba IS settleable now, but with no finals-probe signal its + // pendings are excluded so an offseason/off-day cannot false-page. const z = zeroSettleAlarm([ { sport: 'mlb', settled: 0, pending: 0 }, { sport: 'wnba', settled: 0, pending: 40 }, ]); expect(z.alarm).toBe(false); }); + + test('Wave 1 — WNBA zero-settle WITH finals present DOES page', () => { + const z = zeroSettleAlarm( + [{ sport: 'wnba', settled: 0, pending: 40 }], + { finalsBySport: { wnba: true } }, + ); + expect(z.alarm).toBe(true); + expect(z.pending).toBe(40); + }); + + test('Wave 1 — NBA finals present but SOMETHING settled → no alarm', () => { + const z = zeroSettleAlarm( + [{ sport: 'nba', settled: 5, pending: 30 }], + { finalsBySport: { nba: true } }, + ); + expect(z.alarm).toBe(false); + }); + + test('Wave 1 — NBA finals present but 0 rows to settle → no false alarm', () => { + const z = zeroSettleAlarm( + [{ sport: 'nba', settled: 0, pending: 0 }], + { finalsBySport: { nba: true } }, + ); + expect(z.alarm).toBe(false); + }); + + test('legacy array 2nd arg (settleable list) is still honored', () => { + const z = zeroSettleAlarm([{ sport: 'mlb', settled: 0, pending: 7 }], ['mlb']); + expect(z).toEqual({ alarm: true, settled: 0, pending: 7 }); + }); }); describe('morningHourUtc', () => {