Files
martbost ccfaacc935 Holding tank batches (Marty 2026-11-15), master switch tankBatches OFF
Active members with their own paid package ($20+ InstantAdPay, $25+ LinkSpin via the
refuel record) receive tank people in batches: Paid 10, Fueled 20 (counted refuel streak
or a $50+ package), Twin Engine 25 (both engines this cycle or the top package, the live
catalog's highest, $500 today), +5 per further consecutive refuel month up to 50. Every
2 days per sponsor, topped up to their size, dealt by rotation highest tier first from
tank.adoptable() (grace, rule 3, LinkSpin adoptions respected), never self, own upline,
adopted twice, flagged, spam, mistyped, erased or unsubscribed. Same tank.adopt path
(sponsor change, chat, "X is now your sponsor" email, switch-on reminders); one notice
per batch to the sponsor. Uncontacted after 7 days -> back to the tank as 'unreached'
(not counted). Tank feed: payments-topic card + live toast, sponsor/count/level only.
Member panel "How to get fed leads" (tankfeed.js). Every number is a site setting.

5xYourTeam draft gets its own cap (fiveXDraftCap, default 10): open draft picks only;
plain adoptions, the 24-hour safety net and batches each count their own people.
Admin: GET /api/admin/tank/batches/preview (read-only) + /api/admin/tank/batches.
Chatbot: coming soon only. qa/tank-batch.test.mjs (60 checks) in run.sh member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:59:20 -06:00

317 lines
29 KiB
JavaScript

'use strict';
// 5xYourTeam "The Draft" partner side (Marty approved the rules 2026-11-15). The network holding tank lives HERE (tank.js);
// 5xYourTeam coaches draft from it through four signed calls, and every pick is a real tank adoption through tank.adopt():
//
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card], excluded: {why: n} }
// POST /api/partner/draft/adopt { rid, coach, person, kind, week?, slot?, note? } -> { ok, ref, person, adoptionId, at, expires, holdUntil }
// POST /api/partner/draft/release { rid, coach, ref | person, why: 'coach' | 'return' } -> { ok, outcome: 'returned' | 'kept' | 'done' | <closed status>, already? }
// POST /api/partner/draft/status { ids: [person id] } -> { ok, people: { id: milestones | null } }
// coach = { wallet, hubId?, username?, positions } (the 5xYourTeam claim: positions = 5x positions this wallet holds)
// card = { id, username, door, joinedAt, lastSeen, wallet (bool), ready, holdUntil, opensAt, adoptions (outside 5x), adoptionsTotal, games, surfWei, surfCredits }
//
// Signature: X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256(DRAFT_PARTNER_SECRET, 'draft.v1.' + ts + '\n' + raw body), 5-minute
// window. A dedicated secret (not NETWORK_SSO_SECRET): this one can move sponsors. adopt and release carry a request id (rid): a
// retried or replayed call answers what the first one did and changes nothing.
//
// The rules (project-5xyourteam-draft, 11-15):
// - only 5xYourTeam position holders draft and coach: the signed claim (positions >= 1) REPLACES InstantAdPay's own-$20-buy rule
// for these calls only (the member's own tank button keeps its $20 rule); a coach needs an account here with a wallet linked,
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
// - max 10 open picks a coach (site setting fiveXDraftCap, its own cap since 2026-11-15, not the tank's); max 2 adoptions per person (every pick counts, both sites)
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
// - 24-hour sign-up grace (tank.adopt refuses it; the card carries opensAt); coaches never see contact data: no email, phone or
// address leaves this module, person ids are hub ids (or an opaque i_ id the hub does not know)
// - the only mail: tank.adopt's normal "X is now your sponsor" adoption email. No switch-on-payouts reminders for picks, no
// payments-topic post (5xYourTeam posts its own Draft Day card)
//
// Auto-assign vs the 3-day window (the conflict the 5x build flagged), the rule implemented:
// - a drafted person is an open adoption with a sponsor, so they are out of the tank: no 24-hour activation hold, no auto-assign,
// no sign-up announcement, no dormant-lead rescue while the pick window runs
// - the pick's adoption row expires at +3 days (not IAP's 7), and tank.sweep leaves it alone (hooks.isDraftPick): this module
// closes it at 3 days with the pick's rule (started = payouts on or a purchase, a wallet alone is not started)
// - a returned pick goes back with their ORIGINAL join time (account `created` is never touched, so no new sign-up grace) and,
// with a wallet linked, a fresh 24-hour activation hold like anyone back in the tank (never the company)
// - sponsor moves go through tank.js setSponsor (sponsorfollow + the hub's /v1/sponsor-change with by 'adopt' / 'release')
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
const H = 3600000, D = 86400000;
const RULES = { returnMs: 3 * D, holdMs: 48 * H, maxOpen: 10, maxAdoptions: 2 };
const ADDR = /^0x[0-9a-f]{40}$/;
const lc = v => String(v || '').trim().toLowerCase();
// throwaway / disposable inboxes: the adoption email would go nowhere. Plus a mistyped big-provider domain (emailcheck.js).
const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org',
'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com',
'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']);
const DOORS = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', vbb: 'Viral Banner Blitz',
ctb: 'CryptoTeamBuild', fivex: '5xYourTeam', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', dh: 'DownlineHydra', btc4hits: 'BTC4Hits', stackpol: 'Stack POL' };
let R = null; // { dataDir, accounts, chain, tank, ads, hooks: { hubInfo, resolvePerson, excluded, spamEmails, networkOn, suggestDomain }, requireHub, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const SECRET = () => String((R && R.secret) || process.env.DRAFT_PARTNER_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
// ---- storage: MySQL (draft_picks, draft_log) when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'draft-partner.json'),
load() { if (this.st) return this.st; try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || typeof this.st !== 'object') this.st = {}; this.st.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.log = this.st.log || []; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
async put(p) { const s = this.load(); const i = s.picks.findIndex(x => x.id === p.id); if (i >= 0) s.picks[i] = Object.assign({}, p); this.save(); },
async byId(id) { const x = this.load().picks.find(r => r.id === Number(id)); return x ? Object.assign({}, x) : null; },
async byRid(rid) { const x = this.load().picks.find(r => r.rid === rid); return x ? Object.assign({}, x) : null; },
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
async ofPerson(pid) { return this.load().picks.filter(r => r.personId === pid).map(x => Object.assign({}, x)); },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
async openOfCoach(w) { return this.load().picks.filter(r => r.status === 'open' && r.coachWallet === w).map(x => Object.assign({}, x)); },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async countsByAdoptee() { const m = new Map(); for (const r of this.load().picks) m.set(r.adoptee, (m.get(r.adoptee) || 0) + 1); return m; },
async log(row) { const s = this.load(); s.log.push(row); if (s.log.length > 2000) s.log = s.log.slice(-2000); this.save(); },
async logs(n) { return this.load().log.slice(-(n || 100)).reverse(); }
};
const COLS = ['rid', 'adoptionId', 'adoptee', 'personId', 'coachEmail', 'coachWallet', 'coachHubId', 'kind', 'week', 'slot', 'ts', 'expires', 'holdUntil', 'status', 'closed', 'outcomeWhy', 'walletAt', 'payoutsAt', 'purchaseAt'];
const SQLC = { rid: 'rid', adoptionId: 'adoption_id', adoptee: 'adoptee', personId: 'person_id', coachEmail: 'coach_email', coachWallet: 'coach_wallet', coachHubId: 'coach_hub_id', kind: 'kind', week: 'week', slot: 'slot', ts: 'ts', expires: 'expires', holdUntil: 'hold_until', status: 'status', closed: 'closed', outcomeWhy: 'outcome_why', walletAt: 'wallet_at', payoutsAt: 'payouts_at', purchaseAt: 'purchase_at' };
const NUM = new Set(['adoptionId', 'ts', 'expires', 'holdUntil', 'closed', 'walletAt', 'payoutsAt', 'purchaseAt']);
const rowP = r => { if (!r) return null; const o = { id: Number(r.id) }; for (const k of COLS) { const v = r[SQLC[k]]; o[k] = NUM.has(k) ? Number(v || 0) : (v == null ? null : String(v)); } return o; };
const Q = {
async add(p) { const r = await db.q('INSERT INTO draft_picks (' + COLS.map(k => SQLC[k]).join(',') + ') VALUES (' + COLS.map(() => '?').join(',') + ')', COLS.map(k => p[k] == null ? null : p[k])); return Object.assign({ id: r.insertId }, p); },
async put(p) { await db.q('UPDATE draft_picks SET ' + COLS.map(k => SQLC[k] + '=?').join(',') + ' WHERE id=?', COLS.map(k => p[k] == null ? null : p[k]).concat([p.id])); },
async byId(id) { return rowP((await db.q('SELECT * FROM draft_picks WHERE id=?', [Number(id)]))[0]); },
async byRid(rid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE rid=?', [rid]))[0]); },
async byAdoption(aid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE adoption_id=?', [Number(aid)]))[0]); },
async ofPerson(pid) { return (await db.q('SELECT * FROM draft_picks WHERE person_id=? ORDER BY id', [pid])).map(rowP); },
async open() { return (await db.q("SELECT * FROM draft_picks WHERE status='open' ORDER BY id")).map(rowP); },
async openOfCoach(w) { return (await db.q("SELECT * FROM draft_picks WHERE status='open' AND coach_wallet=?", [w])).map(rowP); },
async recent(n) { return (await db.q('SELECT * FROM draft_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async countsByAdoptee() { return new Map((await db.q('SELECT adoptee, COUNT(*) n FROM draft_picks GROUP BY adoptee')).map(r => [r.adoptee, Number(r.n)])); },
async log(x) { await db.q('INSERT INTO draft_log (ts,op,ok,code,reason,coach,person,ref,rid) VALUES (?,?,?,?,?,?,?,?,?)', [x.ts, x.op, x.ok ? 1 : 0, x.code || null, String(x.reason || '').slice(0, 400), x.coach || null, x.person || null, x.ref || null, x.rid || null]); },
async logs(n) { return (await db.q('SELECT * FROM draft_log ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(r => ({ ts: Number(r.ts), op: r.op, ok: !!r.ok, code: r.code, reason: r.reason, coach: r.coach, person: r.person, ref: r.ref, rid: r.rid })); }
};
const S = () => (db.enabled() ? Q : J);
async function ensureTables() {
if (!db.enabled()) return;
await db.q(`CREATE TABLE IF NOT EXISTS draft_picks (
id INT AUTO_INCREMENT PRIMARY KEY, rid VARCHAR(80) NOT NULL, adoption_id INT NOT NULL, adoptee VARCHAR(190) NOT NULL, person_id VARCHAR(40) NOT NULL,
coach_email VARCHAR(190) NOT NULL, coach_wallet VARCHAR(42) NOT NULL, coach_hub_id VARCHAR(40) NULL, kind VARCHAR(16) NULL, week VARCHAR(16) NULL, slot VARCHAR(16) NULL,
ts BIGINT NOT NULL, expires BIGINT NOT NULL, hold_until BIGINT NOT NULL, status VARCHAR(16) NOT NULL, closed BIGINT NULL, outcome_why VARCHAR(200) NULL,
wallet_at BIGINT NULL, payouts_at BIGINT NULL, purchase_at BIGINT NULL,
UNIQUE KEY rid (rid), KEY adoption (adoption_id), KEY person (person_id), KEY coach (coach_wallet, status), KEY st (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // 5xYourTeam draft picks (each one a tank adoption)
await db.q(`CREATE TABLE IF NOT EXISTS draft_log (
id INT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, op VARCHAR(16) NOT NULL, ok TINYINT NOT NULL, code VARCHAR(40) NULL, reason VARCHAR(400) NULL,
coach VARCHAR(42) NULL, person VARCHAR(40) NULL, ref VARCHAR(40) NULL, rid VARCHAR(80) NULL, KEY t (ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
}
// the draft's own cap (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): site setting fiveXDraftCap (default 10),
// counted over open draft picks only; the member's own tank adoptions and holding tank batches never share it (tank.partnerEligibility)
const capOf = () => { const n = Math.round(Number(R && R.maxOpen ? R.maxOpen() : 10)); return n >= 1 && n <= 100 ? n : 10; };
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; Object.defineProperty(RULES, 'maxOpen', { get: capOf, enumerable: true, configurable: true }); await ensureTables(); }
// ---- signature ----
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
function verify(headers, raw) {
if (!enabled()) return { status: 503, error: 'draft partner not configured' };
const ts = String(headers['x-draft-ts'] || ''), sig = String(headers['x-draft-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' };
const want = sign(ts, raw);
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; }
}
// ---- helpers ----
const idOf = email => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; return hi && /^h_[0-9a-f]{16}$/.test(hi.id) ? hi.id : 'i_' + crypto.createHmac('sha256', SECRET() || 'local').update('pid:' + lc(email)).digest('hex').slice(0, 16); };
const doorOf = (email, via) => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; const k = lc((hi && hi.door) || via); return DOORS[k] || (k === 'hub' ? 'Network' : 'InstantAdPay'); };
function throwaway(email) {
const d = lc(email).split('@')[1] || ''; if (!d) return true;
if (THROWAWAY.has(d)) return true;
const fix = R.hooks && R.hooks.suggestDomain ? R.hooks.suggestDomain(d) : null; return !!(fix && fix !== d); // a mistyped provider: the mail bounces
}
function spamSet() { try { return new Set((R.hooks && R.hooks.spamEmails ? R.hooks.spamEmails() : []).map(lc)); } catch (e) { return new Set(); } }
const hubOff = () => R.requireHub !== false && !(R.hooks && R.hooks.networkOn && R.hooks.networkOn());
async function logCall(op, x) { const row = Object.assign({ ts: clock(), op }, x); try { await S().log(row); } catch (e) { console.error('draft log', e.message); } if (!x.ok) console.log('draft', op, 'refused', x.code || '', String(x.reason || '').slice(0, 120)); return row; }
const fail = async (op, code, reason, x) => { await logCall(op, Object.assign({ ok: false, code, reason }, x || {})); return { error: reason, code }; };
function purchasers() { const s = new Set(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) s.add(Number(ev.buyerId)); return s; }
// a coach: the wallet that holds the 5x position, then a position wallet here, then the hub's person for the hub id
async function coachAccount(c) {
const w = lc(c && c.wallet); if (!ADDR.test(w)) return { code: 'bad_coach', reason: 'Which coach? (wallet missing)' };
let a = await R.accounts.byAddress(w).catch(() => null);
if (!a && R.accounts.positionOwner) { const po = await R.accounts.positionOwner(w).catch(() => null); if (po && po.email) a = await R.accounts.byEmail(po.email); }
if (!a && c.hubId && R.hooks && R.hooks.resolvePerson) { try { const p = await R.hooks.resolvePerson({ id: String(c.hubId) }); if (p && p.email && !p.blocked) a = await R.accounts.byEmail(lc(p.email)); } catch (e) {} }
if (!a) return { code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link a wallet.' };
return { account: a, wallet: w };
}
// ---- the pool ----
let poolCache = null;
async function poolRows(fresh) {
if (!fresh && poolCache && clock() - poolCache.at < 30000) return poolCache;
const list = await R.tank.waiting(); const spam = spamSet(); const ex = { spam: 0, throwaway: 0, adoptedTwice: 0 };
const local = await R.tank.summaryMap(); const mine = await S().countsByAdoptee(); const rows = [];
for (const w of list) {
if ((R.hooks.excluded && R.hooks.excluded(w.email)) || spam.has(lc(w.email))) { ex.spam++; continue; }
if (throwaway(w.email)) { ex.throwaway++; continue; }
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
if (n >= RULES.maxAdoptions) { ex.adoptedTwice++; continue; }
rows.push({ email: w.email, card: { id: idOf(w.email), username: w.username || null, door: doorOf(w.email, w.via), joinedAt: Number(w.joined) || 0, lastSeen: Number(w.lastSeen) || 0,
// adoptions = OUTSIDE 5xYourTeam (5xYourTeam adds its own picks; counting them here too would double them); adoptionsTotal = all
wallet: !!w.wallet, ready: !!w.ready, holdUntil: w.holdUntil || 0, opensAt: w.opensAt || 0, adoptions: Math.max(0, n - (mine.get(w.email) || 0)), adoptionsTotal: n,
games: null, surfWei: null, surfCredits: Number(w.earned) || 0 } }); // games: InstantAdPay keeps no per-member game record (never invented)
}
poolCache = { at: clock(), rows, excluded: ex }; return poolCache;
}
async function pool() {
if (hubOff()) { await logCall('pool', { ok: false, code: 'hub_off', reason: 'the network hub is off, so locked people cannot be ruled out' }); return { ok: true, rules: rulesView(), pool: [], excluded: {}, hubOff: true }; }
const p = await poolRows(false);
return { ok: true, rules: rulesView(), pool: p.rows.map(r => r.card), excluded: p.excluded };
}
const rulesView = () => ({ returnHours: RULES.returnMs / H, holdHours: RULES.holdMs / H, maxOpen: RULES.maxOpen, maxAdoptions: RULES.maxAdoptions, graceHours: (RULES.graceMs || D) / H });
// ---- adopt ----
async function adopt(b) {
const rid = String(b.rid || '').slice(0, 80); const c = b.coach || {}; const pid = String(b.person || '').slice(0, 40); const kind = /^(draft|instant)$/.test(b.kind) ? b.kind : 'draft';
const x = { coach: lc(c.wallet) || null, person: pid || null, rid };
if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return fail('adopt', 'bad_rid', 'A request id (rid) is required.', x);
const prev = await S().byRid(rid);
if (prev) return { ok: true, repeat: true, ref: 'iap:' + prev.id, person: prev.personId, adoptionId: prev.adoptionId, at: prev.ts, expires: prev.expires, holdUntil: prev.holdUntil };
if (!(Number(c.positions) >= 1)) return fail('adopt', 'not_vested', 'Only 5xYourTeam position holders can draft and coach.', x);
if (hubOff()) return fail('adopt', 'hub_off', 'The network hub is off, so nobody can be drafted right now.', x);
const co = await coachAccount(c); if (!co.account) return fail('adopt', co.code, co.reason, x);
if ((await S().openOfCoach(co.wallet)).length >= RULES.maxOpen) return fail('adopt', 'full', 'Your team is full (' + RULES.maxOpen + ' open picks). Help one get started first.', x);
const hit = (await poolRows(true)).rows.find(r => r.card.id === pid);
if (!hit) return fail('adopt', 'gone', 'That player is no longer in the holding tank.', x);
const r = await R.tank.adopt(co.account.email, hit.email, String(b.note || ''), { partner: { positions: Number(c.positions), ttlMs: RULES.returnMs, maxOpen: RULES.maxOpen }, recordNote: '5xYourTeam draft pick (' + kind + (b.week ? ', week ' + String(b.week).slice(0, 10) : '') + (b.slot ? ', slot ' + String(b.slot).slice(0, 10) : '') + ')' });
if (!r || !r.ok) return fail('adopt', (r && r.code) || 'refused', (r && r.error) || 'The tank refused.', x);
poolCache = null;
const now = clock(); const acct = await R.accounts.byEmail(hit.email);
const pick = await S().add({ rid, adoptionId: Number(r.adoption.id), adoptee: hit.email, personId: pid, coachEmail: co.account.email, coachWallet: co.wallet, coachHubId: c.hubId ? String(c.hubId).slice(0, 40) : null,
kind, week: b.week ? String(b.week).slice(0, 16) : null, slot: b.slot ? String(b.slot).slice(0, 16) : null, ts: now, expires: now + RULES.returnMs, holdUntil: now + RULES.holdMs, status: 'open', closed: 0, outcomeWhy: null,
walletAt: acct && acct.address ? now : 0, payoutsAt: 0, purchaseAt: 0 });
await logCall('adopt', Object.assign(x, { ok: true, ref: 'iap:' + pick.id, reason: kind + ' pick by ' + (c.username ? '@' + String(c.username).slice(0, 40) : x.coach) }));
return { ok: true, ref: 'iap:' + pick.id, person: pid, adoptionId: pick.adoptionId, at: pick.ts, expires: pick.expires, holdUntil: pick.holdUntil };
}
// is the pick's adoption still the open one? (released on InstantAdPay itself, moved by a LinkSpin follow, ...) -> closed here too
async function reconcile(p) {
if (p.status !== 'open') return p;
const open = await R.tank.openOf(p.adoptee);
if (open.some(ad => Number(ad.id) === p.adoptionId)) return p;
p.status = 'moved'; p.closed = clock(); p.outcomeWhy = 'the adoption was closed on InstantAdPay (released, moved or followed from LinkSpin)'; await S().put(p);
await logCall('reconcile', { ok: true, code: 'moved', reason: p.outcomeWhy, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
return p;
}
// milestones seen so far (first-seen times; the chain events carry no timestamps here)
async function observe(p, a, buyers) {
if (!a) return p; const now = clock(); let ch = false;
if (a.address && !p.walletAt) { p.walletAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.payoutsAt) { p.payoutsAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.purchaseAt && buyers && buyers.has(Number(a.memberId))) { p.purchaseAt = now; ch = true; }
if (ch) await S().put(p); return p;
}
const started = (p, a) => !!(a && Number(a.memberId) > 0) || !!(p.payoutsAt || p.purchaseAt);
// close one open pick: 'coach' (released after the 48 h hold) or 'return' (3 days, not started). Shared by release() and sweep().
async function closePick(p, why, now) {
const a = await R.accounts.byEmail(p.adoptee);
await observe(p, a, purchasers());
if (started(p, a)) { p.status = 'done'; p.closed = now; p.outcomeWhy = 'started (payouts on or a purchase)'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'done'); return { outcome: 'done', why: p.outcomeWhy }; }
if (why === 'coach' && now < p.holdUntil) return { code: 'hold', reason: 'You picked them less than ' + (RULES.holdMs / H) + ' hours ago. Give them a little time first (' + Math.ceil((p.holdUntil - now) / H) + ' h left).' };
if (why === 'return' && now < p.expires) return { code: 'too_early', reason: 'The pick window runs until ' + new Date(p.expires).toISOString() + '.' };
const count = await R.tank.countAll(p.adoptee);
if (count >= RULES.maxAdoptions) { // their second adoption: they stay with this coach (the tank sweep rule, never back to nobody)
p.status = 'kept'; p.closed = now; p.outcomeWhy = 'adopted twice: stays with this coach'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired');
return { outcome: 'kept', why: p.outcomeWhy };
}
const lk = await R.tank.lockedWhy(p.adoptee);
if (lk === 'unknown') return { code: 'hub_unknown', reason: 'The network record cannot be checked right now. Try again later.' };
if (lk === 'locked') { p.status = 'kept'; p.closed = now; p.outcomeWhy = 'locked on a network contract: never moved'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired'); return { outcome: 'kept', why: p.outcomeWhy }; }
const note = why === 'return' ? '5xYourTeam pick returned: not started in ' + (RULES.returnMs / D) + ' days' : '5xYourTeam pick released by the coach';
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'release', note);
if (r && r.error) return { code: 'refused', reason: r.error };
await R.tank.closeAdoption(p.adoptionId, why === 'return' ? 'expired' : 'dropped'); // both still count toward their two adoptions
p.status = 'returned'; p.closed = now; p.outcomeWhy = note; await S().put(p); poolCache = null;
return { outcome: 'returned', why: note };
}
async function findPick(b) {
const ref = String(b.ref || ''); const m = /^iap:(\d+)$/.exec(ref);
if (m) return S().byId(Number(m[1]));
const pid = String(b.person || ''); const w = lc(b.coach && b.coach.wallet);
const rows = (await S().ofPerson(pid)).filter(p => p.coachWallet === w); return rows.find(p => p.status === 'open') || rows[rows.length - 1] || null;
}
async function release(b) {
const why = b.why === 'return' ? 'return' : 'coach'; const w = lc(b.coach && b.coach.wallet); const rid = String(b.rid || '').slice(0, 80);
const x = { coach: w || null, person: b.person ? String(b.person).slice(0, 40) : null, rid, ref: b.ref ? String(b.ref).slice(0, 40) : null };
let p = await findPick(b);
if (!p) return fail('release', 'no_pick', 'No such pick.', x);
if (p.coachWallet !== w) return fail('release', 'not_yours', 'Not your pick.', x);
x.person = p.personId; x.ref = 'iap:' + p.id;
p = await reconcile(p);
if (p.status !== 'open') { await logCall('release', Object.assign(x, { ok: true, code: 'already', reason: why + ': already ' + p.status })); return { ok: true, already: true, outcome: p.status }; }
const r = await closePick(p, why, clock());
if (!r.outcome) return fail('release', r.code, r.reason, x);
await logCall('release', Object.assign(x, { ok: true, code: r.outcome, reason: why + ': ' + r.why }));
return { ok: true, outcome: r.outcome };
}
// ---- status: milestones for the people 5xYourTeam holds picks for (anyone else answers null) ----
async function status(b) {
const ids = [...new Set((Array.isArray(b.ids) ? b.ids : []).map(v => String(v || '').slice(0, 40)).filter(Boolean))].slice(0, 500);
const buyers = purchasers(); const out = {};
const emails = []; const picksBy = {};
for (const id of ids) { const rows = await S().ofPerson(id); if (!rows.length) { out[id] = null; continue; } picksBy[id] = rows; emails.push(rows[0].adoptee); }
const tot = R.ads && R.ads.earnedTotals ? await R.ads.earnedTotals(emails).catch(() => ({})) : {};
for (const id of Object.keys(picksBy)) {
const rows = picksBy[id]; let last = rows[rows.length - 1]; const email = last.adoptee;
const a = await R.accounts.byEmail(email); if (!a) { out[id] = null; continue; }
last = await reconcile(last); last = await observe(last, a, buyers);
const count = await R.tank.countAll(email);
out[id] = { username: a.username || null, door: doorOf(email, a.joinedVia), lastSeen: Number(a.lastSeen) || 0,
wallet: a.address ? (rows.map(r => r.walletAt).filter(Boolean).sort((x, y) => x - y)[0] || clock()) : 0,
payouts: Number(a.memberId) > 0 ? (last.payoutsAt || clock()) : 0, purchase: Number(a.memberId) > 0 && buyers.has(Number(a.memberId)) ? (last.purchaseAt || clock()) : 0,
adoptions: Math.max(0, count - rows.length), // adoptions outside 5xYourTeam (5x counts its own picks itself)
games: null, surfWei: null, surfCredits: (tot[email] || {}).earned || 0,
pick: { ref: 'iap:' + last.id, status: last.status, coachWallet: last.coachWallet, expires: last.expires, holdUntil: last.holdUntil } };
}
return { ok: true, people: out };
}
// ---- the hourly sweep (server.js, beside tank.sweep): started picks close as done, unstarted ones past 3 days go back ----
let sweeping = null;
function sweep() { if (!sweeping) sweeping = sweepRun().finally(() => { sweeping = null; }); return sweeping; }
async function sweepRun() {
const now = clock(); const out = { done: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const buyers = purchasers();
for (let p of await S().open()) {
p = await reconcile(p); if (p.status !== 'open') { out.moved++; continue; }
const a = await R.accounts.byEmail(p.adoptee); await observe(p, a, buyers);
if (!started(p, a) && now < p.expires) continue;
const r = await closePick(p, 'return', now);
if (!r.outcome) { out.waiting++; continue; }
out[r.outcome] = (out[r.outcome] || 0) + 1;
await logCall('sweep', { ok: true, code: r.outcome, reason: r.why, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
}
return out;
}
// tank.sweep asks this before closing an expired adoption (the pick's own rule decides)
async function isDraftPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
async function adminView() { return { enabled: enabled(), rules: rulesView(), hubOff: hubOff(), picks: (await S().recent(200)).map(p => Object.assign({}, p, { adoptee: undefined, coachEmail: undefined })), log: await S().logs(200) }; }
// one entry for the HTTP routes (server.js) and the cross-repo test: op = pool | adopt | release | status
async function handle(op, body) {
if (op === 'pool') return pool();
if (op === 'adopt') return adopt(body);
if (op === 'release') return release(body);
if (op === 'status') return status(body);
return { error: 'unknown op', code: 'unknown_op' };
}
module.exports = { init, enabled, verify, sign, handle, pool, adopt, release, status, sweep, isDraftPick, adminView, RULES, _poolReset: () => { poolCache = null; } };