From 7edc1a25b0924c14ac87dcae9fca661d9fd26dfc Mon Sep 17 00:00:00 2001 From: martbost Date: Wed, 18 Nov 2026 19:08:51 -0600 Subject: [PATCH] Holding-tank readiness on the tank cards (Marty 2026-11-18, warm-up stage 1, no email) Each waiting lead on the Holding tank card (/tools) and Admin > Members tank card shows how they got into the tank, a stage chip (New / Warming / Engaged / Activated / Ready, real actions only), the network heat 0-100 with its band, and their last real action, from the network hub (POST /v1/tank/readiness). tankready.js is the same module as InstantAdPay's (entry facts from this site's adoption records, follow records and join data; usernames only). Hottest first inside the usual grace / ready-to-activate groups, a "Warm or hot only" toggle. Hub down = the card as before. No mail, no Telegram, no sponsor moves; adoption rules and caps untouched. qa/tank-readiness.test.mjs in member + tankhold; tankready.js / my.js / admin.js ?v=20261118rd, site.css ?v=ls20261118rd. qa member ALL PASSED. Co-Authored-By: Claude Opus 5.5 --- public/admin.html | 4 +- public/assets/admin.js | 8 ++- public/assets/my.js | 14 ++++- public/assets/site.css | 16 +++++ public/assets/tankready.js | 51 +++++++++++++++ public/my.html | 5 +- qa/run.sh | 2 + qa/tank-readiness.test.mjs | 82 ++++++++++++++++++++++++ server.js | 9 ++- tankready.js | 125 +++++++++++++++++++++++++++++++++++++ 10 files changed, 306 insertions(+), 10 deletions(-) create mode 100644 public/assets/tankready.js create mode 100644 qa/tank-readiness.test.mjs create mode 100644 tankready.js diff --git a/public/admin.html b/public/admin.html index 5c11614..95d9e4d 100644 --- a/public/admin.html +++ b/public/admin.html @@ -8,7 +8,7 @@ - + @@ -550,6 +550,6 @@ - + diff --git a/public/assets/admin.js b/public/assets/admin.js index da95b8e..c4f6cf9 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -301,7 +301,13 @@ // ready = wallet linked: the plain activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27) const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; }; const rb = w => (w.opensAt > Date.now() ? ' Opens ' + when(w.opensAt) + '' : '') + (w.ready ? ' Ready to activate · ' + left(w) + '' : ''); - $('tankWait').innerHTML = 'WaitingEmailJoinedLast sign-in' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + rb(w) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '').join('') : 'empty') + // readiness (2026-11-18, network hub): hottest first, stage + heat + last action + how they got here; the hub down = the old table + const RD = window.TankReady; const rdOn = RD && r.waiting.some(w => w.rd); + const wl = rdOn ? r.waiting.slice().sort((a, b) => RD.score(b) - RD.score(a)) : r.waiting; + const rs = r.readiness || {}; const rc = rs.counts || {}; const cnt = o => Object.entries(o || {}).sort((a, b) => b[1] - a[1]).map(([k, v]) => k + ' ' + v).join(', '); + $('tankAdmSub').textContent += rs.on ? (rs.ok === false ? ' · readiness: hub not answering (' + (rs.error || '') + ')' : rc.n ? ' · readiness: how they got here ' + cnt(rc.reasons) + ' · stages ' + cnt(rc.stages) + ' · heat ' + cnt(rc.bands) : ' · readiness: loading') : ' · readiness off'; + const cols = rdOn ? 5 : 4; + $('tankWait').innerHTML = 'WaitingEmailJoinedLast sign-in' + (rdOn ? 'Readiness (hottest first)' : '') + '' + (wl.length ? wl.map(w => '' + esc(w.name) + rb(w) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '' + (rdOn ? '' + (w.rd ? RD.html(w.rd) : 'no answer') + '' : '') + '').join('') : 'empty') + ((r.aligned || []).length ? 'Aligned to their network sponsor (InstantAdPay) instead of the tank' + r.aligned.slice(0, 15).map(x => '' + esc(x.email) + '' + esc(x.toName || x.to) + '' + when(x.at) + '' + esc(x.via || '') + '').join('') : ''); $('tankAdopt').innerHTML = 'MemberAdopted byWhenWindow endsStatus' + (r.adoptions.length ? r.adoptions.map(a => '' + esc(a.adopteeName) + '' + esc(a.adopterName) + '' + when(a.ts) + '' + (a.status === 'released' || a.status === 'invited' ? '' : when(a.expires)) + '' + esc(a.status) + '').join('') : 'none yet'); } catch (e) {} diff --git a/public/assets/my.js b/public/assets/my.js index ac9b207..cb501bb 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -1274,6 +1274,7 @@ } // ── holding tank: waiting members, adopt, my open adoptions ── const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; + let TANK_WARM_ONLY = false; // the "Warm or hot only" toggle on the holding tank (2026-11-18) async function loadTank() { const el = $('tankList'); if (!el) return; try { @@ -1293,10 +1294,17 @@ const opens = w => w.opensAt > Date.now(); // new sign-up: they have 24 hours to say who invited them const opensBadge = w => ' Opens in ' + holdLeft(w.opensAt - Date.now()) + ''; const readyBadge = w => w.ready ? ' Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '' : ''; - el.innerHTML = r.waiting.slice().sort((a, b) => (opens(a) ? 1 : 0) - (opens(b) ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0)).map(w => '
' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '' - + 'joined ' + ago(w.joined) + '' + // readiness (2026-11-18, network hub): hottest first inside the usual groups, a "Warm or hot" toggle, and under each lead its stage, + // heat, last action and how they got here; the hub down = the list exactly as before + const RD = window.TankReady; const rdOn = !!(RD && r.waiting.some(w => w.rd)); + const heatOrder = (a, b) => (rdOn ? RD.score(b) - RD.score(a) : 0); + const list = r.waiting.filter(w => !(rdOn && TANK_WARM_ONLY) || (w.rd && w.rd.heat && w.rd.heat.score >= 40)); + const bar = rdOn ? '
Hottest first ' + list.length + ' of ' + r.waiting.length + '
' : ''; + el.innerHTML = bar + (list.length ? list.slice().sort((a, b) => (opens(a) ? 1 : 0) - (opens(b) ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || heatOrder(a, b)).map(w => '
' + esc(w.name) + (opens(w) ? opensBadge(w) : readyBadge(w)) + '' + + 'joined ' + ago(w.joined) + (w.rd && RD ? RD.html(w.rd) : '') + '' + 'last sign-in: ' + ago(w.lastSeen) + '' - + (r.eligible && !opens(w) ? '' : '') + '
').join(''); + + (r.eligible && !opens(w) ? '' : '') + '
').join('') : '

Nobody warm or hot is waiting right now. Switch the filter off to see everyone.

'); + { const t = $('tankWarmOnly'); if (t) t.addEventListener('click', () => { TANK_WARM_ONLY = !TANK_WARM_ONLY; loadTank(); }); } el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); if (note === null) return; diff --git a/public/assets/site.css b/public/assets/site.css index 8edecbd..2eebd93 100644 --- a/public/assets/site.css +++ b/public/assets/site.css @@ -818,3 +818,19 @@ nav .links a.active{color:var(--ink);background:var(--mint-soft-2);box-shadow:in :root[data-theme="light"] body::before{opacity:.6} :root[data-theme="light"] .ghost{background:linear-gradient(180deg,rgba(23,95,216,.22),transparent 78%);-webkit-background-clip:text;background-clip:text} :root[data-theme="light"] .mockup,:root[data-theme="light"] .modal-card,:root[data-theme="light"] #status,:root[data-theme="light"] #iapChatPanel,:root[data-theme="light"] .chat-drawer{box-shadow:0 18px 50px -20px rgba(15,27,46,.35)} +/* ── holding-tank readiness (2026-11-18): stage chip, heat with its band, last action, how they got here. Theme tokens only. ── */ +.rd-line{display:flex;flex-wrap:wrap;gap:4px 6px;align-items:center;margin-top:4px;font-weight:400;white-space:normal} +.rd-stage,.rd-heat{display:inline-block;font-size:11px;line-height:1.5;padding:0 7px;border-radius:999px;border:1px solid var(--line-strong);color:var(--muted);font-weight:600;font-variant-numeric:tabular-nums} +.rd-s-warming{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)} +.rd-s-engaged{color:var(--violet);border-color:var(--violet-line);background:var(--violet-soft)} +.rd-s-activated{color:var(--mint);border-color:var(--mint-line);background:var(--mint-soft)} +.rd-s-ready{color:var(--ok,#22c55e);border-color:var(--ok,#22c55e);background:var(--ok-soft,rgba(34,197,94,.15))} +.rd-hot{color:var(--bad);border-color:var(--bad);background:var(--bad-soft,rgba(255,143,125,.12))} +.rd-warm{color:var(--amber);border-color:var(--amber-line);background:var(--amber-soft)} +.rd-cooling{color:var(--cyan);border-color:var(--cyan-line);background:var(--cyan-soft)} +.rd-cold{color:var(--muted);border-color:var(--muted-line,var(--line-strong));background:var(--muted-soft)} +.rd-last{font-size:11.5px;color:var(--muted)} +.rd-entry{display:block;font-size:11.5px;color:var(--muted);font-weight:400;white-space:normal;margin-top:2px} +.lin-row .em .rd-line,.lin-row .em .rd-entry{white-space:normal} +.lin-row.rd-row .em{white-space:normal} +.rd-bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:0 0 8px} diff --git a/public/assets/tankready.js b/public/assets/tankready.js new file mode 100644 index 0000000..6a83101 --- /dev/null +++ b/public/assets/tankready.js @@ -0,0 +1,51 @@ +// Holding-tank readiness on the tank cards (Marty 2026-11-18, stage 1 of the tank warm-up). The server attaches `rd` to each waiting +// lead from the network hub: { entry: {reason, site, at, detail}, stage, heat: {score, band, label, trend}, last: {kind, site, at} }. +// A lead without `rd` (the hub is down) renders exactly as before. Shared by InstantAdPay and LinkSpin (same file in both). +(function () { + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const SITES = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', + vbb: 'ViralBannerBlitz', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', fivex: '5xYourTeam', dh: 'DownlineHydra', downlinehydra: 'DownlineHydra', hydra: 'DownlineHydra', + ypb: 'YourProgramBuilder', yourprogrambuilder: 'YourProgramBuilder', vas: 'ViralAdSource', viraladsource: 'ViralAdSource', ctb: 'CryptoTeamBuild', + stackpol: 'Stack POL', earnerscorner: 'Earners Corner', polhunter: 'PolHunter', btc4hits: 'BTC4Hits' }; + const site = s => (s ? SITES[String(s).toLowerCase()] || String(s) : ''); + const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + const day = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getDate() + (d.getFullYear() !== new Date().getFullYear() ? ', ' + d.getFullYear() : ''); }; + const month = t => { if (!t) return ''; const d = new Date(t); return MON[d.getMonth()] + ' ' + d.getFullYear(); }; + const ago = t => { if (!t) return ''; const ms = Date.now() - t; if (ms < 3600e3) return Math.max(1, Math.round(ms / 60e3)) + ' min ago'; if (ms < 86400e3) return Math.round(ms / 3600e3) + 'h ago'; const d = Math.floor(ms / 86400e3); return d === 1 ? 'yesterday' : d + ' days ago'; }; + const who = d => (d && d.from ? ' @' + d.from : ''); + + function entryText(e) { + if (!e || !e.reason || e.reason === 'unknown') return 'How they got here: unknown'; + const d = e.detail || {}; + switch (e.reason) { + case 'joined': { + const src = [d.via ? 'via ' + d.via : '', d.ref && d.ref !== 'direct' ? 'from ' + d.ref : d.ref === 'direct' ? 'typed in directly' : ''].filter(Boolean).join(', '); + return 'Joined ' + (site(e.site) || 'the network') + ' ' + day(e.at) + ' with no sponsor' + (src ? ' (' + src + ')' : ''); + } + case 'imported': return 'Imported old member of ' + (site(d.oldSite) || 'an older network site') + (d.memberSince ? ', member since ' + month(d.memberSince) : '') + (d.lastSeenOld ? ', last seen there ' + month(d.lastSeenOld) : '') + (e.at ? ' (in the tank since ' + day(e.at) + ')' : ''); + case 'rescued': return 'Moved here ' + day(e.at) + ': their sponsor' + who(d) + ' did not reach them in 14 days'; + case 'released': return d.note ? 'Released ' + day(e.at) + ' by' + (who(d) || ' the member') + ' who had adopted them' : 'Released by their sponsor' + who(d) + ' ' + day(e.at); + case 'sponsor_gone': return 'Their sponsor left or was blocked (in the tank since ' + day(e.at) + ')'; + case 'returned': return 'Back in the tank ' + day(e.at) + ': an adoption' + (d.from ? ' by @' + d.from : '') + ' ended before they got started'; + default: return 'How they got here: unknown'; + } + } + const STAGE = { new: ['New', 'Nothing yet beyond joining'], warming: ['Warming', 'Visited or clicked a tracked link'], engaged: ['Engaged', 'Signed in or replied'], activated: ['Activated', 'Wallet linked'], ready: ['Ready', 'Bought something'] }; + const VERB = { signin: 'signed in', visit: 'visited', click: 'clicked a tracked link', wallet: 'linked a wallet', purchase: 'bought a package', upgrade: 'upgraded', message: 'replied to a message', share: 'shared a link' }; + function lastText(l) { + if (!l) return 'no activity yet'; + return (VERB[l.kind] || l.kind) + (l.site ? ' on ' + site(l.site) : '') + ', ' + ago(l.at); + } + // the block that goes under the lead's name: stage chip, heat, last action, entry reason + function html(rd) { + if (!rd) return ''; + const st = STAGE[rd.stage] || STAGE.new; const h = rd.heat || { score: 0, band: 'cold', label: 'Cold' }; + const tr = h.trend === 'up' ? ' ↗' : h.trend === 'down' ? ' ↘' : ''; + return '' + esc(st[0]) + '' + + '' + Number(h.score || 0) + ' · ' + esc(h.label || '') + tr + '' + + '' + esc(lastText(rd.last)) + '' + + '' + esc(entryText(rd.entry)) + ''; + } + const score = m => (m && m.rd && m.rd.heat ? Number(m.rd.heat.score) || 0 : -1); + window.TankReady = { html, entryText, lastText, score, stageLabel: s => (STAGE[s] || STAGE.new)[0] }; +})(); diff --git a/public/my.html b/public/my.html index c6b0ff5..6e8a37a 100644 --- a/public/my.html +++ b/public/my.html @@ -8,7 +8,7 @@ - + @@ -1020,7 +1020,8 @@ - + + diff --git a/qa/run.sh b/qa/run.sh index a1ef866..a3bccbf 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -80,6 +80,7 @@ elif [ "$MODE" = "member" ]; then node qa/networksso-hub.e2e.mjs || status=1 # the network hub as the sign-in provider: push, hub sign-in on another site, wallet partner, sign out everywhere, blocked, replay (skips without ../../network-hub) node qa/networksso-activity.test.mjs || status=1 # the hub activity ping: a signed-in page load, /api/me + heartbeat + admin portal (seen), once a day, never API/bots (real hub, skips without ../../network-hub) node qa/tank-hold.test.mjs || status=1 + node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before node qa/profile-policy.test.cjs || status=1 node qa/netconv.test.mjs || status=1 node qa/topup-positions.test.cjs || status=1 # a top-up the ad's position cannot cover offers the position that can, then moves the ad there (Michael Camire 2026-11-14) @@ -95,6 +96,7 @@ elif [ "$MODE" = "hubsync" ]; then node qa/hubsync.test.cjs || status=1 # needs a network-hub checkout with /v1/resolve {id}: HUB_DIR= elif [ "$MODE" = "tankhold" ]; then node qa/tank-hold.test.mjs || status=1 + node qa/tank-readiness.test.mjs || status=1 # holding tank readiness (2026-11-18): entry reasons, stage, heat against a LOCAL network hub; hub down = card as before elif [ "$MODE" = "nas" ]; then node qa/nas-stop.test.cjs || status=1 node qa/nas-ratio.test.cjs || status=1 diff --git a/qa/tank-readiness.test.mjs b/qa/tank-readiness.test.mjs new file mode 100644 index 0000000..553728a --- /dev/null +++ b/qa/tank-readiness.test.mjs @@ -0,0 +1,82 @@ +// Holding-tank readiness (2026-11-18): the site module against a REAL local network hub (its own temp data dir, throwaway people), +// never production. Checks the entry reasons this site derives from its own records, the signed call, the cache, and that the +// hub being down leaves the tank list exactly as it was. No mail module is even loaded. +// node qa/tank-readiness.test.mjs (HUB_DIR = the network-hub checkout, default ../../network-hub) +import { createRequire } from 'module'; +import fs from 'fs'; import os from 'os'; import path from 'path'; import assert from 'assert'; +const require = createRequire(import.meta.url); +const HUB_DIR = process.env.HUB_DIR || path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '../../../network-hub'); +const SECRET = 'q'.repeat(40); +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'hub-rdy-')); +process.env.HUB_SITES = JSON.stringify({ iap: { secret: SECRET, seeEmails: true } }); +process.env.HUB_ADMIN_SECRET = 'z'.repeat(40); +delete process.env.DATABASE_URL; + +const hubStore = require(path.join(HUB_DIR, 'lib/store')); +const hubPeople = require(path.join(HUB_DIR, 'lib/people')); +const hubAct = require(path.join(HUB_DIR, 'lib/activity')); +const { start } = require(path.join(HUB_DIR, 'server')); +const TR = require('../tankready.js'); + +let pass = 0; const ok = (c, m) => { assert.ok(c, m); pass++; console.log(' ok', m); }; +const DAY = 86400000; const now = Date.now(); + +// the hub knows two of the leads: one imported from an old site, one who signed in on LinkSpin yesterday +hubPeople.importRows([{ email: 'old@t.test', username: 'oldtimer', joinedAt: now - 500 * DAY }], 'vbb'); +const live = hubPeople.join({ site: 'iap', email: 'live@t.test', username: 'livewire' }).person; +hubAct.record(live.id, 'linkspin', 'signin', now - DAY, now); +hubPeople.join({ site: 'iap', email: 'spons@t.test', username: 'sponsorx' }); + +const server = await start(0); const port = server.address().port; +process.env.HUB_URL = 'http://127.0.0.1:' + port; process.env.HUB_SECRET = SECRET; process.env.HUB_SITE = 'iap'; process.env.HUB_ENABLED = '1'; + +// a fake site: accounts, tank waiting list, adoption history, follow records +const accts = { + 'old@t.test': { email: 'old@t.test', username: 'oldtimer', created: now - 3 * DAY, joinedVia: 'hub', joinedRef: 'hub:vbb' }, + 'live@t.test': { email: 'live@t.test', username: 'livewire', created: now - 10 * DAY, joinedVia: 'page', joinedRef: 'viefaucet.com', lastSeen: now - 2 * 3600e3 }, + 'resc@t.test': { email: 'resc@t.test', username: 'rescued1', created: now - 30 * DAY }, + 'dead@t.test': { email: 'dead@t.test', username: 'deadlink', created: now - 30 * DAY }, + 'b4h@t.test': { email: 'b4h@t.test', created: now - 7 * DAY, joinedVia: 'btc4hits', joinedRef: 'btc4hits' }, + 'back@t.test': { email: 'back@t.test', username: 'backagain', created: now - 40 * DAY }, + 'spons@t.test': { email: 'spons@t.test', username: 'sponsorx' } +}; +const waiting = ['old@t.test', 'live@t.test', 'resc@t.test', 'dead@t.test', 'b4h@t.test', 'back@t.test'].map(e => ({ email: e, name: '@' + (accts[e].username || 'x'), joined: accts[e].created, lastSeen: accts[e].lastSeen || 0, wallet: e === 'live@t.test' })); +const hist = new Map([ + ['resc@t.test', [{ adopter: 'spons@t.test', ts: now - 4 * DAY, status: 'rescued', closed: null }]], + ['dead@t.test', [{ adopter: 'dead:gone99', ts: now - 5 * DAY, status: 'rescued', closed: null }]], + ['back@t.test', [{ adopter: 'spons@t.test', ts: now - 20 * DAY, status: 'rescued' }, { adopter: 'spons@t.test', ts: now - 15 * DAY, status: 'expired', closed: now - 8 * DAY }]] +]); +let calls = 0; +TR.init({ site: 'iap', accounts: { byEmail: async e => accts[e] || null }, tank: { waiting: async () => { calls++; return waiting; }, historyMap: async () => hist }, followGet: () => null }); + +console.log('tank readiness: local hub on :' + port); +const c = await TR.refresh(); +ok(c && c.by.size === 6, 'one call returned readiness for all six leads'); +const get = e => c.by.get(e); +ok(get('old@t.test').entry.reason === 'imported' && get('old@t.test').entry.detail.oldSite === 'vbb', 'hub-made account: the hub says imported from ViralBannerBlitz with the old join date'); +ok(get('live@t.test').entry.reason === 'joined' && get('live@t.test').entry.detail.ref === 'viefaucet.com', 'joined with no sponsor, with the source'); +ok(get('live@t.test').stage === 'activated' && get('live@t.test').heat.score >= 40, 'wallet linked = Activated, signed in recently = warm or hot (' + get('live@t.test').heat.score + ')'); +ok(get('live@t.test').last.kind === 'signin' && get('live@t.test').last.site === 'iap', 'last action: the site sign-in 2 hours ago beats the LinkSpin one yesterday'); +ok(get('resc@t.test').entry.reason === 'rescued' && get('resc@t.test').entry.detail.from === 'sponsorx', 'rescued, naming the sponsor by username'); +ok(get('dead@t.test').entry.reason === 'sponsor_gone' && !get('dead@t.test').entry.detail.from, 'dead sponsor link: sponsor gone, no name'); +ok(get('b4h@t.test').entry.reason === 'imported' && get('b4h@t.test').entry.detail.oldSite === 'BTC4Hits', 'BTC4Hits import (not on the hub: the site report alone)'); +ok(get('back@t.test').entry.reason === 'returned', 'back after an adoption window ended (newest record wins)'); +ok(get('b4h@t.test').stage === 'new' && get('b4h@t.test').heat.band === 'cold' && get('b4h@t.test').last === null, 'never seen: New, Cold, no activity'); +const txt = JSON.stringify([...c.by.values()]); +ok(!/@t\.test/.test(txt), 'no email in anything the hub sent back'); +ok(!JSON.stringify(hubStore.all().map(p => p.tankEntry || null)).includes('@'), 'no email stored in the entry facts on the hub'); +ok(hubPeople.byEmail('live@t.test').tankEntry && hubPeople.byEmail('live@t.test').tankEntry.reason === 'joined', 'the entry fact is recorded on the hub'); + +const att = await TR.attach(waiting); +ok(att.every(w => w.rd) && calls === 1, 'attach uses the fresh cache, no second call'); +ok(waiting.every(w => !w.rd), 'the original rows are not changed'); + +// the hub goes away: the card shows the rows as before (after the cache is gone) +server.close(); TR._reset(); +const down = await TR.attach(waiting, 1500); +ok(down.length === 6 && down.every(w => !w.rd), 'hub down: the same rows, no extras, no error'); +ok(TR.status().ok === false, 'status says the hub is not answering'); +process.env.HUB_ENABLED = '0'; TR._reset(); +ok((await TR.attach(waiting)) === waiting, 'switched off: untouched'); +console.log('tank readiness: ALL PASSED (' + pass + ')'); +process.exit(0); diff --git a/server.js b/server.js index 7a4c3e5..886b23d 100644 --- a/server.js +++ b/server.js @@ -35,6 +35,7 @@ const netkb = require('./netkb'); // the shared network KB on the hub; suggest() const kb = require('./kb'); // the assistant's knowledge base: Admin > Knowledge base, seeded from chatbot.js CANNED + kb-seed.js (2026-10-20) const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward +const tankready = require('./tankready'); // holding-tank readiness from the network hub (2026-11-18): entry reason, stage, heat, last action on the tank cards. No mail. const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) const promos = require('./promos'); // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box) @@ -788,6 +789,7 @@ async function boot() { zonereport.init({ dataDir: DATA_DIR }); snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, accounts, rotator, bannerspin, zones, pages, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } }); setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); + tankready.init({ site: 'linkspin', accounts, tank, followGet: e => followStore.get(e) }); // read-only: sends this site's facts, keeps the hub's answer for the tank cards tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore, // network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never // bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held) @@ -1334,6 +1336,7 @@ async function tankAdminAlert(text) { // tank are announced by InstantAdPay, not twice) async function tankReadyTick() { const r = await tank.readyTick(); + tankready.refresh().catch(() => {}); // readiness: send the hub this site's entry facts and refresh the card cache (no mail, no sponsor change) if (r.aligned || r.assigned.length || r.held || r.deferred || r.fresh.length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, deferred: r.deferred })); const sc = siteConfig(); if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r; @@ -2627,7 +2630,8 @@ const server = http.createServer(async (req, res) => { 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.' }); - return json(res, 200, await tank.view(s.email)); + const v = await tank.view(s.email); v.waiting = await tankready.attach(v.waiting); // readiness (hub): entry, stage, heat, last action + return json(res, 200, v); } // -- achievement badge -> Telegram (payments topic + the main group), once per badge per member. // The browser composes the personalised image (canvas, same as Share) and posts it here. @@ -2738,7 +2742,8 @@ const server = http.createServer(async (req, res) => { } if (p === '/api/admin/tank' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await tank.adminView()); + const v = await tank.adminView(); v.waiting = await tankready.attach(v.waiting); v.readiness = Object.assign(tankready.status(), { counts: tankready.counts() }); + return json(res, 200, v); } // -- admin Traffic tab: page views + join-page views + signups + $25 buyers, by referring // domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12) diff --git a/tankready.js b/tankready.js new file mode 100644 index 0000000..bdb2d7e --- /dev/null +++ b/tankready.js @@ -0,0 +1,125 @@ +'use strict'; +// Holding-tank readiness (Marty 2026-11-18, stage 1 of the tank warm-up; review page claude.ai/artifact/76vTtcB67KJNopG3KZu5ca). +// What an adopting sponsor sees on each waiting lead: how they got into the tank, how far along they are (New, Warming, Engaged, +// Activated, Ready), a 0-100 heat score with its band, and their last real action. The network hub computes it +// (POST /v1/tank/readiness, the one heat formula in network-hub lib/heat.js); this module sends the hub what only this +// site knows (its own last sign-in, a linked wallet, and the entry reason from its adoption records and join data) and keeps +// the answer in memory for the tank card. +// +// NO EMAIL, NO MESSAGE, NO SPONSOR CHANGE: read-only here; the hub stores only the entry fact. The hub down = no extras, the tank +// card works exactly as before. The same file runs on InstantAdPay and LinkSpin (deps.site names the site; copy changes to both). +const crypto = require('crypto'); + +const FRESH_MS = 5 * 60 * 1000; // a cached answer this young is used as is +const STALE_MS = 6 * 3600 * 1000; // an older one is still shown while a refresh runs, never past this +const DOWN_MS = 2 * 60 * 1000; // the hub failed: no new try for this long +let R = null; // deps: { site, accounts, tank, followGet(email) } +let cache = { at: 0, by: new Map() }; let busy = null; let downUntil = 0; let last = { at: 0, ok: null, n: 0, ms: 0, error: null, recorded: 0 }; + +const on = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_ENABLED || '')) && String(process.env.HUB_READINESS || '1') !== '0' + && !!process.env.HUB_URL && String(process.env.HUB_SECRET || '').length >= 32 && typeof fetch === 'function'; +const lc = v => String(v || '').trim().toLowerCase(); +function init(deps) { R = deps; } + +async function hubPost(p, body, timeout) { + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', process.env.HUB_SECRET).update(ts + '\n' + raw).digest('hex'); + const r = await fetch(String(process.env.HUB_URL).replace(/\/+$/, '') + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': process.env.HUB_SITE || R.site, 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeout || 20000) }); + let j = null; try { j = await r.json(); } catch (e) {} + if (r.status !== 200) throw new Error('hub ' + p + ' ' + r.status + (j && j.error ? ' ' + j.error : '')); + return j; +} + +// ── how they got into the tank, from this site's own records ── +// adoption history (tank.historyMap: newest 6 per person: adopter, ts, status, closed, note), the sponsor-follow record (a move +// made on the other platform), and the join data. Sponsor emails never leave the site: a username, or nothing. +const ENTRY_STATUS = { rescued: 'rescued', released: 'released', dropped: 'released', expired: 'returned', unreached: 'returned' }; +const LATER = new Set(['open', 'done', 'invited', 'gift', 'moved', 'conflict']); // a sponsor came after: that entry is over +const FOLLOW_BY = { rescue: 'rescued', release: 'released', expire: 'returned', expiry: 'returned' }; +const IMPORTS = { btc4hits: 'BTC4Hits', faucetwave: 'FaucetWave', socialpix: 'SocialPix' }; +async function nameOfEmail(email) { + if (!email || String(email).startsWith('dead:')) return null; + try { const a = await R.accounts.byEmail(lc(email)); return a && a.username ? a.username : null; } catch (e) { return null; } +} +async function localEntry(a, hist, pv) { + const rows = (hist || []).slice().sort((x, y) => (x.closed || x.ts || 0) - (y.closed || y.ts || 0)); + let best = null; + for (const h of rows) { + if (ENTRY_STATUS[h.status]) { + const dead = h.status === 'rescued' && String(h.adopter || '').startsWith('dead:'); + best = { reason: dead ? 'sponsor_gone' : ENTRY_STATUS[h.status], at: Number(h.status === 'rescued' || h.status === 'released' ? h.ts : (h.closed || h.ts)) || 0, adopter: h.adopter, status: h.status }; + } else if (LATER.has(h.status) && best && (h.ts || 0) >= best.at) best = null; + } + // a move made on the other platform that left them with no sponsor here (sponsorfollow), when newer + if (pv && !pv.sponsorEmail && FOLLOW_BY[pv.by] && Number(pv.at) > (best ? best.at : 0)) best = { reason: FOLLOW_BY[pv.by], at: Number(pv.at), adopter: pv.prevEmail || null, site: ({ instantadpay: 'iap', linkspin: 'linkspin' })[lc(pv.origin)] || null }; + if (best) { + const from = best.reason === 'sponsor_gone' ? null : await nameOfEmail(best.adopter); + const detail = {}; if (from) detail.from = from; + if (best.reason === 'sponsor_gone') detail.note = 'their sponsor link no longer leads to a member'; + if (best.status === 'dropped') detail.note = 'released by the member who adopted them'; + return { reason: best.reason, at: best.at, site: best.site || undefined, detail }; + } + const via = lc(a.joinedVia); const ref = lc(a.joinedRef); + if (via === 'hub') return null; // made here for someone who joined elsewhere on the network: the hub knows their first door + if ((via === 'linkspin' || via === 'instantadpay' || via === 'carried') && ref !== 'btc4hits') return null; // a copy of an account from the other platform (LinkSpin: 'carried'): same, the hub knows + const leg = /^legacy:([a-z0-9]+)/.exec(ref); + if (via === 'btc4hits' || ref === 'btc4hits') return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: 'BTC4Hits' } }; + if (leg) return { reason: 'imported', at: Number(a.created) || 0, detail: { oldSite: IMPORTS[leg[1]] || leg[1] } }; + const detail = {}; if (via) detail.via = via; if (ref && !/^hub:/.test(ref)) detail.ref = ref.slice(0, 80); + return { reason: 'joined', at: Number(a.created) || 0, detail }; +} + +// one call for the whole waiting list (a few thousand rows at most) +async function refresh() { + if (!R || !on()) return null; + if (busy) return busy; + busy = (async () => { + const t0 = Date.now(); + try { + const list = await R.tank.waiting(); + const hist = R.tank.historyMap ? await R.tank.historyMap() : new Map(); + const accts = new Map(); + const rows = []; + for (const w of list) { + const a = (await R.accounts.byEmail(w.email)) || { email: w.email, created: w.joined }; + accts.set(w.email, a); + let pv = null; try { pv = R.followGet ? R.followGet(w.email) : null; } catch (e) {} + rows.push({ email: w.email, seenAt: w.lastSeen || 0, wallet: !!w.wallet, entry: await localEntry(a, hist.get(w.email), pv) || undefined }); + } + const r = rows.length ? await hubPost('/v1/tank/readiness', { rows }, 30000) : { rows: [] }; + const by = new Map(); + for (const x of (r.rows || [])) { const src = rows[x.i]; if (src) by.set(src.email, { entry: x.entry, stage: x.stage, heat: x.heat, last: x.last, onHub: !!x.onHub }); } + cache = { at: Date.now(), by }; + last = { at: Date.now(), ok: true, n: by.size, ms: Date.now() - t0, error: null, recorded: r.recorded || 0 }; + return cache; + } catch (e) { + downUntil = Date.now() + DOWN_MS; last = { at: Date.now(), ok: false, n: 0, ms: Date.now() - t0, error: e.message, recorded: 0 }; + console.error('tankready', e.message); + return null; + } finally { busy = null; } + })(); + return busy; +} + +// the readiness for these waiting rows, as rows with `rd` added. Waits for the hub only when nothing usable is cached, and then +// at most `waitMs`; otherwise answers from the cache and refreshes in the background. +async function attach(list, waitMs) { + if (!R || !on() || !Array.isArray(list)) return list; + const age = Date.now() - cache.at; + if (age > FRESH_MS && Date.now() > downUntil) { + const p = refresh(); + if (age > STALE_MS && p) await Promise.race([p, new Promise(res => setTimeout(res, waitMs || 4000))]); + } + if (Date.now() - cache.at > STALE_MS) return list; + return list.map(w => { const x = cache.by.get(w.email); return x ? Object.assign({}, w, { rd: x }) : w; }); +} + +const status = () => Object.assign({ on: on(), cached: cache.by.size, cachedAt: cache.at || null }, last); +// counts for the report: entry reasons and stages across the cached tank +function counts() { + const reasons = {}; const stages = {}; const bands = {}; + for (const x of cache.by.values()) { reasons[x.entry.reason] = (reasons[x.entry.reason] || 0) + 1; stages[x.stage] = (stages[x.stage] || 0) + 1; bands[x.heat.band] = (bands[x.heat.band] || 0) + 1; } + return { at: cache.at, n: cache.by.size, reasons, stages, bands }; +} + +module.exports = { init, refresh, attach, status, counts, localEntry, _reset: () => { cache = { at: 0, by: new Map() }; downUntil = 0; busy = null; } };