'use strict';
// Holding tank batches (Marty 2026-11-15: "let's auto-assign 10 at a time if they've got a paid package of $20 or $25, depending on
// which platform it was. If they fueled their engines or they've bought higher packages, let's raise that batch up to be like 20 or
// 25 at a time and keep climbing up (because I want those people in the holding tank to get people that are active paying sponsors)").
//
// THE RULES (every number is a site setting, see DEFAULTS)
// eligible sponsor signed in within tankBatchActiveDays (7) and holds their own paid package: $20+ on InstantAdPay (a chain
// Purchase by their member number or a linked position) or $25+ on LinkSpin (known here through the refuel
// streak record, the only place LinkSpin packages reach InstantAdPay); not the company, not suspended or flagged,
// someone on this contract in their line and that line takes payouts (tank.batchEligibility)
// batch size Paid 10. Fueled 20: a counted refuel streak is active, or a higher package ($50+ on either site). Twin Engine
// 25: both engines refueled this cycle, or the top package (the highest package on the live InstantAdPay
// catalog, $500 Elite today; LinkSpin $500 Network). Then +5 for every further consecutive refuel month, up to 50.
// "at a time" a sponsor holds at most one batch size of batch people who have not switched on payouts; a person who
// switches on payouts frees their place at once
// cadence every tankBatchEveryDays (2) per sponsor a fresh batch tops them back up to their size. One round deals by
// rotation, highest tier first (ties: longest since their last batch), one person per sponsor per pass, from
// the waiting tank in the order the tank already uses (tank.adoptable: past the 24-hour sign-up grace, rule 3
// applied, nobody adopted on LinkSpin). Never: the sponsor themself, anyone above them in their own line, anyone
// adopted twice, a flagged, spam, throwaway or unsubscribed address
// assignment tank.adopt(.., { batch: true }): the same sponsor change, chat, "X is now your sponsor" email and switch-on-payouts
// reminders as any adoption. The sponsor gets one notice per batch (not one per person)
// follow-up a batch person the sponsor has not contacted (a chat after the assignment, or "Contacted them") within
// tankBatchFollowDays (7) goes back to the tank as 'unreached' (does not count toward their two adoptions:
// the sponsor's miss). Contacted ones close like any adoption window: payouts on or wallet linked = done,
// else back to the tank (counted)
// tank feed per batch: one card to the shared payments topic and the live toast feed, naming the sponsor, the count and
// the level, never the people (Marty 2026-11-15: "if the others see that happening, it may pick up the pace")
// the 24-hour activation-hold safety net (tank.autoAssign) is unchanged and runs beside this; the 5xYourTeam draft has its own cap
// MASTER SWITCH: site setting tankBatches (default '0'). Off: no round, no feed, the member panel answers { on:false }. The follow-up
// still runs for batch people already assigned (they must not sit uncontacted). preview() is read-only whatever the switch says.
const fs = require('fs');
const path = require('path');
const D = 86400000;
const DEFAULTS = {
tankBatches: '0', tankBatchActiveDays: 7, tankBatchBase: 10, tankBatchFueled: 20, tankBatchTwin: 25, tankBatchStep: 5, tankBatchMax: 50,
tankBatchEveryDays: 2, tankBatchFollowDays: 7, tankBatchMinIapCents: 2000, tankBatchMinLsCents: 2500,
tankBatchHigherIapCents: 5000, tankBatchHigherLsCents: 5000, tankBatchTopIapCents: 0 /* 0 = the highest package on the live catalog */, tankBatchTopLsCents: 50000,
tankBatchFeed: '1',
// the assigned people's "X is now your sponsor" emails go out through a throttled queue (Marty 2026-11-15: "spread the emails out"):
// at most tankBatchEmailsPerDay per Central day, spaced evenly between the start and end hour (CT); Telegram cards at least tankBatchFeedGapMin apart
// one announcement per round in the CTB group's General topic (blank topic = General, no thread id; blank chat = the payments group)
tankBatchAnnounce: '1', tankBatchAnnounceChatId: '', tankBatchAnnounceTopicId: '',
tankBatchEmailsPerDay: 100, tankBatchEmailStartHour: 8, tankBatchEmailEndHour: 20, tankBatchFeedGapMin: 2
};
let R = null; // { dataDir, db, accounts, chain, tank, refuel, messages, mailer, siteConfig, hooks: { excluded, excludedPerson, claim, feed, toast, notify, companyId, networkSeen }, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const lc = v => String(v || '').trim().toLowerCase();
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
const nameOf = a => a ? (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'a member')) : 'a member';
function cfg() {
const sc = (R && R.siteConfig && R.siteConfig()) || {};
const num = (k, lo, hi) => { const v = Number(sc[k] == null || sc[k] === '' ? DEFAULTS[k] : sc[k]); return Number.isFinite(v) && v >= lo && v <= hi ? v : DEFAULTS[k]; };
return { on: String(sc.tankBatches == null ? DEFAULTS.tankBatches : sc.tankBatches) === '1', feed: String(sc.tankBatchFeed == null ? '1' : sc.tankBatchFeed) !== '0', announce: String(sc.tankBatchAnnounce == null ? '1' : sc.tankBatchAnnounce) !== '0',
activeDays: num('tankBatchActiveDays', 1, 60), base: num('tankBatchBase', 1, 200), fueled: num('tankBatchFueled', 1, 200), twin: num('tankBatchTwin', 1, 200),
step: num('tankBatchStep', 0, 100), max: num('tankBatchMax', 1, 500), everyDays: num('tankBatchEveryDays', 0.04, 60), followDays: num('tankBatchFollowDays', 1, 60),
minIap: num('tankBatchMinIapCents', 0, 1e7), minLs: num('tankBatchMinLsCents', 0, 1e7), higherIap: num('tankBatchHigherIapCents', 0, 1e7), higherLs: num('tankBatchHigherLsCents', 0, 1e7),
topIap: num('tankBatchTopIapCents', 0, 1e8), topLs: num('tankBatchTopLsCents', 0, 1e8),
perDay: num('tankBatchEmailsPerDay', 1, 5000), startHour: num('tankBatchEmailStartHour', 0, 23), endHour: num('tankBatchEmailEndHour', 1, 24), feedGapMin: num('tankBatchFeedGapMin', 0, 120) };
}
// ---- the ladder (pure: the tests drive it directly) ----
// f = { iapMax, lsMax, refuel: { active, streak, both } | null }, c = cfg() with topIap resolved
function tierFor(f, c) {
const rf = f.refuel || {}; const reasons = [];
const paidIap = f.iapMax >= c.minIap, paidLs = f.lsMax >= c.minLs;
if (!paidIap && !paidLs) return { level: null, size: 0, reasons: ['no own package of ' + usd(c.minIap) + '+ on InstantAdPay or ' + usd(c.minLs) + '+ on LinkSpin'] };
if (paidIap) reasons.push('own ' + usd(f.iapMax) + ' InstantAdPay package'); if (paidLs) reasons.push('own ' + usd(f.lsMax) + ' LinkSpin package');
let level = 'Paid', size = c.base;
const higher = (c.higherIap > 0 && f.iapMax >= c.higherIap) || (c.higherLs > 0 && f.lsMax >= c.higherLs);
const top = (c.topIap > 0 && f.iapMax >= c.topIap) || (c.topLs > 0 && f.lsMax >= c.topLs);
if (rf.active || higher) { level = 'Fueled'; size = c.fueled; if (rf.active) reasons.push('refuel streak month ' + rf.streak); if (higher) reasons.push('higher package (' + usd(c.higherIap) + '+ InstantAdPay / ' + usd(c.higherLs) + '+ LinkSpin)'); }
if ((rf.active && rf.both) || top) { level = 'Twin Engine'; size = c.twin; if (rf.active && rf.both) reasons.push('both engines refueled this cycle'); if (top) reasons.push('top package'); }
const extra = rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0;
if (extra) { size += extra; reasons.push('+' + extra + ' for ' + (rf.streak - 1) + ' further refuel month' + (rf.streak === 2 ? '' : 's')); }
size = Math.min(size, c.max);
const label = level + (rf.active && rf.streak > 1 ? ', month ' + rf.streak : '');
return { level, label, size, reasons };
}
// the member panel's "next step" line: what raises their batch, in leads they can sponsor (never money)
function nextStep(t, f, c) {
const rf = f.refuel || {};
if (!t.level) return 'Buy your own ' + usd(c.minIap) + ' package on InstantAdPay (or ' + usd(c.minLs) + ' on LinkSpin) to start receiving ' + c.base + ' people at a time.';
if (t.size >= c.max) return 'You are at the top of the ladder: ' + c.max + ' people at a time. Keep your refuel streak going to stay there.';
if (t.level === 'Paid') return 'A counted monthly refuel (or a higher package) raises your batch to ' + c.fueled + '. Refuel both InstantAdPay and LinkSpin in the same cycle for ' + c.twin + '.';
if (t.level === 'Fueled' && !(rf.active && rf.both)) return 'Refuel the other engine this cycle too (InstantAdPay and LinkSpin) to raise your batch to ' + Math.min(c.max, c.twin + (rf.active && rf.streak > 1 ? (rf.streak - 1) * c.step : 0)) + '.';
return 'Your next consecutive refuel month adds ' + c.step + ' more (up to ' + c.max + ').';
}
const ladderView = c => [
{ level: 'Paid', size: c.base, how: 'your own ' + usd(c.minIap) + ' InstantAdPay package or ' + usd(c.minLs) + ' LinkSpin package' },
{ level: 'Fueled', size: c.fueled, how: 'a counted monthly refuel, or a higher package (' + usd(c.higherIap) + '+)' },
{ level: 'Twin Engine', size: c.twin, how: 'both engines refueled this cycle, or the top package' },
{ level: 'Streak', size: c.max, how: '+' + c.step + ' for every further consecutive refuel month, up to ' + c.max }
];
// ---- storage: MySQL tank_batch_picks when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'tank-batch.json'),
load() { 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.rounds = this.st.rounds || []; this.st.outbox = this.st.outbox || []; this.st.state = this.st.state || {}; this.st.nextOut = this.st.nextOut || 1; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.st || 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 close(id, status, why) { const x = this.load().picks.find(r => r.id === id); if (x) { x.status = status; x.closed = clock(); x.why = why || null; this.save(); } },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
async lastBySponsor() { const m = new Map(); for (const r of this.load().picks) m.set(r.sponsor, Math.max(m.get(r.sponsor) || 0, r.roundAt || r.at)); return m; },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async addRound(x) { const s = this.load(); s.rounds.push(x); if (s.rounds.length > 200) s.rounds = s.rounds.slice(-200); this.save(); },
async rounds(n) { return this.load().rounds.slice(-(n || 30)).reverse(); },
// outbox: kind 'mail' | 'feed', status queued -> sending -> sent | skipped
async enqueue(x) { const s = this.load(); const row = Object.assign({ id: s.nextOut++, status: 'queued', created: clock(), sentAt: null, why: null }, x); s.outbox.push(row); this.save(); return row; },
async oldest(kind, n) { return this.load().outbox.filter(r => r.kind === kind && r.status === 'queued').sort((a, b) => a.id - b.id).slice(0, n || 1).map(x => Object.assign({}, x)); },
async take(id) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (!x || x.status !== 'queued') return false; x.status = 'sending'; this.save(); return true; },
async finish(id, status, why) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (x) { x.status = status; x.sentAt = clock(); x.why = why || null; this.save(); } },
async counts(kind, since) { const rows = this.load().outbox.filter(r => r.kind === kind); return { queued: rows.filter(r => r.status === 'queued').length, sent: rows.filter(r => r.status === 'sent' && r.sentAt >= since).length, skipped: rows.filter(r => r.status === 'skipped' && r.sentAt >= since).length }; },
async getState(k) { const v = this.load().state[k]; return v === undefined ? null : v; },
async setState(k, v) { const s = this.load(); s.state[k] = v; this.save(); }
};
const rowP = r => ({ id: Number(r.id), adoptionId: Number(r.adoption_id), sponsor: r.sponsor, adoptee: r.adoptee, at: Number(r.at), roundAt: Number(r.round_at), level: r.level, size: Number(r.size), status: r.status, closed: r.closed ? Number(r.closed) : null, why: r.why || null });
const Q = {
async add(p) { const r = await R.db.q('INSERT INTO tank_batch_picks (adoption_id,sponsor,adoptee,at,round_at,level,size,status) VALUES (?,?,?,?,?,?,?,?)', [p.adoptionId, p.sponsor, p.adoptee, p.at, p.roundAt, p.level, p.size, 'open']); return Object.assign({ id: r.insertId }, p); },
async close(id, status, why) { await R.db.q('UPDATE tank_batch_picks SET status=?, closed=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
async open() { return (await R.db.q("SELECT * FROM tank_batch_picks WHERE status='open' ORDER BY id")).map(rowP); },
async byAdoption(aid) { const r = (await R.db.q('SELECT * FROM tank_batch_picks WHERE adoption_id=? LIMIT 1', [Number(aid)]))[0]; return r ? rowP(r) : null; },
async lastBySponsor() { return new Map((await R.db.q('SELECT sponsor, MAX(round_at) t FROM tank_batch_picks GROUP BY sponsor')).map(r => [r.sponsor, Number(r.t)])); },
async recent(n) { return (await R.db.q('SELECT * FROM tank_batch_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async addRound(x) { await R.db.q('INSERT INTO tank_batch_rounds (at, summary) VALUES (?,?)', [x.at, JSON.stringify(x).slice(0, 60000)]); },
async rounds(n) { return (await R.db.q('SELECT summary FROM tank_batch_rounds ORDER BY id DESC LIMIT ?', [Number(n) || 30])).map(r => { try { return JSON.parse(r.summary); } catch (e) { return null; } }).filter(Boolean); },
async enqueue(x) { const r = await R.db.q("INSERT INTO tank_batch_outbox (kind,to_email,sponsor,adoption_id,subject,body,payload,created,status) VALUES (?,?,?,?,?,?,?,?,'queued')", [x.kind, x.to || null, x.sponsor || null, x.adoptionId || null, x.subject || null, x.body || null, x.payload ? JSON.stringify(x.payload) : null, clock()]); return Object.assign({ id: r.insertId, status: 'queued' }, x); },
async oldest(kind, n) { return (await R.db.q("SELECT * FROM tank_batch_outbox WHERE kind=? AND status='queued' ORDER BY id LIMIT ?", [kind, Number(n) || 1])).map(r => ({ id: Number(r.id), kind: r.kind, to: r.to_email, sponsor: r.sponsor, adoptionId: r.adoption_id ? Number(r.adoption_id) : null, subject: r.subject, body: r.body, payload: r.payload ? JSON.parse(r.payload) : null, created: Number(r.created), status: r.status })); },
async take(id) { const r = await R.db.q("UPDATE tank_batch_outbox SET status='sending' WHERE id=? AND status='queued'", [Number(id)]); return Number(r.affectedRows) === 1; },
async finish(id, status, why) { await R.db.q('UPDATE tank_batch_outbox SET status=?, sent_at=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
async counts(kind, since) { const r = (await R.db.q("SELECT SUM(status='queued') q, SUM(status='sent' AND sent_at>=?) s, SUM(status='skipped' AND sent_at>=?) k FROM tank_batch_outbox WHERE kind=?", [since, since, kind]))[0] || {}; return { queued: Number(r.q || 0), sent: Number(r.s || 0), skipped: Number(r.k || 0) }; },
async getState(k) { const r = (await R.db.q('SELECT v FROM tank_batch_state WHERE k=?', [k]))[0]; return r ? JSON.parse(r.v) : null; },
async setState(k, v) { await R.db.q('INSERT INTO tank_batch_state (k,v) VALUES (?,?) ON DUPLICATE KEY UPDATE v=VALUES(v)', [k, JSON.stringify(v)]); }
};
const dbOn = () => !!(R && R.db && R.db.enabled && R.db.enabled());
const S = () => (dbOn() ? Q : J);
async function ensureTables() {
if (!dbOn()) return;
await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_picks (
id INT AUTO_INCREMENT PRIMARY KEY, adoption_id INT NOT NULL, sponsor VARCHAR(190) NOT NULL, adoptee VARCHAR(190) NOT NULL, at BIGINT NOT NULL, round_at BIGINT NOT NULL,
level VARCHAR(40) NULL, size INT NOT NULL DEFAULT 0, status VARCHAR(16) NOT NULL, closed BIGINT NULL, why VARCHAR(200) NULL,
KEY adoption (adoption_id), KEY sp (sponsor, status), KEY st (status), KEY adoptee (adoptee)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // holding tank batches (each one a tank adoption)
await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_outbox (
id INT AUTO_INCREMENT PRIMARY KEY, kind VARCHAR(8) NOT NULL, to_email VARCHAR(190) NULL, sponsor VARCHAR(190) NULL, adoption_id INT NULL, subject VARCHAR(300) NULL,
body MEDIUMTEXT NULL, payload TEXT NULL, created BIGINT NOT NULL, status VARCHAR(10) NOT NULL, sent_at BIGINT NULL, why VARCHAR(200) NULL,
KEY ks (kind, status, id), KEY sent (kind, sent_at), KEY toe (to_email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // the throttled batch emails + spaced Telegram cards (survives deploys)
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_state (k VARCHAR(40) PRIMARY KEY, v TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_rounds (id INT AUTO_INCREMENT PRIMARY KEY, at BIGINT NOT NULL, summary MEDIUMTEXT NOT NULL, KEY t (at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
}
async function init(opts) { R = opts; R.hooks = R.hooks || {}; J.st = null; await ensureTables(); }
// ---- facts about the members ----
function iapMaxByMember() { const m = new Map(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) { const id = Number(ev.buyerId); m.set(id, Math.max(m.get(id) || 0, Number(ev.priceCents) || 0)); } return m; }
async function topIapCents(c) {
if (c.topIap > 0) return c.topIap;
try { const cat = await R.chain.catalog(); const top = Math.max(0, ...(cat || []).map(p => Number(p.priceCents) || 0)); if (top > 0) return top; } catch (e) {}
return 50000; // Elite $500, the top of the published ladder (chatbot.js) when the catalog cannot be read
}
async function factsOf(a, byMember) {
let iapMax = Number(a.memberId) > 0 ? byMember.get(Number(a.memberId)) || 0 : 0;
if (R.accounts.positions) { try { for (const p of await R.accounts.positions(a.email)) if (p.memberId) iapMax = Math.max(iapMax, byMember.get(Number(p.memberId)) || 0); } catch (e) {} }
let rf = null; try { rf = R.refuel && R.refuel.standing ? await R.refuel.standing(a.email, clock()) : null; } catch (e) { rf = null; }
const lsMax = rf ? Number(rf.maxCents.linkspin) || 0 : 0;
if (rf) iapMax = Math.max(iapMax, Number(rf.maxCents.iap) || 0);
return { iapMax, lsMax, refuel: rf };
}
const companyIds = () => new Set([1, Number(R.hooks.companyId ? R.hooks.companyId() : 1) || 1]);
async function lastSeenOf(a) {
let t = Number(a.lastSeen) || 0;
if (R.hooks.networkSeen) { try { t = Math.max(t, Number(await R.hooks.networkSeen(a.email)) || 0); } catch (e) {} }
return t;
}
// every member, sorted out: eligible sponsors (with tier, room, due) and the near misses (why not)
async function sponsors(c, now) {
const byMember = iapMaxByMember(); const co = companyIds(); const last = await S().lastBySponsor();
const openByS = new Map(); for (const p of await S().open()) { if (!openByS.has(p.sponsor)) openByS.set(p.sponsor, []); openByS.get(p.sponsor).push(p); }
const out = [], skipped = []; const why = {};
const skip = (a, reason, extra) => { why[reason] = (why[reason] || 0) + 1; if (skipped.length < 300) skipped.push(Object.assign({ name: nameOf(a), reason }, extra || {})); };
for (const a of await R.accounts.listAll(1e6)) {
if (Number(a.memberId) > 0 && co.has(Number(a.memberId))) continue;
const seen = await lastSeenOf(a); const active = !!seen && now - seen <= c.activeDays * D;
if (!active && !(Number(a.memberId) > 0)) continue; // cheap first: a free inactive account is nobody's near miss
const f = await factsOf(a, byMember); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
if (!t.level) continue; // free members are not sponsors here (not listed: the near misses are paid members)
if (!active) { skip(a, 'not active in the last ' + c.activeDays + ' days', { level: t.label, size: t.size, lastSeen: seen || 0 }); continue; }
const bar = R.hooks.excluded || R.hooks.isSuspended; if (bar && bar(a.email)) { skip(a, 'suspended or flagged'); continue; }
const el = await R.tank.batchEligibility(a.email); if (!el.ok) { skip(a, el.code === 'no_contract_line' ? 'nobody in their line has payouts on at InstantAdPay' : el.reason, { level: t.label, size: t.size }); continue; }
const open = []; for (const p of openByS.get(a.email) || []) { const acc = await R.accounts.byEmail(p.adoptee); if (!(acc && Number(acc.memberId) > 0)) open.push(p); }
const lastAt = last.get(a.email) || 0; const dueAt = lastAt ? lastAt + c.everyDays * D : 0;
out.push({ account: a, email: a.email, name: nameOf(a), username: a.username || null, memberId: Number(a.memberId) || 0, lastSeen: seen, tier: t, facts: f,
holding: open.length, room: Math.max(0, t.size - open.length), lastBatchAt: lastAt, dueAt, due: !dueAt || now >= dueAt });
}
const rank = { 'Twin Engine': 3, Fueled: 2, Paid: 1 };
out.sort((x, y) => y.tier.size - x.tier.size || (rank[y.tier.level] || 0) - (rank[x.tier.level] || 0) || x.lastBatchAt - y.lastBatchAt || y.lastSeen - x.lastSeen || (x.email < y.email ? -1 : 1));
return { list: out, skipped, why };
}
// the waiting people a batch may take, in the tank's own order
async function poolOf() {
const list = await R.tank.adoptable(); const local = await R.tank.summaryMap(); const ex = {}; const rows = [];
const no = k => { ex[k] = (ex[k] || 0) + 1; };
for (const w of list) {
if (R.hooks.excluded && R.hooks.excluded(w.email)) { no('flagged or suspended'); continue; }
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
if (n >= (R.tank.MAX_ADOPTIONS || 2)) { no('adopted twice already'); continue; }
let px = null; if (R.hooks.excludedPerson) { try { px = await R.hooks.excludedPerson(w.email); } catch (e) { px = 'check failed'; } }
if (px) { no(px); continue; }
rows.push(w);
}
return { waiting: list.length, rows, excluded: ex };
}
// one round: who gets whom. Read-only: the live run applies it, the preview shows it.
async function plan(c, now) {
const sp = await sponsors(c, now); const pool = await poolOf();
const takers = sp.list.filter(s => s.due && s.room > 0).map(s => Object.assign(s, { give: [] }));
const left = pool.rows.slice(); const loopCache = new Map();
let moved = true;
while (moved && left.length) {
moved = false;
for (const s of takers) {
if (s.give.length >= s.room || !left.length) continue;
for (let i = 0; i < left.length; i++) {
const w = left[i];
if (w.email === s.email) continue;
const k = w.email + '>' + s.email;
if (!loopCache.has(k)) loopCache.set(k, await R.tank.inDownlineOf(w.email, s.account).catch(() => true));
if (loopCache.get(k)) continue;
s.give.push(w); left.splice(i, 1); moved = true; break;
}
}
}
return { sponsors: sp, pool, takers, left: left.length };
}
// ---- the live round ----
let busy = null;
const lock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatch', fn, 5) : fn());
async function round() {
const c = cfg(); if (!c.on) return { on: false };
if (busy) return busy;
busy = (async () => {
c.topIapResolved = await topIapCents(c);
const now = clock(); const summary = { at: now, batches: [], assigned: 0, refused: 0 }; const cards = [];
await lock(async () => {
const p = await plan(c, now);
for (const s of p.takers) {
if (!s.give.length) continue;
const got = [];
for (const w of s.give) {
const msg = 'Hi, I am ' + s.name + '. ' + (w.via === 'btc4hits' ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so you were matched with me from the holding tank: active members who have bought their own package take turns. I will walk you through the first steps whenever you are ready. Reply here.';
const r = await R.tank.adopt(s.email, w.username || w.email, msg, { batch: true, recordNote: 'holding tank batch (' + s.tier.label + ', ' + s.tier.size + ' at a time)', queueMail: m => S().enqueue({ kind: 'mail', to: m.to, sponsor: m.sponsor, adoptionId: m.adoptionId, subject: m.subject, body: m.body }) }).catch(e => ({ error: e.message }));
if (!(r && r.ok)) { summary.refused++; continue; }
await S().add({ adoptionId: Number(r.adoption.id), sponsor: s.email, adoptee: r.adoptee, at: clock(), roundAt: now, level: s.tier.label, size: s.tier.size, status: 'open' });
got.push(r.adopteeName);
}
if (!got.length) continue;
summary.assigned += got.length; summary.batches.push({ sponsor: s.name, level: s.tier.label, size: s.tier.size, count: got.length });
await tellSponsor(s, got, c);
cards.push([s, got.length]);
}
// the round's announcement for the new members area (General) first, then one card per sponsor in the payments topic;
// all queued: mailTick posts them at least tankBatchFeedGapMin apart
if (cards.length && c.announce) await S().enqueue({ kind: 'feed', payload: { announce: announceText(cards, c), roundAt: now } });
for (const [s, n] of cards) await feedCard(s, n, now, c);
});
if (summary.batches.length) { try { await S().addRound(summary); } catch (e) { console.error('tankbatch round log', e.message); } console.log('tankbatch round', JSON.stringify({ assigned: summary.assigned, batches: summary.batches.length, refused: summary.refused })); }
return Object.assign({ on: true }, summary);
})().finally(() => { busy = null; });
return busy;
}
async function tellSponsor(s, names, c) {
const subject = names.length + ' new ' + (names.length === 1 ? 'person' : 'people') + ' from the holding tank are in your line';
const text = 'As a ' + s.tier.label + ' member you receive up to ' + s.tier.size + ' people at a time from the holding tank. These ' + names.length + ' joined without a sponsor and are now in your line: ' + names.join(', ')
+ '.\n\nEach one got a chat from you and an email saying you are their sponsor. Say hello in the next ' + c.followDays + ' days: anyone you have not contacted by then (a chat from you, or "Contacted them" on their row in My line) goes back to the holding tank for another member.\n\n' + 'https://instantadpay.com/my#line';
if (R.hooks.notify) { try { await R.hooks.notify(s.email, subject, text); } catch (e) {} }
if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) { try { await R.mailer.send(s.email, 'InstantAdPay: ' + subject, text + '\n\nInstantAdPay'); } catch (e) {} }
}
// the round's post for the CTB group's new members area (General topic; Marty 2026-11-15: "Post it to the new members area in
// Telegram"): how many got a sponsor, who received leads grouped by level, and how to qualify. Never the people, never income.
function announceText(cards, c) {
const clean = t => String(t || '').replace(/[<>&]/g, '');
const total = cards.reduce((n, x) => n + x[1], 0);
const order = ['Twin Engine', 'Fueled', 'Paid']; const groups = {};
for (const [s, n] of cards) { const k = order.find(o => s.tier.level === o) || s.tier.level; (groups[k] = groups[k] || []).push(clean(s.username ? '@' + s.username : s.name) + ' ' + n); }
const lines = order.filter(k => groups[k]).map(k => '' + k + ': ' + groups[k].join(', '));
return '\u{1F91D} Holding tank: ' + total + ' new member' + (total === 1 ? '' : 's') + ' just got a sponsor\n'
+ 'Active members who bought their own package received leads they can sponsor:\n\n' + lines.join('\n') + '\n\n'
+ 'How to get fed leads: your own ' + usd(c.minIap) + ' InstantAdPay or ' + usd(c.minLs) + ' LinkSpin package = ' + c.base + ' at a time; a counted monthly refuel or a ' + usd(c.higherIap) + '+ package = ' + c.fueled + '; both engines refueled this cycle or the top package = ' + c.twin + '; +' + c.step + ' for every further refuel month in a row, up to ' + c.max + '. Sign in at least once a week to stay on the list.\n'
+ 'https://instantadpay.com/my';
}
async function feedCard(s, n, roundAt, c) {
if (!c.feed) return;
const who = s.username ? '@' + s.username : s.name;
const what = n + ' new team member' + (n === 1 ? '' : 's');
await S().enqueue({ kind: 'feed', sponsor: s.email, payload: { who, what, level: s.tier.label, roundAt } });
}
// ---- the outbox: throttled emails + spaced Telegram cards. Once everywhere: one MySQL lock across app copies, a row claimed
// queued -> sending by a conditional UPDATE, and a marks claim per row; a crash between claim and send loses that one (never twice).
const TZ = 'America/Chicago';
const ctParts = ts => { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = p.value; return { day: o.year + '-' + o.month + '-' + o.day, hour: Number(o.hour) % 24, minute: Number(o.minute) }; };
const inWindow = (ts, c) => { const h = ctParts(ts).hour; return h >= c.startHour && h < c.endHour; };
function dayStart(ts) { const p = ctParts(ts); return ts - (p.hour * 60 + p.minute) * 60000 - (ts % 60000); } // Central midnight (to the minute)
const gapMs = c => Math.max(60000, Math.floor((c.endHour - c.startHour) * 3600000 / c.perDay));
function nextWindowOpen(ts, c) { let t = ts - (ts % 60000); for (let i = 0; i < 4 * 24 * 7 && !inWindow(t, c); i++) t += 15 * 60000; return t; }
const mlock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatchmail', fn, 2) : fn());
async function stillOk(it) { // right before each send: still in that sponsor's line, and not unsubscribed, blocked or erased
const a = await R.accounts.byEmail(it.to); if (!a) return 'account gone';
const sp = await R.accounts.byEmail(it.sponsor); if (!sp) return 'sponsor gone';
const toks = [sp.username, sp.code, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(x => String(x).toLowerCase());
if (!toks.includes(String(a.sponsorRef || '').toLowerCase())) return 'no longer with this sponsor';
if (R.hooks.excluded && R.hooks.excluded(a.email)) return 'flagged or suspended';
if (R.hooks.excludedPerson) { const px = await Promise.resolve(R.hooks.excludedPerson(a.email)).catch(() => 'check failed'); if (px) return px; }
return null;
}
let mailing = null;
function mailTick() { if (!mailing) mailing = Promise.resolve().then(() => mlock(mailRun)).catch(e => { if (!/lock busy/.test(e.message)) console.error('tankbatch mail', e.message); return { busy: true }; }).finally(() => { mailing = null; }); return mailing; }
async function mailRun() {
const c = cfg(); const now = clock(); const out = { feed: 0, sent: 0, skipped: 0 };
if (await S().getState('paused')) return Object.assign(out, { paused: true });
// one Telegram card per tick, at least feedGapMin after the last
const lastFeed = Number(await S().getState('lastFeedAt')) || 0;
if (now - lastFeed >= c.feedGapMin * 60000) {
const [f] = await S().oldest('feed', 1);
if (f && await S().take(f.id) && (!R.hooks.claim || await Promise.resolve(R.hooks.claim('tbfeed:' + f.id)).catch(() => false))) {
await S().setState('lastFeedAt', now);
const p = f.payload || {};
if (p.announce) { try { if (R.hooks.announce) await R.hooks.announce(p.announce); } catch (e) { console.error('tankbatch announce', e.message); } }
else try { if (R.hooks.feed) await R.hooks.feed(p.who, p.what, p.level); } catch (e) { console.error('tankbatch feed', e.message); }
if (!p.announce) try { if (R.hooks.toast) R.hooks.toast({ type: 'Adopted', sponsor: p.who, member: p.what + ' (' + p.level + ' level)', ts: now }); } catch (e) {}
await S().finish(f.id, 'sent'); out.feed++;
}
}
// one email per tick at most, inside the window, under the day cap, evenly spaced
if (!inWindow(now, c)) return out;
const today = await S().counts('mail', dayStart(now)); if (today.sent >= c.perDay) return out;
const lastMail = Number(await S().getState('lastMailAt')) || 0; if (now - lastMail < gapMs(c)) return out;
for (const it of await S().oldest('mail', 25)) { // skipped rows do not use the slot: the next one goes in the same tick
if (!(await S().take(it.id))) continue;
if (R.hooks.claim && !(await Promise.resolve(R.hooks.claim('tbmail:' + it.id)).catch(() => false))) continue;
const why = await stillOk(it);
if (why) { await S().finish(it.id, 'skipped', why); out.skipped++; continue; }
await S().setState('lastMailAt', now);
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(it.to, it.subject, it.body); } catch (e) { console.error('tankbatch mail send', e.message); }
await S().finish(it.id, 'sent'); out.sent++;
try { if (R.tank.payTrack) R.tank.payTrack(it.to, it.sponsor, it.adoptionId, false); } catch (e) {} // the 24 h / 72 h reminders count from this email
break;
}
return out;
}
async function mailView() {
const c = cfg(); const now = clock(); const today = await S().counts('mail', dayStart(now)); const feeds = await S().counts('feed', dayStart(now));
const paused = !!(await S().getState('paused')); const lastMail = Number(await S().getState('lastMailAt')) || 0;
let next = null;
if (!paused && today.queued) {
next = Math.max(now, lastMail + gapMs(c));
if (today.sent >= c.perDay) next = dayStart(now) + 86400000 + 3 * 3600000; // into tomorrow (DST-safe), then the window
next = nextWindowOpen(next, c);
}
return { paused, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, queued: today.queued, sentToday: today.sent, skippedToday: today.skipped,
nextSendAt: next, feed: { queued: feeds.queued, sentToday: feeds.sent, gapMin: c.feedGapMin }, daysToClear: Math.ceil(today.queued / c.perDay) };
}
async function setPaused(v) { await S().setState('paused', !!v); return mailView(); }
// ---- follow-up: uncontacted batch people go back to the tank ----
let following = null;
function followUp() { if (!following) following = followRun().finally(() => { following = null; }); return following; }
async function followRun() {
const c = cfg(); const now = clock(); const out = { done: 0, unreached: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const back = new Map();
for (const p of await S().open()) {
const open = await R.tank.openOf(p.adoptee);
if (!open.some(ad => Number(ad.id) === p.adoptionId)) { await S().close(p.id, 'moved', 'the adoption was closed elsewhere (released, moved or followed)'); out.moved++; continue; }
const a = await R.accounts.byEmail(p.adoptee);
if (a && Number(a.memberId) > 0) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'payouts on'); out.done++; continue; }
if (now - p.at < c.followDays * D) continue;
if (!a) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'gone', 'account gone'); continue; }
const chat = R.messages && R.messages.lastFrom ? await R.messages.lastFrom(p.sponsor, p.adoptee).catch(() => 0) : 0;
const mk = R.tank.markOf ? await R.tank.markOf(p.adoptee).catch(() => null) : null;
const contacted = chat > p.at + 60000 || !!(mk && mk.contacted > p.at); // the assignment's own chat is sent at p.at: it does not count
if (contacted && a.address) { await R.tank.closeAdoption(p.adoptionId, 'done'); await S().close(p.id, 'done', 'contacted, wallet linked'); out.done++; continue; }
if (contacted && await R.tank.countAll(p.adoptee) >= (R.tank.MAX_ADOPTIONS || 2)) { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'adopted twice: stays with this sponsor'); out.kept++; continue; }
const lk = await R.tank.lockedWhy(p.adoptee);
if (lk === 'unknown') { out.waiting++; continue; }
if (lk === 'locked') { await R.tank.closeAdoption(p.adoptionId, 'expired'); await S().close(p.id, 'kept', 'locked on a network contract'); out.kept++; continue; }
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'expire', contacted ? 'holding tank batch window ended' : 'holding tank batch: not contacted in ' + c.followDays + ' days');
if (r && r.error) { out.waiting++; continue; }
await R.tank.closeAdoption(p.adoptionId, contacted ? 'expired' : 'unreached');
await S().close(p.id, contacted ? 'returned' : 'unreached', contacted ? 'window ended' : 'not contacted');
if (contacted) out.returned++; else { out.unreached++; if (!back.has(p.sponsor)) back.set(p.sponsor, []); back.get(p.sponsor).push(nameOf(a)); }
}
for (const [sp, names] of back) {
if (R.hooks.notify) { try { await R.hooks.notify(sp, names.length + ' from your holding tank batch went back to the tank', names.join(', ') + (names.length === 1 ? ' was' : ' were') + ' in your line for ' + c.followDays + ' days with no chat from you and no "Contacted them" mark, so ' + (names.length === 1 ? 'they have' : 'they have') + ' gone back to the holding tank for another member. Your next batch still comes on schedule: say hello to each new person in the first few days.\n\nhttps://instantadpay.com/my#line'); } catch (e) {} }
}
return out;
}
async function isBatchPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
// the hourly pass (server.js): follow-up always, a round only while the switch is on
async function tick() { const f = await followUp().catch(e => { console.error('tankbatch follow', e.message); return null; }); const r = await round().catch(e => { console.error('tankbatch round', e.message); return { error: e.message }; }); return { follow: f, round: r }; }
// ---- admin preview: the first round against the live tank, nothing written, nothing sent ----
async function preview() {
const c = cfg(); c.topIapResolved = await topIapCents(c); const now = clock();
const p = await plan(c, now);
const sp = p.sponsors.list.map(s => ({ name: s.name, memberId: s.memberId || null, level: s.tier.label, size: s.tier.size, reasons: s.tier.reasons,
lastSeen: s.lastSeen, iapMaxUsd: s.facts.iapMax / 100, lsMaxUsd: s.facts.lsMax / 100,
refuel: s.facts.refuel ? { active: s.facts.refuel.active, streak: s.facts.refuel.streak, both: s.facts.refuel.both, lastDay: s.facts.refuel.lastDay } : null,
holding: s.holding, room: s.room, due: s.due, dueAt: s.dueAt || null,
wouldGet: (s.give || []).length, firstNames: (s.give || []).slice(0, 8).map(w => w.name) }));
const byLevel = {}; for (const s of sp) { const b = byLevel[s.level.replace(/, month \d+$/, '')] = byLevel[s.level.replace(/, month \d+$/, '')] || { sponsors: 0, people: 0 }; b.sponsors++; b.people += s.wouldGet; }
return { readOnly: true, on: c.on, generatedAt: now, settings: Object.assign({}, c, { topIapCents: c.topIapResolved }), ladder: ladderView(c),
emailPlan: await (async () => { const q = (await S().counts('mail', 0)).queued; const people = p.takers.reduce((n, t) => n + t.give.length, 0); return { alreadyQueued: q, thisRound: people, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, daysToClear: Math.ceil((q + people) / c.perDay) }; })(),
tank: { waiting: p.pool.waiting, offered: p.pool.rows.length, excluded: p.pool.excluded, leftAfterRound: p.left },
totals: { eligibleSponsors: sp.length, takingThisRound: p.takers.filter(t => t.give.length).length, people: p.takers.reduce((n, t) => n + t.give.length, 0), capacity: sp.reduce((n, s) => n + s.room, 0), byLevel },
sponsors: sp, notEligible: { counts: p.sponsors.why, members: p.sponsors.skipped } };
}
// ---- the member panel "How to get fed leads" ----
async function myView(email) {
const c = cfg(); if (!c.on) return { on: false };
c.topIapResolved = await topIapCents(c);
const a = await R.accounts.byEmail(lc(email)); if (!a) return { on: true, ladder: ladderView(c) };
const f = await factsOf(a, iapMaxByMember()); const t = tierFor(f, Object.assign({}, c, { topIap: c.topIapResolved }));
const seen = await lastSeenOf(a); const active = !!seen && clock() - seen <= c.activeDays * D;
const mine = (await S().open()).filter(p => p.sponsor === a.email);
const last = (await S().lastBySponsor()).get(a.email) || 0;
return { on: true, ladder: ladderView(c), everyDays: c.everyDays, followDays: c.followDays,
me: { level: t.level, label: t.label || null, size: t.size, reasons: t.reasons, next: nextStep(t, f, c), active, open: mine.length, lastBatchAt: last || null, nextBatchAt: last ? last + c.everyDays * D : null } };
}
async function adminView() { return { settings: cfg(), open: (await S().open()).length, recent: await S().recent(100), rounds: await S().rounds(20) }; }
module.exports = { announceText, mailTick, mailView, setPaused, _gapMs: gapMs, _inWindow: inWindow, init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };