// 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);