diff --git a/public/banners/holding-tank-leads-1200x675.jpg b/public/banners/holding-tank-leads-1200x675.jpg
new file mode 100644
index 0000000..cefd85d
Binary files /dev/null and b/public/banners/holding-tank-leads-1200x675.jpg differ
diff --git a/qa/tank-batch.test.mjs b/qa/tank-batch.test.mjs
index 5d91531..d5570bb 100644
--- a/qa/tank-batch.test.mjs
+++ b/qa/tank-batch.test.mjs
@@ -51,7 +51,7 @@ function bench(opts) {
async listAll() { return [...by.values()].map(pub); }, async positions() { return []; },
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; const t = a.sponsorRef; return find(x => x.username === t || x.code === t || String(x.memberId) === t); }, _by: by };
const events = []; const mails = []; const chats = []; const notices = []; const feeds = []; const toasts = []; const sent = [];
- const standing = new Map(); const optOut = new Set();
+ const standing = new Map(); const optOut = new Set(); const announces = []; const claims = new Set();
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text, at: now }); sent.push({ from, to, at: now }); }, lastFrom: async (f, t) => sent.filter(x => x.from === f && x.to === t).reduce((m, x) => Math.max(m, x.at), 0) };
const mailer = { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } };
const chain = { recentEvents: () => events.slice(), getConfig: () => ({}), catalog: async () => [500, 1000, 2000, 5000, 10000, 25000, 50000].map((p, i) => ({ id: i + 1, priceCents: p })) };
@@ -59,12 +59,12 @@ function bench(opts) {
tank.init({ dataDir: dir, accounts, chain, messages, mailer, site: 'https://instantadpay.test', capOpen: () => 10,
hooks: { isBatchPick: id => tb.isBatchPick(id), isDraftPick: async () => false } });
tank.setClock(clock);
- return { tank, tb, accounts, events, mails, chats, notices, feeds, toasts, standing, optOut, site, dir, messages,
+ return { announces, claims, tank, tb, accounts, events, mails, chats, notices, feeds, toasts, standing, optOut, site, dir, messages,
advance: ms => { now += ms; }, now: () => now,
async start() {
await tb.init({ dataDir: dir, db: { enabled: () => false }, accounts, chain, tank, messages, mailer, siteConfig: () => site, clock,
refuel: { standing: async e => standing.get(e) || null },
- hooks: { companyId: () => 1, claim: async () => true, excludedPerson: async e => optOut.has(e) ? 'unsubscribed from email' : null,
+ hooks: { companyId: () => 1, claim: async k => { if (claims.has(k)) return false; claims.add(k); return true; }, announce: async html => { announces.push(html); }, excludedPerson: async e => optOut.has(e) ? 'unsubscribed from email' : null,
notify: async (to, subject, text) => { notices.push({ to, subject, text }); }, feed: async (who, what, level) => { feeds.push(who + ' just received ' + what + ' from the holding tank (' + level + ' level)'); }, toast: ev => toasts.push(ev) } });
} };
}
@@ -128,11 +128,18 @@ function seed(B, tankCount) {
ok(!B.tank._json.state().adoptions.some(a => a.adoptee === 'upline@tank.co' && a.adopter === 'paid@x.co'), 'never a sponsor\'s own upline');
ok(![...dealt].some(e => /@x\.co$/.test(e)), 'never a sponsor themself');
ok(B.accounts._by.get('t000@tank.co').sponsorRef === 'opgnetwerk', 'the sponsor change is written like an adoption');
- const adoptMails = B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
- ok(adoptMails.length === 51, 'every person gets the normal "X is now your sponsor" email, once', adoptMails.length);
+ const adoptMails = () => B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
+ ok(adoptMails().length === 0, 'the "X is now your sponsor" emails are queued, not sent in a burst', adoptMails().length);
+ const ob = () => JSON.parse(fs.readFileSync(path.join(B.dir, 'tank-batch.json'), 'utf8')).outbox;
+ ok(ob().filter(x => x.kind === 'mail' && x.status === 'queued').length === 51 && ob().filter(x => x.kind === 'mail').every(x => /is now your sponsor on InstantAdPay/.test(x.subject)), '51 adoption emails queued, oldest first', ob().length);
+ ok(!Object.keys(B.tank._ready.state().pay || {}).length, 'no switch-on reminders start before the email goes out');
ok(B.chats.length === 51 && B.chats.every(c => /matched with me from the holding tank/.test(c.text)), 'every person gets a chat from their new sponsor');
ok(B.notices.filter(x => /holding tank are in your line/.test(x.subject)).length === 3 && B.mails.filter(m => /from the holding tank are in your line/.test(m.subject)).length === 3, 'each sponsor gets one notice and one email per batch, not one per person');
- ok(B.feeds.length === 3 && B.feeds[0] === '@opgnetwerk just received 21 new team members from the holding tank (Twin Engine level)', 'tank feed card: sponsor, count, level', B.feeds);
+ ok(B.feeds.length === 0 && B.announces.length === 0, 'Telegram posts wait for the outbox');
+ for (let i = 0; i < 4; i++) { await B.tb.mailTick(); await B.tb.mailTick(); B.advance(2 * 60000); }
+ ok(B.announces.length === 1 && /3 new|51 new members just got a sponsor/.test(B.announces[0]) && /Twin Engine<\/b>: @opgnetwerk 21/.test(B.announces[0]) && /= 25;/.test(B.announces[0]) && !/t0\d\d|income|\u2014/.test(B.announces[0]), 'one round announcement: total, sponsors by level, how to qualify, no people, no income', B.announces[0]);
+ ok(B.feeds.length === 3 && B.feeds[0] === '@opgnetwerk just received 21 new team members from the holding tank (Twin Engine level)', 'tank feed cards: one per sponsor, sponsor, count, level', B.feeds);
+ ok(adoptMails().length === 1, 'one email per 7.2 minutes at most (8 ticks over 6 minutes: one)', adoptMails().length);
ok(!B.feeds.some(f => /t0\d\d/.test(f)) && B.toasts.length === 3 && B.toasts.every(t => t.type === 'Adopted' && !/t0\d\d/.test(t.member)), 'feed and toasts never name the people');
ok(!B.mails.concat(B.notices).some(m => /—/.test(m.subject + m.text)), 'no em dash in any batch copy');
// the member's own tank button and the 5x draft keep their own allowances
@@ -183,4 +190,43 @@ function seed(B, tankCount) {
const ids = B.tank._json.state().adoptions.filter(a => a.status === 'open').map(a => a.id); draftIds = new Set(ids);
ok(!(await B.tank.partnerEligibility('opg@x.co', { positions: 1, maxOpen: 10 })).ok && (await B.tank.eligibility('opg@x.co')).ok, 'ten draft picks fill the draft cap only');
}
+// ---- the throttled outbox: cap, window, skip-if-changed, pause, two app copies ----
+{
+ const B = bench({ site: { tankBatches: '1', tankBatchEmailsPerDay: 5 } }); seed(B, 12); await B.start();
+ await B.tb.round(); // 10 to paider? no: opg / fueler / paider share 12
+ const ob = () => JSON.parse(fs.readFileSync(path.join(B.dir, 'tank-batch.json'), 'utf8')).outbox.filter(x => x.kind === 'mail');
+ const sentMail = () => B.mails.filter(m => /is now your sponsor on InstantAdPay/.test(m.subject));
+ ok(ob().length === 12, '12 queued');
+ // window: 9 PM CT (03:00 UTC next day) nothing goes
+ const at = (h, m) => { const d = new Date(B.now()); const want = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), h + 6, m || 0); B.advance(want - B.now()); };
+ at(21, 0); await B.tb.mailTick(); ok(sentMail().length === 0, 'outside 8 AM to 8 PM CT: nothing sent');
+ at(7, 59 + 24 * 60); await B.tb.mailTick(); ok(sentMail().length === 0, '7:59 AM CT: still nothing');
+ B.advance(60000); await B.tb.mailTick(); ok(sentMail().length === 1, '8:00 AM CT: the first one goes');
+ const v = await B.tb.mailView(); ok(v.sentToday === 1 && v.queued === 11 && v.spacingMin === 144 && v.nextSendAt === B.now() + 144 * 60000, 'admin view: sent today, queued, next send time (12 h / 5 = 144 min apart)', v);
+ B.advance(60 * 60000); await B.tb.mailTick(); ok(sentMail().length === 1, 'spread through the day, not a burst');
+ // skip if changed: the next queued person left that sponsor, the one after unsubscribed: both skipped, the third is sent in the same tick
+ const q = ob().filter(x => x.status === 'queued');
+ B.accounts._by.get(q[0].to).sponsorRef = ''; B.optOut.add(q[1].to);
+ B.advance(90 * 60000); const r = await B.tb.mailTick();
+ ok(r.skipped === 2 && r.sent === 1 && sentMail().length === 2 && !sentMail().some(m => m.to === q[0].to || m.to === q[1].to), 'skip-if-changed: moved and unsubscribed are skipped, the next is sent', r);
+ ok(Object.keys(B.tank._ready.state().pay || {}).length === 2, 'the switch-on reminders start when each email goes out');
+ // pause
+ await B.tb.setPaused(true); B.advance(150 * 60000); await B.tb.mailTick(); ok(sentMail().length === 2 && (await B.tb.mailView()).paused, 'paused: nothing goes');
+ await B.tb.setPaused(false); await B.tb.mailTick(); ok(sentMail().length === 3, 'resumed: sending again');
+ // the day cap (5): 3 sent, 2 more today, then nothing until tomorrow
+ for (let i = 0; i < 6; i++) { B.advance(145 * 60000); if (!B.tb._inWindow(B.now(), B.tb.cfg())) break; await B.tb.mailTick(); }
+ const sentToday = (await B.tb.mailView()).sentToday; ok(sentToday <= 5, 'never more than tankBatchEmailsPerDay in a Central day', sentToday);
+ // two app copies on one store: every row goes once
+ for (const m of ['tankbatch.js']) delete require.cache[require.resolve(path.join(SITE, m))];
+ const tb2 = require(path.join(SITE, 'tankbatch.js'));
+ await tb2.init({ dataDir: B.dir, db: { enabled: () => false }, accounts: B.accounts, chain: { recentEvents: () => [], catalog: async () => [] }, tank: B.tank, messages: B.messages,
+ mailer: { hasKey: () => true, send: async (to, subject, text) => { B.mails.push({ to, subject, text, copy: 2 }); } }, siteConfig: () => B.site, clock: () => B.now(),
+ hooks: { claim: async k => { if (B.claims.has(k)) return false; B.claims.add(k); return true; }, excludedPerson: async e => B.optOut.has(e) ? 'unsubscribed' : null } });
+ B.site.tankBatchEmailsPerDay = 5000; at(9, 0 + 24 * 60);
+ for (let i = 0; i < 40; i++) { await Promise.all([B.tb.mailTick(), tb2.mailTick()]); B.advance(60000); }
+ const per = {}; for (const m of sentMail()) per[m.to] = (per[m.to] || 0) + 1;
+ ok(Object.values(per).every(n => n === 1) && ob().every(x => x.status === 'sent' || x.status === 'skipped'), 'two app copies: every email sent exactly once, the queue drains', per);
+ // preview shows the email plan
+ const pv = await B.tb.preview(); ok(pv.emailPlan && pv.emailPlan.perDay === 5000 && typeof pv.emailPlan.daysToClear === 'number', 'preview carries the email plan', pv.emailPlan);
+}
console.log('\n' + passes + ' passed, ' + fails + ' failed'); process.exit(fails ? 1 : 0);
diff --git a/server.js b/server.js
index c2485f3..a06f945 100644
--- a/server.js
+++ b/server.js
@@ -855,9 +855,15 @@ async function boot() {
hooks: { excluded: em => fraud.excluded(em), companyId: () => Number(siteConfig().defaultSponsorId) || 1, claim: key => marks.claim(key), toast: ev => pushFeed(ev),
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; },
notify: async (email, subject, text) => { const html = '
' + String(text).replace(/&/g, '&').replace(//g, '>').replace(/(https:\/\/[^\s)]+)/g, '$1').split('\n\n').join('
').replace(/\n/g, '
') + '
'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); },
+ // the round's announcement in the new members area (CTB group General: no thread id), with the ladder card image; a caption over
+ // Telegram's 1,024 characters goes as one text post instead
+ announce: async html => { const sc = siteConfig(); const chat = String(sc.tankBatchAnnounceChatId || sc.telegramEchoChatId || '').trim(); if (!sc.telegramBotToken || !chat) return; const topic = String(sc.tankBatchAnnounceTopicId || '').trim() || null;
+ let jpeg = null; try { jpeg = fs.readFileSync(path.join(__dirname, 'public', 'banners', 'holding-tank-leads-1200x675.jpg')); } catch (e) {}
+ if (jpeg && html.length <= 1024 && await telegramSendPhoto(chat, jpeg, html, topic)) return; await telegramSend(chat, html, topic); },
feed: async (who, what, level) => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; const clean = t => String(t || '').replace(/[<>&]/g, ''); await telegramSend(sc.telegramEchoChatId, '\u{1F91D} InstantAdPay · ' + clean(who) + ' just received ' + clean(what) + ' from the holding tank (' + clean(level) + ' level)', sc.telegramEchoTopicId); } } }).catch(e => console.error('tankbatch init', e.message)); }
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.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(() => draftpartner.sweep().then(r => { if (r.done || r.returned || r.kept || r.moved) console.log('draft sweep', JSON.stringify(r)); }).catch(e => console.error('draft sweep', e.message)), 60 * 60 * 1000); // 5xYourTeam picks: 3-day window
burner.init({ chain, ads, accounts });
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
@@ -3892,6 +3898,9 @@ const server = http.createServer(async (req, res) => {
return json(res, 200, await draftpartner.adminView());
}
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 === '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/round' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.round()); } // run a round now (the normal path; nothing while tankBatches is off)
if (p === '/api/admin/tank/batches' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await tankbatch.adminView()); }
if (p === '/api/admin/tank' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
diff --git a/tank.js b/tank.js
index 7338851..fc8904b 100644
--- a/tank.js
+++ b/tank.js
@@ -222,12 +222,14 @@ async function adopt(adopterEmail, who, note, opts) {
const ttl = partner && Number(partner.ttlMs) > 0 ? Number(partner.ttlMs) : TTL_MS;
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + ttl, status: 'open', note: (opts && opts.recordNote) || text });
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = now; rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
- if (!partner) payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick); a draft pick gets the adoption email only (Marty 2026-11-15)
+ if (!partner && !(opts && opts.queueMail)) payTrack(target.email, e, ad.id, auto); // a batch person's reminders start when their queued email goes out (tankbatch.js), so they stay spread too // switch-on-payouts reminders at 24 h and 72 h (payTick); a draft pick gets the adoption email only (Marty 2026-11-15)
const link = activateLink();
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
- if (mailer && mailer.hasKey()) {
+ // a holding tank batch (2026-11-15, Marty: "spread the emails out"): the same email, handed to the throttled queue (opts.queueMail)
+ const queueMail = opts && typeof opts.queueMail === 'function' ? opts.queueMail : null;
+ if (queueMail || (mailer && mailer.hasKey())) {
try {
- await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
+ await (queueMail ? (to, subject, body) => queueMail({ to, subject, body, adoptionId: ad.id, sponsor: e }) : (to, subject, body) => mailer.send(to, subject, body))(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
(b4h ? 'BTC4Hits has closed, and your BTC4Hits account came over to InstantAdPay with the same email. ' : 'You joined InstantAdPay without a sponsor. ') + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\n' + mailPayBlock(nameOf(me), link, !!target.wallet) + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
} catch (err) {}
if (auto) {
@@ -740,5 +742,5 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
-module.exports = { batchEligibility, holdingOf, firstOnContract, inDownlineOf, markOf: email => impl().mark(String(email || '').toLowerCase()), _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
+module.exports = { payTrack, batchEligibility, holdingOf, firstOnContract, inDownlineOf, markOf: email => impl().mark(String(email || '').toLowerCase()), _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
diff --git a/tankbatch.js b/tankbatch.js
index 336ccea..53dc813 100644
--- a/tankbatch.js
+++ b/tankbatch.js
@@ -37,7 +37,12 @@ const DEFAULTS = {
tankBatches: '0', tankBatchActiveDays: 7, tankBatchBase: 10, tankBatchFueled: 20, tankBatchTwin: 25, tankBatchStep: 5, tankBatchMax: 50,
tankBatchEveryDays: 2, tankBatchFollowDays: 7, tankBatchMinIapCents: 2000, tankBatchMinLsCents: 2500,
tankBatchHigherIapCents: 5000, tankBatchHigherLsCents: 5000, tankBatchTopIapCents: 0 /* 0 = the highest package on the live catalog */, tankBatchTopLsCents: 50000,
- tankBatchFeed: '1'
+ tankBatchFeed: '1',
+ // the assigned people's "X is now your sponsor" emails go out through a throttled queue (Marty 2026-11-15: "spread the emails out"):
+ // at most tankBatchEmailsPerDay per Central day, spaced evenly between the start and end hour (CT); Telegram cards at least tankBatchFeedGapMin apart
+ // one announcement per round in the CTB group's General topic (blank topic = General, no thread id; blank chat = the payments group)
+ tankBatchAnnounce: '1', tankBatchAnnounceChatId: '', tankBatchAnnounceTopicId: '',
+ tankBatchEmailsPerDay: 100, tankBatchEmailStartHour: 8, tankBatchEmailEndHour: 20, tankBatchFeedGapMin: 2
};
let R = null; // { dataDir, db, accounts, chain, tank, refuel, messages, mailer, siteConfig, hooks: { excluded, excludedPerson, claim, feed, toast, notify, companyId, networkSeen }, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
@@ -48,11 +53,12 @@ const nameOf = a => a ? (a.username ? '@' + a.username : (a.memberId ? 'member #
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.tankBatches == null ? DEFAULTS.tankBatches : sc.tankBatches) === '1', feed: String(sc.tankBatchFeed == null ? '1' : sc.tankBatchFeed) !== '0',
+ return { on: String(sc.tankBatches == null ? DEFAULTS.tankBatches : sc.tankBatches) === '1', feed: String(sc.tankBatchFeed == null ? '1' : sc.tankBatchFeed) !== '0', announce: String(sc.tankBatchAnnounce == null ? '1' : sc.tankBatchAnnounce) !== '0',
activeDays: num('tankBatchActiveDays', 1, 60), base: num('tankBatchBase', 1, 200), fueled: num('tankBatchFueled', 1, 200), twin: num('tankBatchTwin', 1, 200),
step: num('tankBatchStep', 0, 100), max: num('tankBatchMax', 1, 500), everyDays: num('tankBatchEveryDays', 0.04, 60), followDays: num('tankBatchFollowDays', 1, 60),
minIap: num('tankBatchMinIapCents', 0, 1e7), minLs: num('tankBatchMinLsCents', 0, 1e7), higherIap: num('tankBatchHigherIapCents', 0, 1e7), higherLs: num('tankBatchHigherLsCents', 0, 1e7),
- topIap: num('tankBatchTopIapCents', 0, 1e8), topLs: num('tankBatchTopLsCents', 0, 1e8) };
+ topIap: num('tankBatchTopIapCents', 0, 1e8), topLs: num('tankBatchTopLsCents', 0, 1e8),
+ perDay: num('tankBatchEmailsPerDay', 1, 5000), startHour: num('tankBatchEmailStartHour', 0, 23), endHour: num('tankBatchEmailEndHour', 1, 24), feedGapMin: num('tankBatchFeedGapMin', 0, 120) };
}
// ---- the ladder (pure: the tests drive it directly) ----
@@ -92,8 +98,8 @@ const ladderView = c => [
// ---- storage: MySQL tank_batch_picks when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'tank-batch.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.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.rounds = this.st.rounds || []; return this.st; },
- save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
+ load() { 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.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.rounds = this.st.rounds || []; this.st.outbox = this.st.outbox || []; this.st.state = this.st.state || {}; this.st.nextOut = this.st.nextOut || 1; return this.st; },
+ save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.st || this.load())); fs.renameSync(f + '.tmp', f); },
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
async close(id, status, why) { const x = this.load().picks.find(r => r.id === id); if (x) { x.status = status; x.closed = clock(); x.why = why || null; this.save(); } },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
@@ -101,7 +107,15 @@ const J = {
async lastBySponsor() { const m = new Map(); for (const r of this.load().picks) m.set(r.sponsor, Math.max(m.get(r.sponsor) || 0, r.roundAt || r.at)); return m; },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async addRound(x) { const s = this.load(); s.rounds.push(x); if (s.rounds.length > 200) s.rounds = s.rounds.slice(-200); this.save(); },
- async rounds(n) { return this.load().rounds.slice(-(n || 30)).reverse(); }
+ async rounds(n) { return this.load().rounds.slice(-(n || 30)).reverse(); },
+ // outbox: kind 'mail' | 'feed', status queued -> sending -> sent | skipped
+ async enqueue(x) { const s = this.load(); const row = Object.assign({ id: s.nextOut++, status: 'queued', created: clock(), sentAt: null, why: null }, x); s.outbox.push(row); this.save(); return row; },
+ async oldest(kind, n) { return this.load().outbox.filter(r => r.kind === kind && r.status === 'queued').sort((a, b) => a.id - b.id).slice(0, n || 1).map(x => Object.assign({}, x)); },
+ async take(id) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (!x || x.status !== 'queued') return false; x.status = 'sending'; this.save(); return true; },
+ async finish(id, status, why) { const s = this.load(); const x = s.outbox.find(r => r.id === id); if (x) { x.status = status; x.sentAt = clock(); x.why = why || null; this.save(); } },
+ async counts(kind, since) { const rows = this.load().outbox.filter(r => r.kind === kind); return { queued: rows.filter(r => r.status === 'queued').length, sent: rows.filter(r => r.status === 'sent' && r.sentAt >= since).length, skipped: rows.filter(r => r.status === 'skipped' && r.sentAt >= since).length }; },
+ async getState(k) { const v = this.load().state[k]; return v === undefined ? null : v; },
+ async setState(k, v) { const s = this.load(); s.state[k] = v; this.save(); }
};
const rowP = r => ({ id: Number(r.id), adoptionId: Number(r.adoption_id), sponsor: r.sponsor, adoptee: r.adoptee, at: Number(r.at), roundAt: Number(r.round_at), level: r.level, size: Number(r.size), status: r.status, closed: r.closed ? Number(r.closed) : null, why: r.why || null });
const Q = {
@@ -112,7 +126,14 @@ const Q = {
async lastBySponsor() { return new Map((await R.db.q('SELECT sponsor, MAX(round_at) t FROM tank_batch_picks GROUP BY sponsor')).map(r => [r.sponsor, Number(r.t)])); },
async recent(n) { return (await R.db.q('SELECT * FROM tank_batch_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async addRound(x) { await R.db.q('INSERT INTO tank_batch_rounds (at, summary) VALUES (?,?)', [x.at, JSON.stringify(x).slice(0, 60000)]); },
- async rounds(n) { return (await R.db.q('SELECT summary FROM tank_batch_rounds ORDER BY id DESC LIMIT ?', [Number(n) || 30])).map(r => { try { return JSON.parse(r.summary); } catch (e) { return null; } }).filter(Boolean); }
+ async rounds(n) { return (await R.db.q('SELECT summary FROM tank_batch_rounds ORDER BY id DESC LIMIT ?', [Number(n) || 30])).map(r => { try { return JSON.parse(r.summary); } catch (e) { return null; } }).filter(Boolean); },
+ async enqueue(x) { const r = await R.db.q("INSERT INTO tank_batch_outbox (kind,to_email,sponsor,adoption_id,subject,body,payload,created,status) VALUES (?,?,?,?,?,?,?,?,'queued')", [x.kind, x.to || null, x.sponsor || null, x.adoptionId || null, x.subject || null, x.body || null, x.payload ? JSON.stringify(x.payload) : null, clock()]); return Object.assign({ id: r.insertId, status: 'queued' }, x); },
+ async oldest(kind, n) { return (await R.db.q("SELECT * FROM tank_batch_outbox WHERE kind=? AND status='queued' ORDER BY id LIMIT ?", [kind, Number(n) || 1])).map(r => ({ id: Number(r.id), kind: r.kind, to: r.to_email, sponsor: r.sponsor, adoptionId: r.adoption_id ? Number(r.adoption_id) : null, subject: r.subject, body: r.body, payload: r.payload ? JSON.parse(r.payload) : null, created: Number(r.created), status: r.status })); },
+ async take(id) { const r = await R.db.q("UPDATE tank_batch_outbox SET status='sending' WHERE id=? AND status='queued'", [Number(id)]); return Number(r.affectedRows) === 1; },
+ async finish(id, status, why) { await R.db.q('UPDATE tank_batch_outbox SET status=?, sent_at=?, why=? WHERE id=?', [status, clock(), why ? String(why).slice(0, 200) : null, Number(id)]); },
+ async counts(kind, since) { const r = (await R.db.q("SELECT SUM(status='queued') q, SUM(status='sent' AND sent_at>=?) s, SUM(status='skipped' AND sent_at>=?) k FROM tank_batch_outbox WHERE kind=?", [since, since, kind]))[0] || {}; return { queued: Number(r.q || 0), sent: Number(r.s || 0), skipped: Number(r.k || 0) }; },
+ async getState(k) { const r = (await R.db.q('SELECT v FROM tank_batch_state WHERE k=?', [k]))[0]; return r ? JSON.parse(r.v) : null; },
+ async setState(k, v) { await R.db.q('INSERT INTO tank_batch_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);
@@ -123,6 +144,12 @@ async function ensureTables() {
level VARCHAR(40) NULL, size INT NOT NULL DEFAULT 0, status VARCHAR(16) NOT NULL, closed BIGINT NULL, why VARCHAR(200) NULL,
KEY adoption (adoption_id), KEY sp (sponsor, status), KEY st (status), KEY adoptee (adoptee)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // holding tank batches (each one a tank adoption)
+ await R.db.q(`CREATE TABLE IF NOT EXISTS tank_batch_outbox (
+ id INT AUTO_INCREMENT PRIMARY KEY, kind VARCHAR(8) NOT NULL, to_email VARCHAR(190) NULL, sponsor VARCHAR(190) NULL, adoption_id INT NULL, subject VARCHAR(300) NULL,
+ body MEDIUMTEXT NULL, payload TEXT NULL, created BIGINT NOT NULL, status VARCHAR(10) NOT NULL, sent_at BIGINT NULL, why VARCHAR(200) NULL,
+ KEY ks (kind, status, id), KEY sent (kind, sent_at), KEY toe (to_email)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // the throttled batch emails + spaced Telegram cards (survives deploys)
+ await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_state (k VARCHAR(40) PRIMARY KEY, v TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await R.db.q('CREATE TABLE IF NOT EXISTS tank_batch_rounds (id INT AUTO_INCREMENT PRIMARY KEY, at BIGINT NOT NULL, summary MEDIUMTEXT NOT NULL, KEY t (at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
}
async function init(opts) { R = opts; R.hooks = R.hooks || {}; J.st = null; await ensureTables(); }
@@ -220,7 +247,7 @@ async function round() {
if (busy) return busy;
busy = (async () => {
c.topIapResolved = await topIapCents(c);
- const now = clock(); const summary = { at: now, batches: [], assigned: 0, refused: 0 };
+ const now = clock(); const summary = { at: now, batches: [], assigned: 0, refused: 0 }; const cards = [];
await lock(async () => {
const p = await plan(c, now);
for (const s of p.takers) {
@@ -228,7 +255,7 @@ async function round() {
const got = [];
for (const w of s.give) {
const msg = 'Hi, I am ' + s.name + '. ' + (w.via === 'btc4hits' ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so you were matched with me from the holding tank: active members who have bought their own package take turns. I will walk you through the first steps whenever you are ready. Reply here.';
- const r = await R.tank.adopt(s.email, w.username || w.email, msg, { batch: true, recordNote: 'holding tank batch (' + s.tier.label + ', ' + s.tier.size + ' at a time)' }).catch(e => ({ error: e.message }));
+ const r = await R.tank.adopt(s.email, w.username || w.email, msg, { batch: true, recordNote: 'holding tank batch (' + s.tier.label + ', ' + s.tier.size + ' at a time)', queueMail: m => S().enqueue({ kind: 'mail', to: m.to, sponsor: m.sponsor, adoptionId: m.adoptionId, subject: m.subject, body: m.body }) }).catch(e => ({ error: e.message }));
if (!(r && r.ok)) { summary.refused++; continue; }
await S().add({ adoptionId: Number(r.adoption.id), sponsor: s.email, adoptee: r.adoptee, at: clock(), roundAt: now, level: s.tier.label, size: s.tier.size, status: 'open' });
got.push(r.adopteeName);
@@ -236,8 +263,12 @@ async function round() {
if (!got.length) continue;
summary.assigned += got.length; summary.batches.push({ sponsor: s.name, level: s.tier.label, size: s.tier.size, count: got.length });
await tellSponsor(s, got, c);
- await feedCard(s, got.length, now, c);
+ cards.push([s, got.length]);
}
+ // the round's announcement for the new members area (General) first, then one card per sponsor in the payments topic;
+ // all queued: mailTick posts them at least tankBatchFeedGapMin apart
+ if (cards.length && c.announce) await S().enqueue({ kind: 'feed', payload: { announce: announceText(cards, c), roundAt: now } });
+ for (const [s, n] of cards) await feedCard(s, n, now, c);
});
if (summary.batches.length) { try { await S().addRound(summary); } catch (e) { console.error('tankbatch round log', e.message); } console.log('tankbatch round', JSON.stringify({ assigned: summary.assigned, batches: summary.batches.length, refused: summary.refused })); }
return Object.assign({ on: true }, summary);
@@ -251,15 +282,93 @@ async function tellSponsor(s, names, c) {
if (R.hooks.notify) { try { await R.hooks.notify(s.email, subject, text); } catch (e) {} }
if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) { try { await R.mailer.send(s.email, 'InstantAdPay: ' + subject, text + '\n\nInstantAdPay'); } catch (e) {} }
}
+// the round's post for the CTB group's new members area (General topic; Marty 2026-11-15: "Post it to the new members area in
+// Telegram"): how many got a sponsor, who received leads grouped by level, and how to qualify. Never the people, never income.
+function announceText(cards, c) {
+ const clean = t => String(t || '').replace(/[<>&]/g, '');
+ const total = cards.reduce((n, x) => n + x[1], 0);
+ const order = ['Twin Engine', 'Fueled', 'Paid']; const groups = {};
+ for (const [s, n] of cards) { const k = order.find(o => s.tier.level === o) || s.tier.level; (groups[k] = groups[k] || []).push(clean(s.username ? '@' + s.username : s.name) + ' ' + n); }
+ const lines = order.filter(k => groups[k]).map(k => '' + k + ': ' + groups[k].join(', '));
+ return '\u{1F91D} Holding tank: ' + total + ' new member' + (total === 1 ? '' : 's') + ' just got a sponsor\n'
+ + 'Active members who bought their own package received leads they can sponsor:\n\n' + lines.join('\n') + '\n\n'
+ + 'How to get fed leads: your own ' + usd(c.minIap) + ' InstantAdPay or ' + usd(c.minLs) + ' LinkSpin package = ' + c.base + ' at a time; a counted monthly refuel or a ' + usd(c.higherIap) + '+ package = ' + c.fueled + '; both engines refueled this cycle or the top package = ' + c.twin + '; +' + c.step + ' for every further refuel month in a row, up to ' + c.max + '. Sign in at least once a week to stay on the list.\n'
+ + 'https://instantadpay.com/my';
+}
async function feedCard(s, n, roundAt, c) {
if (!c.feed) return;
- if (R.hooks.claim) { let mine = false; try { mine = await R.hooks.claim('tankbatch:feed:' + s.email + ':' + roundAt); } catch (e) {} if (!mine) return; }
const who = s.username ? '@' + s.username : s.name;
const what = n + ' new team member' + (n === 1 ? '' : 's');
- if (R.hooks.feed) { try { await R.hooks.feed(who, what, s.tier.label); } catch (e) { console.error('tankbatch feed', e.message); } }
- if (R.hooks.toast) { try { R.hooks.toast({ type: 'Adopted', sponsor: who, member: what + ' (' + s.tier.label + ' level)', ts: clock() }); } catch (e) {} }
+ await S().enqueue({ kind: 'feed', sponsor: s.email, payload: { who, what, level: s.tier.label, roundAt } });
}
+// ---- the outbox: throttled emails + spaced Telegram cards. Once everywhere: one MySQL lock across app copies, a row claimed
+// queued -> sending by a conditional UPDATE, and a marks claim per row; a crash between claim and send loses that one (never twice).
+const TZ = 'America/Chicago';
+const ctParts = ts => { const o = {}; for (const p of new Intl.DateTimeFormat('en-US', { timeZone: TZ, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(ts))) o[p.type] = p.value; return { day: o.year + '-' + o.month + '-' + o.day, 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; };
+function dayStart(ts) { const p = ctParts(ts); return ts - (p.hour * 60 + p.minute) * 60000 - (ts % 60000); } // Central midnight (to the minute)
+const gapMs = c => Math.max(60000, Math.floor((c.endHour - c.startHour) * 3600000 / c.perDay));
+function nextWindowOpen(ts, c) { let t = ts - (ts % 60000); for (let i = 0; i < 4 * 24 * 7 && !inWindow(t, c); i++) t += 15 * 60000; return t; }
+const mlock = fn => (dbOn() && R.db.withLock ? R.db.withLock('tankbatchmail', fn, 2) : fn());
+async function stillOk(it) { // right before each send: still in that sponsor's line, and not unsubscribed, blocked or erased
+ const a = await R.accounts.byEmail(it.to); if (!a) return 'account gone';
+ const sp = await R.accounts.byEmail(it.sponsor); if (!sp) return 'sponsor gone';
+ const toks = [sp.username, sp.code, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(x => String(x).toLowerCase());
+ if (!toks.includes(String(a.sponsorRef || '').toLowerCase())) return 'no longer with this sponsor';
+ if (R.hooks.excluded && R.hooks.excluded(a.email)) return 'flagged or suspended';
+ if (R.hooks.excludedPerson) { const px = await Promise.resolve(R.hooks.excludedPerson(a.email)).catch(() => 'check failed'); if (px) return px; }
+ return null;
+}
+let mailing = null;
+function mailTick() { if (!mailing) mailing = Promise.resolve().then(() => mlock(mailRun)).catch(e => { if (!/lock busy/.test(e.message)) console.error('tankbatch mail', e.message); return { busy: true }; }).finally(() => { mailing = null; }); return mailing; }
+async function mailRun() {
+ const c = cfg(); const now = clock(); const out = { feed: 0, sent: 0, skipped: 0 };
+ if (await S().getState('paused')) return Object.assign(out, { paused: true });
+ // one Telegram card per tick, at least feedGapMin after the last
+ const lastFeed = Number(await S().getState('lastFeedAt')) || 0;
+ if (now - lastFeed >= c.feedGapMin * 60000) {
+ const [f] = await S().oldest('feed', 1);
+ if (f && await S().take(f.id) && (!R.hooks.claim || await Promise.resolve(R.hooks.claim('tbfeed:' + f.id)).catch(() => false))) {
+ await S().setState('lastFeedAt', now);
+ const p = f.payload || {};
+ if (p.announce) { try { if (R.hooks.announce) await R.hooks.announce(p.announce); } catch (e) { console.error('tankbatch announce', e.message); } }
+ else try { if (R.hooks.feed) await R.hooks.feed(p.who, p.what, p.level); } catch (e) { console.error('tankbatch feed', e.message); }
+ if (!p.announce) try { if (R.hooks.toast) R.hooks.toast({ type: 'Adopted', sponsor: p.who, member: p.what + ' (' + p.level + ' level)', ts: now }); } catch (e) {}
+ await S().finish(f.id, 'sent'); out.feed++;
+ }
+ }
+ // one email per tick at most, inside the window, under the day cap, evenly spaced
+ if (!inWindow(now, c)) return out;
+ const today = await S().counts('mail', dayStart(now)); if (today.sent >= c.perDay) return out;
+ const lastMail = Number(await S().getState('lastMailAt')) || 0; if (now - lastMail < gapMs(c)) return out;
+ for (const it of await S().oldest('mail', 25)) { // skipped rows do not use the slot: the next one goes in the same tick
+ if (!(await S().take(it.id))) continue;
+ if (R.hooks.claim && !(await Promise.resolve(R.hooks.claim('tbmail:' + it.id)).catch(() => false))) continue;
+ const why = await stillOk(it);
+ if (why) { await S().finish(it.id, 'skipped', why); out.skipped++; continue; }
+ await S().setState('lastMailAt', now);
+ try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(it.to, it.subject, it.body); } catch (e) { console.error('tankbatch mail send', e.message); }
+ await S().finish(it.id, 'sent'); out.sent++;
+ try { if (R.tank.payTrack) R.tank.payTrack(it.to, it.sponsor, it.adoptionId, false); } catch (e) {} // the 24 h / 72 h reminders count from this email
+ break;
+ }
+ return out;
+}
+async function mailView() {
+ const c = cfg(); const now = clock(); const today = await S().counts('mail', dayStart(now)); const feeds = await S().counts('feed', dayStart(now));
+ const paused = !!(await S().getState('paused')); const lastMail = Number(await S().getState('lastMailAt')) || 0;
+ let next = null;
+ if (!paused && today.queued) {
+ next = Math.max(now, lastMail + gapMs(c));
+ if (today.sent >= c.perDay) next = dayStart(now) + 86400000 + 3 * 3600000; // into tomorrow (DST-safe), then the window
+ next = nextWindowOpen(next, c);
+ }
+ return { paused, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, queued: today.queued, sentToday: today.sent, skippedToday: today.skipped,
+ nextSendAt: next, feed: { queued: feeds.queued, sentToday: feeds.sent, gapMin: c.feedGapMin }, daysToClear: Math.ceil(today.queued / c.perDay) };
+}
+async function setPaused(v) { await S().setState('paused', !!v); return mailView(); }
+
// ---- follow-up: uncontacted batch people go back to the tank ----
let following = null;
function followUp() { if (!following) following = followRun().finally(() => { following = null; }); return following; }
@@ -307,6 +416,7 @@ async function preview() {
wouldGet: (s.give || []).length, firstNames: (s.give || []).slice(0, 8).map(w => w.name) }));
const byLevel = {}; for (const s of sp) { const b = byLevel[s.level.replace(/, month \d+$/, '')] = byLevel[s.level.replace(/, month \d+$/, '')] || { sponsors: 0, people: 0 }; b.sponsors++; b.people += s.wouldGet; }
return { readOnly: true, on: c.on, generatedAt: now, settings: Object.assign({}, c, { topIapCents: c.topIapResolved }), ladder: ladderView(c),
+ emailPlan: await (async () => { const q = (await S().counts('mail', 0)).queued; const people = p.takers.reduce((n, t) => n + t.give.length, 0); return { alreadyQueued: q, thisRound: people, perDay: c.perDay, window: c.startHour + ':00 to ' + c.endHour + ':00 CT', spacingMin: Math.round(gapMs(c) / 60000 * 10) / 10, daysToClear: Math.ceil((q + people) / c.perDay) }; })(),
tank: { waiting: p.pool.waiting, offered: p.pool.rows.length, excluded: p.pool.excluded, leftAfterRound: p.left },
totals: { eligibleSponsors: sp.length, takingThisRound: p.takers.filter(t => t.give.length).length, people: p.takers.reduce((n, t) => n + t.give.length, 0), capacity: sp.reduce((n, s) => n + s.room, 0), byLevel },
sponsors: sp, notEligible: { counts: p.sponsors.why, members: p.sponsors.skipped } };
@@ -326,4 +436,4 @@ async function myView(email) {
}
async function adminView() { return { settings: cfg(), open: (await S().open()).length, recent: await S().recent(100), rounds: await S().rounds(20) }; }
-module.exports = { init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };
+module.exports = { announceText, mailTick, mailView, setPaused, _gapMs: gapMs, _inWindow: inWindow, init, cfg, tierFor, nextStep, ladderView, plan, round, followUp, tick, preview, myView, adminView, isBatchPick, DEFAULTS };