f26ac15712
$10 one-time DraftPosition purchases (sponsor 25%, L2-5 5%, 10% Best Coach pot, 45% company) with keeper-signed hub-line vouchers; pure draft engine with a mocked clock; no contact data anywhere; Telegram to an outbox unless TG_LIVE=1. Unit 60/60, smoke 156/156 (Playwright 1280/390). Not deployed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
9.9 KiB
JavaScript
151 lines
9.9 KiB
JavaScript
// The league: the draft engine (draft.js, pure) wired to the store and the holding tank (tankpool.js). One tick at a time:
|
|
// 1. sweep the open picks: fresh milestones from the tank; started picks stay (done), unconverted ones past the return window go
|
|
// back to the pool (or stay with the coach once the person has had their 2 adoptions)
|
|
// 2. on draft day at the draft hour (Central): create the week's draft from the earned order and the pool snapshot
|
|
// 3. while the draft is live: run every decision that is due (a coach in the room gets the clock, an absent coach is auto-picked)
|
|
// 4. when it finishes: the Draft Day card (proof.js, the outbox in phase 1)
|
|
// Every pick goes through tank.adopt() first; a pick is recorded only when the adoption went through.
|
|
// The clock is injectable (clock.now()): tests move it with POST /api/admin/clock when ALLOW_TEST_CLOCK=1 (never in production).
|
|
'use strict';
|
|
const store = require('./store');
|
|
const draft = require('./draft');
|
|
const tank = require('./tankpool');
|
|
|
|
const D = 86400000;
|
|
let C = null, proof = null, offset = 0, busy = Promise.resolve(), cands = [], candsAt = 0;
|
|
const clock = { now: () => Date.now() + offset, set: t => { offset = t - Date.now(); }, offset: () => offset };
|
|
const rules = () => ({ maxOpen: C.picks.maxOpen, maxAdoptions: C.picks.maxAdoptions, graceHours: C.picks.graceHours, holdHours: C.picks.holdHours, returnDays: C.picks.returnDays });
|
|
const lock = fn => { const r = busy.then(fn, fn); busy = r.catch(() => {}); return r; };
|
|
function init(cfg, deps) { C = cfg; proof = deps.proof; }
|
|
|
|
// ---- weeks (Central) ----
|
|
function weekInfo(now) {
|
|
const week = store.ctWeek(now);
|
|
const at = w => store.ctToMs(store.addDays(w, (C.draft.dow + 6) % 7), C.draft.hour); // dow 1 = Monday = the week's first day
|
|
const draftAt = at(week); const next = at(store.addDays(week, 7));
|
|
return { week, prevWeek: store.addDays(week, -7), nextWeek: store.addDays(week, 7), draftAt, nextDraftAt: now < draftAt ? draftAt : next,
|
|
from: store.ctToMs(week, 0), to: store.ctToMs(store.addDays(week, 7), 0) };
|
|
}
|
|
const nameOf = a => { const m = store.member(a); return m && m.username ? m.username : null; };
|
|
const openCount = a => store.picksOf(a).filter(p => p.status === 'open').length;
|
|
|
|
// ---- the pool ----
|
|
async function candidates(now, fresh) {
|
|
if (fresh || now - candsAt > 15000 || !cands.length) { try { cands = await tank.candidates(now); candsAt = now; } catch (e) { console.error('tank candidates', e.message); } }
|
|
return cands;
|
|
}
|
|
async function pool(now) { return draft.pool(await candidates(now), store.picks(), rules(), now); }
|
|
const ownTeam = id => { const m = store.memberByHub(id); return m && store.positionsOf(m.address) > 0 ? (store.firstPositionAt(m.address) || 1) : 0; };
|
|
|
|
// ---- a pick = an adoption ----
|
|
async function makePick(coach, person, kind, extra, now) {
|
|
const c = cands.find(x => x.id === person) || { id: person };
|
|
const r = await tank.adopt({ coach: { address: coach, username: nameOf(coach), hubId: (store.member(coach) || {}).hubId || null }, person, kind });
|
|
if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' };
|
|
const s = (await tank.status([person], now))[person] || {};
|
|
const m = Object.assign({ lastSeen: s.lastSeen || 0, username: s.username || c.username || null, wallet: s.wallet || 0, payouts: s.payouts || 0, purchase: s.purchase || 0, ownTeam: ownTeam(person) }, { door: s.door || c.door || null, games: s.games || c.games || null, surfWei: s.surfWei || c.surfWei || null });
|
|
const p = store.addPick(Object.assign({ week: weekInfo(now).week, kind, coach, coachName: nameOf(coach), person, personName: c.username || s.username || null, door: c.door || null,
|
|
status: 'open', at: now, expires: now + C.picks.returnDays * D, m, tier: draft.tierOf(m), ref: r.ref || null }, extra || {}));
|
|
candsAt = 0; // the pool changed
|
|
store.bump('picks');
|
|
return { ok: true, pickId: p.id, pick: p };
|
|
}
|
|
|
|
// ---- 1. sweep ----
|
|
async function sweep(now) {
|
|
const open = store.picks().filter(p => p.status === 'open' || p.status === 'done' || p.status === 'kept');
|
|
if (!open.length) return { changed: 0 };
|
|
const ids = [...new Set(open.map(p => p.person))];
|
|
const sts = await tank.status(ids, now);
|
|
const statusOf = id => { const s = sts[id]; if (!s) return null; return Object.assign({}, s, { ownTeam: ownTeam(id) }); };
|
|
// done / kept picks only refresh their milestones (cards keep levelling up)
|
|
for (const p of open.filter(x => x.status !== 'open')) { const m = statusOf(p.person); if (m) { const t = draft.tierOf(m); if (t !== p.tier || JSON.stringify(m) !== JSON.stringify(p.m)) { if (t !== p.tier) p.levelAt = now; p.m = m; p.tier = t; store.savePick(p); } } }
|
|
const ch = draft.sweep(store.picks(), statusOf, rules(), now);
|
|
for (const c of ch) {
|
|
if (c.release) { const r = await tank.release({ coach: c.pick.coach, person: c.pick.person, why: 'return window ended' }); if (!r || !r.ok) continue; }
|
|
if (c.set.tier && c.set.tier !== c.pick.tier) c.pick.levelAt = now; // the toast time, on the league clock
|
|
Object.assign(c.pick, c.set); store.savePick(c.pick);
|
|
}
|
|
if (ch.length) candsAt = 0;
|
|
return { changed: ch.length };
|
|
}
|
|
|
|
// ---- 2 + 3. the draft ----
|
|
function ctx(d, now) {
|
|
return { pool: d.poolIds || [], present: a => { const m = store.member(a); return !!(m && m.presenceAt && now - m.presenceAt < C.draft.presenceSeconds * 1000); },
|
|
queue: a => (store.member(a) || {}).queue || [], openCount, rules: rules(), pickSeconds: C.draft.pickSeconds };
|
|
}
|
|
async function ensureDraft(now) {
|
|
const w = weekInfo(now);
|
|
if (now < w.draftAt || store.draft(w.week)) return store.draft(w.week);
|
|
if (now > w.draftAt + C.draft.lateHours * 3600000) return null; // the app was down through draft time: that week is skipped, never run late
|
|
const coaches = store.coaches().map(m => ({ address: m.address, username: m.username, since: store.firstPositionAt(m.address) }));
|
|
const stand = draft.standings(coaches, store.picks(), w.week, w.prevWeek);
|
|
const pl = await pool(now);
|
|
const d = draft.newDraft({ week: w.week, at: now, rounds: C.draft.rounds, order: stand.map(s => s.address), standings: stand.map(s => ({ address: s.address, username: s.username, lastWeek: s.lastWeek, lifetime: s.lifetime })), poolSize: pl.length });
|
|
d.poolIds = pl.map(c => c.id);
|
|
store.putDraft(d);
|
|
console.log('draft: week', w.week, 'started with', stand.length, 'coaches,', pl.length, 'in the pool');
|
|
return d;
|
|
}
|
|
async function advance(d, now) {
|
|
if (!d || d.status !== 'live') return d;
|
|
await candidates(now);
|
|
const was = d.status;
|
|
await draft.run(d, ctx(d, now), act => makePick(act.coach, act.person, 'draft', { slot: draft.slotLabel(act.slot), round: act.slot.round, auto: act.type === 'auto' }, now), now);
|
|
store.putDraft(d);
|
|
if (was === 'live' && d.status === 'done') {
|
|
const rows = d.made.filter(x => x.person).map(x => ({ slot: x.slot, coach: nameOf(x.coach), person: (store.pick(x.pickId) || {}).personName || null }));
|
|
const w = weekInfo(now);
|
|
proof && proof.draftDay(d, rows, { players: rows.length, coaches: d.order.length, potWei: proof.potOf(w.from, w.to) }).catch(() => {});
|
|
}
|
|
return d;
|
|
}
|
|
async function tick() {
|
|
return lock(async () => {
|
|
const now = clock.now();
|
|
const s = await sweep(now).catch(e => { console.error('sweep', e.message); return { changed: 0 }; });
|
|
let d = await ensureDraft(now).catch(e => { console.error('draft create', e.message); return null; });
|
|
d = await advance(d, now).catch(e => { console.error('draft run', e.message); return d; });
|
|
return { swept: s.changed, draft: d ? { week: d.week, status: d.status, made: d.made.length } : null };
|
|
});
|
|
}
|
|
// a coach on the clock picks by hand
|
|
async function manualPick(coach, person) {
|
|
return lock(async () => {
|
|
const now = clock.now(); const d = store.draft(weekInfo(now).week);
|
|
if (!d || d.status !== 'live') return { error: 'The draft is not live right now.' };
|
|
await candidates(now);
|
|
const act = draft.manual(d, coach, person, ctx(d, now), now); if (act.error) return act;
|
|
const res = await makePick(coach, person, 'draft', { slot: draft.slotLabel(act.slot), round: act.slot.round, auto: false }, now);
|
|
draft.record(d, act, res, now); store.putDraft(d);
|
|
if (res.error) return res;
|
|
await advance(d, now);
|
|
return { ok: true, pickId: res.pickId };
|
|
});
|
|
}
|
|
// instant picks: 5 per position, from the current pool, any time outside a live draft
|
|
async function instantPick(coach, person) {
|
|
return lock(async () => {
|
|
const now = clock.now(); const d = store.draft(weekInfo(now).week);
|
|
if (d && d.status === 'live') return { error: 'The draft is live. Instant picks open again when it ends.' };
|
|
if (store.credits(coach) < 1) return { error: 'You have no instant picks left. Your next picks come in the Monday draft.' };
|
|
if (openCount(coach) >= C.picks.maxOpen) return { error: 'Your team is full (' + C.picks.maxOpen + ' open picks). Help one get started first.' };
|
|
const pl = await pool(now); if (!pl.some(c => c.id === person)) return { error: 'That player is no longer available.' };
|
|
const res = await makePick(coach, person, 'instant', {}, now); if (res.error) return res;
|
|
store.addCredits(coach, -1);
|
|
return { ok: true, pickId: res.pickId, credits: store.credits(coach) };
|
|
});
|
|
}
|
|
async function release(coach, pickId) {
|
|
return lock(async () => {
|
|
const now = clock.now(); const p = store.pick(pickId);
|
|
if (!p || p.coach !== coach) return { error: 'Not your pick.' };
|
|
const why = draft.canRelease(p, rules(), now); if (why) return { error: why };
|
|
const r = await tank.release({ coach, person: p.person, why: 'released by the coach' }); if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' };
|
|
p.status = 'returned'; p.releasedAt = now; p.released = true; store.savePick(p); candsAt = 0;
|
|
return { ok: true };
|
|
});
|
|
}
|
|
module.exports = { init, clock, tick, sweep, ensureDraft, advance, manualPick, instantPick, release, pool, candidates, weekInfo, rules, openCount, nameOf };
|