diff --git a/override.js b/override.js new file mode 100644 index 0000000..e4a316c --- /dev/null +++ b/override.js @@ -0,0 +1,92 @@ +// Level-4 override (Marty, decided 2026-10-17; design in memory iap-level4-override): 3% of every purchase goes to the +// buyer's 4th upline when that member has 5+ qualifying buyers (the contract's own buyerCount, same bar as level 3); an +// unqualified 4th upline is skipped and the hunt climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one +// recipient per purchase, so it never costs more than 3%; funded off-chain from the company's 20% and paid weekly with +// the contract's award() from a pre-funded engine wallet, purchases from go-live forward only. +// THIS MODULE IS THE DRY RUN: it computes who would be paid from real purchases and reports it. No money moves. +'use strict'; +const fs = require('fs'); +const path = require('path'); + +let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null; +const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4; +function init(o) { DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; } +const cfg = () => { const s = siteConfig(); return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean), + goLive: Number(s.overrideGoLive || 0) }; }; + +// sponsor + qualifying-buyer count per member, read from the contract (cached 10 minutes per report run) +const memo = new Map(); +async function mem(id) { + const c = memo.get(id); if (c && Date.now() - c.t < 600000) return c.v; + const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 }; + memo.set(id, { t: Date.now(), v }); return v; +} +// who the override for one purchase goes to: { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason } +async function recipientFor(buyerId) { + const ups = []; let cur = buyerId; + for (let i = 0; i < LEVEL - 1 + HOP_CAP; i++) { const s = (await mem(cur)).sponsorId; if (!s || s === cur) break; ups.push(s); cur = s; } + if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' }; + const skipped = []; + for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) { + const id = ups[i], b = (await mem(id)).buyerCount; + if (cfg().house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped }; + if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped }; + skipped.push({ id, buyers: b }); + } + return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped }; +} + +// Central-time week: Monday 00:00 to the next Monday +const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' }); +function weekOf(ts) { + const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value])); + const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday]; + const d = new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)); + return d.toISOString().slice(0, 10); // the Monday, as a date key +} +const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT or CST) + for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (weekOf(t) && new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; } + return Date.parse(day + 'T05:00:00Z'); +}; + +function purchases() { + try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; } +} +// the report for purchases in [from, to): one row per purchase + totals per recipient (amounts in wei strings and cents) +async function report(from, to) { + const c = cfg(); const rows = [], per = {}; + for (const p of purchases()) { + if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue; + const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, cents = Math.round((p.priceCents || 0) * PCT) / 100; + const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message })); + rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: cents, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '' }); + if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usd: 0 }; o.purchases++; o.wei += wei; o.usd += cents; } + } + const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, pol: Number(o.wei) / 1e18, usd: Math.round(o.usd * 100) / 100 })).sort((a, b) => b.usd - a.usd); + const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0); + return { mode: c.mode, from, to, purchases: rows.length, recipients, totals: { wouldPayUsd: Math.round(paidUsd * 100) / 100, wouldPayPol: recipients.reduce((n, o) => n + o.pol, 0), + companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows }; +} +// last full week, or the week containing `day` +async function week(day) { + const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(Date.now() - 7 * 86400000); + const from = ctMidnight(monday), to = ctMidnight(new Date(Date.parse(monday) + 7 * 86400000).toISOString().slice(0, 10)); + return Object.assign(await report(from, to), { week: monday }); +} + +// Monday morning: the dry-run summary to Marty's private Telegram, once per week, and a copy on the volume +const STATE = () => path.join(DATA_DIR, 'override-dryrun.json'); +async function tick() { + if (cfg().mode === 'off' || !notify) return; + const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' }).formatToParts(new Date()).map(p => [p.type, p.value])); + if (parts.weekday !== 'Mon' || Number(parts.hour) < 9) return; + let st = {}; try { st = JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) {} + const r = await week(); if (st.lastWeek === r.week) return; + st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } }); + try { fs.writeFileSync(STATE(), JSON.stringify(st)); } catch (e) {} + const top = r.recipients.slice(0, 8).map(o => '#' + o.recipientId + ': $' + o.usd.toFixed(2) + ' (' + o.pol.toFixed(2) + ' POL, ' + o.purchases + ' buys)').join('\n'); + await notify('\u{1F4CA} Level-4 override, DRY RUN · week of ' + r.week + '\n' + r.purchases + ' purchases, $' + r.totals.salesUsd.toFixed(2) + ' sales\n' + + 'Would pay $' + r.totals.wouldPayUsd.toFixed(2) + ' (' + r.totals.wouldPayPol.toFixed(2) + ' POL) to ' + r.recipients.length + ' members; company keeps $' + r.totals.companyKeepsUsd.toFixed(2) + ' of the 3%.\n' + + (top || 'Nobody qualified this week.') + '\nNo money moved. Details: https://instantadpay.com/api/admin/override?week=' + r.week, null).catch(() => {}); +} +module.exports = { init, report, week, recipientFor, tick, PCT, MIN_BUYERS, HOP_CAP }; diff --git a/server.js b/server.js index 1d766d8..c89ade2 100644 --- a/server.js +++ b/server.js @@ -59,6 +59,7 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S const refill = require('./refill'); const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +const override = require('./override'); // level-4 override, DRY RUN: weekly who-would-be-paid report, no money moves (2026-10-17) const translate = require('./translate'); // help desk: member messages in other languages, replies back in theirs (2026-10-16) const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16) const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16) @@ -562,6 +563,8 @@ async function boot() { telegram: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} InstantAdPay · ' + text, sc.telegramEchoTopicId); }, notify: async (memberId, subject, text, kind) => { const a = await accounts.byMemberId(memberId); if (!a || !a.email) return; 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', [a.email], subject, html, kind || 'notice'); } }); setInterval(() => wednesday.tick().catch(e => console.error('wednesday', e.message)), 5 * 60 * 1000); + override.init({ dataDir: DATA_DIR, chain, siteConfig, notify: supportTelegram }); + setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000); setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com' }); // LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest @@ -4592,6 +4595,14 @@ const server = http.createServer(async (req, res) => { if (!isAdmin(req)) return json(res, 200, { admin: false }); return json(res, 200, { admin: true, email: ADMIN_EMAIL }); } + // -- level-4 override dry run (2026-10-17): ?week=YYYY-MM-DD (any day in the week) or ?from=&to= (ms); rows=1 adds every purchase + if (p === '/api/admin/override' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const from = Number(u.searchParams.get('from')), to = Number(u.searchParams.get('to')); + const r = from && to ? await override.report(from, to) : await override.week(u.searchParams.get('week') || ''); + if (u.searchParams.get('rows') !== '1') delete r.rows; + return json(res, 200, r, { 'Cache-Control': 'no-store' }); + } // -- help desk, admin side (2026-10-16): the Support pane if (p === '/api/admin/support/telegram/register' && req.method === 'POST') { // point @CTBTickets_bot's webhook at this server if (!isAdmin(req)) return json(res, 401, { error: 'auth' });