Sponsor autopilot (sponsorpilot.js): writes to a named sponsor's free directs as the sponsor so they are contacted before the tank rule moves them; paced, 8 AM to 8 PM CT, four messages at most, a reply stops it and pings the owner; switch pilotOn default off (Marty 2026-11-25)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-25 08:31:35 -06:00
parent aae83329da
commit 563407e45b
4 changed files with 347 additions and 0 deletions
+2
View File
@@ -76,6 +76,7 @@ elif [ "$MODE" = "member" ]; then
node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock node qa/networksso-partner.e2e.mjs || status=1 # a partner wallet site (5xYourTeam pattern) through this site: signed in -> straight back; signed out -> sign-in, login ad, Continue -> back; the login-ad clock
node qa/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-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/tank-hold.mjs || status=1 node qa/tank-hold.mjs || status=1
node qa/sponsor-pilot.test.mjs || status=1 # sponsor autopilot: switch off = nothing, pace, cadence, exclusions, reply stops it
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
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/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/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825) node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
@@ -105,6 +106,7 @@ elif [ "$MODE" = "walletnudge" ]; then
node qa/walletnudge.test.cjs || status=1 node qa/walletnudge.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.mjs || status=1 node qa/tank-hold.mjs || status=1
node qa/sponsor-pilot.test.mjs || status=1 # sponsor autopilot: switch off = nothing, pace, cadence, exclusions, reply stops it
node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap node qa/tank-batch.test.mjs || status=1 # holding tank batches: ladder, switch off = no writes, rotation, grace, cadence, follow-up, separate 5x cap
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/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" = "sponsorfollow" ]; then elif [ "$MODE" = "sponsorfollow" ]; then
+133
View File
@@ -0,0 +1,133 @@
// Sponsor autopilot (sponsorpilot.js, Marty 2026-11-25). No server: the real module with in-memory accounts, messages and mail
// on a throwaway dir, mocked clock. node qa/sponsor-pilot.test.mjs
// Covers: switch off = nothing sent or written; only free directs of the named sponsor; first touch after 2 days, later ones
// every 6, four at most, a different message each time; pace (one per tick, gap, day cap, 8 AM to 8 PM Central); a hand-written
// sponsor message postpones the next touch; never-mail people skipped; one send across two app copies (claim); a reply stops
// the automatics and pings once; the copy has no em dashes and no income promise.
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, MIN = 60000;
const P = require(path.join(SITE, 'sponsorpilot.js'));
// noon Central on a fixed day (CST = UTC-6)
let now = Date.UTC(2026, 10, 25, 18, 0, 0);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pilot-'));
const acc = new Map(); const add = a => { acc.set(a.email, Object.assign({ created: now - 30 * DAY, lastSeen: 0, memberId: 0, address: '', sponsorRef: '', username: a.email.split('@')[0] }, a)); };
add({ email: 'marty@x.test', username: 'martbost', memberId: 1, address: '0xabc' });
add({ email: 'other@x.test', username: 'othersp', memberId: 9, address: '0xdef' });
add({ email: 'a@x.test', sponsorRef: 'martbost', created: now - 12 * DAY }); // most overdue
add({ email: 'b@x.test', sponsorRef: 'martbost', created: now - 5 * DAY });
add({ email: 'c@x.test', sponsorRef: 'martbost', created: now - 1 * DAY }); // too new (first touch after 2 days)
add({ email: 'w@x.test', sponsorRef: 'martbost', address: '0x111' }); // wallet linked: not at risk
add({ email: 'm@x.test', sponsorRef: 'martbost', memberId: 44 }); // member: not at risk
add({ email: 'u@x.test', sponsorRef: 'martbost', created: now - 9 * DAY }); // unsubscribed
add({ email: 'f@x.test', sponsorRef: 'martbost', created: now - 9 * DAY }); // flagged
add({ email: 'q@x.test', sponsorRef: 'martbost', created: now - 9 * DAY, mutes: ['marty@x.test'] });
add({ email: 'z@x.test', sponsorRef: 'othersp', created: now - 12 * DAY }); // someone else's direct
const chats = []; const mails = []; const pings = []; const claimed = new Set(); let site = { pilotOn: '0', pilotSponsors: 'martbost' };
const accounts = {
byEmail: async e => acc.get(String(e).toLowerCase()) || null,
byUsername: async u => [...acc.values()].find(a => a.username === u) || null,
downline: async e => { const sp = acc.get(e); return [{ members: [...acc.values()].filter(a => a.sponsorRef === sp.username) }]; },
getMutes: async e => (acc.get(e) || {}).mutes || []
};
const messages = {
sendChat: async (m, from, to, body) => { chats.push({ from, to, body, sent: now }); return { id: chats.length, sent: now }; },
lastFrom: async (from, to) => chats.filter(c => c.from === from && c.to === to).reduce((mx, c) => Math.max(mx, c.sent), 0)
};
const mailer = { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); return true; } };
const noon = () => { now = now - (now % DAY) + 18 * H + DAY; }; // next day, noon Central: keeps every block inside the sending hours
const boot = () => P.init({ dataDir: dir, db: { enabled: () => false }, accounts, messages, mailer, siteConfig: () => site, clock: () => now,
brand: { name: 'InstantAdPay', url: 'https://instantadpay.com/my' }, online: () => false,
hooks: { excluded: em => em === 'f@x.test', excludedPerson: async em => (em === 'u@x.test' ? 'unsubscribed' : null),
claim: async k => { if (claimed.has(k)) return false; claimed.add(k); return true; }, notify: async t => { pings.push(t); } } });
await boot();
// ---- copy ----
{
const all = P.TOUCHES.map((_, i) => P.render(i, { username: 'sam' })).join('\n');
ok(P.TOUCHES.length === 4 && new Set(P.TOUCHES).size === 4, 'four different messages');
ok(!/—|--/.test(all), 'no em dashes in the copy');
ok(!/guarantee|you will earn|you will make|passive income|\$\d/i.test(all), 'no income promise or dollar figure in the copy');
ok(/Hi sam,/.test(all) && !/\{name\}|\{site\}|\{url\}/.test(all), 'placeholders filled');
ok(/Hi there,/.test(P.render(0, {})), 'no username: "Hi there"');
}
// ---- switch off ----
{
const r = await P.tick();
ok(r.off && chats.length === 0 && mails.length === 0 && !fs.existsSync(path.join(dir, 'sponsor-pilot.json')), 'switch off: nothing sent, nothing written', r);
const v = await P.view();
ok(v.sponsors.length === 1 && v.sponsors[0].stats.free === 6 && v.sponsors[0].stats.due === 5, 'preview while off: 6 free directs, 5 past the 2 days (never-mail people are only dropped at send time)', v.sponsors[0]);
ok(!JSON.stringify(v).includes('@x.test'), 'preview prints no email address');
}
// ---- on: order, pace, exclusions ----
site.pilotOn = '1';
{
let r = await P.tick();
ok(r.sent === 1 && chats.length === 1 && chats[0].to === 'a@x.test' && chats[0].from === 'marty@x.test', 'first send goes to the most overdue direct, as the sponsor', chats[0]);
ok(mails.length === 1 && mails[0].to === 'a@x.test' && /New message from @martbost/.test(mails[0].subject) && /Reply in your dashboard/.test(mails[0].body), 'the email goes with it', mails[0]);
r = await P.tick();
ok(r.sent === 0 && chats.length === 1, 'pace: nothing more inside the gap');
ok(P._gapMs(P.cfg()) === 12 * MIN, '60 a day over 12 hours = one every 12 minutes', P._gapMs(P.cfg()));
now += 13 * MIN; r = await P.tick();
ok(r.sent === 1 && chats[1].to === 'b@x.test', 'next tick after the gap: the next most overdue (never-mail people skipped on the way)', [r, chats[1] && chats[1].to]);
now += 13 * MIN; r = await P.tick();
ok(r.sent === 0 && chats.length === 2, 'c joined yesterday, the wallet and member directs, the unsubscribed, flagged and muted ones and the other sponsor\'s direct get nothing', chats.map(c => c.to));
}
// ---- two app copies: one send ----
{
add({ email: 'd@x.test', sponsorRef: 'martbost', created: now - 4 * DAY });
now += 31 * MIN; claimed.add('pilot:d@x.test:0'); // the other copy already took this touch
const r = await P.tick();
ok(r.sent === 0 && !chats.some(c => c.to === 'd@x.test'), 'a touch another copy claimed is not sent twice', r);
claimed.delete('pilot:d@x.test:0'); acc.get('d@x.test').address = '0x9'; // and now they linked a wallet: out of scope
}
// ---- cadence: later touches every 6 days, a new message each time, four at most ----
{
now += 5 * DAY - 2 * H; const a0 = chats.filter(c => c.to === 'a@x.test').length; for (let i = 0; i < 4; i++) { await P.tick(); now += 13 * MIN; }
ok(chats.filter(c => c.to === 'a@x.test').length === a0, 'day 5 after the first touch: nothing more for a yet');
const sentTo = async who => { noon(); const n0 = chats.filter(c => c.to === who).length; for (let i = 0; i < 6; i++) { await P.tick(); now += 13 * MIN; } return chats.filter(c => c.to === who).length - n0; };
now += 1 * DAY; ok(await sentTo('a@x.test') === 1, 'day 6: second touch to a');
const bodies = () => chats.filter(c => c.to === 'a@x.test').map(c => c.body);
ok(bodies()[1] !== bodies()[0] && /link a wallet/.test(bodies()[1]), 'the second message is the wallet one');
now += 6 * DAY; await sentTo('a@x.test'); now += 6 * DAY; await sentTo('a@x.test'); now += 6 * DAY; await sentTo('a@x.test'); now += 6 * DAY; await sentTo('a@x.test');
ok(bodies().length === 4 && new Set(bodies()).size === 4, 'four touches, four different messages, then it stops', bodies().length);
const v = await P.view(); ok(v.sponsors[0].stats.finished >= 1, 'the preview counts them as finished');
}
// ---- a hand-written sponsor message postpones the automatic one ----
{
add({ email: 'h@x.test', sponsorRef: 'martbost', created: now - 20 * DAY });
noon(); chats.push({ from: 'marty@x.test', to: 'h@x.test', body: 'hand written', sent: now - 1 * DAY });
now += 31 * MIN; for (let i = 0; i < 4; i++) { await P.tick(); now += 13 * MIN; }
ok(chats.filter(c => c.to === 'h@x.test').length === 1, 'sponsor wrote by hand yesterday: no automatic message on top');
}
// ---- a reply stops the automatics and pings once ----
{
noon(); add({ email: 'r@x.test', sponsorRef: 'martbost', created: now - 4 * DAY });
now += 31 * MIN; for (let i = 0; i < 4; i++) { await P.tick(); now += 13 * MIN; }
ok(chats.filter(c => c.to === 'r@x.test').length === 1, 'r got the first touch');
ok(await P.onChat('r@x.test', 'marty@x.test', 'How do I link a wallet?') === true && pings.length === 1 && /@r answered/.test(pings[0]) && !/x\.test/.test(pings[0]), 'reply: recorded, owner pinged once, no email in the ping', pings);
ok(await P.onChat('r@x.test', 'marty@x.test', 'hello?') === false && pings.length === 1, 'a second reply does not ping again');
ok(await P.onChat('z@x.test', 'other@x.test', 'hi') === false && await P.onChat('never-touched@x.test', 'marty@x.test', 'hi') === false, 'other sponsors and untouched people are ignored');
now += 7 * DAY; noon(); for (let i = 0; i < 4; i++) { await P.tick(); now += 13 * MIN; }
ok(chats.filter(c => c.to === 'r@x.test').length === 1, 'no automatic message after they answered');
}
// ---- hours and the day cap ----
{
add({ email: 'n@x.test', sponsorRef: 'martbost', created: now - 4 * DAY });
const saved = now; now = Date.UTC(2027, 0, 20, 9, 0, 0); // 3 AM Central
ok((await P.tick()).sent === 0 && !chats.some(c => c.to === 'n@x.test'), 'outside 8 AM to 8 PM Central: nothing');
now = Date.UTC(2027, 0, 20, 18, 0, 0); site.pilotPerDay = 1;
for (const e of ['n2@x.test', 'n3@x.test']) add({ email: e, sponsorRef: 'martbost', created: now - 4 * DAY });
let sent = 0; for (let i = 0; i < 5; i++) { sent += (await P.tick()).sent || 0; now += 3 * H / 5; }
ok(sent === 1, 'day cap 1: one message that Central day', sent);
now = saved; delete site.pilotPerDay;
}
console.log('\n' + passes + ' passed, ' + fails + ' failed');
process.exit(fails ? 1 : 0);
+11
View File
@@ -57,6 +57,7 @@ const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23) const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07) const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const sponsorpilot = require('./sponsorpilot'); // sponsor autopilot (2026-11-25): switch pilotOn, default off
const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off const tankbatch = require('./tankbatch'); // holding tank batches (2026-11-15): switch tankBatches, default off
const siteinvite = require('./siteinvite'); // sponsor invite emails for other network sites (Video App Income, Marty approved 2026-11-20): signed eligible / send, needs SITE_INVITE_SECRET const siteinvite = require('./siteinvite'); // sponsor invite emails for other network sites (Video App Income, Marty approved 2026-11-20): signed eligible / send, needs SITE_INVITE_SECRET
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET) const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
@@ -932,6 +933,13 @@ async function boot() {
await siteinvite.init({ dataDir: DATA_DIR, accounts, mailer, siteConfig, prohibited, await siteinvite.init({ dataDir: DATA_DIR, accounts, mailer, siteConfig, prohibited,
hooks: { excluded: em => fraud.excluded(em), suggestDomain: d => require('./emailcheck').suggestDomain(d), erased: em => erase.isErased(em), hooks: { excluded: em => fraud.excluded(em), suggestDomain: d => require('./emailcheck').suggestDomain(d), erased: em => erase.isErased(em),
excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; } } }).catch(e => console.error('siteinvite init', e.message)); } excludedPerson: async em => { if (spamSet().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed from email'; return null; } } }).catch(e => console.error('siteinvite init', e.message)); }
// sponsor autopilot (sponsorpilot.js, 2026-11-25): writes to the named sponsors' free directs as the sponsor, paced, 8 AM to 8 PM CT; nothing while pilotOn is off
{ let spamP = { at: 0, set: new Set() }; const spamSetP = () => { if (Date.now() - spamP.at > 60000) { try { spamP = { at: Date.now(), set: new Set((((spamscan.view() || {}).last || {}).candidates || []).map(c => String(c.email || '').toLowerCase())) }; } catch (e) { spamP = { at: Date.now(), set: new Set() }; } } return spamP.set; };
await sponsorpilot.init({ dataDir: DATA_DIR, db, accounts, messages, mailer, tank, siteConfig, brand: { name: 'InstantAdPay', url: 'https://instantadpay.com/my' }, online: ls => chatOnline(ls),
hooks: { excluded: em => fraud.excluded(em), claim: key => marks.claim(key),
excludedPerson: async em => { if (spamSetP().has(em)) return 'spam scan'; const d = String(em).split('@')[1] || ''; const fix = require('./emailcheck').suggestDomain(d); if (fix && fix !== d) return 'mistyped email domain'; if (erase.isErased(em)) return 'erased'; if (await drip.isUnsubscribed(em).catch(() => false)) return 'unsubscribed'; return null; },
notify: async text => { const sc = siteConfig(); const chat = String(sc.telegramAdminChatId || '1289244227').trim(); if (sc.telegramBotToken) return telegramSend(chat, text); } } }); }
setInterval(() => sponsorpilot.tick().then(r => { if (r && r.sent) console.log('sponsorpilot sent', r.sent); }).catch(e => console.error('sponsorpilot', e.message)), 60 * 1000);
setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window setTimeout(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 4 * 60 * 1000); // past the deploy overlap window
setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000); setInterval(() => tankbatch.tick().catch(e => console.error('tankbatch', e.message)), 60 * 60 * 1000);
setInterval(() => tankbatch.mailTick().catch(e => console.error('tankbatch mail', e.message)), 60 * 1000); // throttled batch emails (tankBatchEmailsPerDay, 8 AM to 8 PM CT) + spaced Telegram cards setInterval(() => tankbatch.mailTick().catch(e => console.error('tankbatch mail', e.message)), 60 * 1000); // throttled batch emails (tankBatchEmailsPerDay, 8 AM to 8 PM CT) + spaced Telegram cards
@@ -1011,6 +1019,7 @@ function siteConfig() {
tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11 tankAdoptCap: 10, // holding tank: people one adopter may hold at one time (not yet switched on payouts), Marty 2026-11-11
fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches fiveXDraftCap: 10, // 5xYourTeam draft: open picks one coach may hold, its own cap (Marty 2026-11-15), never shared with tankAdoptCap or batches
...siteinvite.DEFAULTS, // sponsor invite emails for other network sites (siteinvite.js): siteInvitesPaused '1' stops them; per-sender and all-senders daily caps ...siteinvite.DEFAULTS, // sponsor invite emails for other network sites (siteinvite.js): siteInvitesPaused '1' stops them; per-sender and all-senders daily caps
...sponsorpilot.DEFAULTS, // sponsor autopilot (sponsorpilot.js, Marty 2026-11-25): master switch pilotOn '0', pilotSponsors = usernames
...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up ...tankbatch.DEFAULTS, // holding tank batches (tankbatch.js, Marty 2026-11-15): master switch tankBatches '0'; every number of the ladder, cadence and follow-up
legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand> legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/<brand>
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
@@ -4035,6 +4044,7 @@ const server = http.createServer(async (req, res) => {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await draftpartner.adminView()); return json(res, 200, await draftpartner.adminView());
} }
if (p === '/api/admin/pilot' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await sponsorpilot.view()); } // sponsor autopilot: read-only state + the messages
if (p === '/api/admin/tank/batches/preview' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.preview()); } // read-only: no writes, no mail if (p === '/api/admin/tank/batches/preview' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.preview()); } // read-only: no writes, no mail
if (p === '/api/admin/tank/batches/mail' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.mailView()); } // queued, sent today, next send time if (p === '/api/admin/tank/batches/mail' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.mailView()); } // queued, sent today, next send time
if (p === '/api/admin/tank/batches/mail' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await tankbatch.setPaused(!!(b && b.paused))); } // pause / resume if (p === '/api/admin/tank/batches/mail' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await tankbatch.setPaused(!!(b && b.paused))); } // pause / resume
@@ -5328,6 +5338,7 @@ const server = http.createServer(async (req, res) => {
return json(res, 403, { error: 'They are not accepting messages from you right now.' }); return json(res, 403, { error: 'They are not accepting messages from you right now.' });
const memberId = s.memberId || await auth.refreshMemberId(s); const memberId = s.memberId || await auth.refreshMemberId(s);
const msg = await messages.sendChat(memberId, me, to, text); const msg = await messages.sendChat(memberId, me, to, text);
sponsorpilot.onChat(me, to, text).catch(() => {}); // a referral answering an automatic sponsor message: stop the automatics, ping the owner once
// email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam) // email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam)
try { try {
if (mailer.hasKey() && !chatOnline(target.lastSeen)) { if (mailer.hasKey() && !chatOnline(target.lastSeen)) {
+201
View File
@@ -0,0 +1,201 @@
'use strict';
// Sponsor autopilot (Marty 2026-11-25: "I need for you to automatically contact and keep up with my referrals in IAP and
// LinkSpin so they don't go back to the holding tank. I'm busy building and managing everything and don't have time to
// manually do it.").
//
// WHAT IT DOES
// For each sponsor named in the site setting pilotSponsors (usernames, comma separated), it writes to that sponsor's FREE
// directs (no wallet, no member number: the only people the dormant-lead rule and the tank windows can move) as the
// sponsor: a real sponsor chat message plus the usual "new message from your sponsor" email. A chat from the sponsor is
// exactly what tank.js counts as contact, so the 10 / 14 day clock and the batch follow-up window restart honestly:
// the person really was written to.
// THE RULES (every number is a site setting, see DEFAULTS)
// first touch pilotFirstDays (2) after the last contact (sign-up, assignment, or the sponsor's own last message)
// later touches every pilotEveryDays (6), a different message each time, up to pilotMaxTouches (4) per person
// then nothing more: a person who never answers four messages is left to the normal tank rule
// a reply stops the automatic messages for that person and pings the owner once (hooks.notify): a human
// conversation is the sponsor's to continue. The sponsor's own reply restarts the clock anyway.
// never anyone muted, flagged, suspended, erased, unsubscribed, spam-scanned or with a mistyped mail domain
// (hooks.excluded / hooks.excludedPerson, the same never-mail list the tank batches use)
// pace at most pilotPerDay (60) messages per Central day across all sponsors, evenly spaced between
// pilotStartHour (8) and pilotEndHour (20) CT, closest to the tank deadline first, one per tick
// once each touch is claimed (hooks.claim 'pilot:<lead>:<n>') so two app copies in a deploy overlap send one
// MASTER SWITCH: site setting pilotOn (default '0'). Off: nothing is sent and nothing is written. view() is read-only.
const fs = require('fs');
const path = require('path');
const D = 86400000;
const DEFAULTS = { pilotOn: '0', pilotSponsors: '', pilotFirstDays: 2, pilotEveryDays: 6, pilotMaxTouches: 4, pilotPerDay: 60, pilotStartHour: 8, pilotEndHour: 20, pilotReplyPing: '1' };
let R = null; // { dataDir, db, accounts, messages, mailer, tank, siteConfig, brand: { name, url }, online(lastSeen), unsubUrl(email) (only where the mailer does not add its own link), hooks: { excluded, excludedPerson, claim, notify }, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const lc = v => String(v || '').trim().toLowerCase();
function cfg() {
const sc = (R && R.siteConfig && R.siteConfig()) || {};
const num = (k, lo, hi) => { const v = Number(sc[k] == null || sc[k] === '' ? DEFAULTS[k] : sc[k]); return Number.isFinite(v) && v >= lo && v <= hi ? v : DEFAULTS[k]; };
return { on: String(sc.pilotOn == null ? DEFAULTS.pilotOn : sc.pilotOn) === '1', ping: String(sc.pilotReplyPing == null ? '1' : sc.pilotReplyPing) !== '0',
sponsors: String(sc.pilotSponsors || '').split(',').map(lc).filter(Boolean).slice(0, 20),
firstDays: num('pilotFirstDays', 0, 60), everyDays: num('pilotEveryDays', 1, 60), maxTouches: num('pilotMaxTouches', 1, 12),
perDay: num('pilotPerDay', 1, 2000), startHour: num('pilotStartHour', 0, 23), endHour: num('pilotEndHour', 1, 24) };
}
// ---- the messages: plain text, the sponsor's own voice, no promises ----
// {name} = the person's username (or "there"), {site} / {url} = the brand. Touch n uses TOUCHES[n] (the last one repeats never: max is capped to the list).
const TOUCHES = [
'Hi {name}, Marty here. I am your sponsor on {site}, so I am the one to ask when something is not clear.\n\nYour account is open and it is free. The first step is simple: sign in with your email at {url} and take a look around.\n\nTell me what you promote and I will point you to the tool that fits it.',
'Hi {name}, Marty again. One thing worth doing this week: link a wallet on the Wallet tab. It is one free signature and it cannot move your funds. That is what lets a payout reach you when someone in your line buys an ad package.\n\nI use SafePal, and any other crypto wallet works too. Stuck anywhere? Reply here and I will help.',
'Hi {name}, checking in. A lot of people join and are not sure what to do next, so here is the short version:\n\n1. Sign in at {url}\n2. Link a wallet\n3. Switch on payouts\n\nAll three are free. After that your invite link is live and you can run your own ads with credits.\n\nWhich step are you on? Reply and I will pick it up from there.',
'Hi {name}, last note from me for now. Your free {site} account is still here whenever you want it: {url}\n\nIf now is not the time, no problem at all. If you do want a hand getting set up, reply to this message and I will help.'
];
function render(n, lead) {
const b = (R && R.brand) || { name: 'InstantAdPay', url: 'https://instantadpay.com/my' };
const name = lead && lead.username ? String(lead.username) : 'there';
return TOUCHES[Math.min(n, TOUCHES.length - 1)].replace(/\{name\}/g, name).replace(/\{site\}/g, b.name).replace(/\{url\}/g, b.url);
}
// ---- storage: MySQL sponsor_pilot_log when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'sponsor-pilot.json'),
load() { if (this.st) return this.st; try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || typeof this.st !== 'object') this.st = {}; this.st.log = this.st.log || []; this.st.state = this.st.state || {}; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
async add(x) { this.load().log.push(x); this.save(); },
async touches(sponsor) { const m = new Map(); for (const r of this.load().log) if (r.sponsor === sponsor) { const c = m.get(r.lead) || { n: 0, last: 0, replied: 0 }; if (r.kind === 'reply') c.replied = Math.max(c.replied, r.at); else { c.n++; c.last = Math.max(c.last, r.at); } m.set(r.lead, c); } return m; },
async sentSince(ts) { return this.load().log.filter(r => r.kind === 'touch' && r.at >= ts).length; },
async recent(n) { return this.load().log.slice(-(n || 50)).reverse().map(x => Object.assign({}, x)); },
async getState(k) { const v = this.load().state[k]; return v === undefined ? null : v; },
async setState(k, v) { this.load().state[k] = v; this.save(); }
};
const Q = {
async add(x) { await R.db.q('INSERT INTO sponsor_pilot_log (sponsor,`lead`,kind,n,at,emailed) VALUES (?,?,?,?,?,?)', [x.sponsor, x.lead, x.kind, x.n || 0, x.at, x.emailed ? 1 : 0]); },
async touches(sponsor) { const m = new Map(); for (const r of await R.db.q("SELECT `lead`, SUM(kind='touch') n, MAX(IF(kind='touch',at,0)) last, MAX(IF(kind='reply',at,0)) replied FROM sponsor_pilot_log WHERE sponsor=? GROUP BY `lead`", [sponsor])) m.set(r.lead, { n: Number(r.n || 0), last: Number(r.last || 0), replied: Number(r.replied || 0) }); return m; },
async sentSince(ts) { const r = await R.db.q("SELECT COUNT(*) c FROM sponsor_pilot_log WHERE kind='touch' AND at>=?", [ts]); return Number((r[0] && r[0].c) || 0); },
async recent(n) { return (await R.db.q('SELECT sponsor,`lead`,kind,n,at,emailed FROM sponsor_pilot_log ORDER BY id DESC LIMIT ?', [Number(n) || 50])).map(r => ({ sponsor: r.sponsor, lead: r.lead, kind: r.kind, n: Number(r.n), at: Number(r.at), emailed: !!r.emailed })); },
async getState(k) { const r = (await R.db.q('SELECT v FROM sponsor_pilot_state WHERE k=?', [k]))[0]; return r ? JSON.parse(r.v) : null; },
async setState(k, v) { await R.db.q('INSERT INTO sponsor_pilot_state (k,v) VALUES (?,?) ON DUPLICATE KEY UPDATE v=VALUES(v)', [k, JSON.stringify(v)]); }
};
const dbOn = () => !!(R && R.db && R.db.enabled && R.db.enabled());
const S = () => (dbOn() ? Q : J);
async function ensureTables() {
if (!dbOn()) return;
await R.db.q(`CREATE TABLE IF NOT EXISTS sponsor_pilot_log (
id INT AUTO_INCREMENT PRIMARY KEY, sponsor VARCHAR(190) NOT NULL, \`lead\` VARCHAR(190) NOT NULL, kind VARCHAR(8) NOT NULL, n INT NOT NULL DEFAULT 0,
at BIGINT NOT NULL, emailed TINYINT NOT NULL DEFAULT 0, KEY sp (sponsor, \`lead\`), KEY ka (kind, at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // sponsor autopilot: one row per automatic message ('touch') and per first reply ('reply')
await R.db.q('CREATE TABLE IF NOT EXISTS sponsor_pilot_state (k VARCHAR(40) PRIMARY KEY, v TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
}
async function init(opts) { R = opts; R.hooks = R.hooks || {}; J.st = null; queue = { at: 0, items: [] }; await ensureTables(); }
const TZ = 'America/Chicago';
const ctParts = ts => { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = p.value; return { hour: Number(o.hour) % 24, minute: Number(o.minute) }; };
const inWindow = (ts, c) => { const h = ctParts(ts).hour; return h >= c.startHour && h < c.endHour; };
const dayStart = ts => { const p = ctParts(ts); return ts - (p.hour * 60 + p.minute) * 60000 - (ts % 60000); };
const gapMs = c => Math.max(60000, Math.floor(Math.max(1, c.endHour - c.startHour) * 3600000 / c.perDay));
async function sponsorAccounts(c) { const out = []; for (const u of c.sponsors) { const a = await R.accounts.byUsername(u).catch(() => null); if (a && a.email) out.push(a); } return out; }
const isFree = a => !!a && !a.memberId && !a.address;
// why this person gets no automatic message at all (null = fine)
async function blocked(sp, lead) {
if (!isFree(lead)) return 'has a wallet or a member number';
if (lc(lead.email) === lc(sp.email)) return 'self';
const toks = [sp.username, sp.code, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(lc);
if (!toks.includes(lc(lead.sponsorRef))) return 'no longer with this sponsor';
if (R.hooks.excluded && R.hooks.excluded(lead.email)) return 'flagged or suspended';
if (R.hooks.excludedPerson) { const px = await Promise.resolve(R.hooks.excludedPerson(lead.email)).catch(() => 'check failed'); if (px) return px; }
try { if ((await R.accounts.getMutes(lead.email)).map(lc).includes(lc(sp.email))) return 'muted this sponsor'; } catch (e) {}
return null;
}
// everyone due a message right now for one sponsor, most overdue first
async function dueFor(sp, c, now) {
const levels = await R.accounts.downline(sp.email, 1); const directs = levels.length ? levels[0].members : [];
const t = await S().touches(lc(sp.email)); const due = []; const stats = { free: 0, due: 0, waiting: 0, finished: 0, replied: 0, touched: 0 };
for (const d of directs) {
if (!isFree(d)) continue; stats.free++;
const rec = t.get(lc(d.email)) || { n: 0, last: 0, replied: 0 };
if (rec.n) stats.touched++;
if (rec.replied) { stats.replied++; continue; }
if (rec.n >= Math.min(c.maxTouches, TOUCHES.length)) { stats.finished++; continue; }
const chat = R.messages && R.messages.lastFrom ? await R.messages.lastFrom(sp.email, d.email).catch(() => 0) : 0;
const since = Math.max(d.created || 0, chat, rec.last);
const wait = (rec.n ? c.everyDays : c.firstDays) * D;
if (now - since < wait) { stats.waiting++; continue; }
stats.due++; due.push({ sponsor: sp.email, lead: d.email, n: rec.n, since });
}
due.sort((a, b) => a.since - b.since);
return { due, stats };
}
let queue = { at: 0, items: [] }; // rebuilt every 30 minutes: listing a big line costs one query per person
async function refill(c, now) {
const items = []; for (const sp of await sponsorAccounts(c)) items.push(...(await dueFor(sp, c, now)).due);
items.sort((a, b) => a.since - b.since); queue = { at: now, items };
}
let ticking = null;
function tick() { if (!ticking) ticking = run().catch(e => { console.error('sponsorpilot', e.message); return { error: e.message }; }).finally(() => { ticking = null; }); return ticking; }
async function run() {
if (!R) return { off: true };
const c = cfg(); const now = clock(); const out = { sent: 0, skipped: 0 };
if (!c.on || !c.sponsors.length) return Object.assign(out, { off: true });
if (!inWindow(now, c)) return out;
if (await S().sentSince(dayStart(now)) >= c.perDay) return Object.assign(out, { capped: true });
if (now - (Number(await S().getState('lastSendAt')) || 0) < gapMs(c)) return out;
if (now - queue.at > 30 * 60000 || !queue.items.length) await refill(c, now);
while (queue.items.length) {
const it = queue.items.shift();
const sp = await R.accounts.byEmail(it.sponsor), lead = await R.accounts.byEmail(it.lead);
if (!sp || !lead || await blocked(sp, lead)) { out.skipped++; continue; }
// re-read at send time: the sponsor may have written by hand, or another copy of the app may have sent this touch
const rec = (await S().touches(lc(sp.email))).get(lc(lead.email)) || { n: 0, last: 0, replied: 0 };
if (rec.replied || rec.n !== it.n) { out.skipped++; continue; }
const chat = await R.messages.lastFrom(sp.email, lead.email).catch(() => 0);
if (now - Math.max(lead.created || 0, chat, rec.last) < (rec.n ? c.everyDays : c.firstDays) * D) { out.skipped++; continue; }
if (R.hooks.claim && !(await Promise.resolve(R.hooks.claim('pilot:' + lc(lead.email) + ':' + rec.n)).catch(() => false))) { out.skipped++; continue; }
const text = render(rec.n, lead);
await S().setState('lastSendAt', now);
await R.messages.sendChat(sp.memberId || 0, sp.email, lead.email, text);
let emailed = false;
try {
if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && !(R.online && R.online(lead.lastSeen))) {
const from = sp.username ? '@' + sp.username : 'your sponsor';
const b = R.brand || { name: 'InstantAdPay', url: 'https://instantadpay.com/my' };
emailed = (await R.mailer.send(lead.email, 'New message from ' + from + ', your ' + b.name + ' sponsor', text + '\n\nReply in your dashboard: ' + b.url + (R.unsubUrl ? '\n\nStop these emails: ' + R.unsubUrl(lead.email) : ''))) !== false;
}
} catch (e) { console.error('sponsorpilot mail', e.message); }
await S().add({ sponsor: lc(sp.email), lead: lc(lead.email), kind: 'touch', n: rec.n + 1, at: now, emailed });
out.sent++; break; // one per tick
}
return out;
}
// a chat message arrived for someone: if it is a pilot person answering their pilot sponsor, record it (stops the
// automatic messages) and ping the owner once. Called from the chat send route; never throws.
async function onChat(fromEmail, toEmail, text) {
try {
if (!R) return false;
const c = cfg(); if (!c.sponsors.length) return false;
const sp = await R.accounts.byEmail(toEmail); if (!sp || !c.sponsors.includes(lc(sp.username))) return false;
const rec = (await S().touches(lc(sp.email))).get(lc(fromEmail)); if (!rec || !rec.n || rec.replied) return false;
await S().add({ sponsor: lc(sp.email), lead: lc(fromEmail), kind: 'reply', n: rec.n, at: clock(), emailed: false });
if (c.ping && R.hooks.notify) {
const a = await R.accounts.byEmail(fromEmail); const who = a && a.username ? '@' + a.username : 'a referral';
const b = R.brand || { name: 'InstantAdPay', url: 'https://instantadpay.com/my' };
await Promise.resolve(R.hooks.notify('\u{1F4AC} ' + b.name + ': ' + who + ' answered your sponsor message (' + (sp.username ? '@' + sp.username : 'you') + '). The automatic messages to them have stopped; this one is yours.\n\n"' + String(text || '').replace(/[<>&]/g, '').slice(0, 300) + '"\n\n' + b.url + '#messages')).catch(() => {});
}
return true;
} catch (e) { console.error('sponsorpilot onChat', e.message); return false; }
}
// read-only: the admin panel and the go/no-go preview. Never prints an email address.
async function view() {
if (!R) return { settings: cfg(), notStarted: true, sponsors: [], messages: [] };
const c = cfg(); const now = clock(); const sponsors = [];
for (const sp of await sponsorAccounts(c)) {
const d = await dueFor(sp, c, now);
sponsors.push({ sponsor: '@' + sp.username, stats: d.stats, next: d.due.slice(0, 5).map(x => ({ touch: x.n + 1, daysSinceContact: Math.floor((now - x.since) / D) })) });
}
const sample = { username: 'yourname' };
return { settings: c, sentToday: await S().sentSince(dayStart(now)), gapMinutes: Math.round(gapMs(c) / 60000), sponsors,
messages: TOUCHES.slice(0, Math.min(c.maxTouches, TOUCHES.length)).map((_, i) => render(i, sample)),
recent: (await S().recent(30)).map(r => ({ kind: r.kind, n: r.n, at: r.at, emailed: r.emailed })) };
}
module.exports = { init, cfg, tick, onChat, view, render, DEFAULTS, TOUCHES, _dueFor: dueFor, _gapMs: gapMs, _inWindow: inWindow };