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>
This commit is contained in:
martbost
2026-11-15 14:58:51 -06:00
parent 1a13f53b9c
commit ccfaacc935
11 changed files with 633 additions and 17 deletions
+3
View File
@@ -220,6 +220,8 @@ const CANNED = [
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
{ id: 'tank-batches', title: 'Holding tank batches (coming soon)', q: ['Will the site send me people from the holding tank?', 'How do I get fed leads?', 'What are holding tank batches?'], tags: ['holding tank', 'batches', 'fed leads', 'auto-assign', 'coming soon'],
a: 'Coming soon, not switched on yet: holding tank batches. The plan is that active members who bought their own package receive a batch of people from the holding tank every 2 days, people who joined without a sponsor and become your referrals to welcome and help. The planned ladder: your own $20 package on InstantAdPay or $25 on LinkSpin = 10 people at a time; a counted monthly refuel or a higher package ($50 or more) = 20; both engines refueled in the same cycle, or the top package = 25; then 5 more for every further refuel month in a row, up to 50. You would need to sign in at least once a week, and anyone you have not contacted within 7 days (a chat, or Contacted them on their row in My line) goes back to the tank for another member. These are leads you can sponsor, not income: what they do next depends on them and on your follow-up. Until it is switched on, adopt by hand from Members > My line > Holding tank as today, and the 24-hour safety net keeps running as it does now.' },
{ id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'],
re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i,
a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come once they have been here 24 hours. A new sign-up shows an Opens in badge until then, with no Adopt button, so they have a day to tell us who invited them (the 24-hour safety net for wallet-linked members still runs on its own clock). To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold up to 10 people from the tank at one time (counting the ones who have not switched on payouts yet) and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 10 people held from the tank who have not switched on payouts yet, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
@@ -394,6 +396,7 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/<username>) right under their bio, above the three-level line and the join button.
- BTC4HITS (2026-11-11): members of the closed BTC4Hits rotator site with a deliverable email were imported as waiting accounts (no wallet, no password, nothing mailed), with their BTC4Hits sponsor when that sponsor was also imported or already a member; the rest join the holding tank when they first sign in. They sign in here with the same email (code sign-in), or on LinkSpin at linkspin.app/from/btc4hits, where their active rotators became spin links. Pro status and old BTC4Hits commissions do not carry over.
- HOLDING TANK BATCHES (COMING SOON, NOT LIVE, approved in principle 2026-11-15; Marty switches it on after reviewing a preview): active members (signed in within 7 days) who bought their own $20+ package on InstantAdPay or $25+ on LinkSpin would receive a batch from the holding tank every 2 days: 10 at a time; 20 with a counted refuel streak or a higher package ($50+); 25 with both engines refueled this cycle or the top package; +5 per further consecutive refuel month, up to 50. People not contacted within 7 days go back to the tank. It is separate from the 5xYourTeam draft (its own cap) and from the hand adoptions (still max 10 held). NEVER say it is live; say it is coming soon. Leads to sponsor, never income.
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; new sign-ups cannot be adopted by hand for 24 hours from sign-up (they show an Opens in badge and no Adopt button); a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 10 held at one time, counting those not yet switched on payouts, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members.
- WHO INVITED YOU (2026-11-07, Marty approved): a member with no sponsor and no member number sees a Who invited you? card on their Overview. They type a username, confirm in an in-page box, and that member becomes their sponsor (it follows to LinkSpin, lifts the activation hold, and the sponsor gets a new-referral email and notice). Refused: themselves, a username that does not exist, someone in their own line, a member who cannot take new members, a member with no payouts on and nobody above them on the contract, and anyone who already has a sponsor or a member number. Nobody invited me hides the card (a small Overview link brings it back while they are in the tank) and changes nothing else. It never blocks the site. It is not an adoption: no 7-day window and it does not count toward the two.
- SIGN-UP GRACE (2026-11-07): for 24 hours from sign-up nobody can adopt a member by hand. The 24-hour auto-assign is unchanged and runs from the wallet link, so a member who links a wallet in their first hour is matched about 24 hours after linking, with at most a short hand-adoption window first. Members back in the tank later have no grace.
+5 -2
View File
@@ -19,7 +19,7 @@
// 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 (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
// - 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
@@ -109,7 +109,10 @@ async function ensureTables() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
}
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
// 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'); }
+1 -1
View File
@@ -59,7 +59,7 @@ function steps(E, h, campIds, ticketIds, memberMsgIds) {
for (const t of ['account_signals', 'daily_views', 'digests', 'drips', 'earned_credits', 'nudges', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'credit_log', 'promo_redemptions', 'positions']) del(t, 'email=?', [E]);
del('prospects', 'owner_email=?', [E]); del('pipeline_notes', 'owner_email=? OR person=?', [E, E]); del('lead_marks', '`lead`=? OR sponsor=?', [E, E]);
upd('ad_reports', "reporter=''", [], 'reporter=?', [E]); upd('promo_codes', 'funder=NULL', [], 'funder=?', [E]);
del('adoptions', 'adoptee=? OR adopter=?', [E, E]);
del('adoptions', 'adoptee=? OR adopter=?', [E, E]); del('tank_batch_picks', 'adoptee=? OR sponsor=?', [E, E]); // holding tank batches (2026-11-15)
del('event_marks', 'k LIKE ?', [like(E)]); del('doc_claims', 'k LIKE ?', [like(E)]);
del('sponsor_messages', 'from_email=?', [E]);
upd('sponsor_messages', 'to_email=?', [tomb], "to_email=? AND kind='chat'", [E]); // the other member's own words stay theirs
+39
View File
@@ -0,0 +1,39 @@
// "How to get fed leads" (holding tank batches, Marty 2026-11-15): the ladder and the member's own level and next step, on the
// Overview. Hidden while the tankBatches switch is off (/api/my/tank/feed answers { on:false }). Leads you can sponsor, never money.
(function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const day = t => t ? new Date(t).toLocaleString('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT' : '';
function mount() {
let el = document.getElementById('tankFeedCard'); if (el) return el;
el = document.createElement('div'); el.className = 'card'; el.id = 'tankFeedCard'; el.hidden = true; el.setAttribute('data-jump', 'How to get fed leads');
const notice = document.getElementById('tankNotice'); const host = notice && notice.closest('.card');
const tankCard = document.getElementById('tankCard');
if (host && host.parentNode) host.parentNode.insertBefore(el, host.nextSibling);
else if (tankCard && tankCard.parentNode) tankCard.parentNode.insertBefore(el, tankCard);
else return null;
return el;
}
function html(v) {
const me = v.me || {};
const rows = (v.ladder || []).map(r => '<li><b>' + esc(r.level) + '</b>: ' + (r.level === 'Streak' ? 'up to ' : '') + r.size + ' people at a time, with ' + esc(r.how) + '</li>').join('');
const mine = me.level
? '<p>Your level: <b>' + esc(me.label || me.level) + '</b>, ' + me.size + ' people at a time' + (me.active ? '' : ' (sign in at least once a week to receive them)') + '.'
+ (me.open ? ' You are helping ' + me.open + ' from your batches right now.' : '') + (me.nextBatchAt ? ' Next batch from ' + esc(day(me.nextBatchAt)) + '.' : '') + '</p>'
: '<p>You are not on the ladder yet.</p>';
return '<div class="card-head"><h3>How to get fed leads</h3><span class="sub">people from the holding tank you can sponsor</span></div>'
+ '<p class="small">Members who joined with no sponsor wait in the holding tank. Active members who bought their own package receive a batch of them every ' + esc(v.everyDays) + ' days, and they become your referrals to welcome and help. These are leads you can sponsor: what happens next depends on your follow-up, and nothing here is a promise of income.</p>'
+ '<ul class="small" style="margin:6px 0 8px 18px;padding:0">' + rows + '</ul>' + mine
+ (me.next ? '<p class="small"><b>Next step:</b> ' + esc(me.next) + '</p>' : '')
+ '<p class="muted small">Say hello to each new person within ' + esc(v.followDays) + ' days (a chat, or Contacted them on their row in My line). Anyone you have not contacted by then goes back to the tank for another member.</p>';
}
async function load() {
try {
const v = await (await fetch('/api/my/tank/feed', { cache: 'no-store' })).json();
const el = mount(); if (!el) return;
if (!v || !v.on) { el.hidden = true; return; }
el.innerHTML = html(v); el.hidden = false;
} catch (e) {}
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', load); else load();
setInterval(load, 600000);
})();
+1 -1
View File
@@ -1312,7 +1312,7 @@
<script src="/assets/support.js?v=20261115cb"></script>
<script src="/assets/netkits.js?v=20261115nk"></script>
<script src="/assets/my.js?v=20261115la"></script>
<script src="/assets/fuel.js?v=20261113sso"></script>
<script src="/assets/fuel.js?v=20261113sso"></script><script src="/assets/tankfeed.js?v=20261115tb"></script>
<script src="/assets/engine-room.js?v=20261113sso"></script>
<script src="/assets/netsso.js?v=20261113sso"></script>
<script src="/assets/chat.js?v=20261016n"></script>
+2
View File
@@ -73,6 +73,7 @@ elif [ "$MODE" = "member" ]; then
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
node qa/tank-hold.mjs || status=1
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
node qa/walletnudge.test.cjs || status=1
node qa/bixpay.test.cjs || status=1
@@ -93,6 +94,7 @@ elif [ "$MODE" = "walletnudge" ]; then
node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.mjs || status=1
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/sponsorfollow-e2e.mjs || status=1
+186
View File
@@ -0,0 +1,186 @@
// Holding tank batches (tankbatch.js, Marty 2026-11-15). No server: the real tank.js + tankbatch.js with in-memory accounts, a
// fake chain, a fake refuel standing and capturing mail/notice/feed hooks, on a throwaway dir, mocked clock. node qa/tank-batch.test.mjs
// Covers: the ladder (incl. opgnetwerk's real case = 25), switch off = no writes, preview writes nothing, highest tier first by
// rotation, sizes, sign-up grace, self / loop / adopted twice / opted out never dealt, cadence (2 days, top up to size), the
// follow-up (uncontacted back to the tank, not counted), tank.sweep leaves batch picks alone, the 5x draft's separate cap.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createRequire } from 'node:module';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL;
let fails = 0, passes = 0; const ok = (c, l, x) => { console.log((c ? 'PASS ' : 'FAIL ') + l + (x !== undefined && !c ? ' ' + String(typeof x === 'string' ? x : JSON.stringify(x)).slice(0, 400) : '')); if (c) passes++; else fails++; };
const DAY = 86400000, H = 3600000;
// ---- the ladder, pure ----
const TB0 = require(path.join(SITE, 'tankbatch.js'));
{
const c = Object.assign({}, { base: 10, fueled: 20, twin: 25, step: 5, max: 50, minIap: 2000, minLs: 2500, higherIap: 5000, higherLs: 5000, topIap: 50000, topLs: 50000 });
const t = f => TB0.tierFor(Object.assign({ iapMax: 0, lsMax: 0, refuel: null }, f), c);
ok(t({}).size === 0 && !t({}).level, 'no package: not on the ladder');
ok(t({ iapMax: 1000 }).size === 0, 'a $10 package does not qualify');
ok(t({ iapMax: 2000 }).size === 10 && t({ iapMax: 2000 }).level === 'Paid', '$20 InstantAdPay = Paid 10');
ok(t({ lsMax: 2500 }).size === 10, '$25 LinkSpin = Paid 10');
ok(t({ lsMax: 2000 }).size === 0, '$20 on LinkSpin is below its $25 bar');
ok(t({ iapMax: 5000 }).size === 20 && t({ iapMax: 5000 }).level === 'Fueled', 'a $50 (higher) package = Fueled 20');
ok(t({ iapMax: 2000, refuel: { active: true, streak: 1, both: false } }).size === 20, 'refuel streak active = Fueled 20');
ok(t({ iapMax: 25000 }).size === 20, '$250 is higher, not top: 20');
ok(t({ iapMax: 50000 }).size === 25 && t({ iapMax: 50000 }).level === 'Twin Engine', 'the top package ($500) = 25');
const opg = t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 1, both: true } });
ok(opg.size === 25 && opg.level === 'Twin Engine', 'opgnetwerk (month 1, both engines 10-27, $20 IAP + $25 LS, nothing above $20) = Twin Engine 25', opg);
ok(t({ iapMax: 2000, refuel: { active: true, streak: 3, both: false } }).size === 30, 'single engine month 3 = 20 + 10 = 30');
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 3, both: true } }).size === 35, 'twin month 3 = 25 + 10 = 35');
ok(t({ iapMax: 2000, lsMax: 2500, refuel: { active: true, streak: 12, both: true } }).size === 50, 'capped at 50');
ok(t({ iapMax: 2000, refuel: { active: false, streak: 0, both: false } }).size === 10, 'a lapsed streak counts nothing');
ok(/20/.test(TB0.nextStep(t({ iapMax: 2000 }), { iapMax: 2000 }, c)), 'next step from Paid names 20');
ok(!/income|earn|\$/.test(TB0.ladderView(c).map(r => r.how).join(' ').replace(/\$\d+/g, '')), 'ladder copy promises no income');
}
// ---- the bench ----
function bench(opts) {
for (const m of ['tank.js', 'tankbatch.js']) delete require.cache[require.resolve(path.join(SITE, m))];
const tank = require(path.join(SITE, 'tank.js')); const tb = require(path.join(SITE, 'tankbatch.js'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankbatch-'));
let now = Date.UTC(2026, 10, 16, 15, 0, 0); const clock = () => now;
const by = new Map(); let n = 100; const pub = a => a ? Object.assign({}, a) : null; const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
const accounts = {
add(email, o) { by.set(email, Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (n++), sponsorRef: '', memberId: 0, address: null, created: now - 5 * DAY, lastSeen: now - 2 * H, joinedVia: 'page', joinedRef: null }, o || {})); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); }, async byUsername(u) { return find(a => a.username === String(u || '').toLowerCase()); }, async byCode(c) { return find(a => a.code === String(c || '').toLowerCase()); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); }, async setSponsorRef(e, ref) { const a = by.get(e); a.sponsorRef = String(ref || ''); return { ok: true }; },
async listAll() { return [...by.values()].map(pub); }, async positions() { return []; },
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; const t = a.sponsorRef; return find(x => x.username === t || x.code === t || String(x.memberId) === t); }, _by: by };
const events = []; const mails = []; const chats = []; const notices = []; const feeds = []; const toasts = []; const sent = [];
const standing = new Map(); const optOut = new Set();
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text, at: now }); sent.push({ from, to, at: now }); }, lastFrom: async (f, t) => sent.filter(x => x.from === f && x.to === t).reduce((m, x) => Math.max(m, x.at), 0) };
const mailer = { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } };
const chain = { recentEvents: () => events.slice(), getConfig: () => ({}), catalog: async () => [500, 1000, 2000, 5000, 10000, 25000, 50000].map((p, i) => ({ id: i + 1, priceCents: p })) };
const site = Object.assign({ tankBatches: '0' }, opts && opts.site);
tank.init({ dataDir: dir, accounts, chain, messages, mailer, site: 'https://instantadpay.test', capOpen: () => 10,
hooks: { isBatchPick: id => tb.isBatchPick(id), isDraftPick: async () => false } });
tank.setClock(clock);
return { tank, tb, accounts, events, mails, chats, notices, feeds, toasts, standing, optOut, site, dir, messages,
advance: ms => { now += ms; }, now: () => now,
async start() {
await tb.init({ dataDir: dir, db: { enabled: () => false }, accounts, chain, tank, messages, mailer, siteConfig: () => site, clock,
refuel: { standing: async e => standing.get(e) || null },
hooks: { companyId: () => 1, claim: async () => true, excludedPerson: async e => optOut.has(e) ? 'unsubscribed from email' : null,
notify: async (to, subject, text) => { notices.push({ to, subject, text }); }, feed: async (who, what, level) => { feeds.push(who + ' just received ' + what + ' from the holding tank (' + level + ' level)'); }, toast: ev => toasts.push(ev) } });
} };
}
function seed(B, tankCount) {
const { accounts, events, standing } = B;
accounts.add('house@x.co', { username: 'house', memberId: 1, address: '0x' + '0'.repeat(40) });
accounts.add('opg@x.co', { username: 'opgnetwerk', memberId: 2, address: '0x' + '2'.repeat(40) });
accounts.add('fuel@x.co', { username: 'fueler', memberId: 3, address: '0x' + '3'.repeat(40) });
accounts.add('paid@x.co', { username: 'paider', memberId: 4, address: '0x' + '4'.repeat(40) });
accounts.add('sleepy@x.co', { username: 'sleepy', memberId: 5, address: '0x' + '5'.repeat(40), lastSeen: B.now() - 9 * DAY });
accounts.add('free@x.co', { username: 'freebie', memberId: 6, address: '0x' + '6'.repeat(40) });
// opgnetwerk's real purchases: 11 x $20, 2 x $10, 9 x $5 on InstantAdPay
let blk = 1; for (let i = 0; i < 11; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 2000, block: blk++ }); for (let i = 0; i < 2; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 1000, block: blk++ }); for (let i = 0; i < 9; i++) events.push({ type: 'Purchase', buyerId: 2, priceCents: 500, block: blk++ });
standing.set('opg@x.co', { active: true, streak: 1, both: true, lastDay: '2026-10-27', maxCents: { iap: 2000, linkspin: 2500 } });
events.push({ type: 'Purchase', buyerId: 3, priceCents: 5000, block: blk++ }); // fueler: a $50 package = higher
events.push({ type: 'Purchase', buyerId: 4, priceCents: 2000, block: blk++ }); // paider: $20
events.push({ type: 'Purchase', buyerId: 5, priceCents: 2000, block: blk++ }); // sleepy: paid but away 9 days
events.push({ type: 'Purchase', buyerId: 6, priceCents: 1000, block: blk++ }); // freebie: $10 only
for (let i = 0; i < tankCount; i++) B.accounts.add('t' + String(i).padStart(3, '0') + '@tank.co', { lastSeen: B.now() - (i + 1) * 60000 });
}
// ---- switch off: nothing written, nothing sent; the preview is read-only ----
{
const B = bench(); seed(B, 70); await B.start();
const r = await B.tb.round();
ok(r.on === false, 'switch off: the round does not run');
ok(!B.mails.length && !B.chats.length && !B.feeds.length && !B.toasts.length && !B.notices.length, 'switch off: no mail, chat, feed or toast');
ok(!fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'switch off: no state file written');
const v = await B.tb.myView('opg@x.co'); ok(v.on === false, 'switch off: the member panel is hidden');
const before = JSON.stringify([...B.accounts._by.values()]);
const pv = await B.tb.preview();
ok(pv.readOnly && pv.on === false, 'preview runs with the switch off');
ok(JSON.stringify([...B.accounts._by.values()]) === before && !B.mails.length && !B.chats.length && !fs.existsSync(path.join(B.dir, 'tank-batch.json')) && !fs.existsSync(path.join(B.dir, 'tank.json')), 'preview writes nothing and sends nothing');
const opg = pv.sponsors.find(s => s.name === '@opgnetwerk');
ok(opg && opg.size === 25 && /Twin Engine/.test(opg.level) && opg.wouldGet === 25, 'preview: opgnetwerk at Twin Engine, 25', opg);
ok(pv.sponsors[0].name === '@opgnetwerk', 'preview: highest tier first');
ok((pv.sponsors.find(s => s.name === '@fueler') || {}).size === 20 && (pv.sponsors.find(s => s.name === '@paider') || {}).size === 10, 'preview: fueler 20, paider 10');
ok(!pv.sponsors.some(s => ['@sleepy', '@freebie', '@house'].includes(s.name)), 'preview: inactive, $10-only and the company are not sponsors');
ok(pv.notEligible.members.some(m => m.name === '@sleepy' && /not active/.test(m.reason)), 'preview: the inactive paid member is listed as a near miss');
ok(pv.totals.people === 55 && pv.tank.leftAfterRound === 15, 'preview: 55 dealt, 15 left', pv.totals);
}
// ---- switch on: a live round ----
{
const B = bench({ site: { tankBatches: '1' } }); seed(B, 50); await B.start();
// exclusions: 2 in the sign-up grace, 1 adopted twice, 1 opted out, 1 above a sponsor in their own line (paider's sponsor)
B.accounts.add('new1@tank.co', { created: B.now() - 2 * H }); B.accounts.add('new2@tank.co', { created: B.now() - 20 * H });
B.accounts.add('twice@tank.co'); const tj = B.tank._json.state(); tj.adoptions.push({ id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'z@x.co', ts: 1, expires: 1, status: 'expired' }, { id: tj.nextId++, adoptee: 'twice@tank.co', adopter: 'y@x.co', ts: 1, expires: 1, status: 'dropped' }); B.tank._json.save();
B.accounts.add('optout@tank.co'); B.optOut.add('optout@tank.co');
B.accounts.add('upline@tank.co', { username: 'uplinez' }); B.accounts._by.get('paid@x.co').sponsorRef = 'uplinez';
const r = await B.tb.round();
const got = e => B.tank._json.state().adoptions.filter(a => a.adopter === e && a.status === 'open').length;
ok(r.on && r.assigned === 51, 'round assigns the whole offered pool (51 open waiting people incl. the upline of paider, 55 places)', r);
ok(got('opg@x.co') === 21 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'rotation: paider fills 10, then opg and fueler share the rest one by one, opg first (21 / 20)', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
const first = B.tank._json.state().adoptions.filter(a => a.status === 'open')[0];
ok(first && first.adopter === 'opg@x.co', 'the first person goes to the highest tier');
const dealt = new Set(B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.adoptee));
ok(!dealt.has('new1@tank.co') && !dealt.has('new2@tank.co'), 'the 24-hour sign-up grace is respected');
ok(!dealt.has('twice@tank.co'), 'nobody adopted twice already');
ok(!dealt.has('optout@tank.co'), 'an opted-out person is never dealt');
ok(!B.tank._json.state().adoptions.some(a => a.adoptee === 'upline@tank.co' && a.adopter === 'paid@x.co'), 'never a sponsor\'s own upline');
ok(![...dealt].some(e => /@x\.co$/.test(e)), 'never a sponsor themself');
ok(B.accounts._by.get('t000@tank.co').sponsorRef === 'opgnetwerk', 'the sponsor change is written like an adoption');
const adoptMails = B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
ok(adoptMails.length === 51, 'every person gets the normal "X is now your sponsor" email, once', adoptMails.length);
ok(B.chats.length === 51 && B.chats.every(c => /matched with me from the holding tank/.test(c.text)), 'every person gets a chat from their new sponsor');
ok(B.notices.filter(x => /holding tank are in your line/.test(x.subject)).length === 3 && B.mails.filter(m => /from the holding tank are in your line/.test(m.subject)).length === 3, 'each sponsor gets one notice and one email per batch, not one per person');
ok(B.feeds.length === 3 && B.feeds[0] === '@opgnetwerk just received 21 new team members from the holding tank (Twin Engine level)', 'tank feed card: sponsor, count, level', B.feeds);
ok(!B.feeds.some(f => /t0\d\d/.test(f)) && B.toasts.length === 3 && B.toasts.every(t => t.type === 'Adopted' && !/t0\d\d/.test(t.member)), 'feed and toasts never name the people');
ok(!B.mails.concat(B.notices).some(m => /—/.test(m.subject + m.text)), 'no em dash in any batch copy');
// the member's own tank button and the 5x draft keep their own allowances
ok((await B.tank.eligibility('opg@x.co')).ok, 'batch people do not use up the member\'s own tank-button cap');
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, '5x draft cap is separate from batches');
const mv = await B.tb.myView('opg@x.co'); ok(mv.on && mv.me.size === 25 && mv.me.open === 21 && /month adds 5/.test(mv.me.next), 'member panel: level, size, open, next step', mv.me);
// cadence: nothing before 2 days; at 2 days only room (size - held) is topped up
const more = n => { for (let i = 0; i < n; i++) B.accounts.add('late' + i + '@tank.co', { created: B.now() - 3 * DAY }); };
more(30);
B.advance(1 * DAY); let r2 = await B.tb.round(); ok(r2.assigned === 0, 'no new batch before 2 days');
B.advance(1 * DAY + H); r2 = await B.tb.round();
ok(got('opg@x.co') === 25 && got('fuel@x.co') === 20 && got('paid@x.co') === 10, 'after 2 days: opg topped up to 25, full sponsors get nothing', [got('opg@x.co'), got('fuel@x.co'), got('paid@x.co')]);
ok(r2.assigned === 4, 'second round dealt 4', r2);
// tank.sweep leaves batch picks to tankbatch (its window ended in the tank's own terms)
for (const a of B.tank._json.state().adoptions) if (a.status === 'open') a.expires = 0; B.tank._json.save();
await B.tank.sweep();
ok(got('opg@x.co') === 25, 'tank.sweep does not close batch adoptions');
// follow-up at 7 days: contacted stay / close, uncontacted go back to the tank as 'unreached' (not counted)
const opgPeople = B.tank._json.state().adoptions.filter(a => a.adopter === 'opg@x.co' && a.status === 'open').map(a => a.adoptee).slice(0, 20);
const [chatted, marked, walletC, activated] = opgPeople;
B.advance(1 * DAY); // now 3 days after the first batch
await B.messages.sendChat(2, 'opg@x.co', chatted, 'hello');
B.tank._json.state().marks[marked] = { sponsor: 'opg@x.co', contacted: B.now(), warned: 0 }; B.tank._json.save();
await B.messages.sendChat(2, 'opg@x.co', walletC, 'hi'); B.accounts._by.get(walletC).address = '0x' + 'a'.repeat(40);
B.accounts._by.get(activated).memberId = 900;
B.advance(2 * DAY); let f = await B.tb.followUp(); ok(f.done === 1 && f.unreached === 0, 'before 7 days only the activated one closes (done)', f);
B.advance(2 * DAY + H); f = await B.tb.followUp();
ok(f.unreached === 47 && f.done === 1 && f.returned === 2, 'at 7 days (first batch only): 47 never contacted go back, contacted+wallet done, 2 contacted without wallet back (counted); the 2-day-old top-up waits', f);
ok(B.accounts._by.get(opgPeople[5]).sponsorRef === '' && (B.tank._json.state().adoptions.find(a => a.adoptee === opgPeople[5] && a.adopter === 'opg@x.co') || {}).status === 'unreached', 'an uncontacted person is back in the tank, status unreached');
ok((await B.tank.countAll(opgPeople[5])) === 0, 'unreached does not count toward their two adoptions');
ok((await B.tank.countAll(chatted)) === 1, 'a contacted, unconverted return still counts');
ok(B.notices.some(x => x.to === 'opg@x.co' && /went back to the tank/.test(x.subject)), 'the sponsor is told once who went back');
}
// ---- the 5x draft cap counts draft picks only ----
{
const B = bench({ site: { tankBatches: '1' } }); seed(B, 15); await B.start();
let draftIds = new Set();
B.tank.init({ dataDir: B.dir, accounts: B.accounts, chain: { recentEvents: () => B.events.slice(), getConfig: () => ({}) }, messages: B.messages, mailer: { hasKey: () => false }, capOpen: () => 10, hooks: { isDraftPick: async id => draftIds.has(id), isBatchPick: id => B.tb.isBatchPick(id) } });
for (let i = 0; i < 10; i++) { const r = await B.tank.adopt('opg@x.co', 't' + String(i).padStart(3, '0') + '@tank.co'); if (r.ok) draftIds.add(r.adoption.id); }
ok(draftIds.size === 10, 'ten plain adoptions');
draftIds = new Set(); // they were plain: the draft has 0 of its own
ok((await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok, 'ten plain adoptions do not fill the draft cap');
ok(!(await B.tank.eligibility('opg@x.co')).ok, 'and they do fill the plain tank-button cap');
const ids = B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.id); draftIds = new Set(ids);
ok(!(await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok && (await B.tank.eligibility('opg@x.co')).ok, 'ten draft picks fill the draft cap only');
}
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
+17 -1
View File
@@ -404,6 +404,22 @@ async function setGoal(email, goal) {
}
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
// ---- one member's standing, read-only (holding tank batches, tankbatch.js 2026-11-15) ---------------------------------
// streak + both engines this cycle (a settled COPY: a passed grace reads as it will be stored), and the biggest package of each
// site the streak has seen (refuels and Pit Stops keep cents; LinkSpin packages reach InstantAdPay only through this record)
async function standing(email, now) {
email = String(email || '').toLowerCase(); if (!email) return null;
const rec0 = await getRec(email); if (!rec0) return null;
const rec = JSON.parse(JSON.stringify(rec0)); settle(rec, ctDay(now || Date.now()));
const max = { iap: 0, linkspin: 0 };
for (const cy of [rec.cycle].concat(rec.history || [])) {
if (!cy) continue;
for (const grp of [cy.sites || {}, cy.pit || {}]) for (const s of ['iap', 'linkspin']) if (grp[s]) max[s] = Math.max(max[s], Number(grp[s].cents) || 0);
}
return { active: !!rec.active && (rec.streak || 0) >= 1, streak: rec.active ? (rec.streak || 0) : 0, both: !!(rec.active && rec.cycle && rec.cycle.both),
lastDay: rec.lastDay || null, dueDay: rec.dueDay || null, maxCents: max };
}
// ---- admin ------------------------------------------------------------------------------------------
async function stats() {
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
@@ -414,5 +430,5 @@ async function stats() {
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
}
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
module.exports = { standing, setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };
+17 -1
View File
@@ -55,6 +55,7 @@ const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
const loginClock = require('./loginadclock'); // login ads on a clock, not only at sign-in (Marty 2026-11-15): see loginadclock.js
const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event
@@ -742,6 +743,7 @@ async function boot() {
networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null,
isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
isDraftPick: id => draftpartner.isDraftPick(id), // a 5xYourTeam pick's adoption: draftpartner.js owns its 3-day window
isBatchPick: id => tankbatch.isBatchPick(id), // a holding tank batch adoption: tankbatch.js owns its follow-up window
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
@@ -763,7 +765,7 @@ async function boot() {
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
await draftpartner.init({ maxOpen: () => siteConfig().fiveXDraftCap, dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
hooks: { hubInfo: email => (hubsync.enabled() ? hubsync.hubInfo(email) : null), resolvePerson: q => (hubsync.enabled() ? hubsync.resolvePerson(q) : null), networkOn: () => hubsync.enabled(),
excluded: em => fraud.excluded(em), spamEmails: () => (((spamscan.view() || {}).last || {}).candidates || []).map(c => c.email), suggestDomain: d => require('./emailcheck').suggestDomain(d) } }).catch(e => console.error('draftpartner init', e.message));
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
@@ -847,6 +849,15 @@ async function boot() {
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
// holding tank batches (tankbatch.js, 2026-11-15): hourly follow-up + a round while tankBatches is on; the feed card goes where the other sale cards go
{ let spamC = { at: 0, set: new Set() }; const spamSet = () => { if (Date.now() - spamC.at > 60000) { try { spamC = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamC = { at: Date.now(), set: new Set() }; } } return spamC.set; };
await tankbatch.init({ dataDir: DATA_DIR, db, accounts, chain, tank, refuel, messages, mailer, siteConfig,
hooks: { excluded: em => fraud.excluded(em), companyId: () => Number(siteConfig().defaultSponsorId) || 1, claim: key => marks.claim(key), toast: ev => pushFeed(ev),
excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; },
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); },
feed: async (who, what, level) => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; const clean = t => String(t || '').replace(/[<>&]/g, ''); await telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>InstantAdPay</b> · <b>' + clean(who) + '</b> just received ' + clean(what) + ' from the holding tank (' + clean(level) + ' level)', sc.telegramEchoTopicId); } } }).catch(e => console.error('tankbatch init', e.message)); }
setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window
setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000);
setInterval(() => draftpartner.sweep().then(r => { if (r.done || r.returned || r.kept || r.moved) console.log('draft sweep', JSON.stringify(r)); }).catch(e => console.error('draft sweep', e.message)), 60 * 60 * 1000); // 5xYourTeam picks: 3-day window
burner.init({ chain, ads, accounts });
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
@@ -921,6 +932,8 @@ function siteConfig() {
leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover)
loginAdEveryHours: 3, // login ad: shown again on the next member page once the last finished view is this many hours old (Marty 2026-11-15)
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches
...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
@@ -3571,6 +3584,7 @@ const server = http.createServer(async (req, res) => {
for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i;
return json(res, 200, { suggest: pick });
}
if (p === '/api/my/tank/feed' && req.method === 'GET') { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); return json(res, 200, await tankbatch.myView(s.email)); } // How to get fed leads (off with tankBatches)
if (p === '/api/my/tank' && req.method === 'GET') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
@@ -3867,6 +3881,8 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await draftpartner.adminView());
}
if (p === '/api/admin/tank/batches/preview' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.preview()); } // read-only: no writes, no mail
if (p === '/api/admin/tank/batches' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.adminView()); }
if (p === '/api/admin/tank' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await tank.adminView());
+33 -11
View File
@@ -17,13 +17,19 @@ const db = require('./db');
const CAP_DEFAULT = 10; let capFn = () => CAP_DEFAULT;
const capOpen = () => { const n = Math.round(Number(capFn())); return n >= 1 && n <= 50 ? n : CAP_DEFAULT; };
async function holding(open) { const out = []; for (const ad of open || []) { const a = await accounts.byEmail(ad.adoptee); if (!(a && Number(a.memberId) > 0)) out.push(ad); } return out; }
// each allowance counts only its own people (Marty 2026-11-15: "5x your team's draft is a different thing altogether"): the member's own
// tank button and the 24-hour safety net count plain adoptions; a 5xYourTeam draft pick counts only against the draft's cap; a holding
// tank batch (tankbatch.js) only against the batch size. A hook that throws counts the adoption as plain (the conservative side).
const pickKind = async id => { try { if (hooks.isDraftPick && await hooks.isDraftPick(id)) return 'draft'; if (hooks.isBatchPick && await hooks.isBatchPick(id)) return 'batch'; } catch (e) {} return 'plain'; };
async function holdingOf(open, kind) { const out = []; for (const ad of await holding(open)) if (await pickKind(ad.id) === kind) out.push(ad); return out; }
const TTL_MS = 7 * 86400000; // an adoption's window to convert
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js), and a record of a
// member naming who invited them (nobody adopted them; nameSponsor below)
const NOT_COUNTED = ['released', 'conflict', 'invited'];
// 'unreached' (2026-11-15): a holding tank batch person the sponsor never contacted, back in the tank; the sponsor's miss, not theirs
const NOT_COUNTED = ['released', 'conflict', 'invited', 'unreached'];
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
@@ -57,10 +63,10 @@ const D = {
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
return rows.map(rowA);
},
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n); },
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n); },
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n) > 0; },
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited','unreached')", [adoptee]); return Number(r[0].n) > 0; },
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
async setMark(lead, f) {
@@ -135,7 +141,7 @@ async function eligibility(email) {
if (!a) return { ok: false, reason: 'Sign in first.' };
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $20 package to adopt from the tank.' };
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $20 or more package first. Adopting is for members who have made that move themselves.' };
const open = await impl().open(a.email); const held = await holding(open); const cap = capOpen();
const open = await impl().open(a.email); const held = await holdingOf(open, 'plain'); const cap = capOpen();
if (held.length >= cap) return { ok: false, reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold. A slot opens when one of them switches on payouts, or when their 7-day window ends.', full: true, cap, held: held.length };
return { ok: true, account: a, open };
}
@@ -154,11 +160,25 @@ async function partnerEligibility(email, p) {
const payee = await firstOnContract(a);
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Neither you nor anyone above you has switched on payouts on InstantAdPay, so a pick who starts there would land under the company. Switch on payouts on InstantAdPay first (one free transaction).' };
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'Your line cannot take new members right now.' };
const open = await impl().open(a.email); const held = await holding(open); const cap = Math.min(capOpen(), Number(p.maxOpen) > 0 ? Number(p.maxOpen) : capOpen());
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold.', full: true, cap, held: held.length };
// the draft's own cap (2026-11-15): only open draft picks count, never the member's plain adoptions or tank batches
const open = await impl().open(a.email); const held = await holdingOf(open, 'draft'); const cap = Number(p.maxOpen) > 0 ? Number(p.maxOpen) : 10;
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You already have ' + held.length + ' open draft picks, and ' + cap + ' at one time is the most a coach can hold.', full: true, cap, held: held.length };
return { ok: true, account: a, open };
}
// a holding tank batch (tankbatch.js, 2026-11-15): tankbatch has already decided the sponsor qualifies (active, own paid package on
// InstantAdPay or LinkSpin) and has room in their batch; this is the InstantAdPay side of the same gate as a 5x coach: a real account,
// not suspended or flagged, someone on THIS contract in their line, and that line takes payouts (else the person walks up to the company)
async function batchEligibility(email) {
const a = await accounts.byEmail(email);
if (!a) return { ok: false, code: 'no_account', reason: 'No such member.' };
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) return { ok: false, code: 'excluded', reason: 'Adoptions are not available on this account.' };
const payee = await firstOnContract(a);
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Nobody in this line has switched on payouts on InstantAdPay.' };
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'This line cannot take new members right now.' };
return { ok: true, account: a };
}
async function view(email) {
const e = String(email || '').toLowerCase();
const el = await eligibility(e);
@@ -175,8 +195,9 @@ async function adopt(adopterEmail, who, note, opts) {
// partner = a 5xYourTeam draft pick (draftpartner.js, 2026-11-15): the coach qualifies by a 5x position instead of the $20 buy,
// the window is the pick's (3 days, partner.ttlMs), the hub is asked fresh that nobody locked is taken, no reminder mails
const partner = (opts && opts.partner) || null;
const batch = !!(opts && opts.batch); // a holding tank batch (tankbatch.js): its own allowance, the grace and the two-adoptions rule still apply
const e = String(adopterEmail || '').toLowerCase();
const el = partner ? await partnerEligibility(e, partner) : await eligibility(e);
const el = partner ? await partnerEligibility(e, partner) : batch ? await batchEligibility(e) : await eligibility(e);
if (!el.ok) return { error: el.reason, code: el.code || 'not_eligible' };
const me = el.account;
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
@@ -187,10 +208,10 @@ async function adopt(adopterEmail, who, note, opts) {
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.', code: 'grace' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.', code: 'linkspin' };
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.', code: 'adopted_twice' }; // the safety net never leaves anyone to the company
if ((partner || batch) && await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
if (partner) { // never anyone locked on a network contract: asked fresh, a hub that does not answer refuses (the conservative side)
const lk = await lockedWhy(target.email);
if (lk) return { error: lk === 'locked' ? 'That member is locked to a sponsor on a network contract.' : 'The network record cannot be checked right now. Try again in a few minutes.', code: lk === 'locked' ? 'locked' : 'hub_unknown' };
if (await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
}
const token = me.username || me.code || String(me.memberId);
const r = await setSponsor(target.email, token, 'adopt');
@@ -255,7 +276,8 @@ async function sweep() {
let done = 0, back = 0, kept = 0;
for (const ad of await impl().open(null)) {
if (ad.expires > now) continue;
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue; // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue;
if (hooks.isBatchPick && await Promise.resolve(hooks.isBatchPick(ad.id)).catch(() => true)) continue; // a holding tank batch: tankbatch.js owns its follow-up window // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
const a = await accounts.byEmail(ad.adoptee);
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
@@ -517,7 +539,7 @@ async function autoAssignRun() {
let done = null;
for (const c of pool) {
if (c.a.email === e) continue;
if ((await holding(await impl().open(c.a.email))).length >= capOpen()) continue;
if ((await holdingOf(await impl().open(c.a.email), 'plain')).length >= capOpen()) continue;
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
if (await inDownlineOf(e, c.a)) continue;
const msg = 'Hi, I am ' + nameOf(c.a) + '. ' + ((a.joinedVia === 'btc4hits' || a.joinedRef === 'btc4hits') ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
@@ -718,5 +740,5 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
module.exports = { _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
module.exports = { batchEligibility, holdingOf, firstOnContract, inDownlineOf, markOf: email => impl().mark(String(email || '').toLowerCase()), _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
+329
View File
@@ -0,0 +1,329 @@
'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 };