Files
instantadpay/sponsorpilot.js
T

202 lines
17 KiB
JavaScript

'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 };