Holding tank batches: throttled emails + round announcement (Marty 2026-11-15: "spread the emails out", "Post it to the new members area")
Assignments still happen at once. Only the assigned people's "X is now your sponsor" emails go into a MySQL outbox (tank_batch_outbox, survives deploys): tankBatchEmailsPerDay (100) per Central day, evenly spaced from tankBatchEmailStartHour 8 to tankBatchEmailEndHour 20 CT, oldest first, through the site mailer (unsubscribe rules + link). Right before each send: still with that sponsor, not unsubscribed, flagged, spam or erased, else skipped. Exactly once across app copies: MySQL lock + conditional UPDATE queued->sending + marks claim per row. The switch-on reminders for a batch person start when their email goes out. Telegram: one announcement per round for the CTB group's General topic (tankBatchAnnounce, tankBatchAnnounceChatId blank = the payments group, tankBatchAnnounceTopicId blank = General), with the ladder card image (banners/holding-tank-leads-1200x675.jpg): total, sponsors by level, how to qualify; then one card per sponsor in the payments topic, at least tankBatchFeedGapMin (2) minutes apart. Sponsor emails stay one digest per round. Admin: GET/POST /api/admin/tank/batches/mail (queued, sent today, next send, pause/resume), POST /api/admin/tank/batches/round (the normal round path). Preview shows the email plan. qa/tank-batch.test.mjs 78 checks (cap, window, skip-if-changed, two copies, pause). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+124
-14
@@ -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 => '<b>' + k + '</b>: ' + groups[k].join(', '));
|
||||
return '\u{1F91D} <b>Holding tank: ' + total + ' new member' + (total === 1 ? '' : 's') + ' just got a sponsor</b>\n'
|
||||
+ 'Active members who bought their own package received leads they can sponsor:\n\n' + lines.join('\n') + '\n\n'
|
||||
+ '<b>How to get fed leads:</b> 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 };
|
||||
|
||||
Reference in New Issue
Block a user