Files

555 lines
49 KiB
JavaScript

// Holding-tank activation hold + 24-hour safety net + network alignment (2026-10-27).
// node qa/tank-hold.mjs (or: bash qa/run.sh tankhold; also part of `bash qa/run.sh member`)
// Part A, no server: tank.js with in-memory accounts, a fake chain and a MOCKED CLOCK (tank.setClock):
// ready clock starts at first sight of a linked wallet, the hold, alignment to a LinkSpin sponsor (and the refusals:
// released-from sponsor, unclaimed shell, loop), the safety net at 24 h (rotation order, cap, 7-day sign-in, company
// excluded, no-payout chain skipped, own-downline skipped), nobody eligible = keep holding + one admin alert.
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, LS_URL pointed at a dead local port so nothing
// reaches LinkSpin): a tank account links a wallet -> /api/me + /api/sponsor answer tankHold with no fallback sponsor,
// the Wallet tab hides Activate payouts and shows the hold text, the Getting started card has no activate button,
// Admin tank shows the ready badge; a member who joined through a link is never held; a LinkSpin row naming a sponsor
// aligns a tank member instead of holding them; the one-tap /my?activate=1#wallet link (stubbed wallet) starts the Activate
// flow only with a wallet, a real sponsor and no hold, and carries on after an on-page sign-in. Never production. Exit code 1 on any failure.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
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; // JSON stores only
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const H = 3600000;
const addr = () => '0x' + crypto.randomBytes(20).toString('hex');
// ---------------- Part A ----------------
function fakeAccounts() {
const by = new Map(); let nextId = 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; };
return {
_by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
async listAll() { return [...by.values()].filter(a => !(a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId)).map(pub); },
isUnclaimedShell: a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId,
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
};
}
function bench(o) {
o = o || {};
const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)];
const tank = require(tankPath);
const dir = o.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-'));
const accounts = o.accounts || fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {};
const notices = []; const claims = o.claims || new Set(); const onChain = o.onChain || new Set();
const blocked = new Set();
const env = o.env || { now: Date.now() };
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) },
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
hooks: { network: e => net[e] || null, isSuspended: () => false, excluded: () => false, payoutBlocked: async id => blocked.has(id), companyId: () => 1,
assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); },
claim: k => { if (claims.has(k)) return false; claims.add(k); return true; }, activated: a => onChain.has(a.address), notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
tank.setClock(() => env.now);
let block = 1000;
const buyer = (email, memberId, o) => { const a = accounts.add(email, Object.assign({ memberId, address: '0x' + crypto.randomBytes(20).toString('hex'), lastSeen: env.now - H }, o || {})); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2000, block: block++ }); return a; };
return { tank, accounts, events, chats, mails, alerts, assigned, net, blocked, env, buyer, dir, notices, claims, onChain };
}
async function partA() {
console.log('-- Part A: tank.js with a mocked clock');
{ // hold + ready clock + safety net rotation
const B = bench(); const { tank, accounts, env } = B;
const t0 = env.now;
accounts.add('free@x.co'); // in the tank, no wallet
const h0 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: held, no clock yet');
accounts._by.get('free@x.co').address = '0x' + 'a'.repeat(40);
const h1 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h1 && h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'wallet linked: clock starts now, until = +24 h');
env.now = t0 + 5 * H;
const h2 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h2.hold.since === t0, 'the clock does not restart on later visits');
const sponsored = accounts.add('kid@x.co', { sponsorRef: 'someone', address: '0x' + 'b'.repeat(40) });
ok((await tank.holdFor(sponsored)) === null, 'a member with a sponsor is never held');
const w = await tank.waiting();
ok(w[0] && w[0].email === 'free@x.co' && w[0].ready && w[0].holdUntil === t0 + 24 * H, 'waiting(): ready member first with holdUntil');
// adopters: A qualified first, B second, C third; D stale (8 days), E company #1, F blocked chain, G full (2 open)
B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13);
B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16);
const tk = await tank.readyTick(); // 5 h in: nothing due
ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh.map(x => x.email)));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
ok(tk.assigned.length === 0, 'not assigned before 24 h');
env.now = t0 + 24 * H - 10 * 60000; // 23 h 50 min: inside the last tick, so the hold never runs past 24 h
const r1 = await tank.readyTick();
ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', 'safety net: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned));
const fa = await accounts.byEmail('free@x.co');
ok(fa.sponsorRef === 'a', 'adoptee now sponsored by A', fa.sponsorRef);
ok((await tank.holdFor(fa)) === null, 'hold lifted once sponsored');
const recs = (await tank.adminView()).adoptions;
ok(recs[0] && recs[0].note === 'auto-assigned after 24 hours in the tank' && recs[0].status === 'open', 'adoption record note', recs[0] && recs[0].note);
ok(B.chats.some(c => c.from === 'a@x.co' && c.to === 'free@x.co'), 'sponsor chat opened');
ok(B.mails.some(m => m.to === 'free@x.co') && B.mails.some(m => m.to === 'a@x.co' && /holding tank is now in your line/.test(m.subject)), 'both sides emailed');
const LINK = 'https://iap.test/my?activate=1#wallet';
ok(B.chats.some(c => c.to === 'free@x.co' && c.text.includes('Switch on payouts in one tap') && c.text.includes(LINK)), 'auto-assign chat carries the one-tap link');
ok(B.mails.some(m => m.to === 'free@x.co' && m.body.includes('Switch on payouts: ' + LINK) && m.body.includes('locks @a in as your sponsor')), 'auto-assign member email carries the one-tap link');
ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup line with "(auto-assigned)")');
// second ready member: rotation moves to B (A was just auto-assigned)
accounts.add('free2@x.co', { address: '0x' + 'c'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r2 = await tank.readyTick();
ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: least recently auto-assigned next (B)', JSON.stringify(r2.assigned));
// third: C; D stale, E company, F blocked chain never picked
accounts.add('free3@x.co', { address: '0x' + 'd'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r3 = await tank.readyTick();
ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned));
// fourth: everyone in rotation has been used once: back to A (oldest auto-assign)
accounts.add('free4@x.co', { address: '0x' + 'e'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
const r4 = await tank.readyTick();
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned));
// since 2026-11-11 the cap is people held at one time who have not switched on payouts (default 10): fill A up by hand
for (let i = 0; i < tank.capOpen(); i++) { accounts.add('fill' + i + '@x.co'); await tank.adopt('a@x.co', 'fill' + i + '@x.co'); }
// A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
accounts.add('free5@x.co', { address: '0x' + 'f'.repeat(40) });
await tank.readyTick(); env.now += 24 * H;
const r5 = await tank.readyTick();
const f5 = await accounts.byEmail('free5@x.co');
ok(r5.assigned.length === 0 && r5.held === 1 && !f5.sponsorRef, 'nobody eligible: keeps holding, never the company');
ok(B.alerts.length === 1 && /free5@x.co/.test(B.alerts[0]), 'admin alerted once');
await tank.readyTick(); await tank.sweep();
ok(B.alerts.length === 1, 'no second alert on later ticks / the hourly sweep');
const h5 = await tank.holdFor(f5);
ok(h5 && h5.hold && h5.hold.until <= env.now, 'still held past the clock (client shows "Any minute now")');
}
{ // one-tap link + switch-on-payouts reminders (24 h member + sponsor, 72 h member only), mocked clock
const B = bench(); const { tank, accounts, env } = B; const LINK = 'https://iap.test/my?activate=1#wallet';
B.buyer('sp@x.co', 41);
accounts.add('m1@x.co', { address: '0x' + '7'.repeat(40) }); accounts.add('m2@x.co'); accounts.add('m3@x.co', { address: '0x' + '8'.repeat(40) }); accounts.add('m4@x.co', { address: '0x' + '9'.repeat(40) });
const r = await tank.adopt('sp@x.co', 'm1', 'Hey, I am your new sponsor.');
ok(r && r.ok && !r.auto, 'manual adoption (setup)', JSON.stringify(r && r.error));
const chat = B.chats.find(c => c.to === 'm1@x.co');
ok(chat && chat.text === 'Hey, I am your new sponsor.\n\nSwitch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + LINK, 'manual adoption chat: own note + the one-tap line', chat && chat.text);
const mail = B.mails.find(m => m.to === 'm1@x.co');
ok(mail && mail.body.includes('Switch on payouts: ' + LINK) && !mail.body.includes('No wallet linked yet'), 'manual adoption email: link, no wallet sentence when linked');
await tank.adopt('sp@x.co', 'm2'); // no wallet yet
ok(B.mails.some(m => m.to === 'm2@x.co' && m.body.includes('No wallet linked yet? The same link shows you how')), 'no wallet: the email says the link walks them through linking');
const t0 = env.now;
env.now = t0 + 23 * H; let p = await tank.payTick();
ok(p.sent.length === 0, 'no reminder before 24 h');
accounts._by.get('m2@x.co').memberId = 51; // m2 switched on payouts: no reminder ever
env.now = t0 + 24 * H + 60000; const mailsBefore = B.mails.length;
p = await tank.payTick();
const r1 = B.mails.slice(mailsBefore);
ok(p.sent.length === 1 && p.sent[0].email === 'm1@x.co' && p.sent[0].stage === 1, '24 h: one reminder, only for the member still off', JSON.stringify(p.sent));
ok(r1.length === 1 && r1[0].to === 'm1@x.co' && r1[0].subject === 'Reminder: switch on payouts with @sp on InstantAdPay' && r1[0].body.includes(LINK), '24 h member email: subject + one-tap link', r1[0] && r1[0].subject);
ok(B.notices.length === 1 && B.notices[0].to === 'sp@x.co' && B.notices[0].subject === "@m1 hasn't switched on payouts yet" && B.notices[0].text.startsWith("@m1 hasn't switched on payouts yet; a nudge from you helps.") && B.notices[0].text.includes(LINK), '24 h sponsor notice', B.notices[0] && B.notices[0].text.slice(0, 80));
ok(!r1.some(m => m.to === 'sp@x.co'), 'the sponsor gets a notice, not an email');
await tank.payTick(); env.now += 15 * 60000; p = await tank.payTick();
ok(p.sent.length === 0 && B.notices.length === 1, 'idempotent: later ticks send nothing more before 72 h');
ok(tank.payView().find(x => x.email === 'm2@x.co').done === 'activated', 'activated member: record closed (activated)');
env.now = t0 + 72 * H + 60000; const m72 = B.mails.length;
p = await tank.payTick();
ok(p.sent.length === 1 && p.sent[0].stage === 2 && B.mails.length === m72 + 1 && B.mails[m72].subject === 'Last reminder: switch on payouts with @sp on InstantAdPay' && B.mails[m72].body.includes(LINK), '72 h: the last reminder, member only', JSON.stringify(p.sent));
ok(B.notices.length === 1, '72 h: no second sponsor notice');
env.now += 24 * H; p = await tank.payTick();
ok(p.sent.length === 0 && tank.payView().find(x => x.email === 'm1@x.co').done === 'reminded', 'after 72 h: done, nothing more');
ok(!/—/.test(B.chats.map(c => c.text).join(' ') + B.mails.map(m => m.subject + m.body).join(' ') + B.notices.map(n => n.subject + n.text).join(' ')), 'no em dashes in member texts');
// m3 activated on chain (MemberActivated) before the account has a memberId; m4 moved away before 24 h: both stop
B.buyer('sp2@x.co', 42);
const r3 = await tank.adopt('sp2@x.co', 'm3'); ok(r3 && r3.ok, 'second sponsor adopts m3 (setup)', JSON.stringify(r3 && r3.error));
const r4 = await tank.adopt('sp2@x.co', 'm4'); ok(r4 && r4.ok, 'second sponsor adopts m4 (setup)', JSON.stringify(r4 && r4.error));
const t3 = env.now; B.onChain.add(accounts._by.get('m3@x.co').address);
accounts._by.get('m4@x.co').sponsorRef = '';
env.now = t3 + 25 * H; p = await tank.payTick();
ok(p.sent.length === 0, 'activated on chain / sponsor changed: no reminder', JSON.stringify(p.sent));
const pv = tank.payView();
ok(pv.find(x => x.email === 'm3@x.co').done === 'activated' && pv.find(x => x.email === 'm4@x.co').done === 'moved', 'records closed as activated / moved');
ok((await tank.adminView()).payReminders.length >= 4, 'adminView lists the reminder records');
}
{ // deploy overlap: a second app copy with a stale tank-ready.json and the shared claim table sends nothing twice
const accounts = fakeAccounts(); const claims = new Set(); const env = { now: Date.now() };
const A = bench({ accounts, claims, env });
A.buyer('ov@x.co', 61); accounts.add('ovm@x.co', { address: '0x' + '6'.repeat(40) });
await A.tank.adopt('ov@x.co', 'ovm');
const stale = fs.readFileSync(path.join(A.dir, 'tank-ready.json'), 'utf8');
env.now += 25 * H;
const pa = await A.tank.payTick();
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-ov-')); fs.writeFileSync(path.join(dir2, 'tank-ready.json'), stale);
const Bc = bench({ accounts, claims, env, dir: dir2 }); // copy B: same accounts + claims, stale state
const pb = await Bc.tank.payTick();
ok(pa.sent.length === 1 && pb.sent.length === 0 && Bc.mails.length === 0 && Bc.notices.length === 0, 'overlap: copy A sends the 24 h reminder, stale copy B sends nothing', JSON.stringify({ a: pa.sent.length, b: pb.sent.length }));
}
{ // own-downline adopter skipped
const B = bench(); const { tank, accounts, env } = B;
accounts.add('top@x.co', { address: '0x' + '1'.repeat(40) });
B.buyer('under@x.co', 21, { sponsorRef: 'top' }); B.buyer('other@x.co', 22);
await tank.readyTick(); env.now += 24 * H;
const r = await tank.readyTick();
ok(r.assigned.length === 1 && r.assigned[0].adopter === 'other@x.co', 'an adopter in the member\'s own downline is skipped', JSON.stringify(r.assigned));
}
{ // network alignment
const B = bench(); const { tank, accounts, net } = B;
accounts.add('lsboss@x.co', { memberId: 31 });
accounts.add('t1@x.co', { address: '0x' + '2'.repeat(40) }); net['t1@x.co'] = { sponsorEmail: 'lsboss@x.co', via: 'same email' };
const h = await tank.holdFor(await accounts.byEmail('t1@x.co'));
ok(h && h.aligned && (await accounts.byEmail('t1@x.co')).sponsorRef === 'lsboss', 'LinkSpin sponsor with an account here: aligned, not held', JSON.stringify(h));
ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @lsboss from LinkSpin'), 'alignment recorded with the reason');
accounts.add('shell@x.co', { joinedVia: 'linkspin', lastSeen: 0 });
accounts.add('t2@x.co'); net['t2@x.co'] = { sponsorEmail: 'shell@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t2@x.co'))).hold, 'sponsor only an unclaimed LinkSpin shell here: held, not aligned');
accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'sponsor with no account here: held');
// released from lsboss on purpose: never back to them
accounts.add('t4@x.co', { sponsorRef: 'lsboss' });
const rel = await tank.release('lsboss@x.co', 't4@x.co');
ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel));
net['t4@x.co'] = { sponsorEmail: 'lsboss@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them');
// loop: the LinkSpin sponsor sits under the tank member
accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline');
}
}
// ---------------- Part B ----------------
// ---------------- Sign-up grace + "Who invited you?" (Marty approved 2026-11-07) ----------------
async function partGrace() {
console.log('-- Sign-up grace + Who invited you: tank.js with a mocked clock');
const M = 60000;
{ // hand adoption: blocked for 24 hours from created, open after, old members untouched
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('new@x.co', { created: t0 - H }); accounts.add('old@x.co');
const w = await tank.waiting(); const row = w.find(x => x.email === 'new@x.co');
ok(row && row.opensAt === t0 + 23 * H, 'waiting(): new sign-up carries opensAt = created + 24 h', JSON.stringify(row));
ok(w.find(x => x.email === 'old@x.co').opensAt === 0, 'waiting(): an old account is open now');
ok(w[w.length - 1].email === 'new@x.co', 'waiting(): grace members sort after the open ones');
ok((await tank.adoptable()).every(x => x.email !== 'new@x.co'), 'adoptable() leaves out grace members (Overview note, weekly email)');
const r = await tank.adopt('ad@x.co', 'new', 'hi');
ok(r.error && /less than 24 hours/.test(r.error) && /23 h 0 min/.test(r.error), 'grace blocks a hand adoption with a plain message', JSON.stringify(r));
ok(!(await accounts.byEmail('new@x.co')).sponsorRef, '...and writes no sponsor');
ok(!B.mails.length && !B.chats.length, '...and tells nobody');
env.now = t0 + 23 * H - M;
ok((await tank.adopt('ad@x.co', 'new', 'hi')).error, 'still blocked one minute before it opens');
env.now = t0 + 23 * H + M;
const r2 = await tank.adopt('ad@x.co', 'new', 'hi');
ok(r2.ok, 'opens after 24 hours', JSON.stringify(r2));
const r3 = await tank.adopt('ad@x.co', 'old', 'hi');
ok(r3.ok, 'an old account is adoptable at once (back in the tank later = no grace)', JSON.stringify(r3));
}
{ // wallet in the first hour: hand adoption opens at 24 h, the safety net keeps its own clock
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11); B.buyer('ad2@x.co', 12);
accounts.add('w@x.co', { created: t0 });
env.now = t0 + H; accounts._by.get('w@x.co').address = addr(); accounts._by.get('w@x.co').lastSeen = env.now;
const t1 = await tank.readyTick();
ok(t1.fresh.length === 0, 'wallet in the first hour: no "adopt them" notice during the grace', JSON.stringify(t1.fresh));
const h = await tank.holdFor(await accounts.byEmail('w@x.co'));
ok(h.hold.since === t0 + H && h.hold.until === t0 + 25 * H, 'the hold clock runs from the wallet link, not stretched by the grace', JSON.stringify(h.hold));
env.now = t0 + 23 * H; ok((await tank.readyTick()).fresh.length === 0, 'still no notice at 23 hours');
ok((await tank.adopt('ad@x.co', 'w', 'hi')).error, 'hand adoption refused at 23 hours');
env.now = t0 + 24 * H + M; for (const em of ['ad@x.co', 'ad2@x.co']) accounts._by.get(em).lastSeen = env.now;
const t2 = await tank.readyTick();
ok(t2.fresh.length === 1 && t2.fresh[0].until === t0 + 25 * H && !t2.assigned.length, 'grace over: notice once, with the real end of the hold', JSON.stringify(t2.fresh));
ok(tank.leftText(t2.fresh[0].until - env.now) === '59 min', 'the notice text can say the time really left', tank.leftText(t2.fresh[0].until - env.now));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
env.now = t0 + 25 * H - 10 * M;
const t3 = await tank.readyTick();
ok(t3.assigned.length === 1 && t3.assigned[0].adoptee === 'w@x.co', 'the rotation takes them inside 24 hours of the wallet link', JSON.stringify(t3.assigned));
}
{ // wallet in the first minutes: the rotation fires just before the grace ends, no notice ever goes out
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('fast@x.co', { created: t0, address: addr() });
env.now = t0 + 5 * M; ok((await tank.readyTick()).fresh.length === 0, 'wallet in minute 5: no notice');
env.now = t0 + 24 * H - 5 * M; accounts._by.get('ad@x.co').lastSeen = env.now;
const t = await tank.readyTick();
ok(t.assigned.length === 1 && t.fresh.length === 0, 'auto path unaffected: assigned inside the grace (24 h from the wallet link), no adopt notice', JSON.stringify({ a: t.assigned, f: t.fresh }));
ok((await accounts.byEmail('fast@x.co')).sponsorRef === 'ad', 'the safety net wrote the sponsor');
}
{ // grace ends in the last tick of the hold: the safety net takes them, nobody is told to adopt someone already gone
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('ad@x.co', 11);
accounts.add('mid@x.co', { created: t0 });
env.now = t0 + 10 * M; accounts._by.get('mid@x.co').address = addr(); await tank.readyTick();
env.now = t0 + 24 * H + M; accounts._by.get('ad@x.co').lastSeen = env.now; // 9 minutes of hold left: inside the last tick
const t = await tank.readyTick();
ok(t.assigned.length === 1 && t.fresh.length === 0, 'no notice for someone the rotation takes in the same tick', JSON.stringify({ a: t.assigned, f: t.fresh }));
}
{ // the arrivals post: announced when the grace ends
const B = bench(); const { tank, env } = B; const t0 = env.now;
const list = [{ email: 'a', joined: t0 - 24 * H - 5 * M }, { email: 'b', joined: t0 - 24 * H - 20 * M }, { email: 'c', joined: t0 - H }];
ok(tank.openedSince(list, t0 - 15 * M).map(x => x.email).join() === 'a', 'openedSince: only people whose grace ended since the last check');
}
{ // Who invited you: every refusal, nothing written
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21);
accounts.add('m@x.co', { username: 'mm1', created: t0 });
accounts.add('kid@x.co', { username: 'kid', sponsorRef: 'mm1' }); // joined under m: a loop
accounts.add('free@x.co', { username: 'free' }); // no payouts, nobody above them
accounts.add('under@x.co', { username: 'under', sponsorRef: 'boss' }); // no payouts, but boss above them
accounts.add('has@x.co', { username: 'hassp', sponsorRef: 'boss' });
accounts.add('bound@x.co', { username: 'bound1', memberId: 55 });
const say = async (e, who) => { const r = await tank.nameSponsor(e, who); return r.error || ''; };
ok(/Type the username/.test(await say('m@x.co', ' ')), 'refused: empty');
ok(/That is you/.test(await say('m@x.co', '@MM1')), 'refused: self (any case, leading @)');
ok(/No member here/.test(await say('m@x.co', 'nosuchname')), 'refused: unknown username');
ok(/No member here/.test(await say('m@x.co', 'bad name!')), 'refused: not a username');
ok(/already have a sponsor/.test(await say('has@x.co', 'boss')), 'refused: already sponsored');
ok(/locked on the contract/.test(await say('bound@x.co', 'boss')), 'refused: member id');
ok(/in your own line/.test(await say('m@x.co', 'kid')), 'refused: chain loop (inDownlineOf)');
ok(/nobody above them/.test(await say('m@x.co', 'free')), 'refused: nobody on the contract in that line (would fall to the company)');
B.blocked.add(21);
ok(/cannot take new members/.test(await say('m@x.co', 'boss')), 'refused: no-payout chain');
B.blocked.delete(21);
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'no refusal wrote a sponsor or sent a notice');
const c = await tank.nameSponsor('m@x.co', 'boss', { check: true });
ok(c.ok && c.name === '@boss' && !(await accounts.byEmail('m@x.co')).sponsorRef && !B.mails.length, 'check mode validates and writes nothing', JSON.stringify(c));
ok((await tank.nameSponsor('m@x.co', 'under', { check: true })).ok, 'a sponsor with no payouts but someone above them on the contract is allowed');
B.net['m2@x.co'] = { sponsorEmail: 'boss@x.co', via: 'email' };
accounts.add('m2@x.co', { username: 'mm2' });
const al = await tank.nameSponsor('m2@x.co', 'under');
ok(al.error && al.aligned && (await accounts.byEmail('m2@x.co')).sponsorRef === 'boss', 'the sponsor the network already knows comes first', JSON.stringify(al));
}
{ // Who invited you: success
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
accounts.add('m@x.co', { username: 'mm1', created: t0 });
const m0 = await accounts.byEmail('m@x.co');
ok(tank.inviteAsk(m0) && tank.inviteAsk(m0).dismissed === false, 'inviteAsk: the card shows for a tank member');
ok(tank.inviteAsk(await accounts.byEmail('boss@x.co')) === null, 'inviteAsk: no card for a member with a sponsor line / member id');
tank.dismissInvite('m@x.co');
ok(tank.inviteAsk(m0).dismissed === true, 'Nobody invited me: card dismissed');
ok(!(await accounts.byEmail('m@x.co')).sponsorRef && (await tank.waiting()).some(w => w.email === 'm@x.co'), '...nothing else changes: still in the tank');
const r = await tank.nameSponsor('m@x.co', '@Boss');
ok(r.ok && r.name === '@boss', 'prompt success', JSON.stringify(r));
const a = await accounts.byEmail('m@x.co');
ok(a.sponsorRef === 'boss', 'sponsor written');
ok((await tank.holdFor(a)) === null && tank.inviteAsk(a) === null, 'hold gone, card gone');
ok(!(await tank.waiting()).some(w => w.email === 'm@x.co'), 'out of the waiting list');
ok(B.mails.length === 1 && B.mails[0].to === 'boss@x.co' && /new referral/.test(B.mails[0].subject), 'the named sponsor gets the notice, nobody else', JSON.stringify(B.mails.map(x => x.to)));
ok(!B.chats.length, 'no chat written in the sponsor\'s name');
const v = await tank.adminView(); const rec = v.adoptions.find(x => x.adoptee === 'm@x.co');
ok(rec && rec.status === 'invited' && rec.adopter === 'boss@x.co', 'admin record: status invited');
ok((await tank.summaryFor('m@x.co')) === null, 'not an adoption: nothing counts toward the two, nothing open on the other site');
const again = await tank.nameSponsor('m@x.co', 'ad');
ok(/already have a sponsor/.test(again.error || '') && (await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'a second name is refused');
env.now = t0 + 8 * 86400000; await tank.sweep();
ok((await accounts.byEmail('m@x.co')).sponsorRef === 'boss', 'no 7-day window: still theirs after a week');
}
{ // a ready member names someone: the hold record clears the way an adoption does, no auto-assign
const B = bench(); const { tank, accounts, env } = B; const t0 = env.now;
B.buyer('boss@x.co', 21); B.buyer('ad@x.co', 22);
accounts.add('r@x.co', { username: 'rr1', created: t0, address: addr() });
await tank.readyTick();
ok(tank.readyRec('r@x.co'), 'setup: on the 24-hour clock');
const r = await tank.nameSponsor('r@x.co', 'boss');
ok(r.ok && !tank.readyRec('r@x.co'), 'the hold record clears', JSON.stringify(r));
env.now = t0 + 24 * H;
for (const em of ['boss@x.co', 'ad@x.co']) accounts._by.get(em).lastSeen = env.now;
ok(!(await tank.readyTick()).assigned.length && (await accounts.byEmail('r@x.co')).sponsorRef === 'boss', 'the rotation leaves them alone');
ok(tank.payView().some(p => p.email === 'r@x.co' && p.adopter === 'boss@x.co'), 'the switch-on-payouts reminders track the named sponsor');
const B2 = bench(); B2.buyer('boss@x.co', 21); const w = '0x' + 'e'.repeat(40); B2.accounts.add('c@x.co', { username: 'cc1', address: w }); B2.onChain.add(w);
ok(/locked on the contract/.test((await B2.tank.nameSponsor('c@x.co', 'boss')).error || ''), 'refused: wallet already on the contract, member number not saved yet');
}
}
async function partB() {
console.log('-- Part B: local copy');
const PORT = Number(process.env.TANKHOLD_PORT || 8799);
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'localtest';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const LSSECRET = crypto.randomBytes(24).toString('hex'); // throwaway
{ const a = { email: 'qa-sponsor@example.com', pass: null, sponsorRef: '', code: 'cqasp1', username: 'qasponsor', address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, memberId: 42 }; // a member with a contract position, for the Who invited you checks
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify({ v: 2, byEmail: { [a.email]: a }, byAddress: {}, byCode: { [a.code]: a.email }, joins: 0, positions: {} })); }
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, LS_SYNC_SECRET: LSSECRET, LS_URL: 'http://127.0.0.1:1' }) });
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
let browser = null;
try {
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config')).ok; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500));
const api = async (p, body, hdr) => { const r = await fetch(BASE + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
const adminH = { Authorization: 'Bearer ' + ADMIN };
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 20 } }, adminH);
async function signIn(email, username, extraCookie, ip) { // ip: X-Forwarded-For of its own (the code guard allows 5 sends per IP per 10 min)
const xf = ip ? { 'X-Forwarded-For': ip } : {};
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, Object.assign({}, xf, extraCookie ? { Cookie: extraCookie } : {}));
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, xf, extraCookie ? { Cookie: extraCookie } : {}), body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).filter(c => /^iap\./.test(c) || c.includes('=')).join('; ');
if (username) await api('/api/my/profile', { username }, { Cookie: cookie });
return cookie;
}
const { ethers } = require('ethers');
async function linkWallet(cookie) {
const w = ethers.Wallet.createRandom();
const c = await api('/api/auth/challenge', { address: w.address }, { Cookie: cookie });
const signature = await w.signMessage(c.j.message);
const v = await api('/api/auth/verify', { address: w.address, signature }, { Cookie: cookie });
return { w, v };
}
// 1. tank member with a wallet
const tc = await signIn('qa-tank@example.com', 'qatankone');
const lw = await linkWallet(tc);
ok(lw.v.j && lw.v.j.linked, 'tank member links a wallet', JSON.stringify(lw.v.j));
const me = (await api('/api/me', null, { Cookie: tc })).j;
ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold));
ok(me && !me.sponsorId && me.sponsorBlocked === 'tankHold', '/api/me: no fallback sponsor (sponsorId ' + (me && me.sponsorId) + ')');
const sp = (await api('/api/sponsor?intent=buy', null, { Cookie: tc })).j;
ok(sp && sp.sponsorId === 1 && !sp.sponsorBlocked && !sp.tankHold, '/api/sponsor (buy) is NEVER held: falls back to the catch position #1 (Marty 2026-10-27)', JSON.stringify({ id: sp && sp.sponsorId, b: sp && sp.sponsorBlocked }));
const spa = (await api('/api/sponsor', null, { Cookie: tc })).j;
ok(spa && !spa.sponsorId && spa.sponsorBlocked === 'tankHold', '/api/sponsor without buy intent still holds (activation only)', JSON.stringify({ id: spa && spa.sponsorId, b: spa && spa.sponsorBlocked }));
const adm = (await api('/api/admin/tank', null, adminH)).j;
const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com');
ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: ready with holdUntil');
// 2. joined through a link: never held, today's behaviour
const jc = await signIn('qa-kid@example.com', 'qakidone', 'iap.sponsor=qatankone');
await linkWallet(jc);
const me2 = (await api('/api/me', null, { Cookie: jc })).j;
ok(me2 && !me2.tankHold && me2.sponsorBlocked !== 'tankHold' && me2.sponsorId > 0, 'member with a sponsor link: no hold, sponsor resolves as before', JSON.stringify({ id: me2 && me2.sponsorId, b: me2 && me2.sponsorBlocked, routed: me2 && me2.sponsorRouted }));
// 3. LinkSpin knows a sponsor for this email: aligned instead of held
await signIn('qa-lsboss@example.com', 'qalsboss');
const tc3 = await signIn('qa-tank3@example.com', 'qatankthree');
const raw = JSON.stringify({ rows: [{ email: 'qa-tank3@example.com', username: 'qatankthree', sponsorEmail: 'qa-lsboss@example.com', joinedAt: Date.now() - 86400000 }] });
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', LSSECRET).update(ts + '\n' + raw).digest('hex');
const pr = await fetch(BASE + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw });
ok(pr.ok, 'LinkSpin row accepted (first-platform rule leaves the sponsor empty)');
const me3 = (await api('/api/me', null, { Cookie: tc3 })).j;
ok(me3 && !me3.tankHold && me3.sponsorBlocked !== 'tankHold', 'tank member LinkSpin knows: aligned, not held', JSON.stringify({ b: me3 && me3.sponsorBlocked, h: me3 && me3.tankHold }));
const adm3 = (await api('/api/admin/tank', null, adminH)).j;
ok(adm3 && adm3.aligned && adm3.aligned.some(x => x.email === 'qa-tank3@example.com' && x.to === 'qa-lsboss@example.com'), 'admin tank lists the alignment');
// 4. the page: Wallet tab + Getting started card
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
browser = await chromium.launch();
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); localStorage.removeItem('iap.gs.collapsed'); } catch (e) {} });
await ctx.addCookies(tc.split('; ').filter(Boolean).map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), url: BASE }; }));
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(BASE + '/my#wallet', { waitUntil: 'load' }); await page.waitForTimeout(4000);
const st = await page.evaluate(() => { const b = document.getElementById('activateBtn'); const n = document.getElementById('tankHoldNote'); const g = document.getElementById('gsNow');
return { card: !document.getElementById('activateCard').hidden, btnHidden: !!(b && b.hidden), note: n && !n.hidden ? n.textContent : null, gs: g ? g.textContent : '', gsBtn: !!document.getElementById('gsGo') }; });
ok(st.card && st.btnHidden, 'Wallet tab: Activate payouts button hidden', JSON.stringify(st));
ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'hold text with time left', st.note);
ok(/Matching you with a sponsor/.test(st.gs) && !st.gsBtn, 'Getting started: hold text, no activate button', st.gs.slice(0, 120));
await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-wallet.png') }).catch(() => {});
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
// 5. one-tap link /my?activate=1#wallet (2026-10-27): IAPWallet.activate is stubbed in the page (records the sponsor id,
// never reaches a wallet); it must start only for a signed-in member with a wallet, a real sponsor and no hold
const STUB = () => { window.__act = []; let real; Object.defineProperty(window, 'IAPWallet', { configurable: true, get() { return real; },
set(v) { if (v && v.activate) v.activate = async id => { window.__act.push(id); throw new Error('qa: activation stub'); }; real = v; } });
try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} };
async function actCtx(cookie, ip) { // ip: its own address for the on-page sign-in (the code guard allows 5 sends per IP per 10 min)
const c = await browser.newContext(Object.assign({ viewport: { width: 390, height: 844 } }, ip ? { extraHTTPHeaders: { 'X-Forwarded-For': ip } } : {})); await c.addInitScript(STUB);
if (cookie) await c.addCookies(cookie.split('; ').filter(Boolean).map(x => { const i = x.indexOf('='); return { name: x.slice(0, i), value: x.slice(i + 1), url: BASE }; }));
const pg = await c.newPage(); pg.on('pageerror', e => errs.push(e.message)); return { c, pg };
}
const actState = pg => pg.evaluate(() => { const n = document.getElementById('actIntentNote'); return { act: window.__act, note: n && !n.hidden ? n.textContent : null, url: location.pathname + location.search + location.hash, hold: (document.getElementById('tankHoldNote') || {}).hidden === false }; });
{ // held tank member: never triggers, the param is dropped, the hold text shows
const { c, pg } = await actCtx(tc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s1 = await actState(pg);
ok(s1.act.length === 0 && !s1.note && s1.hold && !/activate=1/.test(s1.url), '?activate=1 on a held tank member: no activation, hold text, param dropped', JSON.stringify(s1));
await c.close();
}
{ // sponsor link to a member who never switched on payouts (walk-up / routed): no real sponsor, never triggers
ok(me2 && me2.sponsorRouted, 'setup: the link-joined member routes past an unactivated sponsor', JSON.stringify(me2 && me2.sponsorRouted));
const { c, pg } = await actCtx(jc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s2 = await actState(pg);
ok(s2.act.length === 0 && !s2.note, '?activate=1 when no real sponsor resolves: no activation', JSON.stringify(s2));
await c.close();
}
// a member with a real sponsor (#21) and a wallet: the Activate flow starts at once with #21
const pc = await signIn('qa-pay@example.com', 'qapayone', 'iap.sponsor=21', '10.78.0.1'); await linkWallet(pc);
const mp = (await api('/api/me', null, { Cookie: pc })).j;
ok(mp && mp.sponsorId === 21 && !mp.sponsorFallback && !mp.tankHold && !mp.memberId, 'setup: sponsored member, sponsor #21 resolves', JSON.stringify({ id: mp && mp.sponsorId, f: mp && mp.sponsorFallback }));
{ const { c, pg } = await actCtx(pc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4500);
const s3 = await actState(pg);
ok(s3.act.length === 1 && s3.act[0] === 21, '?activate=1: the Activate flow starts once with the sponsor prefilled (#21)', JSON.stringify(s3));
ok(s3.note === 'One free transaction switches on your payouts and locks member #21 in as your sponsor. Confirm it in your wallet.', 'explainer line above the Activate button', s3.note);
ok(/#wallet$/.test(s3.url) && !/activate=1/.test(s3.url), 'Wallet tab open, param consumed', s3.url);
await pg.reload({ waitUntil: 'load' }); await pg.waitForTimeout(3500);
ok((await actState(pg)).act.length === 0, 'a reload does not start it again');
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-activate-link.png') }).catch(() => {});
await c.close(); }
{ // signed out: sign in on the page, then the same flow carries on
const c2 = await signIn('qa-pay2@example.com', 'qapaytwo', 'iap.sponsor=21', '10.78.0.2'); await linkWallet(c2);
const { c, pg } = await actCtx(null, '10.77.' + (1 + Math.floor(Math.random() * 250)) + '.9'); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
ok((await actState(pg)).act.length === 0, 'signed out: nothing starts before sign-in');
await pg.fill('#mcEmail', 'qa-pay2@example.com'); await pg.click('#mcSendBtn');
await pg.waitForFunction(() => (document.getElementById('mcCode') || {}).value, null, { timeout: 15000 }).catch(() => {});
await pg.click('#mcVerifyBtn'); await pg.waitForTimeout(5000);
const s4 = await actState(pg);
ok(s4.act.length === 1 && s4.act[0] === 21, 'signed out -> sign in -> the Activate flow continues with #21', JSON.stringify(s4));
await c.close(); }
{ // sponsored, no wallet yet: link first (note), nothing starts; the intent waits for the link
const c3 = await signIn('qa-pay3@example.com', 'qapaythree', 'iap.sponsor=21', '10.78.0.3');
const { c, pg } = await actCtx(c3); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
const s5 = await actState(pg);
ok(s5.act.length === 0 && s5.note === 'Step 1: link your wallet (one free signature). Then switching on payouts with member #21 starts by itself.', 'no wallet yet: asks to link first, nothing starts', JSON.stringify(s5));
await c.close(); }
ok(!errs.length, 'no page errors (one-tap link pages)', errs.join(' | ').slice(0, 200));
{ // 6. Who invited you + the sign-up grace, on the real page (2026-11-07)
const nc = await signIn('qa-new@example.com', 'qanewone', null, '10.78.0.9');
const m0 = (await api('/api/me', null, { Cookie: nc })).j;
ok(m0 && m0.inviteAsk && m0.inviteAsk.dismissed === false, '/api/me: inviteAsk for a tank member', JSON.stringify(m0 && m0.inviteAsk));
const sc = await signIn('qa-sponsor@example.com', null, null, '10.78.0.10');
const tv = (await api('/api/my/tank', null, { Cookie: sc })).j; const row6 = tv && tv.waiting.find(w => w.email === 'qa-new@example.com');
ok(row6 && row6.opensAt > Date.now(), '/api/my/tank: a new sign-up is listed with opensAt', JSON.stringify(row6));
const bad = await api('/api/my/tank/invited', { who: 'nosuchname' }, { Cookie: nc });
ok(bad.status === 400 && /No member here/.test(bad.j.error), 'POST invited: unknown username refused', JSON.stringify(bad));
const self = await api('/api/my/tank/invited', { who: 'qanewone' }, { Cookie: nc });
ok(self.status === 400 && /That is you/.test(self.j.error), 'POST invited: self refused', JSON.stringify(self));
const anon = await api('/api/my/tank/invited', { who: 'qasponsor' });
ok(anon.status === 401, 'POST invited: signed out refused');
const { c, pg } = await actCtx(nc); await pg.goto(BASE + '/my#overview', { waitUntil: 'load' }); await pg.waitForTimeout(3500);
const vis = id => pg.evaluate(i => { const e = document.getElementById(i); return !!(e && !e.hidden); }, id);
ok(await vis('inviteCard'), 'Overview: Who invited you card shows');
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-invite-card.png') }).catch(() => {});
await pg.fill('#inviteWho', 'nosuchname'); await pg.click('#inviteGo'); await pg.waitForTimeout(700);
ok(/No member here/.test(await pg.textContent('#inviteMsg')), 'card: the refusal shows in the card', await pg.textContent('#inviteMsg'));
await pg.click('#inviteNo'); await pg.waitForTimeout(500);
ok(!(await vis('inviteCard')) && await vis('inviteSmall'), 'card: Nobody invited me hides it, the small link stays');
await pg.reload({ waitUntil: 'load' }); await pg.waitForTimeout(3000);
ok(!(await vis('inviteCard')) && await vis('inviteSmall'), 'card: stays dismissed after a reload');
await pg.click('#inviteBack'); await pg.fill('#inviteWho', '@qasponsor'); await pg.click('#inviteGo'); await pg.waitForSelector('#dlgCancel', { timeout: 8000 }).catch(async e => { throw new Error('no confirm box; card says: ' + await pg.textContent('#inviteMsg') + ' | ' + e.message.slice(0, 80)); });
await pg.click('#dlgCancel'); await pg.waitForTimeout(500);
ok(!(await api('/api/me', null, { Cookie: nc })).j.sponsorName, 'card: Not them writes nothing');
await pg.click('#inviteGo'); await pg.waitForSelector('#dlgOk', { timeout: 5000 }); await pg.click('#dlgOk'); await pg.waitForTimeout(2500);
const m1 = (await api('/api/me', null, { Cookie: nc })).j;
ok(m1 && m1.sponsorName === '@qasponsor' && !m1.inviteAsk, 'card: yes sets the sponsor, the card is gone', JSON.stringify({ n: m1 && m1.sponsorName, a: m1 && m1.inviteAsk }));
ok(!(await vis('inviteCard')) && !(await vis('inviteSmall')), 'card: nothing left on the Overview');
const adm6 = (await api('/api/admin/tank', null, adminH)).j;
ok(adm6.adoptions.some(a => a.adoptee === 'qa-new@example.com' && a.status === 'invited'), 'admin tank: the invited record shows');
await c.close();
const pc2 = await signIn('qa-kid2@example.com', 'qakidtwo', 'iap.sponsor=qasponsor', '10.78.0.11');
const m2 = (await api('/api/me', null, { Cookie: pc2 })).j;
ok(m2 && !m2.inviteAsk, 'a member who joined through a link never sees the card');
ok(!errs.length, 'no page errors (Who invited you)', errs.join(' | ').slice(0, 200));
}
} finally {
if (browser) await browser.close().catch(() => {});
try { srv.kill(); } catch (e) {}
await sleep(500);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
}
}
await partA();
await partGrace();
if (process.argv[2] !== 'unit') await partB();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
process.exit(fails ? 1 : 0);