'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' }; 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', 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) }; } // ---- 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() { 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.rounds = this.st.rounds || []; 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 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(); } }; 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); } }; 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_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 }; 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)' }).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); await feedCard(s, got.length, 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) {} } } async function feedCard(s, n, roundAt, c) { if (!c.feed) return; if (R.hooks.claim) { let mine = false; try { mine = await R.hooks.claim('tankbatch:feed:' + s.email + ':' + roundAt); } catch (e) {} if (!mine) return; } const who = s.username ? '@' + s.username : s.name; const what = n + ' new team member' + (n === 1 ? '' : 's'); if (R.hooks.feed) { try { await R.hooks.feed(who, what, s.tier.label); } catch (e) { console.error('tankbatch feed', e.message); } } if (R.hooks.toast) { try { R.hooks.toast({ type: 'Adopted', sponsor: who, member: what + ' (' + s.tier.label + ' level)', ts: clock() }); } catch (e) {} } } // ---- 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), 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 = { init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };