bfbea142b6
Grace: for 24 hours from an account's created time nobody can adopt the person by hand. They stay on the waiting list after the open ones with an Opens in badge and no Adopt button, and adopt() refuses in plain words. Only sign-up counts, so someone back in the tank later has no grace. Auto-assign does not wait for it: the 24-hour hold still runs from the wallet link and is not stretched. No notice tells people to adopt someone they cannot adopt yet: the wallet-ready post waits for the grace and says the time really left, is skipped when the rotation takes them in that tick, the arrivals post moves to when the grace ends (marks.claim per member), and the Overview note and weekly email count only people who are open. Prompt: a member with no sponsor and no member number sees the card at the top of Overview, types a username, confirms in an in-page box, and that person becomes their sponsor through setSponsor as a deliberate change with by 'invited', so it follows to LinkSpin and clears the hold. Refused: self, unknown username, already sponsored, member number or wallet already on the contract, a chain loop, a suspended sponsor, a no-payout chain, and a line with nobody on the contract (they would walk up to the company). The network sponsor is tried first. Nobody invited me hides it and a small link brings it back. Not an adoption: status 'invited', no 7-day window, not counted toward the two. The named sponsor gets the referral email and an on-site notice. Switch-on-payouts reminders track the named sponsor. Chatbot canned + systemPrompt, KNOWLEDGE_DATE 2026-11-07. my.js, admin.js, admin-sponsorcheck.js ?v=20261107tg. qa/tank-hold.mjs, qa/sponsorfollow.test.cjs and qa/sponsorfollow-e2e.mjs extended (SF_E2E_PORT overrides the ports). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
646 lines
51 KiB
JavaScript
646 lines
51 KiB
JavaScript
'use strict';
|
|
// Holding tank (Marty, 2026-09-11): free members who arrived with no sponsor wait
|
|
// here, and a member who has bought their own $20+ package can adopt one:
|
|
// first come, at most two open adoptions at a time, an adoption falls back into
|
|
// the tank after 7 days if the person never linked a wallet or bought, and a
|
|
// person can be adopted twice at most before they stay wherever they are.
|
|
// Members can also release one of their own free referrals into the tank
|
|
// (pay it forward). The contract binds sponsor at first purchase, so every
|
|
// hand-off here is a site record until then.
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const db = require('./db');
|
|
|
|
const CAP_OPEN = 2; // open adoptions per adopter
|
|
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
|
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
|
|
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
|
|
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
|
|
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js), and a record of a
|
|
// member naming who invited them (nobody adopted them; nameSponsor below)
|
|
const NOT_COUNTED = ['released', 'conflict', 'invited'];
|
|
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
|
|
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
|
|
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
|
const GRACE_MS = 24 * 3600 * 1000; // nobody adopts a new sign-up by hand for this long after `created`, so they can say who invited them (Marty 2026-11-07)
|
|
const BRAND = 'InstantAdPay';
|
|
const LINE_URL = () => siteUrl + '/my#line';
|
|
|
|
let DATA_DIR = '.', accounts, chain, messages, mailer, siteUrl = 'https://instantadpay.com';
|
|
|
|
const J = {
|
|
db: { v: 1, nextId: 1, adoptions: [], marks: {} },
|
|
FILE: () => path.join(DATA_DIR, 'tank.json'),
|
|
load() { try { this.db = Object.assign(this.db, JSON.parse(fs.readFileSync(this.FILE(), 'utf8'))); } catch (e) {} },
|
|
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
|
|
async add(a) { const row = Object.assign({ id: this.db.nextId++ }, a); this.db.adoptions.push(row); this.save(); return row; },
|
|
async open(adopter) { return this.db.adoptions.filter(x => x.status === 'open' && (!adopter || x.adopter === adopter)); },
|
|
async countFor(adoptee) { return this.db.adoptions.filter(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)).length; },
|
|
async setStatus(id, status) { const x = this.db.adoptions.find(r => r.id === id); if (x) { x.status = status; x.closed = Date.now(); this.save(); } },
|
|
async recent(n) { return this.db.adoptions.slice(-(n || 100)).reverse(); },
|
|
async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)); },
|
|
async all() { return this.db.adoptions.slice(); },
|
|
async mark(lead) { return this.db.marks[lead] || null; },
|
|
async setMark(lead, f) { this.db.marks[lead] = Object.assign(this.db.marks[lead] || {}, f); this.save(); }
|
|
};
|
|
const D = {
|
|
async add(a) {
|
|
const r = await db.q('INSERT INTO adoptions (adoptee,adopter,ts,expires,status,note) VALUES (?,?,?,?,?,?)', [a.adoptee, a.adopter, a.ts, a.expires, a.status, a.note || null]);
|
|
return Object.assign({ id: r.insertId }, a);
|
|
},
|
|
async open(adopter) {
|
|
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
|
return rows.map(rowA);
|
|
},
|
|
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n); },
|
|
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
|
|
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
|
|
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict','invited')", [adoptee]); return Number(r[0].n) > 0; },
|
|
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
|
|
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
|
|
async setMark(lead, f) {
|
|
const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f);
|
|
await db.q('INSERT INTO lead_marks (`lead`,sponsor,contacted_ts,warned_ts) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE sponsor=VALUES(sponsor), contacted_ts=VALUES(contacted_ts), warned_ts=VALUES(warned_ts)', [lead, m.sponsor || null, m.contacted || null, m.warned || null]);
|
|
}
|
|
};
|
|
const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null });
|
|
const impl = () => db.enabled() ? D : J;
|
|
|
|
let ads = null;
|
|
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load();
|
|
hooks = opts.hooks || {}; RS.st = null; RS.load(); }
|
|
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to LinkSpin
|
|
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
|
|
let follow = null, store = null;
|
|
const setSponsor = (email, token, by, note) => follow ? follow.setDeliberate(email, token, by, note) : accounts.setSponsorRef(email, token);
|
|
const OTHER = 'LinkSpin';
|
|
const remoteOpen = email => !!(store && store.remoteOpen(email));
|
|
const remoteCount = email => store ? store.remoteCount(email) : 0;
|
|
const countAll = async email => (await impl().countFor(email)) + remoteCount(email); // the two-adoptions limit counts both platforms
|
|
|
|
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
|
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
|
const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or fell back), still free
|
|
|
|
// waiting list: newest sign-in first so a live one is easy to spot
|
|
async function waiting() {
|
|
const all = await accounts.listAll(5000);
|
|
const rows = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
|
// what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers
|
|
const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {};
|
|
return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0,
|
|
wallet: !!a.address, activated: !!a.memberId, // in the tank "activated" is always false (payouts on = out of the tank); wallet can still be linked
|
|
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0,
|
|
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
|
|
opensAt: inGrace(a) ? graceEnd(a) : 0, // new sign-up: nobody can adopt them by hand before this (0 = open now)
|
|
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
|
|
// open before the sign-up grace ones, ready members first (least time left first), then newest sign-in
|
|
.sort((a, b) => (a.opensAt ? 1 : 0) - (b.opensAt ? 1 : 0) || (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || (a.ready && b.ready ? a.readyAt - b.readyAt : 0) || (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
|
}
|
|
|
|
// has this member bought a $20+ package themselves? (the qualifying-for-yourself buy)
|
|
function hasOwnBuy(memberId) {
|
|
if (!memberId) return false;
|
|
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && ev.buyerId === memberId && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS) return true;
|
|
return false;
|
|
}
|
|
async function eligibility(email) {
|
|
const a = await accounts.byEmail(email);
|
|
if (!a) return { ok: false, reason: 'Sign in first.' };
|
|
if (!a.memberId) return { ok: false, reason: 'Switch on payouts and buy your first $20 package to adopt from the tank.' };
|
|
if (!hasOwnBuy(a.memberId)) return { ok: false, reason: 'Buy your own $20 or more package first. Adopting is for members who have made that move themselves.' };
|
|
const open = await impl().open(a.email);
|
|
if (open.length >= CAP_OPEN) return { ok: false, reason: 'You have ' + CAP_OPEN + ' open adoptions. Help one of them link a wallet or buy, and a slot frees up.', full: true };
|
|
return { ok: true, account: a, open };
|
|
}
|
|
|
|
async function view(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
const el = await eligibility(e);
|
|
const mine = [];
|
|
for (const ad of await impl().open(e)) {
|
|
const a = await accounts.byEmail(ad.adoptee);
|
|
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
|
|
}
|
|
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, graceHours: GRACE_MS / 3600000, waiting: await waiting(), mine };
|
|
}
|
|
|
|
async function adopt(adopterEmail, who, note, opts) {
|
|
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
|
const e = String(adopterEmail || '').toLowerCase();
|
|
const el = await eligibility(e);
|
|
if (!el.ok) return { error: el.reason };
|
|
const me = el.account;
|
|
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
|
|
const list = await waiting();
|
|
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
|
if (!target) return { error: 'That member is no longer in the tank.' };
|
|
if (target.email === e) return { error: 'That is you.' };
|
|
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
|
|
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
|
|
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
|
const token = me.username || me.code || String(me.memberId);
|
|
const r = await setSponsor(target.email, token, 'adopt');
|
|
if (r.error) return r;
|
|
const now = Date.now();
|
|
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined InstantAdPay without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
|
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, 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
|
|
payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick)
|
|
const link = activateLink();
|
|
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
|
|
if (mailer && mailer.hasKey()) {
|
|
try {
|
|
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
|
|
'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) {
|
|
try {
|
|
await mailer.send(e, 'InstantAdPay: ' + target.name + ' from the holding tank is now in your line',
|
|
target.name + ' linked a wallet and waited 24 hours in the holding tank without anyone picking them up, so the site assigned them to you (adopters take turns). You are their sponsor now: when they switch on payouts or buy, it locks under you.\n\nWe sent them this chat from you:\n\n' + text + '\n\nSay hello and help them with their first steps: ' + siteUrl + '/my#line\n\nInstantAdPay');
|
|
} catch (err) {}
|
|
}
|
|
}
|
|
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
|
}
|
|
|
|
// pay it forward: give one of your own free referrals to the tank
|
|
async function release(ownerEmail, directEmail) {
|
|
const o = String(ownerEmail || '').toLowerCase(), d = String(directEmail || '').toLowerCase();
|
|
const owner = await accounts.byEmail(o), direct = await accounts.byEmail(d);
|
|
if (!owner || !direct) return { error: 'No such member.' };
|
|
const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String);
|
|
if (!toks.includes(String(direct.sponsorRef || ''))) return { error: 'That member is not in your line.' };
|
|
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
|
|
// picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13)
|
|
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
|
|
let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
|
// adopted on LinkSpin by this same member: the same 3-day commitment applies here
|
|
const rt = store && store.remote(d);
|
|
if (!young && rt && rt.open && rt.adopterEmail === o && rt.ts && Date.now() - rt.ts < HOLD_MS && remoteOpen(d)) young = { ts: rt.ts };
|
|
if (young) {
|
|
const hrs = Math.ceil((HOLD_MS - (Date.now() - young.ts)) / 3600000);
|
|
return { error: 'You picked ' + nameOf(direct) + ' up from the tank ' + Math.max(1, Math.round((Date.now() - young.ts) / 3600000)) + ' hour(s) ago. An adoption is a commitment: message them, help them link a wallet, and if it goes nowhere you can release them in ' + hrs + ' hour(s).' };
|
|
}
|
|
const r = await setSponsor(d, '', 'release');
|
|
if (r.error) return r;
|
|
// an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two
|
|
let closed = 0;
|
|
for (const ad of openAds) { await impl().setStatus(ad.id, 'dropped'); closed++; }
|
|
if (!closed) await impl().add({ adoptee: d, adopter: o, ts: Date.now(), expires: Date.now(), status: 'released', note: 'released to the tank' });
|
|
return { ok: true, adopted: closed > 0, ownerName: nameOf(owner), memberName: nameOf(direct) };
|
|
}
|
|
|
|
// open adoptions past their window: converted ones close as done; the rest fall
|
|
// back into the tank unless the person has been adopted twice already
|
|
async function sweep() {
|
|
const now = Date.now();
|
|
let done = 0, back = 0, kept = 0;
|
|
for (const ad of await impl().open(null)) {
|
|
if (ad.expires > now) continue;
|
|
const a = await accounts.byEmail(ad.adoptee);
|
|
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
|
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
|
|
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
|
await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
|
|
await impl().setStatus(ad.id, 'expired'); back++;
|
|
}
|
|
const r = await rescueSweep();
|
|
const au = await autoAssign().catch(e => { console.error('tank autoAssign', e.message); return { assigned: [], held: 0 }; }); // the 24-hour safety net (also every 15 min in readyTick)
|
|
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead, autoAssigned: au.assigned.length, held: au.held };
|
|
}
|
|
|
|
// pay-it-forward gift record: the sponsor already sent POL wallet-to-wallet; we
|
|
// only log the hash and tell the recipient. Recipient must be in the giver's line.
|
|
async function recordGift(fromEmail, toEmail, tx, pol) {
|
|
const f = String(fromEmail || '').toLowerCase(), t = String(toEmail || '').toLowerCase();
|
|
const giver = await accounts.byEmail(f), to = await accounts.byEmail(t);
|
|
if (!giver || !to) return { error: 'No such member.' };
|
|
const toks = [giver.code, giver.username, giver.memberId ? String(giver.memberId) : null].filter(Boolean).map(String);
|
|
const adopted = (await impl().open(f)).some(ad => ad.adoptee === t);
|
|
if (!toks.includes(String(to.sponsorRef || '')) && !adopted) return { error: 'That member is not in your line.' };
|
|
if (!/^0x[0-9a-fA-F]{64}$/.test(String(tx || ''))) return { error: 'Transaction hash missing.' };
|
|
const amount = Number(pol) || 0;
|
|
const row = { adoptee: t, adopter: f, ts: Date.now(), expires: Date.now(), status: 'gift', note: 'PIF ' + amount + ' POL ' + tx };
|
|
await impl().add(row);
|
|
const cc = chain.getConfig ? chain.getConfig() : {};
|
|
const link = ((cc.explorer || 'https://polygonscan.com').replace(/\/+$/, '')) + '/tx/' + tx;
|
|
const text = nameOf(giver) + ' just sent ' + amount + ' POL to your wallet so you can buy your first package. It is already there: open Buy packages when you are ready. Proof: ' + link;
|
|
try { await messages.sendChat(giver.memberId || 0, f, t, text); } catch (e) {}
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(t, nameOf(giver) + ' sent you POL for your first InstantAdPay package', text + '\n\n' + siteUrl + '/my#buy'); } catch (e) {} }
|
|
return { ok: true };
|
|
}
|
|
|
|
// ── dormant-lead rescue ──
|
|
// a free lead (no wallet, no purchase) whose sponsor has not written to them, on
|
|
// site or by marking "contacted", for WARN_DAYS gets a warning to the sponsor;
|
|
// at RESCUE_DAYS (warning at least 4 days old) the lead moves to the tank.
|
|
// Anyone with an adoption record is left to the tank's own window.
|
|
async function sponsorOf(acct) {
|
|
const t = String(acct.sponsorRef || ''); if (!t) return null;
|
|
return (await accounts.byUsername(t)) || (await accounts.byCode(t)) || (/^\d+$/.test(t) ? await accounts.byMemberId(Number(t)) : null) || null;
|
|
}
|
|
async function lastContact(sponsorEmail, lead) {
|
|
const m = await impl().mark(lead.email);
|
|
const chat = messages ? await messages.lastFrom(sponsorEmail, lead.email) : 0;
|
|
return Math.max(lead.created || 0, chat, (m && m.contacted) || 0);
|
|
}
|
|
// what the coach card shows the sponsor about each free direct
|
|
async function rescueInfo(sponsorEmail, lead) {
|
|
if (!lead || lead.memberId || lead.address) return null;
|
|
if (await impl().hasRecord(lead.email)) return null;
|
|
const since = await lastContact(sponsorEmail, lead);
|
|
const days = Math.floor((Date.now() - since) / 86400000);
|
|
const m = await impl().mark(lead.email);
|
|
return { days, warned: !!(m && m.warned), rescueInDays: Math.max(0, RESCUE_DAYS - days), unreached: days >= WARN_DAYS };
|
|
}
|
|
async function markContacted(sponsorEmail, leadEmail) {
|
|
const s = String(sponsorEmail || '').toLowerCase(), l = String(leadEmail || '').toLowerCase();
|
|
const owner = await accounts.byEmail(s), lead = await accounts.byEmail(l);
|
|
if (!owner || !lead) return { error: 'No such member.' };
|
|
const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String);
|
|
if (!toks.includes(String(lead.sponsorRef || ''))) return { error: 'That member is not in your line.' };
|
|
await impl().setMark(l, { sponsor: s, contacted: Date.now(), warned: 0 });
|
|
return { ok: true };
|
|
}
|
|
async function rescueSweep() {
|
|
const now = Date.now();
|
|
let warned = 0, rescued = 0, dead = 0;
|
|
for (const a of await accounts.listAll(5000)) {
|
|
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
|
|
if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules
|
|
const pv = store && store.get(a.email);
|
|
if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on LinkSpin: the tank's window rules there
|
|
const sp = await sponsorOf(a);
|
|
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
|
if (now - (a.created || 0) < 86400000) continue;
|
|
await setSponsor(a.email, '', 'rescue', 'dead sponsor link ' + a.sponsorRef);
|
|
await impl().add({ adoptee: a.email, adopter: 'dead:' + a.sponsorRef, ts: now, expires: now, status: 'rescued', note: 'sponsor link ' + a.sponsorRef + ' resolves to nobody' });
|
|
dead++; continue;
|
|
}
|
|
if (sp.email === a.email) continue;
|
|
const since = await lastContact(sp.email, a);
|
|
const days = (now - since) / 86400000;
|
|
if (days < WARN_DAYS) continue;
|
|
const m = (await impl().mark(a.email)) || {};
|
|
if (!m.warned || m.warned < since) {
|
|
await impl().setMark(a.email, { sponsor: sp.email, warned: now });
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, 'InstantAdPay: you have not reached ' + nameOf(a),
|
|
nameOf(a) + ' joined through your link ' + Math.floor(days) + ' days ago and there is no message from you to them on the site.\n\nContact them, or mark "Contacted them" on their row in Members > My line if you reached them by phone or text. If nothing happens in the next ' + (RESCUE_DAYS - WARN_DAYS) + ' days they move to the holding tank so another member can help them.\n\n' + siteUrl + '/my#line'); } catch (e) {} }
|
|
warned++; continue;
|
|
}
|
|
if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) {
|
|
await setSponsor(a.email, '', 'rescue', 'no contact for ' + Math.floor(days) + ' days');
|
|
await impl().add({ adoptee: a.email, adopter: sp.email, ts: now, expires: now, status: 'rescued', note: 'rescued from ' + nameOf(sp) + ' after ' + Math.floor(days) + ' days without contact' });
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, 'InstantAdPay: ' + nameOf(a) + ' moved to the holding tank',
|
|
nameOf(a) + ' joined through your link ' + Math.floor(days) + ' days ago and was never contacted, so they have moved to the holding tank where another member can pick them up. Nothing on-chain changed. Your other referrals are unaffected.\n\n' + siteUrl + '/my#line'); } catch (e) {} }
|
|
rescued++;
|
|
}
|
|
}
|
|
return { warned, rescued, dead };
|
|
}
|
|
|
|
// -- network tank (sponsorfollow.js) --
|
|
// a deliberate sponsor change arrived from LinkSpin and was applied here: open adoptions of this person by someone else
|
|
// close quietly (no chat, no mail: the platform where it happened already told everyone)
|
|
async function onFollow(email, inc, d) {
|
|
const e = String(email || '').toLowerCase(); const to = String((inc && inc.sponsorEmail) || '').toLowerCase();
|
|
const status = d && d.conflict ? 'conflict' : ({ release: 'dropped', expire: 'expired', rescue: 'expired' }[inc && inc.by] || 'moved');
|
|
let closed = 0;
|
|
for (const ad of await impl().open(null)) if (ad.adoptee === e && ad.adopter !== to) { await impl().setStatus(ad.id, status); closed++; }
|
|
return closed;
|
|
}
|
|
// what a sync row says about this platform's own adoptions of a person: how many count, and the open one if any
|
|
function summaryOf(rows) {
|
|
let count = 0, open = null;
|
|
for (const x of rows) { if (!NOT_COUNTED.includes(x.status)) count++; if (x.status === 'open' && (!open || x.ts > open.ts)) open = x; }
|
|
if (!count && !open) return null;
|
|
return { count, open: !!open, adopterEmail: open ? open.adopter : null, ts: open ? open.ts : null, expires: open ? open.expires : null };
|
|
}
|
|
async function summaryMap() {
|
|
const by = new Map(); for (const x of await impl().all()) { if (!by.has(x.adoptee)) by.set(x.adoptee, []); by.get(x.adoptee).push(x); }
|
|
const out = new Map(); for (const [k, rows] of by) { const s = summaryOf(rows); if (s) out.set(k, s); } return out;
|
|
}
|
|
async function summaryFor(email) { const e = String(email || '').toLowerCase(); return summaryOf((await impl().all()).filter(x => x.adoptee === e)); }
|
|
async function historyMap() {
|
|
const out = new Map();
|
|
for (const x of await impl().all()) { if (!out.has(x.adoptee)) out.set(x.adoptee, []); out.get(x.adoptee).push({ adopter: x.adopter, ts: x.ts, status: x.status, closed: x.closed || null, note: x.status === 'open' ? null : (x.note || null) }); }
|
|
for (const v of out.values()) v.splice(0, Math.max(0, v.length - 6));
|
|
return out;
|
|
}
|
|
|
|
// ── activation hold (Marty, 2026-10-27: "hold them for no longer than 24 hours") ──
|
|
// The contract binds a sponsor for good at the first activation or purchase. A tank member (no sponsor, no member
|
|
// number) who switched on payouts used to be bound under the fallback position (#1), which took them out of the tank
|
|
// for ever. Now, in this order:
|
|
// 1. ALIGN: someone the network already knows (LinkSpin has a sponsor for the same email or wallet) is placed under
|
|
// that sponsor, when the sponsor has a real account here and is not a sponsor this person was released or rescued
|
|
// from. Ordinary sponsor write (accounts.setSponsorRef): LinkSpin already agrees, so nothing follows anywhere.
|
|
// 2. HOLD: otherwise /api/me and /api/sponsor answer tankHold instead of the fallback and the site refuses the
|
|
// activation / first purchase. The clock starts when the member is first seen with a wallet linked ("ready").
|
|
// 3. SAFETY NET: a ready member nobody adopted within 24 hours goes to the next eligible adopter in rotation
|
|
// (least recently auto-assigned first, ties by who qualified first) through the same adopt() path. Nobody
|
|
// eligible: keep holding, alert the admin once. Never the company.
|
|
const READY_MS = 24 * 3600 * 1000; // the longest a ready member is held
|
|
const TICK_MS = 15 * 60 * 1000; // readyTick cadence: auto-assign starts one tick early so the hold never runs past 24 h
|
|
const AUTO_SEEN_MS = 7 * 86400000; // an auto-assign adopter signed in within the last 7 days
|
|
let hooks = {};
|
|
let clock = () => Date.now(); // qa/tank-hold.mjs mocks it
|
|
function setClock(fn) { clock = typeof fn === 'function' ? fn : (() => Date.now()); }
|
|
const RS = {
|
|
st: null, FILE: () => path.join(DATA_DIR, 'tank-ready.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.ready = this.st.ready || {}; this.st.adopters = this.st.adopters || {}; this.st.aligned = this.st.aligned || [];
|
|
return this.st;
|
|
},
|
|
save() { try { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('tank-ready save', e.message); } }
|
|
};
|
|
const holdOf = rec => rec ? { since: rec.readyAt, until: rec.readyAt + READY_MS } : null;
|
|
// first time seen in the tank with a wallet linked: the 24-hour clock starts (accounts already linked at deploy start then)
|
|
function markReady(a) {
|
|
if (!a || !inTank(a) || !a.address) return null;
|
|
const st = RS.load(); const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
|
const cur = st.ready[e];
|
|
if (!cur || cur.done) { st.ready[e] = { readyAt: clock(), notified: cur ? cur.notified || false : false }; RS.save(); } // back in the tank later: a fresh clock
|
|
return st.ready[e];
|
|
}
|
|
function readyRec(email) { const r = RS.load().ready[String(email || '').toLowerCase()]; return r && !r.done ? r : null; }
|
|
// sponsors this person was moved away from here on purpose (adopted then dropped, released, rescued) never count
|
|
async function previousSponsors(email) {
|
|
const e = String(email || '').toLowerCase(); const out = new Set();
|
|
for (const ad of await impl().all()) if (ad.adoptee === e && ad.adopter && !String(ad.adopter).startsWith('dead:')) out.add(String(ad.adopter).toLowerCase());
|
|
const pv = store && store.get(e); if (pv && pv.prevEmail) out.add(String(pv.prevEmail).toLowerCase());
|
|
const m = await impl().mark(e); if (m && m.sponsor) out.add(String(m.sponsor).toLowerCase());
|
|
return out;
|
|
}
|
|
async function alignToNetwork(a) {
|
|
if (!a || !inTank(a) || !hooks.network) return null;
|
|
const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
|
const n = hooks.network(e, a.address || null); if (!n || !n.sponsorEmail) return null;
|
|
const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null;
|
|
if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from
|
|
const sp = await accounts.byEmail(spEmail);
|
|
if (!sp || (accounts.isUnclaimedShell && accounts.isUnclaimedShell(sp))) return null; // the sponsor must really be here
|
|
if (hooks.isSuspended && hooks.isSuspended(sp.email)) return null;
|
|
const token = sp.username || sp.code || (sp.memberId ? String(sp.memberId) : ''); if (!token) return null;
|
|
let cur = sp; const seen = new Set(); // never a loop (they cannot sit under their own downline)
|
|
for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
|
const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null;
|
|
const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null;
|
|
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')';
|
|
st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', at: clock(), why });
|
|
if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300);
|
|
if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; }
|
|
RS.save();
|
|
console.log('tank align', e, '->', sp.email, why);
|
|
if (hooks.aligned) { try { await hooks.aligned({ email: e, name: nameOf(fresh), sponsorEmail: sp.email, sponsorName: nameOf(sp), why }); } catch (err) {} }
|
|
return { to: sp.email, toName: nameOf(sp), via: n.via || 'email', why };
|
|
}
|
|
// /api/me and /api/sponsor, when the fallback position would be used: align first, else the hold
|
|
async function holdFor(a) {
|
|
if (!a || !inTank(a)) return null;
|
|
const al = await alignToNetwork(a).catch(e => { console.error('tank align', e.message); return null; });
|
|
if (al) return { aligned: al };
|
|
const rec = markReady(a);
|
|
return { hold: rec ? holdOf(rec) : { since: null, until: null } };
|
|
}
|
|
// adopters for the safety net, in rotation order
|
|
async function rotation(excludeEmail) {
|
|
const qual = new Map(); // member # -> block of their first own $20+ purchase
|
|
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS && ev.buyerId) { const b = Number(ev.block) || 0; const id = Number(ev.buyerId); if (!qual.has(id) || b < qual.get(id)) qual.set(id, b); }
|
|
const company = Number(hooks.companyId ? hooks.companyId() : 1) || 1; const now = clock(); const st = RS.load(); const out = [];
|
|
for (const a of await accounts.listAll(5000)) {
|
|
const id = Number(a.memberId) || 0;
|
|
if (!id || id === company || id === 1 || !qual.has(id) || a.email === excludeEmail) continue;
|
|
if (!a.lastSeen || now - a.lastSeen > AUTO_SEEN_MS) continue;
|
|
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) continue; // suspended or fraud-flagged: the same rule as a manual adoption
|
|
out.push({ a, last: Number(st.adopters[a.email]) || 0, q: qual.get(id) });
|
|
}
|
|
out.sort((x, y) => x.last - y.last || x.q - y.q);
|
|
return out;
|
|
}
|
|
async function inDownlineOf(adoptee, adopter) { // is the adopter somewhere under the adoptee? (adopting them would close a loop)
|
|
let cur = await accounts.sponsorOf(adopter.email); const seen = new Set();
|
|
for (let i = 0; cur && i < 60; i++) { if (cur.email === adoptee || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
|
return false;
|
|
}
|
|
let autoBusy = null; // readyTick (15 min) and sweep (hourly) never run the safety net at the same time
|
|
function autoAssign() { if (!autoBusy) autoBusy = autoAssignRun().finally(() => { autoBusy = null; }); return autoBusy; }
|
|
async function autoAssignRun() {
|
|
const st = RS.load(); const now = clock(); const out = { assigned: [], held: 0 };
|
|
const due = [];
|
|
for (const [e, rec] of Object.entries(st.ready)) {
|
|
if (rec.done) continue;
|
|
const a = await accounts.byEmail(e);
|
|
if (!a || !inTank(a)) { rec.done = clock(); continue; } // adopted, aligned, bought or gone: the hold has lifted
|
|
if (remoteOpen(e) || !a.address) continue; // picked up on LinkSpin (the follow lands here shortly) / wallet unlinked
|
|
if (now < rec.readyAt + READY_MS - TICK_MS) continue;
|
|
due.push([e, rec, a]);
|
|
}
|
|
due.sort((x, y) => x[1].readyAt - y[1].readyAt);
|
|
let pool = null;
|
|
for (const [e, rec, a] of due) {
|
|
if (!pool) pool = await rotation(e);
|
|
let done = null;
|
|
for (const c of pool) {
|
|
if (c.a.email === e) continue;
|
|
if ((await impl().open(c.a.email)).length >= CAP_OPEN) continue;
|
|
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
|
|
if (await inDownlineOf(e, c.a)) continue;
|
|
const msg = 'Hi, I am ' + nameOf(c.a) + '. You joined InstantAdPay without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
|
|
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
|
|
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
|
|
}
|
|
if (done) {
|
|
st.adopters[done.adopter] = clock(); rec.done = clock(); rec.autoAssigned = done.adopter;
|
|
for (const c of pool) c.last = Number(st.adopters[c.a.email]) || 0;
|
|
pool.sort((x, y) => x.last - y.last || x.q - y.q);
|
|
out.assigned.push(done); RS.save();
|
|
if (hooks.assigned) { try { await hooks.assigned(done); } catch (err) {} }
|
|
} else {
|
|
out.held++;
|
|
if (!rec.noAdopterAlerted) {
|
|
rec.noAdopterAlerted = clock(); RS.save();
|
|
if (hooks.adminAlert) { try { await hooks.adminAlert('InstantAdPay holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $20+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not suspended or on a no-payout chain). They stay on hold, never under the company. Adopt them from My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
|
}
|
|
}
|
|
}
|
|
RS.save();
|
|
return out;
|
|
}
|
|
// every 15 minutes (server.js): align whoever the network already knows, start the clock for new ready members,
|
|
// run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them).
|
|
async function readyTick() {
|
|
const st = RS.load(); const fresh = []; let aligned = 0;
|
|
for (const a of await accounts.listAll(5000)) {
|
|
if (!inTank(a)) continue;
|
|
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
|
if (remoteOpen(a.email)) continue;
|
|
const rec = markReady(a);
|
|
// linkedNow: the member was on the site when they became ready, so they linked the wallet just now; otherwise the
|
|
// wallet predates this tank visit (e.g. a dormant member returned by a sponsor; Marty 2026-10-29: the notice read as a
|
|
// fresh link) and the notice says so, with their last sign-in
|
|
// Sign-up grace (2026-11-07): no "adopt them" post for someone who cannot be adopted yet; announced when the grace ends,
|
|
// and not at all when the safety net takes them in this same tick (nothing left for anyone to do)
|
|
if (rec && !rec.notified && !inGrace(a)) { rec.notified = clock(); if (clock() < rec.readyAt + READY_MS - TICK_MS) fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS, lastSeen: a.lastSeen || 0, linkedNow: (a.lastSeen || 0) >= rec.readyAt - 15 * 60 * 1000 }); }
|
|
}
|
|
RS.save();
|
|
const auto = await autoAssign();
|
|
const pay = await payTick().catch(e => { console.error('tank payTick', e.message); return { sent: [] }; });
|
|
return { fresh, aligned, assigned: auto.assigned, held: auto.held, reminders: pay.sent };
|
|
}
|
|
|
|
// ── one-tap switch on payouts after an assignment (Marty, 2026-10-27) ──
|
|
// The contract only has activate(sponsorId) from the member's OWN wallet (non-custodial), so the site cannot switch
|
|
// payouts on for them. What it can do: every assignment (manual adoption or the 24-hour safety net) carries a link to
|
|
// /my?activate=1#wallet, which starts the Activate flow with the sponsor filled in (my.js), and a member who has not
|
|
// switched on payouts gets ONE reminder email at 24 hours (and the new sponsor ONE notice), and a last email at 72 hours.
|
|
// Stops as soon as they activate or buy (memberId / MemberActivated), or the sponsor changes. State: tank-ready.json
|
|
// `pay` (adoptee email -> { at, adopter, adoptionId, auto, r1, r2, done }). Deploy overlap: each send is gated by
|
|
// hooks.claim (marks.claim, one MySQL row per key across both app copies) and the record is saved before the send.
|
|
const PAY_R1_MS = 24 * 3600 * 1000; // first reminder (member email + sponsor notice)
|
|
const PAY_R2_MS = 72 * 3600 * 1000; // last reminder (member email only)
|
|
const activateLink = () => siteUrl + '/my?activate=1#wallet';
|
|
const chatPayLine = link => 'Switch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + link;
|
|
function mailPayBlock(sponsorName, link, hasWallet) {
|
|
return 'Switch on payouts: ' + link + '\n'
|
|
+ 'One tap opens your wallet with ' + sponsorName + ' already filled in as your sponsor. It is one free transaction, no package needed, and it locks ' + sponsorName + ' in as your sponsor so every payment in your line can reach you.'
|
|
+ (hasWallet ? '' : ' No wallet linked yet? The same link shows you how (one free signature) and then carries on.');
|
|
}
|
|
function payTrack(adoptee, adopter, adoptionId, auto) {
|
|
const st = RS.load(); st.pay = st.pay || {};
|
|
st.pay[String(adoptee).toLowerCase()] = { at: clock(), adopter: String(adopter).toLowerCase(), adoptionId: adoptionId || null, auto: !!auto, r1: 0, r2: 0, done: null };
|
|
RS.save();
|
|
}
|
|
const claimOnce = async key => { if (!hooks.claim) return true; try { return !!(await hooks.claim(key)); } catch (e) { return false; } };
|
|
async function payTick() {
|
|
const st = RS.load(); st.pay = st.pay || {}; const now = clock(); const sent = [];
|
|
for (const [e, rec] of Object.entries(st.pay)) {
|
|
if (rec.done) continue;
|
|
const a = await accounts.byEmail(e);
|
|
if (!a) { rec.done = 'gone'; rec.doneAt = now; continue; }
|
|
if (Number(a.memberId) > 0) { rec.done = 'activated'; rec.doneAt = now; continue; } // switched on payouts or bought
|
|
if (a.address && hooks.activated) { let act = null; try { act = await hooks.activated(a); } catch (err) {} if (act) { rec.done = 'activated'; rec.doneAt = now; continue; } }
|
|
const sp = await accounts.byEmail(rec.adopter);
|
|
const toks = sp ? [sp.code, sp.username, sp.memberId ? String(sp.memberId) : null].filter(Boolean).map(x => String(x).toLowerCase()) : [];
|
|
if (!sp || !toks.includes(String(a.sponsorRef || '').toLowerCase())) { rec.done = 'moved'; rec.doneAt = now; continue; } // released, expired or moved
|
|
const age = now - rec.at; const link = activateLink(); const spName = nameOf(sp); const name = nameOf(a);
|
|
const noWallet = a.address ? '' : '\n\nNo wallet linked yet? The same link shows you how (one free signature) and then carries on.';
|
|
if (!rec.r1 && age >= PAY_R1_MS) {
|
|
rec.r1 = now; RS.save();
|
|
if (age >= PAY_R2_MS) rec.r1skipped = true; // already past 72 h (e.g. the app was down): one email only, the last one below
|
|
else if (await claimOnce('tankpay1:' + e + ':' + rec.at)) {
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(e, 'Reminder: switch on payouts with ' + spName + ' on InstantAdPay',
|
|
'Yesterday ' + spName + ' became your sponsor on InstantAdPay, but your payouts are not switched on yet, so nothing in your line can pay you.\n\nSwitch on payouts: ' + link + '\n\nOne tap opens your wallet with ' + spName + ' already filled in as your sponsor. It is one free transaction, no package needed, and it locks ' + spName + ' in as your sponsor.' + noWallet + '\n\nQuestions? Message ' + spName + ' in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay'); } catch (err) {} }
|
|
if (hooks.notify) { try { await hooks.notify(sp.email, name + ' hasn\'t switched on payouts yet',
|
|
name + ' hasn\'t switched on payouts yet; a nudge from you helps. They were assigned to you 24 hours ago and we sent them a reminder with a one-tap link.\n\nSend them a chat from My line (' + siteUrl + '/my#line), or pass on the same link: ' + link + '\n\nWhen they tap it, their wallet opens with you filled in as their sponsor.'); } catch (err) {} }
|
|
sent.push({ email: e, stage: 1, adopter: sp.email });
|
|
}
|
|
}
|
|
if (!rec.r2 && age >= PAY_R2_MS) {
|
|
rec.r2 = now; RS.save();
|
|
if (await claimOnce('tankpay2:' + e + ':' + rec.at)) {
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(e, 'Last reminder: switch on payouts with ' + spName + ' on InstantAdPay',
|
|
'Three days ago ' + spName + ' became your sponsor on InstantAdPay, and your payouts are still switched off, so any payment meant for you in your line cannot reach you.\n\nSwitch on payouts: ' + link + '\n\nOne tap opens your wallet with ' + spName + ' already filled in. It is one free transaction, no package needed, and it locks ' + spName + ' in as your sponsor.' + noWallet + '\n\nThis is the last reminder. Your account and your sponsor stay as they are.\n\nInstantAdPay'); } catch (err) {} }
|
|
sent.push({ email: e, stage: 2, adopter: sp.email });
|
|
}
|
|
rec.done = 'reminded'; rec.doneAt = now;
|
|
}
|
|
}
|
|
RS.save();
|
|
return { sent };
|
|
}
|
|
function payView() { return Object.entries(RS.load().pay || {}).map(([email, r]) => Object.assign({ email }, r)).sort((x, y) => y.at - x.at).slice(0, 100); }
|
|
function alignedRecent(n) { return RS.load().aligned.slice(-(n || 50)).reverse(); }
|
|
|
|
// ── sign-up grace + "Who invited you?" (Marty approved 2026-11-07: "24-hour grace plus the prompt") ──
|
|
// Nov 2: @santoridaviss signed up with no referral at 10:35 PM, was adoptable at 2:24 AM and adopted at 3:36 AM, before he
|
|
// could say who invited him. So:
|
|
// GRACE: for 24 hours from the account's `created`, nobody can adopt the person BY HAND. They stay on the waiting list with
|
|
// opensAt set (the card shows "Opens in ...", no Adopt button). The dates are each site's own account dates. Only sign-up
|
|
// counts: someone back in the tank later (released, rescued, window ended) is past it.
|
|
// The safety net does not wait for the grace (opts.auto skips it): Marty's rule is a wallet-linked member is held for no
|
|
// longer than 24 hours, so autoAssign keeps its clock from the wallet link. Wallet linked in the first 15 minutes: the
|
|
// rotation can fire up to 15 minutes before the grace ends, and hand adoption never opens for them. Wallet linked in the
|
|
// first hour: hand adoption opens at 24 hours and the rotation takes them about an hour after that.
|
|
// Notices: readyTick announces a ready member only once they can be adopted, and only when time is left (adoptableOf and
|
|
// openedSince keep the Overview note, the arrivals post and the weekly email to people who are open too).
|
|
// PROMPT: a tank member can name who invited them. nameSponsor() goes through setSponsor like adopt(), so it follows to the
|
|
// other site and clears the hold the same way, but it is the member's own choice: only ever for the signed-in member,
|
|
// never an open adoption (no 7-day window, no fall-back, no count toward the two), recorded as status 'invited'.
|
|
function graceEnd(a) { return (Number(a && a.created) || 0) + GRACE_MS; }
|
|
function inGrace(a) { return graceEnd(a) > clock(); }
|
|
function leftText(ms) { const m = Math.max(1, Math.ceil(Number(ms) / 60000) || 1); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; }
|
|
const adoptableOf = list => (list || []).filter(w => !(w.opensAt > clock()));
|
|
async function adoptable() { return adoptableOf(await waiting()); }
|
|
// people whose grace ended after `since` (the arrivals post: announced when they can be adopted, not when they sign up)
|
|
function openedSince(list, since) { const now = clock(); return (list || []).filter(w => { const t = (Number(w.joined) || 0) + GRACE_MS; return t > since && t <= now; }); }
|
|
// what the dashboard needs: null = no card. dismissed = they tapped "Nobody invited me" (a small link brings the card back).
|
|
function inviteAsk(a) {
|
|
if (!a || !inTank(a) || remoteOpen(a.email)) return null;
|
|
return { dismissed: !!(RS.load().noInvite || {})[String(a.email || '').toLowerCase()] };
|
|
}
|
|
function dismissInvite(email) { const st = RS.load(); st.noInvite = st.noInvite || {}; st.noInvite[String(email || '').toLowerCase()] = clock(); RS.save(); return { ok: true }; }
|
|
// someone in the named person's line (them first) already has a contract position? Otherwise the member would be walked up to
|
|
// the company at their first activation, the one thing the tank exists to stop
|
|
async function firstOnContract(sp) {
|
|
let cur = sp; const seen = new Set();
|
|
for (let i = 0; cur && i < 60; i++) { if (Number(cur.memberId) > 0) return cur; if (seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
|
return null;
|
|
}
|
|
// opts.check: every refusal, nothing written (the card asks "is this them?" before the real call)
|
|
async function nameSponsor(email, who, opts) {
|
|
const e = String(email || '').toLowerCase(); const check = !!(opts && opts.check);
|
|
const LOCKED = 'Your payouts are already on, so your sponsor is locked on the contract.';
|
|
let a = await accounts.byEmail(e);
|
|
if (!a) return { error: 'Sign in first.' };
|
|
if (Number(a.memberId) > 0) return { error: LOCKED };
|
|
if (a.sponsorRef) return { error: 'You already have a sponsor.' };
|
|
if (a.address) { // wallet on the contract already, member number not saved yet
|
|
if (hooks.bound) { const id = await Promise.resolve(hooks.bound(a)).catch(() => -1); if (id < 0) return { error: 'Could not check the contract just now. Try again in a minute.' }; if (id > 0) return { error: LOCKED }; }
|
|
else if (hooks.activated && await Promise.resolve(hooks.activated(a)).catch(() => false)) return { error: LOCKED };
|
|
}
|
|
if (remoteOpen(e)) return { error: 'You were just picked up on ' + OTHER + ', so you already have a sponsor.' };
|
|
const al = await alignToNetwork(a).catch(() => null); // one identity: the sponsor the network already knows comes first
|
|
if (al) return { error: 'You already have a sponsor on the network: ' + al.toName + '.', aligned: true };
|
|
const key = String(who || '').trim().toLowerCase().replace(/^@+/, '');
|
|
if (!key) return { error: 'Type the username of the person who invited you.' };
|
|
const sp = /^[a-z0-9_]{3,20}$/.test(key) ? await accounts.byUsername(key) : null;
|
|
if (!sp || (accounts.isUnclaimedShell && accounts.isUnclaimedShell(sp))) return { error: 'No member here has the username ' + key + '. Check the spelling with the person who invited you.' };
|
|
if (String(sp.email).toLowerCase() === e) return { error: 'That is you. Type the username of the person who invited you.' };
|
|
const bar = hooks.excluded || hooks.isSuspended;
|
|
if (bar && bar(sp.email)) return { error: nameOf(sp) + ' cannot take new members right now.' };
|
|
if (await inDownlineOf(e, sp)) return { error: nameOf(sp) + ' is in your own line, so they cannot be your sponsor.' };
|
|
const payee = await firstOnContract(sp);
|
|
if (!payee) return { error: nameOf(sp) + ' has not switched on payouts yet, and nobody above them has either, so you cannot go under them yet. Ask them to switch on payouts, then come back here.' };
|
|
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { error: nameOf(sp) + ' cannot take new members right now.' };
|
|
if (check) return { ok: true, check: true, name: nameOf(sp) };
|
|
a = await accounts.byEmail(e);
|
|
if (!a || !inTank(a)) return { error: 'You already have a sponsor.' };
|
|
const token = sp.username || sp.code || String(sp.memberId);
|
|
const r = await setSponsor(e, token, 'invited', 'named by the member on the Who invited you card');
|
|
if (r && r.error) return r;
|
|
const now = clock();
|
|
const ad = await impl().add({ adoptee: e, adopter: String(sp.email).toLowerCase(), ts: now, expires: now, status: 'invited', note: 'named by the member on the Who invited you card' });
|
|
{ const rr = RS.load().ready[e]; if (rr && !rr.done) { rr.done = now; rr.namedSponsor = sp.email; RS.save(); } } // the hold lifts: their sponsor resolves now
|
|
const name = nameOf(a);
|
|
payTrack(e, sp.email, ad.id, false); // the same switch-on-payouts reminders as an adoption (payTick)
|
|
const subject = 'You have a new referral on ' + BRAND;
|
|
const text = name + ' joined ' + BRAND + ' without a sponsor link and told us you invited them, so they are on your team from today. Say hello and help them with their first steps: ' + LINE_URL();
|
|
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, subject, text + '\n\n' + BRAND); } catch (err) {} }
|
|
if (hooks.notify) { try { await hooks.notify(sp.email, subject, text); } catch (err) {} }
|
|
return { ok: true, name: nameOf(sp), sponsorEmail: sp.email, member: name };
|
|
}
|
|
|
|
async function adminView() {
|
|
const recent = await impl().recent(200);
|
|
const names = {};
|
|
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
|
|
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
|
|
}
|
|
|
|
module.exports = { 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, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|