Compare commits
60 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f1482deb12 | |||
| 6096bf38c6 | |||
| 1089942bca | |||
| fa5acf0745 | |||
| 8b03dd2311 | |||
| 59607d0c94 | |||
| e5c55c2d8b | |||
| 4645d5605a | |||
| fc81c6a4db | |||
| 06f0a87452 | |||
| 27d663ca29 | |||
| b239417cc5 | |||
| 47638ac1fe | |||
| 7f80d82486 | |||
| cecba6b313 | |||
| a4642341aa | |||
| 962cdf08b5 | |||
| 13f3ff56f8 | |||
| bf5cf62caf | |||
| 8ca5ed99e8 | |||
| f322786071 | |||
| 5802fd9835 | |||
| 1b77825256 | |||
| 974d888314 | |||
| 8ecef442a1 | |||
| 6b3cdaaa70 | |||
| 15f5374fac | |||
| 50337bfbbc | |||
| 6cc868d10a | |||
| 61c0c52c3b | |||
| 7cadeaa2d9 | |||
| 42a1cce2f1 | |||
| ce977698b9 | |||
| 46bb7dd9dd | |||
| ebdab6c545 | |||
| 43e841721a | |||
| 87a45169d0 | |||
| 38369d6858 | |||
| 91f2e2ec74 | |||
| 4587b5cc58 | |||
| eac83c3eee | |||
| e2eb1578aa | |||
| 89b5969b25 | |||
| c45f1769e7 | |||
| 610f47c625 | |||
| a405c2cdd1 | |||
| 31b167e046 | |||
| 6a3313a861 | |||
| 839c867595 | |||
| 32eefae473 | |||
| 7e902b9b26 | |||
| 4e51470cf5 | |||
| 06b0924651 | |||
| 16ec626d2c | |||
| 1c2928553a | |||
| 3ee605a8bf | |||
| 8b1395a90c | |||
| 9992dd061d | |||
| 6f194596fe | |||
| 1e040f21ff |
+1
-1
@@ -71,7 +71,7 @@ async function view(email) {
|
|||||||
try { out.credits = await ads.balances([...ids], acct.email); } catch (e) { out.credits = null; }
|
try { out.credits = await ads.balances([...ids], acct.email); } catch (e) { out.credits = null; }
|
||||||
try { out.earnedSplit = await ads.earnedSplit(acct.email); } catch (e) {}
|
try { out.earnedSplit = await ads.earnedSplit(acct.email); } catch (e) {}
|
||||||
// campaigns
|
// campaigns
|
||||||
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: c.views, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
|
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: (Number(c.imps) || 0) + (Number(c.impsNas) || 0), pack: c.type === 'visits' ? (Number(c.body) || 0) : 0, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
|
||||||
// line (3 levels) with wallet / bought / qualified per person
|
// line (3 levels) with wallet / bought / qualified per person
|
||||||
const levels = await accounts.downline(acct.email, 3).catch(() => []);
|
const levels = await accounts.downline(acct.email, 3).catch(() => []);
|
||||||
const boughtIds = new Set(chain.recentEvents(1e9).filter(ev => ev.type === 'Purchase').map(ev => ev.buyerId));
|
const boughtIds = new Set(chain.recentEvents(1e9).filter(ev => ev.type === 'Purchase').map(ev => ev.buyerId));
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ async function run() {
|
|||||||
{
|
{
|
||||||
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
|
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
|
||||||
const issues = [];
|
const issues = [];
|
||||||
for (const c of byType('login').filter(c => !c.expires)) { const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
|
for (const c of byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status))) { /* a reservation in the login-ad line is paid up front and has no end date yet (2026-10-23) */ const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
|
||||||
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires).length + ' per-day campaigns compared (30-day slots are paid up front)');
|
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status)).length + ' per-day campaigns compared (30-day slots are paid up front)');
|
||||||
}
|
}
|
||||||
// 4. featured: a live booking older than two hours must have views
|
// 4. featured: a live booking older than two hours must have views
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -146,10 +146,15 @@ function sessionCookie(token) {
|
|||||||
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
|
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
|
||||||
}
|
}
|
||||||
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
||||||
|
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
||||||
|
// signs in from, so their own clicks count as tests on LinkSpin). Never throws into the caller.
|
||||||
|
let seenFn = null; function onSeen(fn) { seenFn = fn; }
|
||||||
async function fromRequest(req) {
|
async function fromRequest(req) {
|
||||||
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
return impl().get(decodeURIComponent(m[1]));
|
const s = await impl().get(decodeURIComponent(m[1]));
|
||||||
|
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
||||||
|
return s;
|
||||||
}
|
}
|
||||||
async function refreshMemberId(sess) {
|
async function refreshMemberId(sess) {
|
||||||
if (!sess) return 0;
|
if (!sess) return 0;
|
||||||
@@ -172,4 +177,4 @@ async function logout(req) {
|
|||||||
if (s) await impl().drop(s.token);
|
if (s) await impl().drop(s.token);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, refreshMemberId, logout };
|
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const path = require('path');
|
|||||||
const { spawn } = require('child_process');
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
let PUBLIC_DIR = null;
|
let PUBLIC_DIR = null;
|
||||||
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 } };
|
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 } , refuelStart: { file: 'badge-refuelstart.jpg', ribbonY: 0.735 }, refuel3: { file: 'badge-refuel3.jpg', ribbonY: 0.783 }, refuel6: { file: 'badge-refuel6.jpg', ribbonY: 0.716 }, refuel12: { file: 'badge-refuel12.jpg', ribbonY: 0.744 } };
|
||||||
let FONT;
|
let FONT;
|
||||||
function font() {
|
function font() {
|
||||||
if (FONT !== undefined) return FONT;
|
if (FONT !== undefined) return FONT;
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ function head(o) {
|
|||||||
+ '</head><body><div class="wrap bl">';
|
+ '</head><body><div class="wrap bl">';
|
||||||
}
|
}
|
||||||
function tail() {
|
function tail() {
|
||||||
return '</div><script src="/assets/common.js?v=20261016n"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
return '</div><script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||||
}
|
}
|
||||||
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
|
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
|
||||||
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
|
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
|
||||||
@@ -152,7 +152,7 @@ function rss(posts) {
|
|||||||
return '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>InstantAdPay blog</title><link>' + SITE + '/blog</link><description>Coaching and teaching articles from Marty Bostick.</description>' + items + '</channel></rss>';
|
return '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>InstantAdPay blog</title><link>' + SITE + '/blog</link><description>Coaching and teaching articles from Marty Bostick.</description>' + items + '</channel></rss>';
|
||||||
}
|
}
|
||||||
function sitemap(posts) {
|
function sitemap(posts) {
|
||||||
const pages = ['/', '/facts', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday', '/wednesday', '/presentation'];
|
const pages = ['/', '/facts', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation'];
|
||||||
const u = pages.map(p => '<url><loc>' + SITE + p + '</loc><changefreq>weekly</changefreq></url>').join('')
|
const u = pages.map(p => '<url><loc>' + SITE + p + '</loc><changefreq>weekly</changefreq></url>').join('')
|
||||||
+ posts.map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq></url>').join('');
|
+ posts.map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq></url>').join('');
|
||||||
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
|
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
|
||||||
|
|||||||
+209
-64
@@ -4,15 +4,27 @@
|
|||||||
//
|
//
|
||||||
// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED
|
// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED
|
||||||
// answers and FACTS below in the same commit.
|
// answers and FACTS below in the same commit.
|
||||||
|
//
|
||||||
|
// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is
|
||||||
|
// the one source the assistant answers from. Each CANNED regex becomes its entry's instant-answer
|
||||||
|
// pattern (same order, first match wins), and for everything else the best-matching entries go into
|
||||||
|
// the system prompt. Admin > Knowledge base edits entries; an edited entry is no longer refreshed from
|
||||||
|
// the code. If the KB store fails, the in-code CANNED list still answers.
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const https = require('https');
|
const https = require('https');
|
||||||
|
const http = require('http');
|
||||||
|
const kb = require('./kb');
|
||||||
|
const kbSeed = require('./kb-seed');
|
||||||
|
|
||||||
let DATA_DIR = null;
|
let DATA_DIR = null;
|
||||||
let chain = null;
|
let chain = null;
|
||||||
|
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
|
||||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||||
|
|
||||||
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; }
|
function init(opts) {
|
||||||
|
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
|
||||||
|
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||||
function key() {
|
function key() {
|
||||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||||
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||||
@@ -20,58 +32,105 @@ function key() {
|
|||||||
function enabled() { return !!key(); }
|
function enabled() { return !!key(); }
|
||||||
|
|
||||||
// ---- canned answers: instant, free, always in voice ----
|
// ---- canned answers: instant, free, always in voice ----
|
||||||
const KNOWLEDGE_DATE = '2026-10-18'; // bump whenever the canned answers / prompt are brought up to date
|
const KNOWLEDGE_DATE = '2026-10-28'; // bump whenever the canned answers / prompt are brought up to date
|
||||||
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
|
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
|
||||||
const CANNED = [
|
const CANNED = [
|
||||||
{ re: SUPPORT_RE, handoff: true,
|
{ id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'],
|
||||||
|
re: SUPPORT_RE, handoff: true,
|
||||||
a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' },
|
a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' },
|
||||||
{ re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i,
|
{ id: 'level4-override', title: 'The Level 4 override (3%)', q: ['What is the Level 4 override?', 'Do I earn from my fourth level?', 'How does the 3% override work?'], tags: ['override', 'level 4', 'fourth level', 'commission', 'payouts'],
|
||||||
a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the Pass badge. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' },
|
re: /(level ?(4|four)|4th level|fourth level|override|3 ?%|three percent)/i,
|
||||||
{ re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i,
|
a: 'The Level 4 override is 3% of every package bought four levels below you, paid by the company on top of the three levels the contract pays. It goes to the buyer’s 4th sponsor up if that member has 5 or more qualifying buyers (direct referrals who bought $20 or more, the same bar as level 3). If they do not have 5 yet, it moves up the line to the next member who does, up to 25 steps, and each purchase pays one override to one person. It is paid weekly in POL from a company wallet, every Monday after 9 AM Central for the Monday to Sunday week before, through the contract’s award function, so every payment has a Polygon link, and it shows in your Earnings as "Level 4 override". Weekly totals under 0.01 POL carry over to the next week. It counts purchases from the start date on, not earlier ones. It comes from the platform’s 20% share, so the 50/20/10 split does not change. What you earn depends on real purchases in your line; nothing is guaranteed.' },
|
||||||
|
{ id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'],
|
||||||
|
re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i,
|
||||||
|
a: 'The Game Pass is $5 for 7 days and covers all ten games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the gold Game Pass badge with your name. Per game: PolHunter 5 missions a day instead of 3 plus 2 Ad Detective cases; Gem Kingdom one free continue a day; Spooky Doors one extra door a day; ClutterHunt 2 bonus hints a day; SpellWheel daily streak 0.30 POL instead of 0.15 plus 1 free hint a day; PolyBreak daily gem limit 1.5 POL instead of 0.5 plus an extra paddle every round; POL Miner daily crystal limit 1.5 POL instead of 0.5 plus one free supply crate every day; PolyWarriors a 4th daily mission and defense pays 25 Circuits instead of 15; Drip Runner a free shield at the start of every run; Road Agent 2 patrols a day and 25% more scrap. The full list is on the Game Pass card. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Get it in Members > Games > Game Pass: every pass is paid by a NEW package purchase of $5 or more. Tap Get the Pass, then buy the package; the pass starts the moment that purchase settles on chain. Your sponsor and team are paid from that package as usual, and you keep every credit of the package for your ads. Credits you already hold (earned or purchased) never buy a pass, and a package bought before you tapped Get the Pass does not count. Buying again while a pass is active adds 7 days.' },
|
||||||
|
// game POL to any linked wallet (Marty, 2026-10-27, "build all three"): sits ahead of the per-game entries so "my Gem Kingdom POL never came" lands here
|
||||||
|
{ id: 'game-pol-wallet', title: 'Getting your game POL (link your wallet)', q: ['Why was my game POL not sent?', 'It says POL is waiting for my wallet', 'Do I need to switch on payouts to get game POL?'], tags: ['games', 'game pol', 'link wallet', 'waiting for your wallet', 'not sent'],
|
||||||
|
re: /(pol (is )?waiting for (my |your |a )?wallet|link (my |your |a )?wallet to (receive|get)|(game|games|gem ?kingdom|drip ?runner|clutter ?hunt|spooky ?doors|road ?agent|poly ?break|spell ?wheel|poly ?warriors?)\b[^.?!]{0,60}\bpol\b[^.?!]{0,40}\b(not (been )?(paid|sent)|never (paid|sent|arrived|came)|stuck|waiting|pending|switch on|activat\w*)|(switch on|turn on|activate) payouts?[^.?!]{0,40}\b(game|games)\b[^.?!]{0,20}\bpol\b)/i,
|
||||||
|
a: 'Game POL is paid to the wallet linked to your InstantAdPay account. Linking is one free signature on your Wallet tab (https://instantadpay.com/my#wallet): it is not a transaction and it cannot move funds. Once your wallet is linked, every game sends your POL automatically, usually within the hour, including everything you earned before you linked it (each game still pays once your balance reaches the payout line shown in that game). You do not need to switch on payouts for game POL: a linked wallet is paid even before it is activated, so a member waiting in the holding tank for a sponsor still gets their game POL. If a game already has a different wallet on file for you, it keeps paying that one; open Help if that needs changing.' },
|
||||||
|
{ id: 'road-agent', title: 'Road Agent (night-highway shooter)', q: ['What is Road Agent?', 'How do fuel stops work in Road Agent?'], tags: ['games', 'road agent', 'fuel stop'],
|
||||||
|
re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i,
|
||||||
a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' },
|
a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' },
|
||||||
{ re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
|
{ id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'],
|
||||||
|
re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
|
||||||
a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=<username>), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' },
|
a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=<username>), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' },
|
||||||
{ re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i,
|
{ id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'],
|
||||||
|
re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i,
|
||||||
a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' },
|
a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' },
|
||||||
{ re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
|
{ id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'],
|
||||||
|
re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
|
||||||
a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' },
|
a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a free word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' },
|
||||||
{ re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i,
|
{ id: 'polminer', title: 'POL Miner mining game', q: ['What is POL Miner?', 'How do Polygon crystals work in POL Miner?', 'What is a supply crate?'], tags: ['games', 'polminer', 'mining', 'polygon crystal', 'supply crate'],
|
||||||
|
re: /(pol ?miner|mining game|digging game|polygon crystals?|pink crystals?|drill boss(es)?|supply crates?)/i,
|
||||||
|
a: 'POL Miner (https://polminer.com, also in Members > Games) is a free dig-down mining game. Dig through the layers of dirt and rock, haul ore up to sell for coins, upgrade your pick, lamp, cart and thruster, and beat a drill boss every 30 m to open the way deeper. The rare glowing pink Polygon crystals pay a random amount of POL the first time you dig each one out, each drill boss pays POL the first time you beat it, and so do your first trips to 50, 100, 150 and 200 m. Coins are for upgrades only and never turn into POL. You can play as a guest right away; sign in with your InstantAdPay account in the game and what you earned as a guest is collected. POL collects in your POL Miner balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab) once it reaches the payout amount. Low on lamp power or coins? Park on the SUPPLY pad: a short sponsor visit opens a supply crate with a full lamp and coins.' },
|
||||||
|
{ id: 'polybreak', title: 'PolyBreak brick breaker', q: ['What is PolyBreak?', 'How do I get another paddle?'], tags: ['games', 'polybreak', 'brick breaker', 'gem'],
|
||||||
|
re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i,
|
||||||
a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' },
|
a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' },
|
||||||
{ re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i,
|
{ id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'],
|
||||||
|
re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i,
|
||||||
a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' },
|
a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' },
|
||||||
{ re: /(clutter ?hunt|hidden.object|haunted manor)/i,
|
{ id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'],
|
||||||
|
re: /(clutter ?hunt|hidden.object|haunted manor)/i,
|
||||||
a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Haunted Manor (six rooms) through Oct 31, then new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' },
|
a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Haunted Manor (six rooms) through Oct 31, then new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' },
|
||||||
{ re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
|
{ id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'],
|
||||||
|
re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
|
||||||
a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' },
|
a: 'Spooky Doors (https://spookydoors.com) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' },
|
||||||
{ re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|refuel)/i,
|
{ id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do game refuels work?'], tags: ['games', 'drip runner', 'game refuel', 'games tab'],
|
||||||
|
re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|(?<!(monthly|my|your|the|a) )refuels?(?!(ing)? ?(day|streak|bonus|window|kit|card|guide)))/i, // 2026-10-24: questions about the Monthly Refuel streak go to the 'refuel' entry, not here
|
||||||
a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' },
|
a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' },
|
||||||
{ re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i,
|
{ id: 'gem-kingdom', title: 'Gem Kingdom match-3 and Crowns', q: ['What is Gem Kingdom?', 'How do I buy Crowns?', 'What do the bosses pay?'], tags: ['games', 'gem kingdom', 'crowns', 'match-3'],
|
||||||
|
re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i,
|
||||||
a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' },
|
a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' },
|
||||||
{ re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
|
{ id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'],
|
||||||
|
re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
|
||||||
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
||||||
{ re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||||
|
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||||
|
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||||
|
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
|
||||||
|
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
||||||
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
||||||
{ re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i,
|
{ id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'],
|
||||||
a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
|
re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i,
|
||||||
|
a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Since 2026-10-23 a $5+ Friday package also gives you a free 7-day Game Pass (once per Friday, all ten games); if that package is the one starting a pass you already ordered, it does not add a second week. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
|
||||||
|
// 2026-10-23 conversion pixel (LinkSpin counts, IAP shows): Campaigns > Conversion tracking
|
||||||
|
{ id: 'conversion-tracking', title: 'Conversion tracking (goal pixel)', q: ['How do I track conversions?', 'Can I see which ad brought a sign-up or sale?', 'Where do I put the goal pixel?', 'What is the landing tag?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion tracking', 'goal pixel', 'landing tag', 'cost per goal', 'aweber', 'getresponse', 'wordpress', 'setup guide'],
|
||||||
|
re: /(conver(sion|t)s?.{0,20}(track|pixel|goal)|track(ing)?.{0,30}(conversions?|sign.?ups?|sales|subscribers|leads)|goal pixel|landing tag|tracking pixel|cost per (goal|lead|sale|sign.?up|conversion)|thank.?you page|lsclk)/i,
|
||||||
|
a: 'Conversion tracking shows which of your ads bring subscribers and sales, not just clicks. It lives in your dashboard under Campaigns > Conversion tracking (https://instantadpay.com/my#campaigns). Three steps: 1) add a goal, like subscriber or sale (a default value is optional); 2) put the landing tag on the page your ad points to; 3) put the goal pixel on your thank-you page. Every click on your ad carries a click id (lsclk=...), and LinkSpin, our sister site, matches each goal to the click: first by the click id still in the address, then the id the landing tag stored, then LinkSpin\'s cookie, and last a 24-hour match on the same connection and browser (the panel says how sure each kind is). Each goal counts once per click, only within 30 days of a real click on your ad, and each campaign shows its goals and its cost per goal (30 days) in credits: the credits that campaign spent in the same 30 days, divided by its goals. Using Aweber or GetResponse? Set the form\'s thank-you (success) page to a page on YOUR site that carries the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL). If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. The Send a test conversion button fires your real pixel in test mode (Last test updates); to check your real thank-you page, add &test=1 to its pixel and open it once. Tests and your own clicks (on your ads, and on your LinkSpin spin links and Banner Spins) never count in your numbers; the card says how many of your own clicks were kept as tests. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://instantadpay.com/conversion-tracking' },
|
||||||
|
// 2026-10-23 (Marty: "they need to pay for the slot now to get a place in line"): 6 member slots, then a prepaid line
|
||||||
|
{ id: 'login-ads', title: 'Login ads: slots and the paid line', q: ['How do login ads work?', 'All login ad slots are taken, what now?', 'Can I reserve a login ad slot?', 'Can I cancel my login ad reservation?'], tags: ['login ad', 'login slot', 'reserve', 'queue', 'line', 'refund'],
|
||||||
|
re: /(log ?in.?ads?|sign.?in ads?|log ?in (ad )?(slots?|sponsor)|(reserve|reservation|queue|place in line|waiting list).{0,40}log ?in|log ?in.{0,40}(slots?|reserve|reservation|queue|place in line|waiting list)|reserve (a |the )?(next )?slot)/i,
|
||||||
|
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
|
||||||
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
|
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
|
||||||
// signed out, and the honest answer reads far better than letting it look like a fault.
|
// signed out, and the honest answer reads far better than letting it look like a fault.
|
||||||
{ re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||||
|
re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
||||||
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
|
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
|
||||||
{ re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
{ id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'],
|
||||||
|
re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
||||||
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
|
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
|
||||||
{ re: /(pyramid|ponzi|scam|scheme)/i,
|
{ id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'],
|
||||||
|
re: /(pyramid|ponzi|scam|scheme)/i,
|
||||||
a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' },
|
a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' },
|
||||||
{ re: /(withdraw|cash ?out|payout request|minimum payout)/i,
|
{ id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'],
|
||||||
|
re: /(withdraw|cash ?out|payout request|minimum payout)/i,
|
||||||
a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' },
|
a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' },
|
||||||
// "how much do I earn" used to fall through to the PRICE answer below, because that one
|
// "how much do I earn" used to fall through to the PRICE answer below, because that one
|
||||||
// matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17).
|
// matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17).
|
||||||
{ re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
|
{ id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'],
|
||||||
|
re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
|
||||||
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
|
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
|
||||||
{ re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
|
{ id: 'network-rate', title: 'Network views and partner visits cost a quarter of the rate', q: ['Do network views use my credits?', 'How much do Network Ad Space views cost?', 'Why are network views cheaper?'], tags: ['network views', 'network ad space', 'syndication', 'passivedrip', 'partner visits', 'credits', 'rate'],
|
||||||
|
re: /((network (views?|ad space)|syndicat\w*|partner (sites?|visits?)).{0,60}(credits?|charge[ds]?|cost|spend|balance|budget|free|pay|rate|cheap)|(credits?|charge[ds]?|cost|spend|balance|budget|pay|rate).{0,60}(network (views?|ad space)|syndicat\w*|partner (sites?|visits?)))/i,
|
||||||
|
a: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs a quarter of the rate: 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/4 rate)" lines in Credit activity.' },
|
||||||
|
{ id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'],
|
||||||
|
re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
|
||||||
a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' },
|
a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' },
|
||||||
{ re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i,
|
{ id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'],
|
||||||
|
re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i,
|
||||||
a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' },
|
a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' },
|
||||||
{ re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i,
|
{ id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'],
|
||||||
|
re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i,
|
||||||
a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' },
|
a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' },
|
||||||
// PIF + the holding tank. Asked together often ("should I pif someone from the tank"),
|
// PIF + the holding tank. Asked together often ("should I pif someone from the tank"),
|
||||||
// and the honest answer is that the order matters: you cannot PIF someone still in the
|
// and the honest answer is that the order matters: you cannot PIF someone still in the
|
||||||
@@ -80,62 +139,124 @@ const CANNED = [
|
|||||||
// ("should I fund their first package", "can I buy it for them"). It needs BOTH a
|
// ("should I fund their first package", "can I buy it for them"). It needs BOTH a
|
||||||
// paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions
|
// paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions
|
||||||
// like "which package should I buy" are not stolen (Marty, 2026-09-17).
|
// like "which package should I buy" are not stolen (Marty, 2026-09-17).
|
||||||
{ re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i,
|
{ id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'],
|
||||||
|
re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i,
|
||||||
a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' },
|
a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' },
|
||||||
{ re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i,
|
{ id: 'tank-hold', title: 'Matched with a sponsor (activation on hold)', q: ['Why can I not switch on payouts?', 'It says I am being matched with a sponsor'], tags: ['holding tank', 'switch on payouts', 'matched with a sponsor', 'ready to activate'],
|
||||||
a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances.' },
|
re: /(being matched|matched with a sponsor|(can.?t|cannot|unable to) (i )?(switch on|turn on|activate) (my )?payouts|activate (button|payouts) (is )?(gone|missing|hidden)|ready to activate)/i,
|
||||||
{ re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
|
a: 'You joined without a sponsor, so you are in the holding tank. The contract locks your sponsor for good the first time you switch on payouts or buy, so switching on payouts on its own waits until a real member picks you up. Buying is never held: you can buy a package any time, and with no sponsor it goes through under the company position. Once your wallet is linked, members see you at the top of their holding tank with a Ready to activate badge. If nobody adopts you within 24 hours, the site assigns you to the next eligible member in turn (someone active with their own $20 package). As soon as you have a sponsor, the Switch on payouts button comes back. If you already have a sponsor on LinkSpin with the same email or wallet, you are placed under them right away.' },
|
||||||
|
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
|
||||||
|
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
|
||||||
|
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
|
||||||
|
{ id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'],
|
||||||
|
re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i,
|
||||||
|
a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 2 open adoptions, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
|
||||||
|
{ id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'],
|
||||||
|
re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
|
||||||
a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' },
|
a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' },
|
||||||
{ re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i,
|
{ id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'],
|
||||||
|
re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i,
|
||||||
a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' },
|
a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' },
|
||||||
{ re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
|
{ id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'],
|
||||||
|
re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
|
||||||
a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' },
|
a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' },
|
||||||
{ re: /(referral link|invite link|share link|refer)/i,
|
{ id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'],
|
||||||
|
re: /(referral link|invite link|share link|refer)/i,
|
||||||
a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
|
a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
|
||||||
{ re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i,
|
{ id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'],
|
||||||
|
re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i,
|
||||||
a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' },
|
a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' },
|
||||||
{ re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
|
{ id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'],
|
||||||
|
re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
|
||||||
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' },
|
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' },
|
||||||
{ re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'],
|
||||||
|
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||||
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
|
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
|
||||||
{ re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
|
{ id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'],
|
||||||
|
re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
|
||||||
a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' },
|
a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' },
|
||||||
{ re: /(solo ad|inbox ad|inbox)/i,
|
{ id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'],
|
||||||
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members — give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
|
re: /(solo ad|inbox ad|inbox)/i,
|
||||||
{ re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i,
|
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
|
||||||
|
{ id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'],
|
||||||
|
re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i,
|
||||||
a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' },
|
a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' },
|
||||||
{ re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
|
{ id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'],
|
||||||
|
re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
|
||||||
a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' },
|
a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' },
|
||||||
{ re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
|
{ id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'],
|
||||||
|
re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
|
||||||
a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' },
|
a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' },
|
||||||
{ re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
|
{ id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'],
|
||||||
|
re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
|
||||||
a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' },
|
a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' },
|
||||||
{ re: /(verified visit|visit pack|buy visits|visits campaign)/i,
|
{ id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'],
|
||||||
|
re: /(verified visit|visit pack|buy visits|visits campaign)/i,
|
||||||
a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' },
|
a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' },
|
||||||
{ re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
|
{ id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'],
|
||||||
|
re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
|
||||||
a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' },
|
a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' },
|
||||||
{ re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i,
|
{ id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'],
|
||||||
|
re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i,
|
||||||
a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' },
|
a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' },
|
||||||
{ re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
|
{ id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'],
|
||||||
|
re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
|
||||||
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
|
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
|
||||||
{ re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
|
||||||
|
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
||||||
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
|
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
|
||||||
{ re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
|
||||||
|
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
||||||
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
|
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
|
||||||
{ re: /(safe|trust|rug|run away|company disappear)/i,
|
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
|
||||||
|
re: /(safe|trust|rug|run away|company disappear)/i,
|
||||||
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
|
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence)
|
||||||
|
function seeds() {
|
||||||
|
return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source,
|
||||||
|
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ);
|
||||||
|
}
|
||||||
|
|
||||||
// ---- facts for the AI fallback ----
|
// ---- facts for the AI fallback ----
|
||||||
function systemPrompt() {
|
// PASS TIERS (2026-10-22): the passes above the weekly Game Pass (Explorer, Champion, Sovereign, Legend; names from gamepass.js
|
||||||
|
// TIER_DEFS). While sovTiers is off the assistant only says they are coming soon; once on, it quotes the live prices and contents.
|
||||||
|
function passTiersFact() {
|
||||||
|
let t = null; try { t = PASS_TIERS ? PASS_TIERS() : null; } catch (e) { t = null; }
|
||||||
|
const soon = '- MORE GAME PASSES: monthly and yearly passes for Shards of Valor are COMING SOON and are not on sale yet. If someone asks about them (or about an Explorer, Champion, Sovereign or Legend pass, or a monthly or yearly pass), say they are coming soon and that the $5 weekly Game Pass is the pass on sale today. Never quote their prices, contents or a launch date.\n';
|
||||||
|
if (!t || !t.on) return soon;
|
||||||
|
const rows = (t.rows || []).filter(r => r.sale);
|
||||||
|
if (!rows.length) return soon;
|
||||||
|
return '- GAME PASS TIERS (on sale, Members > Games > Game Pass at https://instantadpay.com/my#games): beside the $5 weekly Game Pass, ' + rows.map(r => r.name + ' $' + r.usd + ' for ' + r.days + ' days (' + 'paid by the $' + r.usd + ' package, and the member keeps that package’s ad credits): ' + r.perks.join('; ')).join(' | ')
|
||||||
|
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in all ten games with the SAME daily POL caps (1.50 / 5 POL): a higher pass never pays more POL. Passes run side by side, each with its own end date; no auto-renew; buying again adds the pass length from its end date (or from now if it ended). Every pass is paid by a NEW package purchase of at least its price, made after tapping Get on that pass (since 2026-10-25 every pass price IS a one-click package amount: $5, $20, $50, $100, $250, so the right package is exactly the price); the pass starts when it settles, the sponsor and team are paid from the package as usual, and the member keeps the package credits for ads. Credits already held never buy a pass. Nothing earned in a game is taken away when a pass ends.\n';
|
||||||
|
}
|
||||||
|
// SYNDICATED RATE (Marty, 2026-10-27, approved 4:1) follows ads rates().synRateDivisor; the canned answer quotes 1/4, so
|
||||||
|
// the fast path rewrites it when the admin picks another N, and the AI fact always states the live N.
|
||||||
|
const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisor()) || 1)); } catch (e) { return 4; } };
|
||||||
|
const netRateAnswer = n => n === 1 ? 'Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery uses credits at the same rate as views and visits here.'
|
||||||
|
: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs 1/' + n + ' of the rate: ' + n + ' network views cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/' + n + ' rate)" lines in Credit activity.';
|
||||||
|
function synFact() { const n = SYN_N(); return '- NETWORK RATE (live, Marty 2026-10-27): delivery ON instantadpay.com is charged at the normal rate. Network Ad Space impressions of banner/text ads cost 1/' + n + ' of the on-site rate (' + n + ' network views = the price of 1 view here; credit log line "Network views (1/' + n + ' rate)"), and PassiveDrip partner visits use up 1 visit of a pack per ' + n + ' partner visits. The budget is the limit, burns follow what was charged, nothing charged before 2026-10-27 changed. AdRevLinks popups and DripOffers clicks are not charged. Game refuels and Spooky Doors are charged as normal visits.' + String.fromCharCode(10); }
|
||||||
|
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
|
||||||
|
let REFUEL_ON = () => false;
|
||||||
|
// POL Miner (2026-10-28) follows site config gamesLive: until 'polminer' is in it the assistant only says it is coming soon
|
||||||
|
let GAME_LIVE = () => false;
|
||||||
|
const POLMINER_SOON_ANSWER = 'POL Miner, a dig-down mining game where rare Polygon crystals pay POL, is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it launches.';
|
||||||
|
const pmLive = () => { try { return !!GAME_LIVE('polminer'); } catch (e) { return false; } };
|
||||||
|
function polminerFact() { return pmLive() ? '- POL MINER (https://polminer.com, Members > Games): a free dig-down mining game. Dig, sell ore for coins, upgrade pick/lamp/cart/thruster, beat a drill boss every 30 m. Pink Polygon crystals pay a random POL amount the first time each one is dug out; each boss pays POL on its first win per account; first trips to 50/100/150/200 m pay POL. Coins never turn into POL. Guests can play and collect at sign-in. POL is paid automatically to the wallet linked on InstantAdPay. The SUPPLY pad opens a sponsored supply crate (full lamp + coins, never POL) after a short sponsor visit.\n' : '- POL MINER: COMING SOON, not open yet. Never send members to polminer.com; say it is coming soon to the Games tab.\n'; }
|
||||||
|
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
|
||||||
|
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
|
||||||
|
function systemPrompt(kbBlock) {
|
||||||
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
||||||
|
|
||||||
FACTS:
|
FACTS:
|
||||||
- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company-paid, off-chain decision, on-chain payment. 3% of every package purchase (the POL actually paid) goes to the buyer's 4th upline on the contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = direct referral with a $20+ purchase, same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; the company account (#1) or no qualified upline = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId), shown in Earnings as 'Level 4 override' with a Polygon link and announced by email and an on-site notice. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split 50/20/10 is unchanged. Never promise amounts.
|
||||||
|
${passTiersFact()}${refuelFact()}${synFact()}${polminerFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||||
- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time.
|
- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time.
|
||||||
- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=<username>; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/<username>. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide.
|
- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=<username>; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/<username>. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide.
|
||||||
- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money.
|
- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money.
|
||||||
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
- CONVERSION TRACKING (LIVE 2026-10-23): Campaigns > Conversion tracking in /my#campaigns. Every click on a member's ad (through /api/ads/click) gets a click id added to the target address as lsclk=<id>; the advertiser adds a goal (name like subscriber or sale, optional default value), puts the LinkSpin landing tag (t.js) on the page the ad points to and the goal pixel (cv.gif image, or the cv.js script) on the thank-you page. LinkSpin (sister site, same email) counts the goals; matching order: click id in the address (url, surest), the id the landing tag stored (stored), LinkSpin's cookie (cookie), a 24-hour match on hashed IP plus browser (soft, least sure). Each goal counts once per click, only within 30 days of a real click, only for the pixel owner's own ads; the advertiser's own clicks (signed in, or from a browser they sign in from; their linked positions share their email so count as them too) and the Send a test conversion button count as tests, never in the numbers; the card shows 'N from your own clicks, kept as tests'. SEND A TEST CONVERSION (2026-10-26) loads the member's real LinkSpin pixel in test mode from their browser (falls back to the signed partner call if the browser blocks it), so Last test updates. Each campaign row shows goals and COST PER GOAL (30 DAYS) in credits (2026-10-26: the credits the campaign spent in the last 30 days, from the credit activity log, divided by its goals in the same 30 days; a campaign started inside the window uses its spend since start; never quote it in dollars). Autoresponder tip: set the Aweber or GetResponse thank-you (success) page to a page on the member's own site carrying the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL); if they cannot, the cookie or the 24-hour match can still count it, less surely. Privacy: the click id is random and nothing personal is sent. SETUP GUIDE (public, 2026-10-24): https://instantadpay.com/conversion-tracking (LinkSpin's copy: https://linkspin.app/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, Last test updates, then remove it), what to do without code on the thank-you page, how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest). Send members there for any setup question.
|
||||||
|
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Since 2026-10-23 the same $5+ Friday package also gives a FREE 7-day Game Pass automatically (once per member per Friday; not a second week when that package itself fulfils a pass order; the Game Pass badge posts the first time). Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
||||||
- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report.
|
- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report.
|
||||||
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
||||||
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
||||||
@@ -150,6 +271,7 @@ FACTS:
|
|||||||
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
|
- WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase.
|
||||||
- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/<username>) right under their bio, above the three-level line and the join button.
|
- INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/<username>) right under their bio, above the three-level line and the join button.
|
||||||
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 2 open adoptions, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members.
|
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 2 open adoptions, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members.
|
||||||
|
- TANK ACTIVATION HOLD (2026-10-27, Marty: never default a tank member to the company): a tank member (no sponsor, not activated) can NOT switch on payouts on its own yet (a PURCHASE is NEVER held, Marty 2026-10-27: with no sponsor anywhere a buy goes ahead under the catch position #1); the Wallet tab and Getting started card say "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left, and the activate button is hidden. The 24-hour clock starts when they link a wallet; they then show at the top of every holding tank with a green "Ready to activate" badge and hours left, and a post goes to the team's Telegram payments topic. If nobody adopts them in 24 hours, the site auto-assigns them to the next eligible adopter in rotation (own $20+ package, fewer than 2 open adoptions, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. ONE-TAP SWITCH ON PAYOUTS (2026-10-27): every tank assignment (manual adoption or the 24-hour auto-assign) sends the member a chat and an email with a Switch on payouts link, https://instantadpay.com/my?activate=1#wallet; it opens the Wallet tab and starts the normal Activate payouts flow with the new sponsor prefilled (after sign-in, and after linking a wallet if none is linked yet). It never starts while the hold applies or when no sponsor resolves. The site cannot activate for anyone: activation is one free transaction from the member's own wallet. Not activated 24 hours after the assignment: one reminder email to the member with the same link and one notice to the sponsor ("@x hasn't switched on payouts yet; a nudge from you helps"); at 72 hours one last email to the member only; both stop once the member switches on payouts or buys.
|
||||||
- DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign.
|
- DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign.
|
||||||
- FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk.
|
- FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk.
|
||||||
- ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account.
|
- ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account.
|
||||||
@@ -167,12 +289,12 @@ FACTS:
|
|||||||
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
|
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
|
||||||
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
|
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
|
||||||
- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members.
|
- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members.
|
||||||
- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). Paid with 500 PURCHASED-grade credits (ads.gamePurchase purchasedOnly, the PolyWarriors mint rule; earned credits never buy a pass); with no purchased credits the pass waits and a $5 package bought meanwhile starts it automatically (the member keeps the package credits). Buying while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit.
|
- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL NINE games (linked positions share it). PAYMENT (changed 2026-10-22): every pass is paid by a NEW on-chain package purchase of at least the pass price ($5 for the weekly pass), bought from one of the member's own positions AFTER tapping Get the Pass. The pass starts the moment that purchase settles. The sponsor and team are paid from that package exactly like any package, and the member keeps every credit of the package for ads. Credits (earned or purchased, old balances included) NEVER buy a pass, and a package bought before tapping Get the Pass does not count; if someone asks why, say the pass is paid by a fresh package so the team that brought them in is paid too. Passes bought before this change keep running. Buying again while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. PER-GAME PERKS (live 2026-10-22, also listed on the Game Pass card): PolHunter 5 missions/day instead of 3 + 2 Ad Detective cases/day; Gem Kingdom 1 free continue/day; Spooky Doors +1 door/day; ClutterHunt 2 bonus hints/day; SpellWheel streak 0.30 POL instead of 0.15 + 1 free hint/day; PolyBreak gem limit 1.5 POL/day instead of 0.5 + extra paddle every round; PolyWarriors 4th daily mission + defense 25 Circuits instead of 15; Drip Runner free shield every run; Road Agent 2 patrols/day + 25% more scrap. Buying a pass unlocks the gold Game Pass achievement badge (Members > Overview badges, share or post to Telegram). New free caps started 2026-10-26 (moved up from the announced 10-29).
|
||||||
- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts.
|
- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts.
|
||||||
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
|
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
|
||||||
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
|
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
|
||||||
- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends.
|
- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends.
|
||||||
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 3 member slots run at once because every slot shares the same sign-ins; when all 3 are taken the buy is refused until one ends, and a paused slot can only be resumed while a slot is open. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
|
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18 and 2026-10-23): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the member can RESERVE THE NEXT SLOT (since 2026-10-23): they pay the full slot price right then (same purchased-credits-only rule, balance drops at once, credit log 'Login slot reserved (queue #N)'), the ad waits in a paid line, first paid first served, and its 30 days do not start until its turn. Members > Campaigns shows their place in line and an ESTIMATED start date in Central time, worked out from the live slots' end dates and the reservations ahead; it is only an estimate because a slot ends early if its owner archives it. The oldest reservation starts automatically the moment a slot frees (a slot expires, or its owner pauses it to end or archive it; also checked every minute), and the owner gets an on-site notice and an email. Before it starts the owner can edit the link, image or headline for free, or cancel for a FULL refund (credited back as purchased credits, credit log 'Login slot reservation cancelled: refund'); after it starts normal slot rules apply. A freed slot goes to the line first: a paused slot can only be resumed while live slots plus reservations leave a place open, otherwise the owner is told the line is ahead of them. The admin can see the line and cancel-and-refund a reservation. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
|
||||||
- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check.
|
- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check.
|
||||||
- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.)
|
- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.)
|
||||||
- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet.
|
- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet.
|
||||||
@@ -203,6 +325,7 @@ FACTS:
|
|||||||
- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings.
|
- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings.
|
||||||
- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-04 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no paid ad is left for that player, the door shows a house ad for one of our own programs: a smaller treat (5 candy), and it still counts toward the 15 doors. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. DOOR PACKS: creating a verified-visits campaign, the advertiser picks Everywhere (3 credits per visit, as before), Behind Spooky Doors (4 credits per door) or Golden Spooky Door (6 credits per door; the player gets +2 bonus candy). Paid up front like any visit pack. Door packs are served first on doors (Golden Doors before door packs), each player sees a pack at most once per Central day, they never run on the Earn tab or refuels during the season, and from Nov 1 any doors left run as normal visits; the campaign shows doors opened and unique players. Never promise earnings or call it income.
|
- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-04 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no paid ad is left for that player, the door shows a house ad for one of our own programs: a smaller treat (5 candy), and it still counts toward the 15 doors. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. DOOR PACKS: creating a verified-visits campaign, the advertiser picks Everywhere (3 credits per visit, as before), Behind Spooky Doors (4 credits per door) or Golden Spooky Door (6 credits per door; the player gets +2 bonus candy). Paid up front like any visit pack. Door packs are served first on doors (Golden Doors before door packs), each player sees a pack at most once per Central day, they never run on the Earn tab or refuels during the season, and from Nov 1 any doors left run as normal visits; the campaign shows doors opened and unique players. Never promise earnings or call it income.
|
||||||
- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards. (2026-10-03) FREE REVIVE: after a defeat, a short verified visit to a member's page (InstantAdPay verified-visit flow inside the game, shares the 20-a-day refuel allowance with Drip Runner) revives the party once per battle; a revived win earns at most 2 stars. SPECIALS in the Crown shop: Hero Bundle (one time, $5 = 500 credits: a tier-1 forge weapon, one building level, 60 Crowns), Kingdom Pass ($10 = 1,000 credits for 30 days: 10 Crowns a day credited on the first visit each Central day, a 25-Crown chest every 7 days, the three Royal hero looks; no auto-renew, buying again adds 30 days), Hero looks (cosmetic only: Halloween looks Pumpkin Knight, Moon Witch, Scarecrow Ranger for 40 Crowns each, sold through Oct 31 and kept forever; Royal looks with the Pass). Only the purchased-credit part of a purchase funds the POL reward pool.
|
- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards. (2026-10-03) FREE REVIVE: after a defeat, a short verified visit to a member's page (InstantAdPay verified-visit flow inside the game, shares the 20-a-day refuel allowance with Drip Runner) revives the party once per battle; a revived win earns at most 2 stars. SPECIALS in the Crown shop: Hero Bundle (one time, $5 = 500 credits: a tier-1 forge weapon, one building level, 60 Crowns), Kingdom Pass ($10 = 1,000 credits for 30 days: 10 Crowns a day credited on the first visit each Central day, a 25-Crown chest every 7 days, the three Royal hero looks; no auto-renew, buying again adds 30 days), Hero looks (cosmetic only: Halloween looks Pumpkin Knight, Moon Witch, Scarecrow Ranger for 40 Crowns each, sold through Oct 31 and kept forever; Royal looks with the Pass). Only the purchased-credit part of a purchase funds the POL reward pool.
|
||||||
|
- GAME POL TO ANY LINKED WALLET (2026-10-27, Marty): game POL (Drip Runner, Gem Kingdom, ClutterHunt, Spooky Doors, Road Agent, PolyBreak, SpellWheel, PolyWarriors) is paid to the wallet LINKED to the member's InstantAdPay account (one free signature on the Wallet tab, https://instantadpay.com/my#wallet). Activation is NOT needed: a linked wallet that has not switched on payouts (for example a holding-tank member waiting for a sponsor) is paid too. InstantAdPay hands the linked wallet to every game where the member has a balance (hourly, and on every sign-in to a game), and the game sends the POL on its own sweep once the balance reaches that game's payout line, including everything earned before the link. A game that already holds a different wallet keeps paying that one (it is never replaced automatically). Players with no linked wallet get at most three reminders ("X POL is waiting for your wallet": link your wallet, one free signature, and it's sent automatically, including everything you've earned so far), and in the games the reward screen says "Link your wallet to receive this POL" with the same link. Never tell a member to switch on payouts to get game POL.
|
||||||
- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (a member video once every page has been visited), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/<username>; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref=<username> to keep the referral).
|
- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (a member video once every page has been visited), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/<username>; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref=<username> to keep the referral).
|
||||||
- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly.
|
- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly.
|
||||||
- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires.
|
- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires.
|
||||||
@@ -218,22 +341,27 @@ RULES:
|
|||||||
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
|
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
|
||||||
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
|
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
|
||||||
- No em dashes. If you do not know, say so and point to /contract or the ledger.
|
- No em dashes. If you do not know, say so and point to /contract or the ledger.
|
||||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.`;
|
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function askAI(message, historyText) {
|
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
|
||||||
|
function endpoint() {
|
||||||
|
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
|
||||||
|
}
|
||||||
|
function askAI(message, historyText, kbBlock) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const body = JSON.stringify({
|
const body = JSON.stringify({
|
||||||
model: MODEL,
|
model: MODEL,
|
||||||
reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers)
|
reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers)
|
||||||
max_tokens: 300,
|
max_tokens: 300,
|
||||||
messages: [
|
messages: [
|
||||||
{ role: 'system', content: systemPrompt() },
|
{ role: 'system', content: systemPrompt(kbBlock) },
|
||||||
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
|
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
|
||||||
{ role: 'user', content: String(message).slice(0, 600) }
|
{ role: 'user', content: String(message).slice(0, 600) }
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST',
|
const ep = endpoint();
|
||||||
|
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
|
||||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
||||||
'Content-Length': Buffer.byteLength(body) }, timeout: 30000 },
|
'Content-Length': Buffer.byteLength(body) }, timeout: 30000 },
|
||||||
res => {
|
res => {
|
||||||
@@ -260,16 +388,33 @@ function askAI(message, historyText) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i;
|
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i;
|
||||||
async function answer(message, historyText) {
|
// every reply leaves without em dashes (Marty's voice rule; the model slips one in now and then, 2026-10-20)
|
||||||
|
async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') r.reply = r.reply.replace(/\s*\u2014\s*/g, ', '); return r; }
|
||||||
|
async function answerRaw(message, historyText) {
|
||||||
const msg = String(message || '').trim();
|
const msg = String(message || '').trim();
|
||||||
if (!msg) return { error: 'Say something first.' };
|
if (!msg) return { error: 'Say something first.' };
|
||||||
for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||||
|
let hit = null, kbOk = true;
|
||||||
|
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||||
|
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||||
|
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
|
||||||
|
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && SYN_N() !== 4) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||||
|
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||||
|
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||||
|
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||||
|
let kbBlock = '', kbIds = [];
|
||||||
|
try {
|
||||||
|
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||||
|
const hits = await kb.context(query, 5);
|
||||||
|
const hitsOk = pmLive() ? hits : hits.filter(h => !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))); // not live yet: keep its answer out of the prompt
|
||||||
|
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
|
||||||
|
} catch (e) { console.error('kb search', e.message); }
|
||||||
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true };
|
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true };
|
||||||
// One retry: the usual failure is a single provider dropping the request, and asking
|
// One retry: the usual failure is a single provider dropping the request, and asking
|
||||||
// again almost always lands. Only after both fail do we admit defeat.
|
// again almost always lands. Only after both fail do we admit defeat.
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
// handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16)
|
// handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16)
|
||||||
try { const reply = await askAI(msg, historyText); return Object.assign({ reply }, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
|
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
|
||||||
catch (e) {
|
catch (e) {
|
||||||
console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message);
|
console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message);
|
||||||
if (attempt === 0) await new Promise(r => setTimeout(r, 700));
|
if (attempt === 0) await new Promise(r => setTimeout(r, 700));
|
||||||
@@ -279,4 +424,4 @@ async function answer(message, historyText) {
|
|||||||
return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true };
|
return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, answer, enabled, KNOWLEDGE_DATE };
|
module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt };
|
||||||
|
|||||||
@@ -180,6 +180,8 @@ function clickSource(referer) {
|
|||||||
} catch (e) { return 'unknown'; }
|
} catch (e) { return 'unknown'; }
|
||||||
}
|
}
|
||||||
async function recordClick(campaignId, referer) { try { await impl().addClick(Number(campaignId), clickSource(referer), Date.now()); } catch (e) {} }
|
async function recordClick(campaignId, referer) { try { await impl().addClick(Number(campaignId), clickSource(referer), Date.now()); } catch (e) {} }
|
||||||
|
// clicks on these campaigns since a moment (the Engine Room's clicks-this-week dial, 2026-10-24)
|
||||||
|
async function clicksSince(campaignIds, since) { if (!campaignIds.length) return 0; const rows = await impl().clicksFor(campaignIds.map(Number)); return rows.filter(r => Number(r.ts) >= since).length; }
|
||||||
async function clickSources(campaignIds) {
|
async function clickSources(campaignIds) {
|
||||||
const rows = await impl().clicksFor(campaignIds.map(Number));
|
const rows = await impl().clicksFor(campaignIds.map(Number));
|
||||||
const out = {};
|
const out = {};
|
||||||
@@ -358,4 +360,4 @@ function init(opts) { X = arguments[0] || {};
|
|||||||
J.load();
|
J.load();
|
||||||
}
|
}
|
||||||
async function viewsSince(since) { return impl().viewsSince(since); }
|
async function viewsSince(since) { return impl().viewsSince(since); }
|
||||||
module.exports = { init, weeklyDigest, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, refHost, viewsSince };
|
module.exports = { init, weeklyDigest, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince };
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ async function bootstrap() {
|
|||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN height INT NULL'); // banner size (IAB) → also NAS height
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN height INT NULL'); // banner size (IAB) → also NAS height
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_ad_id INT NULL'); // syndicated NAS sponsorads.ID
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_ad_id INT NULL'); // syndicated NAS sponsorads.ID
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_served INT NOT NULL DEFAULT 0'); // NAS impressions already reconciled into spend
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_served INT NOT NULL DEFAULT 0'); // NAS impressions already reconciled into spend
|
||||||
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN syn_imps INT NOT NULL DEFAULT 0'); // syndicated delivery counted off-site (IAP: PassiveDrip visits; LinkSpin: partner-zone views), charged at 1/synRateDivisor
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN drip_id INT NULL'); // syndicated DripOffers campaigns.id (2026-09-18)
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN drip_id INT NULL'); // syndicated DripOffers campaigns.id (2026-09-18)
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN expires BIGINT NULL'); // featured rotation end time
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN expires BIGINT NULL'); // featured rotation end time
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN starts BIGINT NULL'); // featured run start (booked day); any type: scheduled start
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN starts BIGINT NULL'); // featured run start (booked day); any type: scheduled start
|
||||||
@@ -138,6 +139,17 @@ async function bootstrap() {
|
|||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
|
||||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
|
||||||
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
|
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
|
||||||
|
// prepaid login-ad line (2026-10-23): status 'queued' = paid and waiting for a slot (never serves), 'cancelled' = refunded
|
||||||
|
// before it started; queued_at orders the line (first paid, first served). status is VARCHAR(12), so no change there.
|
||||||
|
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL');
|
||||||
|
// short lease locks shared by every app copy (two run for ~30 s on each deploy): one conditional UPDATE takes a lock
|
||||||
|
// (holder IS NULL OR lease_until < now), the holder clears it, and an expired lease can be taken over after a crash
|
||||||
|
await q(`CREATE TABLE IF NOT EXISTS app_locks (
|
||||||
|
name VARCHAR(40) PRIMARY KEY,
|
||||||
|
holder VARCHAR(60) NULL,
|
||||||
|
lease_until BIGINT NOT NULL DEFAULT 0
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||||
|
await q("INSERT IGNORE INTO app_locks (name, holder, lease_until) VALUES ('login_queue', NULL, 0)");
|
||||||
// linked positions: extra wallets owned by one email account (Qualified Start).
|
// linked positions: extra wallets owned by one email account (Qualified Start).
|
||||||
// Each is its own on-chain member sponsored by the account's main member.
|
// Each is its own on-chain member sponsored by the account's main member.
|
||||||
await q(`CREATE TABLE IF NOT EXISTS positions (
|
await q(`CREATE TABLE IF NOT EXISTS positions (
|
||||||
@@ -414,4 +426,24 @@ async function importJsonOnce() {
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, enabled, q: (...a) => q(...a) };
|
// A named lock that holds across every app copy (MySQL GET_LOCK on one dedicated connection), for read-modify-write of a
|
||||||
|
// record two copies might touch at once (the refuel streak, 2026-10-24). Without a database: a per-process queue.
|
||||||
|
const localLocks = new Map();
|
||||||
|
async function withLock(name, fn, secs) {
|
||||||
|
const key = String(name).slice(0, 60);
|
||||||
|
if (!enabled() || !pool) {
|
||||||
|
const prev = localLocks.get(key) || Promise.resolve();
|
||||||
|
let release; const mine = new Promise(r => { release = r; });
|
||||||
|
const tail = prev.then(() => mine); localLocks.set(key, tail);
|
||||||
|
await prev;
|
||||||
|
try { return await fn(); } finally { release(); if (localLocks.get(key) === tail) localLocks.delete(key); }
|
||||||
|
}
|
||||||
|
const conn = await pool.getConnection();
|
||||||
|
try {
|
||||||
|
const [[row]] = await conn.query('SELECT GET_LOCK(?, ?) AS ok', [key, Number(secs) || 10]);
|
||||||
|
if (!row || Number(row.ok) !== 1) throw new Error('lock busy: ' + key);
|
||||||
|
try { return await fn(); } finally { try { await conn.query('SELECT RELEASE_LOCK(?)', [key]); } catch (e) {} }
|
||||||
|
} finally { conn.release(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, enabled, q: (...a) => q(...a), withLock };
|
||||||
|
|||||||
@@ -23,9 +23,9 @@ Every member earns real POL in our games, and that does not change. What is new:
|
|||||||
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
|
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
|
||||||
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
|
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
|
||||||
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
|
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
|
||||||
- **How to get it.** Members > Games > Game Pass. It costs 500 purchased credits, the credits from a package you bought. If you
|
- **How to get it.** Members > Games > Game Pass. Tap Get the Pass, then buy a new package of $5 or more. The pass starts the
|
||||||
have none, buy a $5 package and the pass starts the moment it settles; you keep every credit of that package for your ads. Buying
|
moment that purchase settles. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your
|
||||||
while a pass is active adds 7 days.
|
ads. Credits you already hold never buy a pass. Buying again while a pass is active adds 7 days.
|
||||||
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
|
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
|
||||||
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
|
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
|
||||||
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
|
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
|
||||||
@@ -48,3 +48,25 @@ The Pass does not change what any reward pays. Free play pays; the Pass plays mo
|
|||||||
|
|
||||||
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
|
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
|
||||||
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
|
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
|
||||||
|
|
||||||
|
## Update draft, 2026-10-22: how the Game Pass is paid (not sent)
|
||||||
|
|
||||||
|
Status: DRAFT for Marty's review. Nothing has been posted, emailed or published.
|
||||||
|
|
||||||
|
**Short version (Telegram / feed)**
|
||||||
|
|
||||||
|
A change to how the Game Pass is paid: from today every pass is paid by a new package purchase. Tap Get the Pass in Members >
|
||||||
|
Games, buy a package of $5 or more, and the pass starts the moment it settles. Your sponsor and team are paid from that package,
|
||||||
|
and you keep all of its credits for your ads. Credits you already hold no longer buy a pass. Passes you already have keep running.
|
||||||
|
|
||||||
|
**Release note (Admin > Releases)**
|
||||||
|
|
||||||
|
**The Game Pass is now paid with a new package**
|
||||||
|
|
||||||
|
- Tap Get the Pass (or Get on any pass) in Members > Games. Then buy a package of at least the pass price: $5 for the weekly Game
|
||||||
|
Pass.
|
||||||
|
- The pass starts the moment that purchase settles on chain. A package bought before you tapped Get does not count.
|
||||||
|
- Your sponsor and team are paid from that package exactly like any other package, and every credit of the package stays yours for
|
||||||
|
your ads.
|
||||||
|
- Credits you already hold, earned or purchased, no longer buy a pass.
|
||||||
|
- Any pass you already have keeps running to its end date.
|
||||||
|
|||||||
+80
-26
@@ -1,5 +1,8 @@
|
|||||||
# Game Pass: draft spec (2026-10-16)
|
# Game Pass: draft spec (2026-10-16)
|
||||||
|
|
||||||
|
> **PAYMENT RULE CHANGED 2026-10-22 (Marty): every pass is paid by a FRESH on-chain package purchase; no pass is ever bought with
|
||||||
|
> credits again.** See "Payment: the package rail" at the end. Older sections below that mention credits describe the rule as it was.
|
||||||
|
|
||||||
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
|
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
|
||||||
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
|
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
|
||||||
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
|
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
|
||||||
@@ -31,7 +34,7 @@ a single day. No other game pays more than 2 POL for any single reward.
|
|||||||
## 2. The pass
|
## 2. The pass
|
||||||
|
|
||||||
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
|
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
|
||||||
- Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
|
- (Superseded 2026-10-22, see "Payment: the package rail".) Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
|
||||||
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
|
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
|
||||||
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
|
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
|
||||||
just a free cap increase.
|
just a free cap increase.
|
||||||
@@ -95,7 +98,7 @@ that anyway." The paced total cap spreads a big boss payout over a few days; the
|
|||||||
> `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
|
> `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
|
||||||
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
|
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
|
||||||
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
|
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
|
||||||
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skips the credit charge.
|
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skipped the credit charge (retired 2026-10-22: there is no charge any more; the dev purchase event takes `minedAt`, `now` and `tx`).
|
||||||
|
|
||||||
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
|
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
|
||||||
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
|
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
|
||||||
@@ -114,7 +117,7 @@ with its shared secret (the `/api/partner/player` pattern); the new calls use th
|
|||||||
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
|
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
|
||||||
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
|
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
|
||||||
`passTournamentPct` 5.
|
`passTournamentPct` 5.
|
||||||
- Pass purchase: `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
|
- Pass purchase (superseded 2026-10-22: Buy only opens an order, a fresh package fulfils it): `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
|
||||||
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
|
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
|
||||||
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
|
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
|
||||||
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
|
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
|
||||||
@@ -215,33 +218,56 @@ sales. If the POL rate is unavailable the tick retries next hour.
|
|||||||
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
|
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
|
||||||
Game Pass keys show in the Site settings form).
|
Game Pass keys show in the Site settings form).
|
||||||
|
|
||||||
## Pass tiers: Explorer and Champion (IAP side, 2026-10-18)
|
## Pass tiers: Explorer, Champion, Sovereign, Legend (IAP side, 2026-10-18; restructured 2026-10-22)
|
||||||
|
|
||||||
Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form: paid tiers add Shards of Valor islands and looks, never
|
Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form on 2026-10-18 (never more POL) and Dallas's new structure
|
||||||
power, never more POL. The weekly pass is unchanged.
|
on 2026-10-22 (plus Sovereign and the yearly Legend). On 2026-10-25 Marty set every tier price to an InstantAdPay one-click
|
||||||
|
package amount ($5, $10, $20, $50, $100, $250, $500), so the cheapest qualifying package is exactly the pass price and the pass
|
||||||
|
comes with that package's ad credits (was $19.99 / $39.99 / $99.99 / $249.99). The weekly pass is unchanged. Everything above weekly stays
|
||||||
|
switched off for members (`sovTiers` 0) until Marty flips it.
|
||||||
|
|
||||||
- **Tiers**: `weekly` (500 credits, 7 days), `explorer` (2000, 30 days), `champion` (4000, 30 days). Every tier is a Game Pass
|
| Tier | Name | Price | Length | In Shards of Valor (each includes everything below) |
|
||||||
holder everywhere with exactly the pass caps; `polgrant` keeps answering `pass: true` (a boolean).
|
|---|---|---|---|---|
|
||||||
- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until } }`, the legacy `until` mirrors the weekly
|
| `weekly` | Game Pass | 500 credits ($5) | 7 days | the Game Pass in all nine games, the Sunless Vault, weapons unlocked |
|
||||||
tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing = weekly). Lazy migration: a record
|
| `explorer` | Explorer | 2000 ($20, the Activation package) | 30 days | weapons, gear, 2 DLC islands |
|
||||||
without `tiers` reads its `until` as the weekly tier.
|
| `champion` | Champion | 5000 ($50, the Builder package) | 30 days | weapons, gear, 4 DLC islands of your choice, the Druid hero, level cap 30 |
|
||||||
- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end). The hand-off token
|
| `sovereign` | Sovereign | 10000 ($100, the Growth package) | 30 days | weapons, gear, all DLC islands, the Necromancer hero, level cap 40 |
|
||||||
carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries `pass: { active, until, tier, tiers }`.
|
| `legend` | Legend | 25000 ($250, the Leader package) | 365 days | weapons, gear, all DLC islands, every hero including the Archer, level cap 40 |
|
||||||
- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Explorer/Champion need `sovTiers` on (and the weekly pass on);
|
|
||||||
while off, only the `ADMIN_EMAIL` account sees and can buy them (admin preview on the card). Short of purchased credits: a
|
- **One table**: `gamepass.js` `TIER_DEFS` holds the rank, wire key, display name, settings stem, default price/length and the
|
||||||
|
member-card list for every tier. Rename a tier there (the card, admin pane, charge label and chatbot all read it).
|
||||||
|
- **Rank**: weekly < explorer < champion < sovereign < legend. Every tier is a Game Pass holder everywhere with exactly the pass
|
||||||
|
caps; `polgrant` keeps answering `pass: true` (a boolean).
|
||||||
|
- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until }, sovereign: { until }, legend: { until } }`,
|
||||||
|
the legacy `until` mirrors the weekly tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing =
|
||||||
|
weekly). Lazy migration: a record without `tiers` reads its `until` as the weekly tier.
|
||||||
|
- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end; `tiers` has all five
|
||||||
|
keys). The hand-off token carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries
|
||||||
|
`pass: { active, until, tier, tiers }`, so Shards of Valor sees `sovereign` / `legend`.
|
||||||
|
- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Every tier above weekly needs `sovTiers` on (and the weekly pass
|
||||||
|
on); while off, nobody sees or buys them on /my, the admin included (2026-10-25: the member card shows every account the
|
||||||
|
member view). The admin tests them in Admin > Game Pass > Tier test and preview (`GET /api/admin/gamepass/preview`, `POST
|
||||||
|
/api/admin/gamepass/test-buy | test-cancel | test-comp { tier }`, always the signed-in admin's own account). Short of purchased credits: a
|
||||||
waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase,
|
waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase,
|
||||||
each tx once). There is no $40 package, so Champion's copy names the $50 one.
|
each tx once). Copy names the package that pays for the pass, which since 2026-10-25 is exactly the price: $20 (Explorer), $50
|
||||||
- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)`. Tiers run side by side;
|
(Champion), $100 (Sovereign), $250 (Legend); the card says the pass comes with that package's ad credits.
|
||||||
when a higher one ends the next one shows through. Admin comp takes a tier; `POST /api/admin/gamepass/revoke { email, tier, why }`
|
- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)` by its length (Legend: 365
|
||||||
ends one tier now (support refunds only, credits are not returned by it).
|
days). Tiers run side by side; when a higher one ends the next one shows through. Admin comp takes a tier;
|
||||||
- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1`.
|
`POST /api/admin/gamepass/revoke { email, tier, why }` ends one tier now (support refunds only, credits are not returned by it).
|
||||||
- **Settings**: `sovTiers` 0, `gamePassExplorerEnabled` 1 / `gamePassChampionEnabled` 1 (a `0` stops one tier),
|
- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1` (then every tier's
|
||||||
`gamePassExplorerPriceCredits` 2000, `gamePassChampionPriceCredits` 4000, `gamePassExplorerDays` / `gamePassChampionDays` 30,
|
sales do).
|
||||||
`passTournamentTierSales` 0.
|
- **Settings** (defaults): `sovTiers` 0; kill switches `gamePassExplorerEnabled` / `gamePassChampionEnabled` /
|
||||||
- **Member UI**: the Games tab card shows the three tiers side by side (end dates in Central time); `/my#passes` opens it (the
|
`gamePassSovereignEnabled` / `gamePassLegendEnabled` 1 (a `0` stops one tier); `gamePassExplorerPriceCredits` 2000,
|
||||||
|
`gamePassChampionPriceCredits` 5000, `gamePassSovereignPriceCredits` 10000, `gamePassLegendPriceCredits` 25000;
|
||||||
|
`gamePassExplorerDays` / `gamePassChampionDays` / `gamePassSovereignDays` 30, `gamePassLegendDays` 365;
|
||||||
|
`passTournamentTierSales` 0. A value saved in the site settings file wins over these defaults.
|
||||||
|
- **Chatbot**: while `sovTiers` is off the assistant only says more passes are coming soon (no prices, no contents, no date); once
|
||||||
|
on, its fact lists each tier on sale with the live price, length and contents.
|
||||||
|
- **Member UI**: the Games tab card shows the tiers side by side (end dates in Central time); `/my#passes` opens it (the
|
||||||
Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button.
|
Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button.
|
||||||
- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer through the real
|
- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer and Sovereign through the
|
||||||
`ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`).
|
real `ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`, and a Legend order is fulfilled by
|
||||||
|
a $250 package).
|
||||||
|
|
||||||
## Games: as built (2026-10-16, local commits only, nothing deployed)
|
## Games: as built (2026-10-16, local commits only, nothing deployed)
|
||||||
|
|
||||||
@@ -314,3 +340,31 @@ drives the REAL `spooky-doors/server/polgrant.js` and `polhunter/lib/tournament.
|
|||||||
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
|
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
|
||||||
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
|
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
|
||||||
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
|
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
|
||||||
|
|
||||||
|
## Payment: the package rail (2026-10-22, Marty)
|
||||||
|
|
||||||
|
**Why.** A pass paid from a credit balance brings in no new money and pays nobody upline: credits come from packages whose POL was
|
||||||
|
already split on chain ($2.50 sponsor, $1 level 2, $0.50 level 3, $1 company on a $5 package). Today's pass buyer paid from an old
|
||||||
|
balance. From now on every pass is a fresh package purchase, so the sponsor and team are paid exactly like any package.
|
||||||
|
|
||||||
|
**Rule.**
|
||||||
|
- `POST /api/my/gamepass/buy { tier }` never charges anything. It opens a waiting order for that tier (or returns the one already
|
||||||
|
open) and answers `{ needPay: true, order, orderTs, package, payUrl, message }`. The card sends the member to Buy credits.
|
||||||
|
- The order is fulfilled only by an on-chain `Purchase` event (`gamepass.onEvent`, inside the `marks.claim` block, so one app copy
|
||||||
|
acts) that meets ALL of:
|
||||||
|
- the buyer id is one of this account's own positions: the main member id (`accounts.byMemberId`) or a linked position
|
||||||
|
(`accounts.positionByMember`);
|
||||||
|
- `priceCents` is at least the tier price (setting `gamePass*PriceCredits`, now read as cents; the copy names the package that
|
||||||
|
covers it: $5, $20, $50, $100, $250);
|
||||||
|
- the purchase was mined AFTER the order was opened: block time from `eth_getBlockByNumber` (server.js `blockTime` dep), with a
|
||||||
|
30 s clock grace; if the block cannot be read after 3 tries the indexed-at time is used (never earlier than the block);
|
||||||
|
- the tx has never paid a pass or an order before (checked across every order and every bought row, every account).
|
||||||
|
- One pass per purchase: the highest-priced waiting order the package covers. The member keeps every credit of the package.
|
||||||
|
- Bought row: `{ via: 'package', tier, tx, cents, order, buyerId, usd: <pass price>, packageUsd }`. `buyerId` marks the new rail.
|
||||||
|
- Existing passes are untouched (never revoked). On 2026-10-22 production held two sales: one `via: 'credits'` (500 credits,
|
||||||
|
campaign 513) and one `via: 'package'` fulfilled under the old rule (tx 0xdbfb77c7...). No order was left waiting.
|
||||||
|
- Admin > Game Pass > **Pass sales**: every sale with how it was paid ("package", "credit-paid (old rule)", "package (old rule)"),
|
||||||
|
pass value, package value and the package tx; the header splits the counts. Stats field `passes.pay` and `sales`.
|
||||||
|
- Tests: `qa/gamepass.mjs` (order, package mined before the order refused, too small refused, another member refused, fresh package
|
||||||
|
fulfils, replayed tx refused, extend while active); `qa/sov-passes-store.cjs` and `qa/sov-passes-local.mjs` updated the same way.
|
||||||
|
- Not changed: the caps, the tiers, the tournament (pool = pass price of each sale), the hand-off claims.
|
||||||
|
|||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
// Email typo check for NEW addresses (2026-10-22, after SendGrid bounces to gmai.com / outlook.comz).
|
||||||
|
// Same file lives in InstantAdPay and LinkSpin. Catches:
|
||||||
|
// 1. near-misses of the big mailbox providers (gmai.com, gmial.com, hotmial.com, yaho.com) -> "Did you mean ...?"
|
||||||
|
// 2. mistyped endings (.con, .cmo, .comz, .nett) -> "Did you mean ...?"
|
||||||
|
// 3. domains that cannot receive mail at all (no MX and no A/AAAA record)
|
||||||
|
// A DNS timeout or server error never blocks anyone (fails open). Only call it where an address enters for the
|
||||||
|
// first time - existing accounts must always be able to sign in with the address they already have.
|
||||||
|
const dns = require('dns').promises;
|
||||||
|
|
||||||
|
const POPULAR = ['gmail.com', 'googlemail.com', 'yahoo.com', 'ymail.com', 'hotmail.com', 'outlook.com', 'live.com',
|
||||||
|
'msn.com', 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'protonmail.com', 'proton.me', 'mail.com', 'gmx.com',
|
||||||
|
'gmx.de', 'yandex.com', 'yandex.ru', 'zoho.com', 'comcast.net', 'att.net', 'verizon.net', 'sbcglobal.net',
|
||||||
|
'bellsouth.net', 'cox.net', 'charter.net', 'yahoo.co.uk', 'hotmail.co.uk', 'btinternet.com', 'yahoo.fr',
|
||||||
|
'hotmail.fr', 'orange.fr', 'web.de', 't-online.de', 'libero.it', 'yahoo.com.br', 'outlook.com.br', 'rediffmail.com',
|
||||||
|
'qq.com', '163.com', 'naver.com', 'seznam.cz', 'wp.pl', 'mail.ru'];
|
||||||
|
const POP = new Set(POPULAR);
|
||||||
|
// endings that are typos of .com/.net/.org (real TLDs like .co, .cm, .om are deliberately NOT here)
|
||||||
|
const BAD_TLD = { con: 'com', cmo: 'com', comm: 'com', comz: 'com', coom: 'com', cpm: 'com', vom: 'com', xom: 'com',
|
||||||
|
ocm: 'com', cmon: 'com', 'com.com': 'com', nett: 'net', nte: 'net', ent: 'net', ogr: 'org', orgg: 'org', rog: 'org' };
|
||||||
|
|
||||||
|
// optimal string alignment distance (Damerau-Levenshtein with adjacent swaps), capped
|
||||||
|
function dist(a, b) {
|
||||||
|
if (Math.abs(a.length - b.length) > 2) return 9;
|
||||||
|
const d = [];
|
||||||
|
for (let i = 0; i <= a.length; i++) { d[i] = [i]; }
|
||||||
|
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
||||||
|
for (let i = 1; i <= a.length; i++) {
|
||||||
|
for (let j = 1; j <= b.length; j++) {
|
||||||
|
const c = a[i - 1] === b[j - 1] ? 0 : 1;
|
||||||
|
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c);
|
||||||
|
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d[a.length][b.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
// providers that only ever use ONE domain, so gmail.co / gmail.cm / icloud.net are always typos.
|
||||||
|
// (outlook, hotmail, yahoo, live have real national domains like hotmail.it, so they are not listed.)
|
||||||
|
const SINGLE = { gmail: 'gmail.com', googlemail: 'googlemail.com', icloud: 'icloud.com', aol: 'aol.com',
|
||||||
|
protonmail: 'protonmail.com', ymail: 'ymail.com' };
|
||||||
|
const split = d => { const i = d.indexOf('.'); return i < 0 ? [d, ''] : [d.slice(0, i), d.slice(i + 1)]; };
|
||||||
|
|
||||||
|
function suggestDomain(domain) {
|
||||||
|
if (POP.has(domain)) return null;
|
||||||
|
const labels = domain.split('.');
|
||||||
|
const two = labels.slice(-2).join('.'), last = labels[labels.length - 1];
|
||||||
|
let d = domain;
|
||||||
|
if (BAD_TLD[two]) d = labels.slice(0, -2).concat(BAD_TLD[two]).join('.');
|
||||||
|
else if (BAD_TLD[last]) d = labels.slice(0, -1).concat(BAD_TLD[last]).join('.');
|
||||||
|
if (POP.has(d)) return d;
|
||||||
|
const near = nearestPopular(d);
|
||||||
|
if (near) return near;
|
||||||
|
return d !== domain ? d : null; // ending fixed but not a known provider: still suggest the fixed ending
|
||||||
|
}
|
||||||
|
|
||||||
|
function nearestPopular(domain) {
|
||||||
|
const [name, suffix] = split(domain);
|
||||||
|
if (SINGLE[name] && domain !== SINGLE[name]) return SINGLE[name];
|
||||||
|
let best = null, bestD = 9;
|
||||||
|
for (const p of POPULAR) {
|
||||||
|
const [pn, ps] = split(p);
|
||||||
|
if (ps !== suffix) continue; // only compare names that share the same ending
|
||||||
|
const dd = dist(name, pn);
|
||||||
|
if (dd < bestD) { best = p; bestD = dd; }
|
||||||
|
}
|
||||||
|
// 1 edit always counts; 2 edits only for longer names, so short real domains are left alone
|
||||||
|
return (bestD === 1 || (bestD === 2 && name.length >= 6)) ? best : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withTimeout(promise, ms) {
|
||||||
|
return Promise.race([promise, new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'ETIMEOUT' })), ms))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// true = has somewhere to deliver, false = definitely cannot receive mail, null = could not tell (fail open)
|
||||||
|
async function domainReceives(domain) {
|
||||||
|
const gone = c => c === 'ENOTFOUND' || c === 'ENODATA' || c === 'ESERVFAIL_NXDOMAIN';
|
||||||
|
try {
|
||||||
|
const mx = await withTimeout(dns.resolveMx(domain), 3000);
|
||||||
|
if (mx && mx.length && !(mx.length === 1 && mx[0].exchange === '')) return true; // RFC 7505 null MX = no mail
|
||||||
|
if (mx && mx.length) return false;
|
||||||
|
} catch (e) { if (!gone(e.code)) return null; }
|
||||||
|
try { await withTimeout(dns.resolve4(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
|
||||||
|
try { await withTimeout(dns.resolve6(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -> null when the address is fine, or { error, suggestion } to show the person
|
||||||
|
async function emailIssue(email) {
|
||||||
|
const e = String(email || '').trim().toLowerCase();
|
||||||
|
const at = e.lastIndexOf('@');
|
||||||
|
if (at < 1) return null; // the caller's own format check handles this
|
||||||
|
const local = e.slice(0, at), domain = e.slice(at + 1);
|
||||||
|
const fix = suggestDomain(domain);
|
||||||
|
if (fix && fix !== domain) {
|
||||||
|
const suggestion = local + '@' + fix;
|
||||||
|
return { error: 'Did you mean ' + suggestion + '? Please check the email address.', suggestion };
|
||||||
|
}
|
||||||
|
if (POP.has(domain)) return null;
|
||||||
|
const ok = await domainReceives(domain);
|
||||||
|
if (ok === false) return { error: 'The email domain "' + domain + '" cannot receive mail. Please check the address.', suggestion: null };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { emailIssue, suggestDomain, domainReceives };
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
// The Engine Room (Fuel Your Offers stage 4, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
|
||||||
|
// LinkSpin. Each site gathers its OWN facts (facts shape below) and answers the other's signed /api/partner/engine call
|
||||||
|
// with them; build() turns both sites' facts + the refuel streak (InstantAdPay is its source of truth) + the member's goal
|
||||||
|
// into one plain dashboard: three dials, the streak panel, warning lights, six part lights and one "next move".
|
||||||
|
//
|
||||||
|
// facts (per site): { site: 'iap'|'linkspin', ok, credits: { available, inCampaigns }, campaigns: [{ id, name, type, status,
|
||||||
|
// budget, delivered, clicks, created }], clicksWeek, loginFree, buyUrl, adsUrl,
|
||||||
|
// LinkSpin only: goalsMonth, goalsCount, conv30, parts: { bannerSpin, spinLink, page, testing } each { state, note } }
|
||||||
|
// Everything is credits and counts. Nothing here is money or a promise.
|
||||||
|
'use strict';
|
||||||
|
const DAY = 86400000;
|
||||||
|
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : Number(v) || 0);
|
||||||
|
const LINKS = {
|
||||||
|
iapBuy: 'https://instantadpay.com/my#buy', iapCampaigns: 'https://instantadpay.com/my#campaigns', iapTracking: 'https://instantadpay.com/my#conversions',
|
||||||
|
lsBuy: 'https://linkspin.app/credits#buy', lsAds: 'https://linkspin.app/ads', lsLinks: 'https://linkspin.app/links', lsBanner: 'https://linkspin.app/links#b', lsPages: 'https://linkspin.app/pages', lsConv: 'https://linkspin.app/conversions',
|
||||||
|
};
|
||||||
|
// 2026-10-25 (Marty: "the flow from InstantAdPay to LinkSpin is confusing"): every link points at the screen on the site the
|
||||||
|
// member is ON when that site can do the job (buy, campaigns, conversion goals: InstantAdPay's Campaigns > Conversion
|
||||||
|
// tracking card writes the same LinkSpin goals). Only LinkSpin-only tools (Banner Spin, spin links, pages) cross over, and
|
||||||
|
// engine-room.js tags those links with ?from=<site>&task=<key> so LinkSpin shows an arrival strip with the first step.
|
||||||
|
const linksFor = site => site === 'linkspin'
|
||||||
|
? { buy: LINKS.lsBuy, campaigns: LINKS.lsAds, tracking: LINKS.lsConv }
|
||||||
|
: { buy: LINKS.iapBuy, campaigns: LINKS.iapCampaigns, tracking: LINKS.iapTracking };
|
||||||
|
const ACTIVE = new Set(['active', 'paused']);
|
||||||
|
|
||||||
|
// credits a day across recent campaigns: what each delivered over the days it has run (30 at most), summed
|
||||||
|
function burnPerDay(camps, now) {
|
||||||
|
let b = 0;
|
||||||
|
for (const c of camps) {
|
||||||
|
const age = Math.max(1, Math.min(30, (now - n0(c.created)) / DAY));
|
||||||
|
if (c.status !== 'active' && now - n0(c.created) > 30 * DAY) continue;
|
||||||
|
b += n0(c.delivered) / age;
|
||||||
|
}
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
function part(state, label, note, link, key) { return { state, label, note, link, key }; }
|
||||||
|
|
||||||
|
function build(o) {
|
||||||
|
const now = o.now || Date.now();
|
||||||
|
const rf = o.refuel || { on: false };
|
||||||
|
if (!rf.on) return { on: false };
|
||||||
|
const sites = [o.iap, o.ls].filter(f => f && f.ok);
|
||||||
|
const camps = sites.flatMap(f => (f.campaigns || []).map(c => Object.assign({ site: f.site }, c)));
|
||||||
|
const recent = camps.filter(c => ACTIVE.has(c.status) || now - n0(c.created) <= 30 * DAY || c.status === 'out');
|
||||||
|
const locked = !rf.started;
|
||||||
|
const here = o.site === 'linkspin' ? 'linkspin' : 'iap', L = linksFor(here);
|
||||||
|
// ---- dial 1: fuel left vs this cycle's refuel ----
|
||||||
|
const left = sites.reduce((s, f) => s + n0(f.credits && f.credits.available) + n0(f.credits && f.credits.inCampaigns), 0);
|
||||||
|
const cy = rf.cycle || null;
|
||||||
|
const refuelCredits = cy ? ['iap', 'linkspin'].reduce((s, k) => s + (cy[k] && cy[k].refueled ? n0(cy[k].credits) + n0(cy[k].bonus) : 0), 0) : 0;
|
||||||
|
const burn = burnPerDay(recent, now);
|
||||||
|
const daysLeft = burn > 0 ? Math.floor(left / burn) : null;
|
||||||
|
const fuel = { left: Math.round(left), refuelCredits: Math.round(refuelCredits), pct: refuelCredits > 0 ? Math.max(0, Math.min(100, Math.round(left / refuelCredits * 100))) : null,
|
||||||
|
burnPerDay: Math.round(burn), daysLeft, label: 'Fuel left' };
|
||||||
|
// ---- dial 2: clicks this week, and per 1,000 credits on recent campaigns ----
|
||||||
|
const clicksWeek = sites.reduce((s, f) => s + n0(f.clicksWeek), 0), clicksPrev = sites.reduce((s, f) => s + n0(f.clicksPrevWeek), 0);
|
||||||
|
const del = recent.reduce((s, c) => s + n0(c.delivered), 0), clk = recent.reduce((s, c) => s + n0(c.clicks), 0);
|
||||||
|
// the dial reads this week against last week: half way = the same as last week
|
||||||
|
const clicks = { week: clicksWeek, prevWeek: clicksPrev, pct: clicksPrev > 0 ? Math.min(100, Math.round(clicksWeek / (2 * clicksPrev) * 100)) : null, per1000: del >= 100 ? Math.round(clk / del * 1000 * 10) / 10 : null, label: 'Clicks this week' };
|
||||||
|
// ---- dial 3: goals this month (conversion pixel, LinkSpin keeps it for both sites) vs the member's own goal ----
|
||||||
|
const lsF = o.ls && o.ls.ok ? o.ls : null;
|
||||||
|
const goalTarget = Math.max(0, Math.round(n0(o.goal))) || null;
|
||||||
|
const goals = { month: lsF ? n0(lsF.goalsMonth) : null, target: goalTarget, pct: goalTarget && lsF ? Math.min(100, Math.round(n0(lsF.goalsMonth) / goalTarget * 100)) : null, tracking: lsF ? n0(lsF.goalsCount) > 0 : null, label: 'Goals this month' };
|
||||||
|
// ---- warning lights ----
|
||||||
|
const low = camps.filter(c => c.status === 'active' && n0(c.budget) > 0 && n0(c.delivered) >= n0(c.budget) * 0.8);
|
||||||
|
const out = camps.filter(c => c.status === 'out' && now - n0(c.created) <= 60 * DAY);
|
||||||
|
const running = camps.filter(c => c.status === 'active');
|
||||||
|
const refuelSoon = rf.active && rf.daysToRefuel != null && rf.daysToRefuel <= 5;
|
||||||
|
const loginFree = sites.filter(f => n0(f.loginFree) > 0).map(f => f.site);
|
||||||
|
const warnings = [
|
||||||
|
{ key: 'low', on: low.length > 0, label: 'Ads at 80%', note: low.length ? low.length + ' ad' + (low.length === 1 ? ' is' : 's are') + ' past 80% of budget' : 'none running low' },
|
||||||
|
{ key: 'out', on: out.length > 0, label: 'Ads out', note: out.length ? out.length + ' ad' + (out.length === 1 ? '' : 's') + ' finished delivering' + (running.length ? '' : ', nothing running now') : 'none out' },
|
||||||
|
{ key: 'refuel', on: !!refuelSoon, label: 'Refuel day coming', note: rf.active ? (rf.windowOpen ? 'window open: refuel day ' + rf.refuelDayLabel : 'refuel day ' + rf.refuelDayLabel) : 'no refuel day yet' },
|
||||||
|
{ key: 'login', on: loginFree.length > 0, label: 'Login slot open', note: loginFree.length ? 'a login-ad slot is free on ' + loginFree.map(s => s === 'iap' ? 'InstantAdPay' : 'LinkSpin').join(' and ') : 'all login slots taken' },
|
||||||
|
];
|
||||||
|
// ---- the six parts ----
|
||||||
|
const P = (lsF && lsF.parts) || {};
|
||||||
|
const pFuel = !camps.length ? part('grey', 'Fuel', 'no ads yet', L.campaigns, 'ads')
|
||||||
|
: out.length && !running.length ? part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads')
|
||||||
|
: low.length || (daysLeft != null && daysLeft < 5) ? part('amber', 'Fuel', daysLeft != null && daysLeft < 5 ? 'about ' + daysLeft + ' days left at your burn' : 'an ad is running low', L.buy, 'refuel')
|
||||||
|
: running.length ? part('green', 'Fuel', running.length + ' ad' + (running.length === 1 ? '' : 's') + ' running', L.campaigns, 'ads') : part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads');
|
||||||
|
const pick = (k, label, link, key) => { const x = P[k]; return x ? part(x.state, label, x.note, link, key) : part('grey', label, lsF ? 'not set up' : 'LinkSpin did not answer', link, key); };
|
||||||
|
const parts = [pFuel, pick('bannerSpin', 'Banner spin', LINKS.lsBanner, 'bannerspin'), pick('spinLink', 'Spin link', LINKS.lsLinks, 'spinlink'), pick('page', 'Page', LINKS.lsPages, 'page'), pick('testing', 'Testing', LINKS.lsLinks, 'testing'),
|
||||||
|
lsF ? (n0(lsF.goalsCount) === 0 ? part('grey', 'Conversion tracking', 'no goal set', L.tracking, 'conversions') : n0(lsF.conv30) === 0 ? part('amber', 'Conversion tracking', 'no conversions tracked yet', L.tracking, 'conversions') : part('green', 'Conversion tracking', n0(lsF.conv30) + ' in 30 days', L.tracking, 'conversions'))
|
||||||
|
: part('grey', 'Conversion tracking', 'LinkSpin did not answer', L.tracking, 'conversions')];
|
||||||
|
// ---- one next move ----
|
||||||
|
const per1000 = c => n0(c.delivered) >= 200 ? n0(c.clicks) / n0(c.delivered) * 1000 : null;
|
||||||
|
const ranked = running.filter(c => per1000(c) != null).sort((a, b) => per1000(b) - per1000(a));
|
||||||
|
const linkFor = c => c.site === 'linkspin' ? LINKS.lsAds : LINKS.iapCampaigns;
|
||||||
|
const availAll = sites.reduce((s, f) => s + n0(f.credits && f.credits.available), 0);
|
||||||
|
let next;
|
||||||
|
const mIap = rf.minUsd ? rf.minUsd.iap : 20, mLs = rf.minUsd ? rf.minUsd.linkspin : 25;
|
||||||
|
const firstWhy = here === 'linkspin' ? 'A package of $' + mLs + ' or more here (or $' + mIap + '+ on InstantAdPay) starts the streak and lights this room.' : 'A package of $' + mIap + ' or more here (or $' + mLs + '+ on LinkSpin) starts the streak and lights this room.';
|
||||||
|
if (locked) next = { key: 'start', label: 'Refuel to start your engine', why: firstWhy, link: L.buy, guide: '/refuel' };
|
||||||
|
else if (rf.windowOpen) next = { key: 'refuel', label: 'Refuel now', why: 'Your refuel window is open: +' + rf.next.single + '% on one site, +' + rf.next.both + '% on each with both. A $' + (here === 'linkspin' ? mLs : mIap) + '+ package here counts.', link: L.buy, guide: '/refuel' };
|
||||||
|
else if (out.length && !running.length && availAll >= 100) next = { key: 'relaunch', label: 'Relaunch an ad', why: 'Nothing is running and you have ' + Math.round(availAll).toLocaleString('en-US') + ' credits free.', link: linkFor(out[0]) };
|
||||||
|
else if (daysLeft != null && daysLeft < 5) next = { key: 'pitstop', label: 'Top up' + (rf.pitStop && (rf.pitStop.iap || rf.pitStop.linkspin) ? ' (Pit Stop +' + rf.pitStop.pct + '%)' : ''), why: 'About ' + daysLeft + ' days of fuel left at your current burn.', link: L.buy };
|
||||||
|
else if (low.length) { const best = low.slice().sort((a, b) => (per1000(b) || 0) - (per1000(a) || 0))[0]; next = { key: 'topup', label: 'Top up the winner', why: '"' + (best.name || 'your ad') + '" is past 80% of its budget.', link: linkFor(best) }; }
|
||||||
|
else if (parts[5].state === 'grey') next = { key: 'tracking', label: 'Set up conversion tracking', why: here === 'linkspin' ? 'Count signups and sales back to the ad that sent them. Step 1: add a goal, then paste its two snippets on your pages.' : 'Count signups and sales back to the ad that sent them. Step 1: add a goal under Campaigns > Conversion tracking, then paste its two snippets on your pages.', link: parts[5].link, guide: '/conversion-tracking' };
|
||||||
|
else if (parts[1].state === 'grey') next = { key: 'bannerspin', label: 'Make a Banner Spin', why: 'Test up to 5 banners in one ad slot and let the winner show.' + (here === 'linkspin' ? '' : ' Banner Spin is a LinkSpin tool: the same email signs you in there.'), link: LINKS.lsBanner };
|
||||||
|
else if (parts[4].state !== 'green') next = { key: 'testing', label: 'Test A against B', why: 'Add a second page to your spin link so the rotation can pick a winner.' + (here === 'linkspin' ? '' : ' Spin links live on LinkSpin: the same email signs you in there.'), link: LINKS.lsLinks };
|
||||||
|
else if (ranked.length >= 2 && per1000(ranked[0]) > per1000(ranked[ranked.length - 1]) * 1.5) { const worst = ranked[ranked.length - 1]; next = { key: 'cut', label: 'Cut the loser', why: '"' + (worst.name || 'an ad') + '" brings the fewest clicks per 1,000 credits. Pause it and move the credits to "' + (ranked[0].name || 'your best ad') + '".', link: linkFor(worst) }; }
|
||||||
|
else next = { key: 'cruise', label: 'Keep it running', why: 'Every part is lit. Check again on your refuel day.', link: L.campaigns };
|
||||||
|
return {
|
||||||
|
on: true, locked, fuel, clicks, goals,
|
||||||
|
streak: { active: !!rf.active, months: rf.streak || 0, best: rf.best || 0, refuelDay: rf.refuelDayLabel || null, graceEnd: rf.graceLabel || null, windowOpen: !!rf.windowOpen, next: rf.next || null, pitStop: rf.pitStop || null, freeMiss: rf.freeMiss || null, both: !!(cy && cy.both), note: streakNote(rf, cy) },
|
||||||
|
warnings, parts, next, site: here, sites: { iap: !!(o.iap && o.iap.ok), linkspin: !!(o.ls && o.ls.ok) }, at: now,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// this site's own facts for one member. d: { site, adminMember, ads, coach, now?, bannerspin?, rotator?, pages?, convtrack? }
|
||||||
|
const monthStartCT = now => { const day = new Date(now).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const [y, m] = day.split('-').map(Number);
|
||||||
|
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, 1, off); const t = new Date(ts); if (t.toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) === day.slice(0, 8) + '01' && Number(t.toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })) % 24 === 0) return ts; } return Date.UTC(y, m - 1, 1, 6); };
|
||||||
|
async function facts(d, email) {
|
||||||
|
const now = d.now || Date.now(); const e = String(email || '').toLowerCase();
|
||||||
|
const out = { site: d.site, ok: true, credits: { available: 0, inCampaigns: 0 }, campaigns: [], clicksWeek: 0, loginFree: 0 };
|
||||||
|
try { const v = await d.adminMember.view(e); if (v && v.credits) out.credits = { available: n0(v.credits.available), inCampaigns: n0(v.credits.inCampaigns) }; } catch (er) {}
|
||||||
|
let list = []; try { list = (await d.ads.listCampaigns(e)).filter(c => !c.house && c.type !== 'game'); } catch (er) {}
|
||||||
|
out.campaigns = list.map(c => ({ id: c.id, name: c.name || null, type: c.type, status: c.status, budget: n0(c.budget), delivered: n0(c.spent), clicks: n0(c.clicks), created: n0(c.created) }));
|
||||||
|
try { out.clicksWeek = await d.coach.clicksSince(list.map(c => c.id), now - 7 * DAY); out.clicksPrevWeek = Math.max(0, (await d.coach.clicksSince(list.map(c => c.id), now - 14 * DAY)) - out.clicksWeek); } catch (er) {}
|
||||||
|
try { out.loginFree = n0((await d.ads.loginSlots()).free); } catch (er) {}
|
||||||
|
if (d.site === 'linkspin') {
|
||||||
|
const since30 = now - 30 * DAY;
|
||||||
|
try { out.goalsCount = d.convtrack.goalsOf(e).length; out.goalsMonth = d.convtrack.countSince(e, monthStartCT(now)); out.conv30 = d.convtrack.countSince(e, since30); } catch (er) { out.goalsCount = 0; out.goalsMonth = 0; out.conv30 = 0; }
|
||||||
|
const parts = {};
|
||||||
|
let spins = [], rots = [], pgs = [];
|
||||||
|
try { spins = await d.bannerspin.list(e); } catch (er) {}
|
||||||
|
try { rots = await d.rotator.list(e); } catch (er) {}
|
||||||
|
try { pgs = await d.pages.list(e); } catch (er) {}
|
||||||
|
const liveB = s => s.banners.filter(b => b.active && !b.adminOff);
|
||||||
|
if (!spins.length) parts.bannerSpin = { state: 'grey', note: 'not set up' };
|
||||||
|
else { const seen = spins.filter(s => !s.paused && s.imps30 > 0); parts.bannerSpin = seen.length ? { state: 'green', note: seen.reduce((n, s) => n + s.imps30, 0).toLocaleString('en-US') + ' views in 30 days' } : { state: 'amber', note: 'no views yet' }; }
|
||||||
|
if (!rots.length) parts.spinLink = { state: 'grey', note: 'not set up' };
|
||||||
|
else { const w = rots.reduce((n, r) => n + n0(r.hits7), 0); parts.spinLink = w > 0 ? { state: 'green', note: w.toLocaleString('en-US') + ' clicks this week' } : { state: 'amber', note: 'no clicks this week' }; }
|
||||||
|
const pub = pgs.filter(p => p.status === 'published');
|
||||||
|
parts.page = !pgs.length ? { state: 'grey', note: 'not set up' } : !pub.length ? { state: 'amber', note: 'draft only, not published' } : pub.some(p => n0(p.views) > 0) ? { state: 'green', note: pub.length + ' published' } : { state: 'amber', note: 'published, no views yet' };
|
||||||
|
const rotTest = rots.some(r => !r.paused && r.destinations.filter(x => x.active).length >= 2);
|
||||||
|
const rotTraffic = rots.some(r => !r.paused && r.destinations.filter(x => x.active && x.hits7 > 0).length >= 2);
|
||||||
|
const bsTest = spins.some(s => !s.paused && liveB(s).length >= 2);
|
||||||
|
const bsTraffic = spins.some(s => !s.paused && liveB(s).filter(b => b.imps30 > 0).length >= 2);
|
||||||
|
parts.testing = rotTraffic || bsTraffic ? { state: 'green', note: 'two or more versions getting traffic' } : rotTest || bsTest ? { state: 'amber', note: 'two versions set up, waiting for traffic' } : (rots.length || spins.length) ? { state: 'amber', note: 'only one version: add a second to test' } : { state: 'grey', note: 'not set up' };
|
||||||
|
out.parts = parts;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the streak panel's one line about the next refuel (2026-10-24): once BOTH sites are refueled this cycle it says so,
|
||||||
|
// and only a cycle with one site done asks for the other one, by name
|
||||||
|
function streakNote(rf, cy) {
|
||||||
|
const nx = rf && rf.next; if (!rf || !rf.active || !nx) return '';
|
||||||
|
if (rf.windowOpen) return 'Window open: next refuel +' + nx.single + '% (+' + nx.both + '% on each with both).';
|
||||||
|
const iapDone = !!(cy && cy.iap && cy.iap.refueled), lsDone = !!(cy && cy.linkspin && cy.linkspin.refueled);
|
||||||
|
if ((cy && cy.both) || (iapDone && lsDone)) return 'Both engines fueled this cycle: +' + (nx.secondEngine || (cy.iap && cy.iap.pct) || 0) + '% on each.';
|
||||||
|
if (nx.secondEngine) return 'Refuel ' + (iapDone ? 'LinkSpin' : 'InstantAdPay') + ' this cycle for +' + nx.secondEngine + '% on both.';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { streakNote, build, facts, burnPerDay, monthStartCT, LINKS };
|
||||||
+132
-52
@@ -1,10 +1,10 @@
|
|||||||
// Game Pass (2026-10-16): the $5 weekly pass across all nine games, and the account-wide POL cap service the games call
|
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (ten with POL Miner, 2026-10-28), and the account-wide POL cap service the games call
|
||||||
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
|
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
|
||||||
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
|
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
|
||||||
//
|
//
|
||||||
// What lives here:
|
// What lives here:
|
||||||
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
|
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
|
||||||
// - waiting orders order -> { status, email, ts, tx } (a $5+ package bought while an order waits fulfils it: the pwpasses pattern)
|
// - pass orders order -> { status, email, ts, tx } (every pass is paid by a FRESH package purchase: see buy() / onEvent())
|
||||||
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
|
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
|
||||||
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
|
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
|
||||||
// - admin stats
|
// - admin stats
|
||||||
@@ -18,19 +18,49 @@
|
|||||||
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
|
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
|
||||||
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
|
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
|
||||||
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
|
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
|
||||||
// `sovTiers` (default off; only ADMIN_EMAIL can see and buy them while it is off). No proration, no auto-renew: buying again
|
// `sovTiers` (default off; while it is off the admin tests them from Admin > Game Pass, never on the member card). No proration, no auto-renew: buying again
|
||||||
// extends that tier from max(now, until).
|
// extends that tier from max(now, until).
|
||||||
|
// 2026-10-22 (Marty): every pass rides the package rail so sponsors get paid. Buying a pass never spends a credit balance any more
|
||||||
|
// (today's buyer paid from an old balance, so no new money came in and nobody upline was paid). A pass click opens an order; the
|
||||||
|
// order is fulfilled ONLY by an on-chain package Purchase of at least the tier price, mined after the order was opened, bought by
|
||||||
|
// one of that member's own positions (main or linked), each purchase tx used once. The member keeps that package's credits for ads.
|
||||||
|
// Bought rows: via 'package' (with tx and cents). The two rows from before this change are via 'credits' and 'package' and stay.
|
||||||
|
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 and Champion $39.99 (30 days), plus Sovereign $99.99 (30 days)
|
||||||
|
// and Legend $249.99 (365 days, the yearly pass), all in TIER_DEFS below and all behind the same sovTiers switch. The weekly
|
||||||
|
// pass is unchanged ($5 / 7 days / the same caps). Rank weekly < explorer < champion < sovereign < legend.
|
||||||
|
// 2026-10-25 (Marty): every tier price equals an InstantAdPay one-click package, so the cheapest qualifying package is exactly
|
||||||
|
// the pass price (no silent overpay): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend
|
||||||
|
// $250 (was 249.99); weekly $5 unchanged. The pass comes with that package's ad credits.
|
||||||
'use strict';
|
'use strict';
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
const TZ = 'America/Chicago';
|
const TZ = 'America/Chicago';
|
||||||
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent', 'shardsofvalor'];
|
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent', 'shardsofvalor', 'polminer'];
|
||||||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent', shardsofvalor: 'Shards of Valor' };
|
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent', shardsofvalor: 'Shards of Valor', polminer: 'POL Miner' };
|
||||||
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
|
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
|
||||||
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
|
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
|
||||||
const TIERS = ['weekly', 'explorer', 'champion']; // lowest to highest
|
// THE pass table (2026-10-22, Dallas's structure, Marty approved): lowest to highest, a higher tier includes everything below.
|
||||||
const TIER_NAMES = { weekly: 'Game Pass', explorer: 'Explorer', champion: 'Champion' };
|
// Rename a tier here (name) and nowhere else: the member card, the admin pane, the charge label and the chatbot read it from here.
|
||||||
|
// key = the wire value the games read (flag().tier / tiers); set = the Admin > Settings stem (gamePass<set>Enabled /
|
||||||
|
// PriceCredits / Days; weekly keeps its original gamePassPriceCredits / gamePassDays); price = the pass price in cents (100 = $1;
|
||||||
|
// the setting keeps its old 'PriceCredits' name): the package that pays for a pass must cost at least this much;
|
||||||
|
// perks = what the member card lists. Every tier is a Game Pass holder everywhere with the SAME caps (no extra POL).
|
||||||
|
const TIER_DEFS = [
|
||||||
|
{ key: 'weekly', name: 'Game Pass', set: '', price: 500, days: 7,
|
||||||
|
perks: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and weapons unlocked'] },
|
||||||
|
{ key: 'explorer', name: 'Explorer', set: 'Explorer', price: 2000, days: 30,
|
||||||
|
perks: ['Everything in the Game Pass, in every game', 'Shards of Valor: weapons and gear unlocked', 'Shards of Valor: 2 bonus islands'] },
|
||||||
|
{ key: 'champion', name: 'Champion', set: 'Champion', price: 5000, days: 30,
|
||||||
|
perks: ['Everything in Explorer', 'Shards of Valor: 4 bonus islands of your choice', 'Shards of Valor: the Druid hero', 'Shards of Valor: level cap 30'] },
|
||||||
|
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
|
||||||
|
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: the Necromancer hero', 'Shards of Valor: level cap 40'] },
|
||||||
|
{ key: 'legend', name: 'Legend', set: 'Legend', price: 25000, days: 365,
|
||||||
|
perks: ['Everything in Sovereign, for a full year', 'Shards of Valor: every bonus island', 'Shards of Valor: every hero, the Archer included', 'Shards of Valor: level cap 40'] },
|
||||||
|
];
|
||||||
|
const TIERS = TIER_DEFS.map(d => d.key); // lowest to highest
|
||||||
|
const TIER_NAMES = Object.fromEntries(TIER_DEFS.map(d => [d.key, d.name]));
|
||||||
|
const TIER_DEF = Object.fromEntries(TIER_DEFS.map(d => [d.key, d]));
|
||||||
const tierOk = t => TIERS.includes(t);
|
const tierOk = t => TIERS.includes(t);
|
||||||
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
|
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
|
||||||
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
||||||
@@ -63,14 +93,12 @@ function cfg() {
|
|||||||
return {
|
return {
|
||||||
enabled: on('gamePassEnabled'),
|
enabled: on('gamePassEnabled'),
|
||||||
price, days,
|
price, days,
|
||||||
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Explorer/Champion need the master
|
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Every tier above weekly needs the
|
||||||
// switch sovTiers AND the weekly pass switched on; their own gamePass<Tier>Enabled is a kill switch (missing = on).
|
// master switch sovTiers AND the weekly pass switched on; its own gamePass<Set>Enabled is a kill switch (missing = on).
|
||||||
tierSales: on('sovTiers'),
|
tierSales: on('sovTiers'),
|
||||||
tiers: {
|
tiers: Object.fromEntries(TIER_DEFS.map(d => [d.key, d.key === 'weekly' ? { price, days, sale: on('gamePassEnabled') }
|
||||||
weekly: { price, days, sale: on('gamePassEnabled') },
|
: { price: Math.max(1, Math.round(n('gamePass' + d.set + 'PriceCredits', d.price))), days: Math.max(1, Math.round(n('gamePass' + d.set + 'Days', d.days))),
|
||||||
explorer: { price: Math.max(1, Math.round(n('gamePassExplorerPriceCredits', 2000))), days: Math.max(1, Math.round(n('gamePassExplorerDays', 30))), sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePassExplorerEnabled') },
|
sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePass' + d.set + 'Enabled') }])),
|
||||||
champion: { price: Math.max(1, Math.round(n('gamePassChampionPriceCredits', 4000))), days: Math.max(1, Math.round(n('gamePassChampionDays', 30))), sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePassChampionEnabled') },
|
|
||||||
},
|
|
||||||
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
|
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
|
||||||
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
|
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
|
||||||
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
|
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
|
||||||
@@ -137,6 +165,11 @@ function extend(e, via, extra, now, tier) {
|
|||||||
}
|
}
|
||||||
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
|
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e) out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
|
||||||
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
|
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
|
||||||
|
// the admin's tier test: drop a waiting order that was opened for testing, so a later real package never fulfils it by surprise
|
||||||
|
function cancelOrder(email, tier) {
|
||||||
|
const e = String(email || '').toLowerCase(); const w = waitingOrder(e, tier || 'weekly'); if (!w) return { ok: true, none: true };
|
||||||
|
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, tier: w.tier };
|
||||||
|
}
|
||||||
function comp(email, why, tier, now) { // support comp: counts as no sale
|
function comp(email, why, tier, now) { // support comp: counts as no sale
|
||||||
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
|
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
|
||||||
return { active: true, until: x.until, days: x.days, tier: x.tier };
|
return { active: true, until: x.until, days: x.days, tier: x.tier };
|
||||||
@@ -150,21 +183,23 @@ function revoke(email, tier, why, now) {
|
|||||||
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
|
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
|
||||||
return { ok: true, tier, was, until: t };
|
return { ok: true, tier, was, until: t };
|
||||||
}
|
}
|
||||||
// on sale for this viewer: the tier's own switch, or the admin account testing Explorer/Champion while sovTiers is off
|
// on sale for this viewer: the tier's own switch, or the admin portal's tier test (Admin > Game Pass) while sovTiers is off
|
||||||
const tierOpen = (c, tier, admin) => !!(c.tiers[tier].sale || (admin && tier !== 'weekly'));
|
const tierOpen = (c, tier, preview) => !!(c.tiers[tier].sale || (preview && tier !== 'weekly'));
|
||||||
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
|
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
|
||||||
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
|
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
|
||||||
|
|
||||||
// GET /api/my/gamepass. opts.admin = the ADMIN_EMAIL account (sees Explorer/Champion while sovTiers is off).
|
// GET /api/my/gamepass: exactly what a member sees, for EVERY account, the admin's included (2026-10-25, Marty: no admin-only
|
||||||
|
// tier UI on the member card). opts.preview = the admin portal's tier test (GET /api/admin/gamepass/preview): every tier, each
|
||||||
|
// one open to the admin's own account while sovTiers is off.
|
||||||
function view(email, now, opts) {
|
function view(email, now, opts) {
|
||||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e, 'weekly');
|
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e, 'weekly');
|
||||||
const admin = !!(opts && opts.admin); const T = tiersOf(p);
|
const admin = !!(opts && opts.preview); const T = tiersOf(p);
|
||||||
const caps = capsFor(e, t);
|
const caps = capsFor(e, t);
|
||||||
// the tier rows this member sees: weekly always; Explorer/Champion while on sale, to the admin, or to a current holder (holders
|
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
|
||||||
// keep their pass when a sale is switched off, they just cannot buy more)
|
// keep their pass when a sale is switched off, they just cannot buy more)
|
||||||
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
|
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
|
||||||
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
|
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
|
||||||
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
|
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
|
||||||
});
|
});
|
||||||
const tiered = passRows.some(r => r.tier !== 'weekly');
|
const tiered = passRows.some(r => r.tier !== 'weekly');
|
||||||
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, price: c.price, days: c.days, usd: c.price / 100,
|
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, price: c.price, days: c.days, usd: c.price / 100,
|
||||||
@@ -174,46 +209,67 @@ function view(email, now, opts) {
|
|||||||
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales };
|
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales };
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /api/my/gamepass/buy { tier }. `charge(price, label)` runs ads.gamePurchase(purchasedOnly) and resolves { ok } | { error: 'short', ... } | { error }.
|
// POST /api/my/gamepass/buy { tier }. tier missing = weekly (exactly the pass as it was before tiers). opts.preview = the admin
|
||||||
// tier missing = weekly (exactly the pass as it was before tiers). opts.admin = the ADMIN_EMAIL account.
|
// portal's tier test (POST /api/admin/gamepass/test-buy, the admin's own account only): a tier that is not on sale still opens an order.
|
||||||
async function buy(email, charge, now, tier, opts) {
|
// A pass is ALWAYS paid by a fresh package purchase (2026-10-22, Marty: the pass rides the package rail so sponsors get paid). This never
|
||||||
|
// spends credits: it opens (or reuses) a waiting order for that tier and sends the member to buy a package of at least the tier price.
|
||||||
|
// The order is fulfilled by onEvent() below; the member keeps every credit of that package for ads.
|
||||||
|
function buy(email, now, tier, opts) {
|
||||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
|
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
|
||||||
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
|
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
|
||||||
if (!tierOk(tier)) return { error: 'There is no such pass.' };
|
if (!tierOk(tier)) return { error: 'There is no such pass.' };
|
||||||
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
|
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
|
||||||
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
|
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
|
||||||
else if (!tierOpen(c, tier, !!(opts && opts.admin))) return { error: 'The ' + name + ' pass is not open yet.' };
|
else if (!tierOpen(c, tier, !!(opts && opts.preview))) return { error: 'The ' + name + ' pass is not open yet.' };
|
||||||
const r = await charge(tc.price, (tier === 'weekly' ? 'Game Pass' : name + ' pass') + ' (' + tc.days + ' days)');
|
let w = waitingOrder(e, tier); const reused = !!w;
|
||||||
if (r && r.ok) {
|
|
||||||
const x = extend(e, 'credits', { credits: tc.price, campaignId: r.campaignId || null }, t, tier);
|
|
||||||
console.log('gamepass bought with credits', tier, e, tc.price, 'until', new Date(x.until).toISOString());
|
|
||||||
return { ok: true, active: true, tier, until: x.until, days: tc.days, paid: 'credits' };
|
|
||||||
}
|
|
||||||
if (r && r.error === 'short') {
|
|
||||||
// no purchased-grade credits on a position: the pass waits for a package of at least its price (bought while the order waits, it fulfils it)
|
|
||||||
let w = waitingOrder(e, tier);
|
|
||||||
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
|
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
|
||||||
const pkg = packageFor(tc.price / 100);
|
const pkg = packageFor(tc.price / 100);
|
||||||
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, price: tc.price, usd: tc.price / 100, package: pkg, available: r.available || 0, need: r.need || tc.price,
|
if (!reused) console.log('gamepass order opened', tier, e, w.order, 'needs a package of', tc.price, 'cents');
|
||||||
message: (tier === 'weekly' ? 'The pass' : 'The ' + name + ' pass') + ' is paid with purchased credits. Buy a $' + pkg + ' package and the pass starts the moment it settles; you keep every credit of the package for your ads.' };
|
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, orderTs: w.ts, reused,
|
||||||
}
|
price: tc.price, usd: tc.price / 100, package: pkg,
|
||||||
return { error: (r && r.error) || 'The purchase did not go through. Nothing was taken.' };
|
message: (tier === 'weekly' ? 'Your Game Pass' : 'Your ' + name + ' pass') + ' starts the moment your next package of $' + pkg + ' or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
|
||||||
}
|
}
|
||||||
|
|
||||||
// a package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers
|
// A package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers.
|
||||||
// (one pass per purchase of $5 or more, each tx counted once)
|
// Rules (2026-10-22): the buyer must be one of this account's own positions (main member id or a linked position); the purchase must
|
||||||
|
// be mined AFTER the order was opened (block time, ORDER_SKEW_MS for clock drift); one pass per purchase of $5 or more; each tx used
|
||||||
|
// once across every account and order. Credit balances never fulfil an order.
|
||||||
|
const ORDER_SKEW_MS = 30000;
|
||||||
|
function txUsed(tx) {
|
||||||
|
if (!tx) return false;
|
||||||
|
for (const [, o] of orders) if (o && o.tx === tx) return true;
|
||||||
|
for (const [, p] of passes) if (p && (p.bought || []).some(b => b.tx && b.tx === tx)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
async function ownerOf(ev) { // the account behind the buying position
|
||||||
|
if (ev.devEmail && !R.isProd) return String(ev.devEmail).toLowerCase();
|
||||||
|
const id = Number(ev.buyerId) || 0; if (!id) return null;
|
||||||
|
let a = await R.accounts.byMemberId(id);
|
||||||
|
if (!a && R.accounts.positionByMember) { const pos = await R.accounts.positionByMember(id); if (pos && pos.email) a = { email: pos.email }; }
|
||||||
|
return a && a.email ? String(a.email).toLowerCase() : null;
|
||||||
|
}
|
||||||
|
async function minedAt(ev) { // block time in ms; the indexed-at time only when the block cannot be read (it is never earlier than the block)
|
||||||
|
if (ev.devMinedAt && !R.isProd) return Number(ev.devMinedAt);
|
||||||
|
if (ev.block && R.blockTime) {
|
||||||
|
for (let i = 0; i < 3; i++) { try { const s = await R.blockTime(ev.block); if (s > 0) return s * 1000; } catch (e) {} await new Promise(r => setTimeout(r, 1500)); }
|
||||||
|
console.warn('gamepass: block time unavailable for', ev.block, '- using the indexed-at time');
|
||||||
|
}
|
||||||
|
return Number(ev.ts) || Date.now();
|
||||||
|
}
|
||||||
async function onEvent(ev) {
|
async function onEvent(ev) {
|
||||||
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
|
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
|
||||||
const c = cfg(); const cents = ev.priceCents || 0;
|
const c = cfg(); const cents = ev.priceCents || 0;
|
||||||
if (!TIERS.some(k => cents >= c.tiers[k].price)) return null;
|
if (!TIERS.some(k => cents >= c.tiers[k].price)) return null;
|
||||||
const a = (ev.devEmail && !R.isProd) ? { email: ev.devEmail } : await R.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
|
const e = await ownerOf(ev); if (!e) return null;
|
||||||
const e = String(a.email).toLowerCase();
|
if (!waitingOrders(e).length) return null;
|
||||||
const p = passes.get(e); if (p && (p.bought || []).some(b => b.tx && b.tx === ev.tx)) return null; // each purchase counts once
|
if (txUsed(ev.tx)) return null; // each purchase counts once, everywhere
|
||||||
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price).sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].price || x.ts - y.ts)[0];
|
const at = await minedAt(ev);
|
||||||
if (!w) return null;
|
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price && at + ORDER_SKEW_MS >= o.ts)
|
||||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now() }));
|
.sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].price || x.ts - y.ts)[0];
|
||||||
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order }, ev.ts || Date.now(), w.tier);
|
if (!w) { console.log('gamepass: package', String(ev.tx).slice(0, 12), 'by', e, 'fulfils no order (bought before the order or too small)'); return null; }
|
||||||
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), 'until', new Date(x.until).toISOString());
|
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
|
||||||
|
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: c.tiers[w.tier].price / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), w.tier);
|
||||||
|
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents, until', new Date(x.until).toISOString());
|
||||||
return { order: w.order, until: x.until, tier: w.tier };
|
return { order: w.order, until: x.until, tier: w.tier };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,13 +346,13 @@ function voidGrant(o) {
|
|||||||
|
|
||||||
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
|
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
|
||||||
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
|
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
|
||||||
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (Explorer and Champion include everything Weekly gives)
|
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (every tier above weekly includes everything Weekly gives)
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
|
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
|
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
|
||||||
// the pool counts weekly pass sales only, unless passTournamentTierSales adds Explorer/Champion sales (default off: the pool exactly as before tiers)
|
// the pool counts weekly pass sales only, unless passTournamentTierSales adds the sales of every tier above weekly (default off: the pool exactly as before tiers)
|
||||||
function salesIn(start, end, withTiers) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end && (withTiers || rowTier(b) === 'weekly')) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
|
function salesIn(start, end, withTiers) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end && (withTiers || rowTier(b) === 'weekly')) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
|
||||||
function scoresFor(wk, emails) {
|
function scoresFor(wk, emails) {
|
||||||
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
|
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
|
||||||
@@ -374,6 +430,29 @@ function tierStats(t) {
|
|||||||
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
|
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
// every sale row, newest first, labelled by how it was paid. Rows from the new package rail carry buyerId (2026-10-22); the two
|
||||||
|
// rows from before (one paid with a credit balance, one fulfilled by a package under the old rule) are labelled as such.
|
||||||
|
function payLabel(b) {
|
||||||
|
if (b.via === 'credits') return 'credit-paid (old rule)';
|
||||||
|
if (b.via === 'package') return ('buyerId' in b) ? 'package' : 'package (old rule)';
|
||||||
|
return String(b.via || '?');
|
||||||
|
}
|
||||||
|
function salesList(limit) {
|
||||||
|
const out = [];
|
||||||
|
for (const [e, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b)) out.push({ ts: b.ts, email: e, tier: rowTier(b), name: TIER_NAMES[rowTier(b)], via: b.via, label: payLabel(b),
|
||||||
|
tx: b.tx || null, usd: Number(b.usd) || 0, packageUsd: b.packageUsd || (b.cents ? b.cents / 100 : null), credits: b.credits || null, buyerId: b.buyerId || null });
|
||||||
|
return out.sort((a, b) => b.ts - a.ts).slice(0, limit || 50);
|
||||||
|
}
|
||||||
|
function payMix() {
|
||||||
|
const m = { credit: { n: 0, usd: 0 }, packageOld: { n: 0, usd: 0 }, package: { n: 0, usd: 0, packageUsd: 0 } };
|
||||||
|
for (const [, p] of passes) for (const b of (p && p.bought) || []) {
|
||||||
|
if (!isSale(b)) continue; const usd = Number(b.usd) || 0;
|
||||||
|
const k = b.via === 'credits' ? 'credit' : (b.via === 'package' && !('buyerId' in b)) ? 'packageOld' : 'package';
|
||||||
|
m[k].n += 1; m[k].usd = Math.round((m[k].usd + usd) * 100) / 100;
|
||||||
|
if (k === 'package') m.package.packageUsd = Math.round((m.package.packageUsd + (Number(b.packageUsd) || (b.cents ? b.cents / 100 : 0))) * 100) / 100;
|
||||||
|
}
|
||||||
|
return m;
|
||||||
|
}
|
||||||
function adminStats(now) {
|
function adminStats(now) {
|
||||||
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
|
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
|
||||||
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
|
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
|
||||||
@@ -401,7 +480,8 @@ function adminStats(now) {
|
|||||||
return { enabled: c.enabled, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
|
return { enabled: c.enabled, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
|
||||||
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
|
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
|
||||||
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
|
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
|
||||||
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting },
|
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting, pay: payMix() },
|
||||||
|
sales: salesList(50),
|
||||||
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
|
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
|
||||||
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
|
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
|
||||||
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
|
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
|
||||||
@@ -422,5 +502,5 @@ function prune(now) {
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, flag, view, buy, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
module.exports = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, flag, view, buy, cancelOrder, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||||||
_ledger: () => L };
|
_ledger: () => L };
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
let R = null;
|
let R = null;
|
||||||
const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip', polybreak: 'PolyBreak', shardsofvalor: 'Shards of Valor' };
|
const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip', polybreak: 'PolyBreak', polminer: 'POL Miner', shardsofvalor: 'Shards of Valor' };
|
||||||
const wallets = () => Object.fromEntries(String(process.env.GAME_WALLETS || '').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [k, a] = x.split(':'); return [String(k).toLowerCase(), String(a || '').toLowerCase()]; }).filter(([k, a]) => k && /^0x[0-9a-f]{40}$/.test(a)));
|
const wallets = () => Object.fromEntries(String(process.env.GAME_WALLETS || '').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [k, a] = x.split(':'); return [String(k).toLowerCase(), String(a || '').toLowerCase()]; }).filter(([k, a]) => k && /^0x[0-9a-f]{40}$/.test(a)));
|
||||||
const KEY = () => String(process.env.ETHERSCAN_KEY || '').trim();
|
const KEY = () => String(process.env.ETHERSCAN_KEY || '').trim();
|
||||||
// money never flows to these from a game wallet as a payout: Marty's fee wallets, the other game wallets
|
// money never flows to these from a game wallet as a payout: Marty's fee wallets, the other game wallets
|
||||||
|
|||||||
+4
-2
@@ -4,8 +4,8 @@
|
|||||||
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
|
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
|
||||||
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
|
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
|
||||||
'use strict';
|
'use strict';
|
||||||
let tickets = null;
|
let tickets = null, accounts = null;
|
||||||
function init(d) { tickets = d.tickets; }
|
function init(d) { tickets = d.tickets; accounts = d.accounts || null; }
|
||||||
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
|
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
|
||||||
|
|
||||||
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
|
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
|
||||||
@@ -63,6 +63,8 @@ async function handle(buf, contentType) {
|
|||||||
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
|
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
|
||||||
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
|
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
|
||||||
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
|
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
|
||||||
|
// new tickets only from member emails (Marty 2026-10-24); LinkSpin-first members are InstantAdPay accounts too (lsinbound)
|
||||||
|
canOpen: accounts ? async addr => { try { return !!(await accounts.byEmail(addr)); } catch (e) { return true; } } : null,
|
||||||
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
|
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
|
||||||
if (r && r.error) return 'refused: ' + r.error;
|
if (r && r.error) return 'refused: ' + r.error;
|
||||||
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
|
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
|
||||||
|
|||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the public FAQ on the home page,
|
||||||
|
// the Platform Facts page (/facts), the wallets guide's Common questions, and support replies worth
|
||||||
|
// keeping. An entry here that nobody has edited in Admin > Knowledge base is refreshed when its text
|
||||||
|
// changes in this file; edit it in the admin pane and it becomes the admin's own.
|
||||||
|
// House rules: plain words, no em dashes, never a promise of income.
|
||||||
|
const FAQ = [
|
||||||
|
{ id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket',
|
||||||
|
questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'],
|
||||||
|
tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'],
|
||||||
|
answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. InstantAdPay runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open instantadpay.com in SafePal\'s browser (or the browser with the extension), sign in with your email and tap Link wallet (one free signature). You only need a wallet to buy a package or receive payouts.' },
|
||||||
|
{ id: 'f-how-fast', title: 'How fast do I really get paid?', source: 'faq',
|
||||||
|
questions: ['How fast do I get paid?', 'When does my commission arrive?', 'Is there an approval step for payouts?'],
|
||||||
|
tags: ['payout', 'speed', 'same transaction', 'ledger'],
|
||||||
|
answer: 'Payouts happen inside the very transaction that pays for the package. There is no approval step and nobody holding funds. Your share lands in your own wallet the moment your referral\'s purchase confirms, and the public ledger at https://instantadpay.com/ledger lets you watch each one go through.' },
|
||||||
|
{ id: 'f-what-buying', title: 'What am I actually buying?', source: 'faq',
|
||||||
|
questions: ['What am I actually buying?', 'What is the product?', 'Do bigger packages give bonus credits?'],
|
||||||
|
tags: ['product', 'ad delivery', 'credits', 'packages'],
|
||||||
|
answer: 'You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. The $5 package mints 500 credits, and the bigger packages mint bonus credits on top, up to 70,000 on the $500 package. Earnings only come from referring people who also buy real ad delivery, and the contract splits every purchase automatically. Nothing is a promise of income.' },
|
||||||
|
{ id: 'f-refunds', title: 'Refunds', source: 'faq',
|
||||||
|
questions: ['Can I get a refund?', 'Is my purchase refundable?', 'Can a POL payment be reversed or charged back?', 'What happens if my campaign fails to deliver?'],
|
||||||
|
tags: ['refund', 'chargeback', 'reverse payment', 'final'],
|
||||||
|
answer: 'Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in your balance until you spend them. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to your balance, labeled as returned purchased credits.' },
|
||||||
|
{ id: 'f-credits-transfer', title: 'Can credits be transferred or turned into POL?', source: 'faq',
|
||||||
|
questions: ['Can I transfer credits to another member?', 'Can I give my credits to a friend?', 'Can I sell my credits or exchange them for POL?', 'Are credits a token?'],
|
||||||
|
tags: ['credits', 'transfer', 'cash value', 'token'],
|
||||||
|
answer: 'No. Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash. Purchased credits are recorded on-chain and burned as your campaigns spend them; earned credits (welcome, viewing, visits, promo codes) are kept by the site and labeled separately.' },
|
||||||
|
{ id: 'f-price-feed', title: 'How the POL price of a package is set', source: 'faq',
|
||||||
|
questions: ['How is the POL price calculated?', 'Why did the POL amount change?', 'What price feed do you use?'],
|
||||||
|
tags: ['price', 'chainlink', 'pol price', 'rate'],
|
||||||
|
answer: 'Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon, so the POL amount moves with the market. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers. Any package price change waits 24 hours before it takes effect.' },
|
||||||
|
{ id: 'f-contract', title: 'The contract address and network', source: 'faq',
|
||||||
|
questions: ['What is the contract address?', 'Which network is the contract on?', 'Is the contract verified?', 'Can the split be changed?'],
|
||||||
|
tags: ['contract', 'address', 'polygonscan', 'verified', 'polygon'],
|
||||||
|
answer: 'InstantAdPay runs on Polygon mainnet (chain id 137). The contract is 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 and its source is verified and public. The percentages and qualification rules are constants in the code, there is no function that changes them, and the contract holds no member funds. The plain-language review is at https://instantadpay.com/contract and the reference facts at https://instantadpay.com/facts.' },
|
||||||
|
{ id: 'f-platform-share', title: 'Where the platform share goes', source: 'faq',
|
||||||
|
questions: ['Where does the 20 percent platform share go?', 'What are the platform wallets?', 'What happens to a share nobody qualifies for?'],
|
||||||
|
tags: ['platform', 'platform wallets', 'fees', 'pass-up'],
|
||||||
|
answer: 'The 20 percent platform share is two fixed 10 percent fees to platform wallet A (0x7627fc78876948ac9d95c1c9eb061e7d6d647b70) and B (0x8b7d33849a2c4d92c985be31e46dc564ba901ad2). Platform income pays for operations, development, marketing and the game rewards. If nobody within 25 steps qualifies for a level, that share goes to wallet A, and every pass-up is recorded on-chain with the reason. Overpayment is returned to the buyer in the same transaction.' },
|
||||||
|
{ id: 'f-active-viewing', title: 'Why the video or timer paused', source: 'faq',
|
||||||
|
questions: ['Why did my video ad pause?', 'Why did the countdown stop?', 'Why was my view not counted?'],
|
||||||
|
tags: ['video', 'timer', 'countdown', 'paused', 'anti-fraud'],
|
||||||
|
answer: 'Viewing is active only: video ads pause when you switch tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early. Keep the tab in front until the countdown finishes and pass the quick check.' },
|
||||||
|
{ id: 'f-game-rewards', title: 'Where game POL rewards come from', source: 'faq',
|
||||||
|
questions: ['Where do the game rewards come from?', 'Are game rewards guaranteed?', 'Why did a game reward not pay?'],
|
||||||
|
tags: ['games', 'rewards', 'pool', 'pol'],
|
||||||
|
answer: 'The network games pay small POL rewards for gameplay milestones from game wallets and reward pools the company tops up from platform income (some games also fund a pool from in-game sales). Rewards are per action, paid while the pool covers them, and never guaranteed. You sign in to every game with your InstantAdPay account, so your sponsor carries across them.' },
|
||||||
|
{ id: 'f-not-investment', title: 'What InstantAdPay is not', source: 'faq',
|
||||||
|
questions: ['Is this an investment?', 'Is there guaranteed income?', 'Does InstantAdPay hold my money?'],
|
||||||
|
tags: ['investment', 'income', 'guarantee', 'custody', 'disclaimer'],
|
||||||
|
answer: 'InstantAdPay is an advertising platform with a referral program, not an investment, token sale or security. Credits are not a token and have no cash value. It does not hold member money: payments are split by the contract in the same transaction. And it is not a guarantee of income: referral payouts happen only when real advertising is bought in your line.' },
|
||||||
|
{ id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq',
|
||||||
|
questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'],
|
||||||
|
tags: ['pol', 'fees', 'gas', 'buy packages'],
|
||||||
|
answer: 'The Buy packages tab shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' },
|
||||||
|
{ id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq',
|
||||||
|
questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'],
|
||||||
|
tags: ['moonpay', 'card', 'declined', 'buy pol'],
|
||||||
|
answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check.' },
|
||||||
|
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
||||||
|
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
||||||
|
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
||||||
|
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
|
||||||
|
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
|
||||||
|
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
|
||||||
|
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
|
||||||
|
answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' },
|
||||||
|
{ id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq',
|
||||||
|
questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'],
|
||||||
|
tags: ['recovery phrase', 'private key', 'scam', 'security'],
|
||||||
|
answer: 'Never share your recovery phrase or private key with anyone. Nobody from InstantAdPay will ever ask for them, and nobody from InstantAdPay will message you first asking for money or wallet access. If someone does, do not reply, and tell support through Help at https://instantadpay.com/my#help.' },
|
||||||
|
{ id: 'f-conv-thankyou', title: 'Conversion tracking with Aweber or GetResponse', source: 'faq',
|
||||||
|
questions: ['How do I track sign-ups from my ads?', 'Where do I put the goal pixel?', 'How do I use conversion tracking with Aweber?', 'How do I use conversion tracking with GetResponse?', 'My autoresponder thank-you page is not mine, can I still track?'],
|
||||||
|
tags: ['conversion tracking', 'goal pixel', 'landing tag', 'aweber', 'getresponse', 'thank you page', 'autoresponder'],
|
||||||
|
answer: 'Open Campaigns > Conversion tracking, add a goal (like subscriber), then copy its two snippets: the landing tag goes on the page your ad points to, the goal pixel on your thank-you page. Set your autoresponder\'s thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose \'Thank You Page: custom page\' and paste your page\'s address. GetResponse: in the form or landing page settings, pick \'Thank-you page: custom URL\' and paste your page\'s address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. Use Send a test conversion to check the pixel; tests never count in your numbers.' },
|
||||||
|
];
|
||||||
|
module.exports = { FAQ };
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
|
||||||
|
// The chatbot answers from maintained entries, and good support replies become entries.
|
||||||
|
//
|
||||||
|
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
|
||||||
|
// updated, created, edited, deleted, seedHash }
|
||||||
|
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
|
||||||
|
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
|
||||||
|
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
|
||||||
|
// path serves the new text.
|
||||||
|
// source canned | faq | ticket | admin
|
||||||
|
//
|
||||||
|
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||||
|
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||||
|
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||||
|
//
|
||||||
|
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
|
||||||
|
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
|
||||||
|
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
|
||||||
|
//
|
||||||
|
// Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else
|
||||||
|
// DATA_DIR/kb.json (local dev and the QA harness).
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const db = require('./db');
|
||||||
|
|
||||||
|
let DATA_DIR = null, SEEDS = [], ready = null;
|
||||||
|
let cache = null, cacheAt = 0, index = null;
|
||||||
|
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||||
|
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
|
||||||
|
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
|
||||||
|
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
|
||||||
|
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
|
||||||
|
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
|
||||||
|
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
|
||||||
|
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
|
||||||
|
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
|
||||||
|
function stem(w) {
|
||||||
|
if (SYN[w]) return SYN[w];
|
||||||
|
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
|
||||||
|
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
|
||||||
|
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
|
||||||
|
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
|
||||||
|
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
function words(text) {
|
||||||
|
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
|
||||||
|
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
|
||||||
|
}
|
||||||
|
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
|
||||||
|
function terms(text) {
|
||||||
|
const w = words(text), out = w.slice();
|
||||||
|
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
|
||||||
|
const K1 = 1.2, B = 0.75;
|
||||||
|
function fieldText(e, f) {
|
||||||
|
if (f === 'questions') return (e.questions || []).join(' . ');
|
||||||
|
if (f === 'tags') return (e.tags || []).join(' . ');
|
||||||
|
return e[f] || '';
|
||||||
|
}
|
||||||
|
function buildIndex(entries) {
|
||||||
|
const docs = entries.map(e => {
|
||||||
|
const d = { e, f: {} };
|
||||||
|
for (const f of Object.keys(FIELDS)) {
|
||||||
|
const t = terms(fieldText(e, f)), tf = new Map();
|
||||||
|
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
|
||||||
|
d.f[f] = { tf, len: t.length };
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
});
|
||||||
|
const df = new Map(), avg = {};
|
||||||
|
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
|
||||||
|
for (const d of docs) {
|
||||||
|
const seen = new Set();
|
||||||
|
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
|
||||||
|
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
|
||||||
|
}
|
||||||
|
return { docs, df, avg, n: docs.length };
|
||||||
|
}
|
||||||
|
function rank(idx, query, k) {
|
||||||
|
if (!idx || !idx.n) return [];
|
||||||
|
const qt = [...new Set(terms(query))];
|
||||||
|
if (!qt.length) return [];
|
||||||
|
const out = [];
|
||||||
|
for (const d of idx.docs) {
|
||||||
|
let s = 0;
|
||||||
|
for (const t of qt) {
|
||||||
|
const n = idx.df.get(t); if (!n) continue;
|
||||||
|
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
|
||||||
|
for (const f of Object.keys(FIELDS)) {
|
||||||
|
const tf = d.f[f].tf.get(t); if (!tf) continue;
|
||||||
|
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||||
|
}
|
||||||
|
out.sort((a, b) => b.score - a.score);
|
||||||
|
return out.slice(0, k || 5);
|
||||||
|
}
|
||||||
|
// keep hits that are close to the best one, and only when the best is a real match
|
||||||
|
const MIN_SCORE = 3;
|
||||||
|
function relevant(hits) {
|
||||||
|
if (!hits.length || hits[0].score < MIN_SCORE) return [];
|
||||||
|
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
|
||||||
|
return hits.filter(h => h.score >= floor);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- store
|
||||||
|
const row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '',
|
||||||
|
handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '',
|
||||||
|
edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) });
|
||||||
|
function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } }
|
||||||
|
const D = {
|
||||||
|
async ensure() {
|
||||||
|
await db.q(`CREATE TABLE IF NOT EXISTS kb_entries (
|
||||||
|
id VARCHAR(64) PRIMARY KEY,
|
||||||
|
title VARCHAR(200) NOT NULL,
|
||||||
|
questions TEXT NULL,
|
||||||
|
answer TEXT NOT NULL,
|
||||||
|
tags VARCHAR(800) NULL,
|
||||||
|
pattern TEXT NULL,
|
||||||
|
handoff TINYINT NOT NULL DEFAULT 0,
|
||||||
|
ord INT NULL,
|
||||||
|
source VARCHAR(16) NOT NULL DEFAULT 'admin',
|
||||||
|
ticket_ref VARCHAR(20) NULL,
|
||||||
|
seed_hash CHAR(40) NULL,
|
||||||
|
edited TINYINT NOT NULL DEFAULT 0,
|
||||||
|
deleted TINYINT NOT NULL DEFAULT 0,
|
||||||
|
created BIGINT NOT NULL,
|
||||||
|
updated BIGINT NOT NULL,
|
||||||
|
INDEX (deleted, updated)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||||
|
},
|
||||||
|
async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); },
|
||||||
|
async put(e) {
|
||||||
|
await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags),
|
||||||
|
pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash),
|
||||||
|
edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`,
|
||||||
|
[e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order,
|
||||||
|
e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const J = {
|
||||||
|
file: () => path.join(DATA_DIR, 'kb.json'),
|
||||||
|
async ensure() {},
|
||||||
|
async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
|
||||||
|
async put(e) {
|
||||||
|
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
|
||||||
|
if (i >= 0) all[i] = e; else all.push(e);
|
||||||
|
const tmp = J.file() + '.tmp';
|
||||||
|
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
|
||||||
|
fs.renameSync(tmp, J.file());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const store = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- seeds
|
||||||
|
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
|
||||||
|
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
|
||||||
|
function seedEntry(s) {
|
||||||
|
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
|
||||||
|
order: s.order == null ? null : s.order, source: s.source || 'faq' };
|
||||||
|
}
|
||||||
|
async function syncSeeds() {
|
||||||
|
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
|
||||||
|
const seedIds = new Set(SEEDS.map(s => s.id));
|
||||||
|
let added = 0, refreshed = 0, retired = 0;
|
||||||
|
for (const s of SEEDS) {
|
||||||
|
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
|
||||||
|
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
|
||||||
|
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
|
||||||
|
}
|
||||||
|
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
|
||||||
|
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
|
||||||
|
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
|
||||||
|
}
|
||||||
|
|
||||||
|
function init(opts) {
|
||||||
|
DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null;
|
||||||
|
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
|
||||||
|
return ready;
|
||||||
|
}
|
||||||
|
async function load(force) {
|
||||||
|
if (ready) await ready;
|
||||||
|
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
|
||||||
|
const all = await store().all();
|
||||||
|
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
const rx = new Map();
|
||||||
|
function compiled(src) {
|
||||||
|
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
|
||||||
|
return rx.get(src);
|
||||||
|
}
|
||||||
|
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the chatbot side
|
||||||
|
async function fastPath(msg) {
|
||||||
|
const list = (await load()).filter(e => e.pattern).sort(byOrder);
|
||||||
|
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||||
|
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
||||||
|
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
|
||||||
|
function promptBlock(hits) {
|
||||||
|
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
||||||
|
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||||
|
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||||
|
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||||
|
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the admin side
|
||||||
|
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
|
||||||
|
function validate(o, cur) {
|
||||||
|
o = o || {};
|
||||||
|
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
|
||||||
|
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
|
||||||
|
const answer = clean(o.answer).slice(0, 4000);
|
||||||
|
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
|
||||||
|
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
|
||||||
|
if (!title) return { error: 'Give the entry a title or at least one question.' };
|
||||||
|
if (!answer) return { error: 'The answer is empty.' };
|
||||||
|
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
|
||||||
|
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
|
||||||
|
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
|
||||||
|
}
|
||||||
|
async function list(q) {
|
||||||
|
const all = (await load(true)).slice();
|
||||||
|
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||||
|
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
|
||||||
|
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||||
|
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||||
|
return ranked.concat(plain);
|
||||||
|
}
|
||||||
|
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
|
||||||
|
async function create(o) {
|
||||||
|
const v = validate(o); if (v.error) return v;
|
||||||
|
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||||
|
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||||
|
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||||
|
await store().put(e); await load(true);
|
||||||
|
return { ok: true, entry: e };
|
||||||
|
}
|
||||||
|
async function update(id, o) {
|
||||||
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
|
const v = validate(o, cur); if (v.error) return v;
|
||||||
|
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||||
|
await store().put(e); await load(true);
|
||||||
|
return { ok: true, entry: e };
|
||||||
|
}
|
||||||
|
async function remove(id) {
|
||||||
|
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||||
|
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||||
|
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
|
||||||
|
// KNOWLEDGE_DATE already speaks for the code.
|
||||||
|
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||||
|
async function stamp() {
|
||||||
|
const all = await load();
|
||||||
|
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
|
||||||
|
return { updated: max ? ctDay(max) : '', count: all.length };
|
||||||
|
}
|
||||||
|
async function test(question) {
|
||||||
|
const fast = await fastPath(String(question || ''));
|
||||||
|
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||||
|
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||||
|
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
|
||||||
|
// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes
|
||||||
|
// LinkSpin, never mixed).
|
||||||
|
//
|
||||||
|
// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600
|
||||||
|
// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + <month>/<size>.<ext>).
|
||||||
|
// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's).
|
||||||
|
//
|
||||||
|
// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit
|
||||||
|
// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } }
|
||||||
|
// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits.
|
||||||
|
// streak month 3+ at unlock an animated GIF version of each banner size
|
||||||
|
// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration
|
||||||
|
//
|
||||||
|
// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner
|
||||||
|
// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/<hash>.<ext> and served
|
||||||
|
// publicly at /kitimg/<hash>.<ext> (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of
|
||||||
|
// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const { spawn } = require('child_process');
|
||||||
|
|
||||||
|
const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] };
|
||||||
|
const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630'];
|
||||||
|
// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px)
|
||||||
|
const LAYOUT = {
|
||||||
|
'728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] },
|
||||||
|
'468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] },
|
||||||
|
'300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] },
|
||||||
|
'160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] },
|
||||||
|
'1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] },
|
||||||
|
};
|
||||||
|
let X = {}, DIR = null, OUT = null, FILE = null, SALT = null;
|
||||||
|
const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
|
||||||
|
const norm = e => String(e || '').trim().toLowerCase();
|
||||||
|
|
||||||
|
function init(opts) {
|
||||||
|
X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json');
|
||||||
|
try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {}
|
||||||
|
const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {}
|
||||||
|
if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } }
|
||||||
|
}
|
||||||
|
const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap';
|
||||||
|
const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay';
|
||||||
|
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } }
|
||||||
|
function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); }
|
||||||
|
const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7);
|
||||||
|
const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
|
||||||
|
|
||||||
|
// ---- admin: the kits ---------------------------------------------------------------------------------
|
||||||
|
function baseFile(month, size) {
|
||||||
|
const d = path.join(DIR, month);
|
||||||
|
for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
function kitView(k) {
|
||||||
|
const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; });
|
||||||
|
return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 };
|
||||||
|
}
|
||||||
|
function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); }
|
||||||
|
function saveKit(b) {
|
||||||
|
const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' };
|
||||||
|
const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() };
|
||||||
|
if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80);
|
||||||
|
if (b.released != null) {
|
||||||
|
if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' };
|
||||||
|
k.released = !!b.released;
|
||||||
|
}
|
||||||
|
if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; }
|
||||||
|
k.updated = Date.now(); s.kits[month] = k; save(s);
|
||||||
|
return { ok: true, kit: kitView(k) };
|
||||||
|
}
|
||||||
|
const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' };
|
||||||
|
function uploadBase(month, size, buf, mime) {
|
||||||
|
if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' };
|
||||||
|
if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' };
|
||||||
|
const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()];
|
||||||
|
if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' };
|
||||||
|
const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true });
|
||||||
|
for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} }
|
||||||
|
fs.writeFileSync(path.join(d, size + '.' + ext), buf);
|
||||||
|
const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s);
|
||||||
|
return { ok: true, kit: kitView(s.kits[month]) };
|
||||||
|
}
|
||||||
|
// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs)
|
||||||
|
function usePlaceholder(month) {
|
||||||
|
const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-';
|
||||||
|
const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'],
|
||||||
|
'1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] };
|
||||||
|
const done = [];
|
||||||
|
for (const size of ORDER) {
|
||||||
|
const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue;
|
||||||
|
const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size);
|
||||||
|
}
|
||||||
|
return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the renderer ---------------------------------------------------------------------------------------
|
||||||
|
let FONT;
|
||||||
|
function font() {
|
||||||
|
if (FONT !== undefined) return FONT;
|
||||||
|
FONT = process.env.BADGE_FONT || null; if (FONT) return FONT;
|
||||||
|
const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) return f; } return null; };
|
||||||
|
for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } }
|
||||||
|
if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf';
|
||||||
|
return FONT;
|
||||||
|
}
|
||||||
|
const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%');
|
||||||
|
function run(args, cwd) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd });
|
||||||
|
const out = []; let err = '';
|
||||||
|
p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; });
|
||||||
|
p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box
|
||||||
|
async function renderStill(base, size, name, link, stage, outFile) {
|
||||||
|
const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font();
|
||||||
|
if (!F) return { error: 'No font for the renderer.' };
|
||||||
|
const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules
|
||||||
|
const qrFile = outFile + '.qr.png';
|
||||||
|
await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } });
|
||||||
|
const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F;
|
||||||
|
const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H));
|
||||||
|
const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]);
|
||||||
|
const showName = stage !== 0, showQr = stage === undefined || stage === 2;
|
||||||
|
const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]'];
|
||||||
|
let last = 'b';
|
||||||
|
if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; }
|
||||||
|
if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; }
|
||||||
|
const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1'];
|
||||||
|
if (/\.jpg$/.test(outFile)) args.push('-q:v', '3');
|
||||||
|
args.push(path.resolve(outFile));
|
||||||
|
const r = await run(args, winPath ? path.dirname(F) : undefined);
|
||||||
|
try { fs.unlinkSync(qrFile); } catch (e) {}
|
||||||
|
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) };
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping
|
||||||
|
async function renderGif(base, size, name, link, outFile) {
|
||||||
|
const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png');
|
||||||
|
for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; }
|
||||||
|
const list = outFile + '.txt';
|
||||||
|
fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n");
|
||||||
|
const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]);
|
||||||
|
for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} }
|
||||||
|
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) };
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28);
|
||||||
|
function indexFile() { return path.join(OUT, 'index.json'); }
|
||||||
|
function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); }
|
||||||
|
// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes }
|
||||||
|
async function personal(who, month, size, variant) {
|
||||||
|
const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' };
|
||||||
|
const v = Math.round(fs.statSync(base).mtimeMs);
|
||||||
|
const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png';
|
||||||
|
const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link);
|
||||||
|
const out = path.join(OUT, h + '.' + ext);
|
||||||
|
if (!fs.existsSync(out)) {
|
||||||
|
const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext);
|
||||||
|
let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; }
|
||||||
|
if (r.error) return r;
|
||||||
|
try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} }
|
||||||
|
noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() });
|
||||||
|
}
|
||||||
|
const [w, hh] = SIZES[size];
|
||||||
|
return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext };
|
||||||
|
}
|
||||||
|
// public serving: only files already rendered for an entitled member
|
||||||
|
function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; }
|
||||||
|
|
||||||
|
// ---- the member ------------------------------------------------------------------------------------------
|
||||||
|
async function whoOf(email) {
|
||||||
|
const w = await X.linkFor(norm(email)); if (!w || !w.link) return null;
|
||||||
|
return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link };
|
||||||
|
}
|
||||||
|
async function myKits(email) {
|
||||||
|
const ent = (await X.entitled(norm(email)).catch(() => null)) || null;
|
||||||
|
if (!ent || !ent.on) return { on: false };
|
||||||
|
const s = load(); const months = ent.months || {};
|
||||||
|
const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month
|
||||||
|
const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => {
|
||||||
|
const streakAt = months[k.month] || 0; const unlocked = streakAt > 0;
|
||||||
|
return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 });
|
||||||
|
});
|
||||||
|
// the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet
|
||||||
|
const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m);
|
||||||
|
if (customMonths.length) {
|
||||||
|
const e = norm(email); const have = s.credits[e] || {}; let changed = false;
|
||||||
|
for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; }
|
||||||
|
if (changed) { s.credits[e] = have; save(s); }
|
||||||
|
}
|
||||||
|
const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used }));
|
||||||
|
const cur = nowMonth; const who = await whoOf(email).catch(() => null);
|
||||||
|
return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur],
|
||||||
|
kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null,
|
||||||
|
nextRefuel: ent.nextRefuel || null };
|
||||||
|
}
|
||||||
|
async function renderFor(email, month, size, variant) {
|
||||||
|
const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' };
|
||||||
|
const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' };
|
||||||
|
if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' };
|
||||||
|
if (!SIZES[size]) return { error: 'No such size.' };
|
||||||
|
if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' };
|
||||||
|
const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' };
|
||||||
|
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
|
||||||
|
}
|
||||||
|
async function preview(month, size, username, variant) {
|
||||||
|
const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname');
|
||||||
|
const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link };
|
||||||
|
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font };
|
||||||
+1
-1
@@ -141,7 +141,7 @@ async function renderPage() {
|
|||||||
const w = winners();
|
const w = winners();
|
||||||
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
||||||
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261016n"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
|
||||||
|
// this module does three things:
|
||||||
|
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
|
||||||
|
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
|
||||||
|
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
|
||||||
|
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
|
||||||
|
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
|
||||||
|
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
|
||||||
|
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
|
||||||
|
// summary cached 60 s per email.
|
||||||
|
// owners (2026-10-26) the soft keys members sign in from ride on the click push, so LinkSpin keeps a member's own
|
||||||
|
// clicks (ads here, spin links and Banner Spins there) as tests, never counted
|
||||||
|
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
|
||||||
|
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
|
||||||
|
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
|
||||||
|
const cache = new Map(); // email -> { at, data }
|
||||||
|
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||||
|
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||||
|
const on = () => SECRET().length >= 32;
|
||||||
|
const useDb = () => !!(R && R.db && R.db.enabled());
|
||||||
|
const JCAP = 5000;
|
||||||
|
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
|
||||||
|
|
||||||
|
function init(deps) {
|
||||||
|
R = deps;
|
||||||
|
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
|
||||||
|
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
|
||||||
|
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||||
|
}
|
||||||
|
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
|
||||||
|
// device, placement, target, spent, is_self, ts, pushed is reserved)
|
||||||
|
async function ensureTable() {
|
||||||
|
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
|
||||||
|
id VARCHAR(16) PRIMARY KEY,
|
||||||
|
campaign_id INT NOT NULL,
|
||||||
|
owner_email VARCHAR(190) NOT NULL,
|
||||||
|
cname VARCHAR(80) NULL,
|
||||||
|
ctype VARCHAR(12) NULL,
|
||||||
|
sk VARCHAR(24) NULL,
|
||||||
|
country VARCHAR(4) NULL,
|
||||||
|
device VARCHAR(8) NULL,
|
||||||
|
placement VARCHAR(80) NULL,
|
||||||
|
target VARCHAR(500) NULL,
|
||||||
|
spent INT NOT NULL DEFAULT 0,
|
||||||
|
is_self TINYINT NOT NULL DEFAULT 0,
|
||||||
|
ts BIGINT NOT NULL,
|
||||||
|
pushed TINYINT NOT NULL DEFAULT 0,
|
||||||
|
INDEX (pushed, ts),
|
||||||
|
INDEX (campaign_id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers (pure) ----
|
||||||
|
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
||||||
|
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
|
||||||
|
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
|
||||||
|
function placementOf(referer) {
|
||||||
|
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
|
||||||
|
catch (e) { return null; }
|
||||||
|
}
|
||||||
|
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
|
||||||
|
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
|
||||||
|
function withClickId(target, id) {
|
||||||
|
const t = String(target || '');
|
||||||
|
let u; try { u = new URL(t); } catch (e) { return t; }
|
||||||
|
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
|
||||||
|
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
|
||||||
|
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
||||||
|
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- own-click tests (Marty approved 2026-10-26) ----
|
||||||
|
// A member's own click is a test on LinkSpin, on every click type. LinkSpin knows the soft keys its members sign in from;
|
||||||
|
// InstantAdPay members may never sign in there, so the soft keys of their InstantAdPay sessions ride along with the click
|
||||||
|
// push as owners: [{ owner, sk, ts }] (no raw IP, same hash as the click rows). Queued at most once per 6 h per
|
||||||
|
// email + soft key; a failed push puts them back. Also checked here so an own click is flagged self=1 at the source.
|
||||||
|
const OWN_MS = 31 * 86400e3, ownSeen = new Map(); let ownQueue = new Map();
|
||||||
|
function noteSession(email, ip, ua) {
|
||||||
|
const e = String(email || '').trim().toLowerCase(); if (!e || e.length > 190) return false;
|
||||||
|
const sk = softKey(ip, ua); const k = e + '|' + sk; const now = Date.now();
|
||||||
|
if (now - (ownSeen.get(k) || 0) < 6 * 3600e3) return false;
|
||||||
|
ownSeen.set(k, now); if (ownSeen.size > 50000) ownSeen.delete(ownSeen.keys().next().value);
|
||||||
|
if (on()) { ownQueue.set(k, { owner: e, sk, ts: now }); if (ownQueue.size > 5000) ownQueue.delete(ownQueue.keys().next().value); }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
function isOwnerSk(owner, sk) { const t = ownSeen.get(String(owner || '').toLowerCase() + '|' + sk); return !!(t && Date.now() - t <= OWN_MS); }
|
||||||
|
function takeOwners() { const out = [...ownQueue.values()].slice(0, 2000); for (const o of out) ownQueue.delete(o.owner + '|' + o.sk); return out; }
|
||||||
|
function requeueOwners(list) { for (const o of list || []) if (!ownQueue.has(o.owner + '|' + o.sk)) ownQueue.set(o.owner + '|' + o.sk, o); }
|
||||||
|
|
||||||
|
// ---- storage ----
|
||||||
|
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
|
||||||
|
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
|
||||||
|
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
|
||||||
|
|
||||||
|
// c = the campaign (ads.campaignById shape); returns the stored row
|
||||||
|
async function record(c, req, opts) {
|
||||||
|
const o = opts || {};
|
||||||
|
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||||||
|
const ua = String(req.headers['user-agent'] || '');
|
||||||
|
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
|
||||||
|
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
|
||||||
|
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
|
||||||
|
if (useDb()) {
|
||||||
|
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
|
||||||
|
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
|
||||||
|
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
|
||||||
|
async function unpushed(n) {
|
||||||
|
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
|
||||||
|
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
|
||||||
|
}
|
||||||
|
async function markPushed(ids) {
|
||||||
|
if (!ids.length) return;
|
||||||
|
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
|
||||||
|
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
|
||||||
|
}
|
||||||
|
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
|
||||||
|
const cut = Date.now() - 120 * 86400e3;
|
||||||
|
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
|
||||||
|
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- LinkSpin calls ----
|
||||||
|
async function signedPost(pth, body, timeoutMs) {
|
||||||
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||||
|
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
|
||||||
|
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
||||||
|
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
|
||||||
|
return j || {};
|
||||||
|
}
|
||||||
|
async function flush() {
|
||||||
|
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
|
||||||
|
flushing = true; let sent = 0;
|
||||||
|
try {
|
||||||
|
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time; owners (own soft keys) ride on the first request
|
||||||
|
const rows = await unpushed(500); const owners = round === 0 ? takeOwners() : [];
|
||||||
|
if (!rows.length && !owners.length) break;
|
||||||
|
let res; try { res = await signedPost('/api/partner/clicks', { clicks: rows, owners }, 20000); } catch (e) { requeueOwners(owners); throw e; }
|
||||||
|
if (!res || res.ok !== true) { requeueOwners(owners); throw new Error('linkspin answered without ok'); }
|
||||||
|
if (rows.length) { await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now(); }
|
||||||
|
if (owners.length) stats.owners = (stats.owners || 0) + owners.length;
|
||||||
|
if (rows.length < 500) break;
|
||||||
|
}
|
||||||
|
fails = 0; nextAt = 0; return { sent };
|
||||||
|
} catch (e) {
|
||||||
|
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
|
||||||
|
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
|
||||||
|
return { error: e.message, sent };
|
||||||
|
} finally { flushing = false; }
|
||||||
|
}
|
||||||
|
// op summary is cached 60 s per email; any write clears that email's cache
|
||||||
|
async function summary(email, fresh) {
|
||||||
|
const e = String(email || '').toLowerCase();
|
||||||
|
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
|
||||||
|
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
|
||||||
|
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
async function goalOp(email, op, fields) {
|
||||||
|
const e = String(email || '').toLowerCase();
|
||||||
|
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
|
||||||
|
const body = Object.assign({ op, email: e }, fields || {});
|
||||||
|
const out = await signedPost('/api/partner/conv', body, 10000);
|
||||||
|
cache.delete(e); return out;
|
||||||
|
}
|
||||||
|
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
|
||||||
|
module.exports = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
|
||||||
+46
-9
@@ -16,7 +16,15 @@
|
|||||||
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
|
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
|
||||||
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
|
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
|
||||||
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
|
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
|
||||||
|
// - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy
|
||||||
|
// adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear
|
||||||
|
// back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the
|
||||||
|
// change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound,
|
||||||
|
// diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly.
|
||||||
|
// - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list
|
||||||
|
// hides someone adopted on LinkSpin and the two-adoptions limit counts both sites.
|
||||||
'use strict';
|
'use strict';
|
||||||
|
const SF = require('./sponsorfollow');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
@@ -35,7 +43,7 @@ function load() {
|
|||||||
}
|
}
|
||||||
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
|
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
|
||||||
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
||||||
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync }
|
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) }
|
||||||
|
|
||||||
function clean(x) {
|
function clean(x) {
|
||||||
if (!x || typeof x !== 'object') return null;
|
if (!x || typeof x !== 'object') return null;
|
||||||
@@ -44,9 +52,18 @@ function clean(x) {
|
|||||||
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
|
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
|
||||||
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
|
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
|
||||||
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
|
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
|
||||||
return { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
||||||
|
if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js)
|
||||||
|
out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy);
|
||||||
|
const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null;
|
||||||
|
out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin';
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
const tokenOf = a => a.username || a.code;
|
const tokenOf = a => a.username || a.code;
|
||||||
|
// released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js)
|
||||||
|
const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); };
|
||||||
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
|
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
|
||||||
|
|
||||||
// would binding `email` under `sp` close a loop (sp already sits below email)?
|
// would binding `email` under `sp` close a loop (sp already sits below email)?
|
||||||
@@ -94,7 +111,14 @@ async function place(email, depth, ctx) {
|
|||||||
ctx.done.add(email); R.lssync.mute(email);
|
ctx.done.add(email); R.lssync.mute(email);
|
||||||
let a = await A.byEmail(email); let wrote = false;
|
let a = await A.byEmail(email); let wrote = false;
|
||||||
if (!r) return a;
|
if (!r) return a;
|
||||||
if (!a) {
|
const inc = SF.incomingOf(r);
|
||||||
|
if (a && inc && R.follow) {
|
||||||
|
// a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here)
|
||||||
|
const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) });
|
||||||
|
if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); }
|
||||||
|
else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); }
|
||||||
|
a = await A.byEmail(email);
|
||||||
|
} else if (!a) {
|
||||||
let tok = '';
|
let tok = '';
|
||||||
if (r.sponsorEmail) {
|
if (r.sponsorEmail) {
|
||||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||||
@@ -104,7 +128,9 @@ async function place(email, depth, ctx) {
|
|||||||
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
|
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
|
||||||
a = x.account;
|
a = x.account;
|
||||||
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
|
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
|
||||||
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail) {
|
// a new waiting account built from a deliberate change carries the same record, so its row does not echo back
|
||||||
|
if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' });
|
||||||
|
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) {
|
||||||
// our own waiting account, still without a sponsor: this row (or a later one) names one
|
// our own waiting account, still without a sponsor: this row (or a later one) names one
|
||||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||||
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
|
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
|
||||||
@@ -119,7 +145,7 @@ async function resolvePending(ctx) {
|
|||||||
const s = load(); const A = R.accounts;
|
const s = load(); const A = R.accounts;
|
||||||
for (const [email, spEmail] of Object.entries(s.pending)) {
|
for (const [email, spEmail] of Object.entries(s.pending)) {
|
||||||
const a = await A.byEmail(email);
|
const a = await A.byEmail(email);
|
||||||
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef) { delete s.pending[email]; continue; } // claimed or bound meanwhile: leave it
|
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it
|
||||||
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
|
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
|
||||||
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
|
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
|
||||||
R.lssync.mute(email); ctx.done.add(email);
|
R.lssync.mute(email); ctx.done.add(email);
|
||||||
@@ -129,9 +155,10 @@ async function resolvePending(ctx) {
|
|||||||
}
|
}
|
||||||
async function handle(rows) {
|
async function handle(rows) {
|
||||||
const s = load(); s.stats.batches++;
|
const s = load(); s.stats.batches++;
|
||||||
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0 };
|
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
|
||||||
const ctx = { sum, done: new Set() }; const batch = [];
|
const ctx = { sum, done: new Set() }; const batch = [];
|
||||||
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
|
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
|
||||||
|
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
|
||||||
try {
|
try {
|
||||||
for (const r of batch) {
|
for (const r of batch) {
|
||||||
try { await place(r.email, 0, ctx); }
|
try { await place(r.email, 0, ctx); }
|
||||||
@@ -141,9 +168,9 @@ async function handle(rows) {
|
|||||||
} finally {
|
} finally {
|
||||||
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
|
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
|
||||||
}
|
}
|
||||||
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors']) s.stats[k] += sum[k];
|
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k];
|
||||||
s.last = Object.assign({ at: Date.now() }, sum); save();
|
s.last = Object.assign({ at: Date.now() }, sum); save();
|
||||||
return sum;
|
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
|
||||||
}
|
}
|
||||||
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
|
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
|
||||||
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
|
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
|
||||||
@@ -151,4 +178,14 @@ function adminView() {
|
|||||||
const s = load();
|
const s = load();
|
||||||
return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() });
|
return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() });
|
||||||
}
|
}
|
||||||
module.exports = { init, receive, adminView };
|
// The holding tank asks (tank.js alignToNetwork, 2026-10-27): does LinkSpin already know a sponsor for this person?
|
||||||
|
// The newest row LinkSpin sent for the same email, else for the same wallet. LinkSpin's sponsorEmail is always a real
|
||||||
|
// member there (its sponsorRef; LinkSpin never writes the company fallback into an account). Read only.
|
||||||
|
function networkSponsor(email, address) {
|
||||||
|
if (!R) return null; const s = load(); const e = norm(email); const w = norm(address);
|
||||||
|
const r = s.rows[e];
|
||||||
|
if (r && r.sponsorEmail && r.sponsorEmail !== e) return { sponsorEmail: r.sponsorEmail, via: 'same email' };
|
||||||
|
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
module.exports = { init, receive, adminView, networkSponsor };
|
||||||
|
|||||||
@@ -5,8 +5,15 @@
|
|||||||
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
|
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
|
||||||
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
|
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
|
||||||
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
|
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
|
||||||
|
//
|
||||||
|
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
|
||||||
|
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
|
||||||
|
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
|
||||||
|
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
|
||||||
|
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
|
||||||
'use strict';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
|
const SF = require('./sponsorfollow');
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
@@ -20,11 +27,16 @@ function load() { if (state) return state; try { state = JSON.parse(fs.readFileS
|
|||||||
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
||||||
|
|
||||||
function init(deps) { R = deps; load(); }
|
function init(deps) { R = deps; load(); }
|
||||||
async function rowFor(acct, byRef) {
|
async function rowFor(acct, byRef, tankMap) {
|
||||||
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
|
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
|
||||||
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
|
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
|
||||||
return { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
||||||
|
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
|
||||||
|
const T = R.tank && R.tank();
|
||||||
|
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
|
||||||
|
return row;
|
||||||
}
|
}
|
||||||
|
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
|
||||||
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
|
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
|
||||||
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
|
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
|
||||||
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||||
@@ -36,7 +48,7 @@ function profileOf(a) {
|
|||||||
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
|
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
|
||||||
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
|
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
|
||||||
}
|
}
|
||||||
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|')).digest('hex').slice(0, 16);
|
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
|
||||||
|
|
||||||
async function post(rows) {
|
async function post(rows) {
|
||||||
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
|
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
|
||||||
@@ -48,8 +60,9 @@ async function post(rows) {
|
|||||||
async function push(rows) {
|
async function push(rows) {
|
||||||
const st = load(); let sent = 0;
|
const st = load(); let sent = 0;
|
||||||
for (let i = 0; i < rows.length; i += 100) {
|
for (let i = 0; i < rows.length; i += 100) {
|
||||||
const chunk = rows.slice(i, i + 100); await post(chunk); sent += chunk.length;
|
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
|
||||||
for (const r of chunk) st.hashes[r.email] = hashOf(r);
|
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
|
||||||
|
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
|
||||||
}
|
}
|
||||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
||||||
}
|
}
|
||||||
@@ -65,7 +78,8 @@ async function tick(force) {
|
|||||||
try {
|
try {
|
||||||
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
||||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
||||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
|
||||||
|
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||||
const sent = rows.length ? await push(rows) : 0;
|
const sent = rows.length ? await push(rows) : 0;
|
||||||
return { accounts: all.length, changed: rows.length, sent };
|
return { accounts: all.length, changed: rows.length, sent };
|
||||||
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
||||||
@@ -82,7 +96,9 @@ async function release(email, sent) {
|
|||||||
const a = await R.accounts.byEmail(e);
|
const a = await R.accounts.byEmail(e);
|
||||||
if (a && sent) {
|
if (a && sent) {
|
||||||
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
|
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
|
||||||
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail)) { load().hashes[e] = hashOf(r); save(); same = true; }
|
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
|
||||||
|
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
|
||||||
|
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
|
||||||
}
|
}
|
||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
|
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
|
||||||
|
|||||||
@@ -133,4 +133,15 @@ async function topUp(nasAdId, addImpressions, days) {
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind };
|
// restart a STOPPED ad (deactivate zeroed `remaining`) with `addImpressions` more, re-basing `assigned` on the TRUE served
|
||||||
|
// count we recorded at the stop. A plain topUp would leave assigned - remaining = the whole old allocation, so the
|
||||||
|
// undelivered part would read back as served (the same trap as deactivate, one step later).
|
||||||
|
async function restart(nasAdId, trueServed, addImpressions, days) {
|
||||||
|
if (!enabled()) return { skipped: 'flag-off' };
|
||||||
|
const add = Math.max(0, Math.floor(Number(addImpressions) || 0)), base = Math.max(0, Math.floor(Number(trueServed) || 0));
|
||||||
|
await q(`UPDATE sponsorads SET assigned=?, remaining=?, approved=1, EDate=DATE_ADD(NOW(), INTERVAL ? DAY) WHERE ID=?`,
|
||||||
|
[base + add, add, Number(days || 30), Number(nasAdId)]);
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, restart, impressionsPerCredit, nasKind };
|
||||||
|
|||||||
+342
-68
@@ -1,92 +1,366 @@
|
|||||||
// Level-4 override (Marty, decided 2026-10-17; design in memory iap-level4-override): 3% of every purchase goes to the
|
// Level-4 override (Marty, decided 2026-10-17, approved to build for real 2026-10-23; design in memory iap-level4-override):
|
||||||
// buyer's 4th upline when that member has 5+ qualifying buyers (the contract's own buyerCount, same bar as level 3); an
|
// 3% of every purchase goes to the buyer's 4th upline on the CONTRACT sponsor chain when that member has 5+ qualifying
|
||||||
// unqualified 4th upline is skipped and the hunt climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one
|
// buyers (the contract's own buyerCount, the same bar as level 3); an unqualified 4th upline is skipped and the hunt
|
||||||
// recipient per purchase, so it never costs more than 3%; funded off-chain from the company's 20% and paid weekly with
|
// climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one recipient per purchase, so it never costs more than
|
||||||
// the contract's award() from a pre-funded engine wallet, purchases from go-live forward only.
|
// 3%; company ids (overrideHouseIds) keep it. Funded off-chain from the company's 20% and paid weekly with the contract's
|
||||||
// THIS MODULE IS THE DRY RUN: it computes who would be paid from real purchases and reports it. No money moves.
|
// award(toMemberId) from a pre-funded payer wallet, purchases from overrideGoLive forward only (no back-pay).
|
||||||
|
//
|
||||||
|
// MODES (site setting overrideMode):
|
||||||
|
// 'off' nothing at all.
|
||||||
|
// 'dryrun' (default) the Monday who-would-be-paid report to Marty's private Telegram. No money moves.
|
||||||
|
// 'live' pays, but ONLY when overrideGoLive is set AND a payer key is present (env OVERRIDE_PAYER_KEY or
|
||||||
|
// OVERRIDE_PAYER_KEY_FILE). Missing either one: it reports as a dry run and says why it did not pay.
|
||||||
|
//
|
||||||
|
// MONEY SAFETY (why each piece exists):
|
||||||
|
// - Every "do this once" is a claim that only one running copy of the app can win: an exclusive file create on the
|
||||||
|
// shared volume (fs 'wx'), plus a row in event_marks when MySQL is on. A deploy runs two copies for ~30 s (the
|
||||||
|
// 2026-09-25 double Friday bonus); a claim that cannot be checked counts as LOST (fail closed), never as won.
|
||||||
|
// - A week's plan (who gets how much) is computed once, written to the volume and never recomputed, so a later read
|
||||||
|
// of buyer counts cannot change an amount that is already being paid.
|
||||||
|
// - A payout row is marked 'sending' on disk BEFORE the transaction is sent and gets its tx hash the moment the node
|
||||||
|
// accepts it. A row whose answer was lost is 'review': it is never sent again automatically. The chain index can
|
||||||
|
// settle it (an AwardPaid from the payer wallet to that member for that exact amount), or the admin does.
|
||||||
|
// - Amounts under the dust minimum (overrideDustPol, default 0.01 POL) and pre-flight failures (award() would revert,
|
||||||
|
// no gas spent) are carried to the next week's plan.
|
||||||
|
// - Hard cap per week (overridePayCapPol, default 100 POL): a plan over the cap is held whole, nothing is sent.
|
||||||
|
// - The wallet must hold the week's total plus gas for every send, or nothing is sent and Marty is told.
|
||||||
|
// - Weeks are paid in order; a week that is held or needs review stops the later weeks until it is resolved.
|
||||||
'use strict';
|
'use strict';
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
let ethersLib = null; try { ethersLib = require('ethers'); } catch (e) { /* optional: the payer stays off without it */ }
|
||||||
|
|
||||||
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null;
|
|
||||||
const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4;
|
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 GAS_LIMIT = 150000n; // award(): reentrancy guard + member read + capped-gas send + event, ~60k; generous headroom
|
||||||
const cfg = () => { const s = siteConfig(); return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean),
|
const WEI = 10n ** 18n;
|
||||||
goLive: Number(s.overrideGoLive || 0) }; };
|
|
||||||
|
|
||||||
// sponsor + qualifying-buyer count per member, read from the contract (cached 10 minutes per report run)
|
// ---- Central-time week math (pure, shared by every instance) ----
|
||||||
const memo = new Map();
|
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
|
||||||
async function mem(id) {
|
const CT_HOUR = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' });
|
||||||
const c = memo.get(id); if (c && Date.now() - c.t < 600000) return c.v;
|
function weekOf(ts) { // the Monday (YYYY-MM-DD, Central) of the week holding ts
|
||||||
const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 };
|
const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
|
||||||
memo.set(id, { t: Date.now(), v }); return v;
|
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday];
|
||||||
|
return new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)).toISOString().slice(0, 10);
|
||||||
}
|
}
|
||||||
// who the override for one purchase goes to: { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
|
const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT = UTC-5, CST = UTC-6)
|
||||||
async function recipientFor(buyerId) {
|
for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; }
|
||||||
|
return Date.parse(day + 'T05:00:00Z');
|
||||||
|
};
|
||||||
|
const addDays = (day, n) => new Date(Date.parse(day + 'T12:00:00Z') + n * 86400000).toISOString().slice(0, 10);
|
||||||
|
const weekBounds = monday => ({ from: ctMidnight(monday), to: ctMidnight(addDays(monday, 7)) });
|
||||||
|
// the week may be settled from 9 AM Central on the Monday after it
|
||||||
|
const payableAt = monday => ctMidnight(addDays(monday, 7)) + 9 * 3600000;
|
||||||
|
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
|
||||||
|
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
|
||||||
|
|
||||||
|
function create() {
|
||||||
|
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null, db = null, now = () => Date.now();
|
||||||
|
let BRAND = 'InstantAdPay', SITE_URL = 'https://instantadpay.com', HOUSE_DEFAULT = '1', payerOverride = null;
|
||||||
|
const lastError = { at: 0, msg: '' };
|
||||||
|
|
||||||
|
function init(o) {
|
||||||
|
DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; db = o.db || null;
|
||||||
|
if (o.brand) BRAND = o.brand; if (o.siteUrl) SITE_URL = o.siteUrl; if (o.houseDefault) HOUSE_DEFAULT = String(o.houseDefault);
|
||||||
|
if (o.payer) payerOverride = o.payer; // tests: a fake signer, never the real chain
|
||||||
|
if (o.now) now = o.now;
|
||||||
|
}
|
||||||
|
const cfg = () => {
|
||||||
|
const s = siteConfig();
|
||||||
|
const num = (v, d) => { const n = Number(v); return v === undefined || v === '' || !isFinite(n) ? d : n; };
|
||||||
|
return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || HOUSE_DEFAULT).split(',').map(x => Number(x.trim())).filter(Boolean),
|
||||||
|
goLive: Number(s.overrideGoLive || 0), dustWei: toWei(Math.max(0, num(s.overrideDustPol, 0.01)).toFixed(18)), capWei: toWei(Math.max(0, num(s.overridePayCapPol, 100)).toFixed(18)) };
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- the payer wallet (OVERRIDE_PAYER_KEY; never logged, never returned) ----
|
||||||
|
function keyHex() {
|
||||||
|
let k = String(process.env.OVERRIDE_PAYER_KEY || '').trim();
|
||||||
|
if (!k && process.env.OVERRIDE_PAYER_KEY_FILE) { try { k = fs.readFileSync(process.env.OVERRIDE_PAYER_KEY_FILE, 'utf8').trim(); } catch (e) {} }
|
||||||
|
if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
|
||||||
|
return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
|
||||||
|
}
|
||||||
|
let realPayer = null;
|
||||||
|
function payer() {
|
||||||
|
if (payerOverride) return payerOverride;
|
||||||
|
const k = keyHex(); if (!k || !ethersLib) return null;
|
||||||
|
if (realPayer) return realPayer;
|
||||||
|
const c = chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc]; let idx = 0;
|
||||||
|
const wallet = () => new ethersLib.Wallet(k, new ethersLib.JsonRpcProvider(urls[idx % urls.length], Number(c.chainId), { staticNetwork: true }));
|
||||||
|
const ctr = w => new ethersLib.Contract(chain.getConfig().contract, ['function award(uint32 toMemberId) payable'], w);
|
||||||
|
const address = new ethersLib.Wallet(k).address;
|
||||||
|
realPayer = {
|
||||||
|
address,
|
||||||
|
balance: async () => { try { return await wallet().provider.getBalance(address); } catch (e) { idx++; throw e; } },
|
||||||
|
fees: async () => { const g = await chain.suggestedFees(); return { maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) }; },
|
||||||
|
// a revert here (unknown member, a wallet that refuses POL) costs nothing and sends nothing
|
||||||
|
preflight: async (id, wei) => { await ctr(wallet()).award.staticCall(Number(id), { value: BigInt(wei) }); },
|
||||||
|
send: async (id, wei, fees) => { const tx = await ctr(wallet()).award(Number(id), Object.assign({ value: BigInt(wei), gasLimit: GAS_LIMIT }, fees)); return { hash: tx.hash, wait: () => tx.wait(1) }; }
|
||||||
|
};
|
||||||
|
return realPayer;
|
||||||
|
}
|
||||||
|
function liveState() {
|
||||||
|
const c = cfg(), why = [];
|
||||||
|
if (c.mode !== 'live') why.push('overrideMode is ' + c.mode + ', not live');
|
||||||
|
if (!c.goLive) why.push('overrideGoLive is not set');
|
||||||
|
if (!payerOverride && !keyHex()) why.push('no payer key (OVERRIDE_PAYER_KEY)');
|
||||||
|
if (!payerOverride && !ethersLib) why.push('ethers is not installed');
|
||||||
|
return { ready: !why.length, why };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- one-time claims, fail closed ----
|
||||||
|
const dir = (...p) => path.join(DATA_DIR, 'override', ...p);
|
||||||
|
const mkdirp = d => { try { fs.mkdirSync(d, { recursive: true }); } catch (e) {} };
|
||||||
|
const safe = k => String(k).replace(/[^a-zA-Z0-9_.:-]/g, '_').replace(/:/g, '__').slice(0, 150);
|
||||||
|
async function claim(key) {
|
||||||
|
if (db && db.enabled && db.enabled()) {
|
||||||
|
try { const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', ['ov:' + String(key).slice(0, 150), now()]); if (!(r && r.affectedRows === 1)) return false; }
|
||||||
|
catch (e) { lastError.at = now(); lastError.msg = 'claim ' + key + ': ' + e.message; return false; }
|
||||||
|
}
|
||||||
|
mkdirp(dir('claims'));
|
||||||
|
try { fs.closeSync(fs.openSync(dir('claims', safe(key)), 'wx')); return true; }
|
||||||
|
catch (e) { if (e.code !== 'EEXIST') { lastError.at = now(); lastError.msg = 'claim file ' + key + ': ' + e.message; } return false; }
|
||||||
|
}
|
||||||
|
const claimed = key => fs.existsSync(dir('claims', safe(key)));
|
||||||
|
|
||||||
|
// ---- payout store: one small JSON file per week header and per (week, member) row, each with a single writer ----
|
||||||
|
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
|
||||||
|
const writeJ = (f, o) => { mkdirp(path.dirname(f)); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
|
||||||
|
const getWeek = wk => readJ(dir('weeks', wk, 'week.json'));
|
||||||
|
const putWeek = (wk, patch) => { const cur = getWeek(wk) || { week: wk }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'week.json'), o); return o; };
|
||||||
|
const getRow = (wk, id) => readJ(dir('weeks', wk, 'm' + id + '.json'));
|
||||||
|
const putRow = (wk, id, patch) => { const cur = getRow(wk, id) || { week: wk, memberId: id }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'm' + id + '.json'), o); return o; };
|
||||||
|
const rowsOf = wk => { try { return fs.readdirSync(dir('weeks', wk)).filter(f => /^m\d+\.json$/.test(f)).map(f => readJ(dir('weeks', wk, f))).filter(Boolean).sort((a, b) => a.memberId - b.memberId); } catch (e) { return []; } };
|
||||||
|
const plannedWeeks = () => { try { return fs.readdirSync(dir('weeks')).filter(w => /^\d{4}-\d{2}-\d{2}$/.test(w)).sort(); } catch (e) { return []; } };
|
||||||
|
|
||||||
|
// ---- who gets the override on one purchase ----
|
||||||
|
const memo = new Map();
|
||||||
|
async function mem(id) {
|
||||||
|
const c = memo.get(id); if (c && 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: now(), v }); return v;
|
||||||
|
}
|
||||||
|
// { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
|
||||||
|
async function recipientFor(buyerId) {
|
||||||
const ups = []; let cur = 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; }
|
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' };
|
if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' };
|
||||||
const skipped = [];
|
const skipped = [], house = cfg().house;
|
||||||
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
|
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
|
||||||
const id = ups[i], b = (await mem(id)).buyerCount;
|
const id = ups[i];
|
||||||
if (cfg().house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
|
if (house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
|
||||||
|
const b = (await mem(id)).buyerCount;
|
||||||
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
|
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
|
||||||
skipped.push({ id, buyers: b });
|
skipped.push({ id, buyers: b });
|
||||||
}
|
}
|
||||||
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
|
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Central-time week: Monday 00:00 to the next Monday
|
// every Purchase in the full-history index (chain.recentEvents keeps the whole history in memory; the file is the fallback)
|
||||||
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
|
function purchases() {
|
||||||
function weekOf(ts) {
|
try { if (chain && chain.recentEvents) return chain.recentEvents(1e9).filter(e => e.type === 'Purchase'); } catch (e) {}
|
||||||
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 []; }
|
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)
|
// purchases in [from, to) (and from overrideGoLive on): one row per purchase + totals per recipient
|
||||||
async function report(from, to) {
|
async function report(from, to) {
|
||||||
const c = cfg(); const rows = [], per = {};
|
const c = cfg(); const rows = [], per = {};
|
||||||
for (const p of purchases()) {
|
for (const p of purchases()) {
|
||||||
if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue;
|
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) / 10000; // dollars: price cents x 3% / 100
|
const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, usd = Math.round((p.priceCents || 0) * PCT) / 10000; // dollars: price cents x 3% / 100
|
||||||
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message }));
|
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message, readFailed: true }));
|
||||||
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 || '' });
|
rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: usd, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '', readFailed: !!r.readFailed });
|
||||||
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; }
|
if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usdCents: 0 }; o.purchases++; o.wei += wei; o.usdCents += (p.priceCents || 0) * PCT / 100; }
|
||||||
}
|
}
|
||||||
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 recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, wei: o.wei.toString(), pol: Number(o.wei) / 1e18, usd: Math.round(o.usdCents) / 100 })).sort((a, b) => b.usd - a.usd || a.recipientId - b.recipientId);
|
||||||
const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0);
|
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),
|
return { mode: c.mode, from, to, purchases: rows.length, readFailures: rows.filter(x => x.readFailed).length, recipients,
|
||||||
companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows };
|
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`
|
// last full week, or the week containing `day`
|
||||||
async function week(day) {
|
async function week(day) {
|
||||||
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(Date.now() - 7 * 86400000);
|
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(now() - 7 * 86400000);
|
||||||
const from = ctMidnight(monday), to = ctMidnight(new Date(Date.parse(monday) + 7 * 86400000).toISOString().slice(0, 10));
|
const b = weekBounds(monday);
|
||||||
return Object.assign(await report(from, to), { week: monday });
|
return Object.assign(await report(b.from, b.to), { week: monday, status: weekStatus(monday) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- planning: freeze who gets how much for one closed week (single writer via claim) ----
|
||||||
|
// carried rows from earlier weeks roll into this plan; under-dust totals are carried again
|
||||||
|
async function plan(wk) {
|
||||||
|
if (getWeek(wk)) return getWeek(wk);
|
||||||
|
const b = weekBounds(wk);
|
||||||
|
if (now() < b.to) return null; // not closed yet
|
||||||
|
const r = await report(b.from, b.to);
|
||||||
|
if (r.readFailures) { lastError.at = now(); lastError.msg = 'week ' + wk + ': ' + r.readFailures + ' sponsor reads failed, plan postponed'; return null; } // never plan on a partial read
|
||||||
|
if (!await claim('plan:' + wk)) return getWeek(wk); // another copy is planning (or did)
|
||||||
|
putWeek(wk, { state: 'planning', created: now(), from: b.from, to: b.to, purchases: r.purchases, salesUsd: r.totals.salesUsd, companyKeepsUsd: r.totals.companyKeepsUsd });
|
||||||
|
const per = {};
|
||||||
|
for (const o of r.recipients) per[o.recipientId] = { wei: BigInt(o.wei), usd: o.usd, purchases: o.purchases, carriedIn: 0n, carriedFrom: [] };
|
||||||
|
for (const w of plannedWeeks().filter(w => w < wk)) for (const row of rowsOf(w)) {
|
||||||
|
if (row.state !== 'carried') continue;
|
||||||
|
const o = per[row.memberId] = per[row.memberId] || { wei: 0n, usd: 0, purchases: 0, carriedIn: 0n, carriedFrom: [] };
|
||||||
|
o.wei += BigInt(row.amountWei); o.usd = Math.round((o.usd + (row.usd || 0)) * 100) / 100; o.carriedIn += BigInt(row.amountWei); o.carriedFrom.push(w);
|
||||||
|
putRow(w, row.memberId, { state: 'rolled', rolledInto: wk });
|
||||||
|
}
|
||||||
|
const dust = cfg().dustWei; let total = 0n, n = 0;
|
||||||
|
for (const [id, o] of Object.entries(per)) {
|
||||||
|
const st = o.wei < dust ? 'carried' : 'pending'; if (st === 'pending') { total += o.wei; n++; }
|
||||||
|
putRow(wk, Number(id), { amountWei: o.wei.toString(), usd: o.usd, purchases: o.purchases, carriedInWei: o.carriedIn.toString(), carriedFrom: o.carriedFrom, state: st, note: st === 'carried' ? 'under the ' + polStr(dust) + ' POL minimum, carried to next week' : '' });
|
||||||
|
}
|
||||||
|
return putWeek(wk, { state: n ? 'planned' : 'paid', totalWei: total.toString(), recipients: n, planned: now() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// settle rows whose send answer was lost, from the chain index only (AwardPaid from the payer to that member, that amount)
|
||||||
|
function reconcile(wk, pay) {
|
||||||
|
if (!pay || !chain.recentEvents) return;
|
||||||
|
const b = weekBounds(wk), used = overrideTxs(true);
|
||||||
|
for (const row of rowsOf(wk)) {
|
||||||
|
if (row.state !== 'review' && row.state !== 'sent') continue;
|
||||||
|
const hit = chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && e.toId === row.memberId && String(e.amountWei) === String(row.amountWei)
|
||||||
|
&& String(e.from || '').toLowerCase() === String(pay.address).toLowerCase() && e.ts >= b.to
|
||||||
|
&& (row.txHash ? String(e.tx).toLowerCase() === String(row.txHash).toLowerCase() : !used.has(String(e.tx).toLowerCase())));
|
||||||
|
if (hit) putRow(wk, row.memberId, { state: 'paid', txHash: hit.tx, note: 'confirmed from the chain index' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// admin decision for a stuck row: 'carry' (you checked the payer wallet and nothing went out) or 'paid' with the tx,
|
||||||
|
// which must be an AwardPaid in the chain index from the payer wallet to that member for that exact amount
|
||||||
|
async function resolve(wk, memberId, action, tx) {
|
||||||
|
const r = getRow(wk, Number(memberId)); if (!r) return { error: 'no such row' };
|
||||||
|
if (!['review', 'failed', 'sending', 'sent'].includes(r.state)) return { error: 'row is ' + r.state + ', nothing to resolve' };
|
||||||
|
if (action === 'carry') { putRow(wk, r.memberId, { state: 'carried', note: 'admin: nothing went out, carried to next week (was ' + r.state + ')' }); return finishWeek(wk); }
|
||||||
|
if (action === 'paid') {
|
||||||
|
const p = (payerOverride || keyHex()) ? payer() : null;
|
||||||
|
const hit = p && chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
|
||||||
|
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.amountWei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + polStr(r.amountWei) + ' POL in the chain index' };
|
||||||
|
putRow(wk, r.memberId, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return finishWeek(wk);
|
||||||
|
}
|
||||||
|
return { error: 'action must be carry or paid' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- paying one planned week (live only) ----
|
||||||
|
async function pay(wk) {
|
||||||
|
const live = liveState(); if (!live.ready) return { week: wk, paid: 0, why: live.why };
|
||||||
|
let w = getWeek(wk); if (!w) return { week: wk, why: ['not planned'] };
|
||||||
|
if (w.state === 'planning') return { week: wk, why: ['plan is being written (or a plan write stopped halfway: needs review if this lasts)'] };
|
||||||
|
const p = payer(); reconcile(wk, p);
|
||||||
|
let rows = rowsOf(wk).filter(r => r.state === 'pending');
|
||||||
|
if (!rows.length) return finishWeek(wk);
|
||||||
|
const c = cfg(); const total = rows.reduce((n, r) => n + BigInt(r.amountWei), 0n);
|
||||||
|
if (total > c.capWei) { putWeek(wk, { state: 'held', heldWhy: 'over the weekly cap: ' + polStr(total) + ' POL planned, cap ' + polStr(c.capWei) + ' POL' }); await alertOnce(wk, 'cap', '⛔ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPlanned ' + polStr(total) + ' POL is over the weekly cap of ' + polStr(c.capWei) + ' POL. Nothing was sent. Raise overridePayCapPol or review the plan, then press Pay this week now in admin.'); return { week: wk, held: 'cap' }; }
|
||||||
|
let fees, bal;
|
||||||
|
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { lastError.at = now(); lastError.msg = 'payer read: ' + e.message; return { week: wk, why: ['payer read failed: ' + e.message] }; }
|
||||||
|
const gas = BigInt(rows.length) * GAS_LIMIT * fees.maxFeePerGas;
|
||||||
|
if (bal < total + gas) { putWeek(wk, { state: 'held', heldWhy: 'payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL, needs ' + polStr(total + gas) + ' (payouts ' + polStr(total) + ' + gas ' + polStr(gas) + ')' }); await alertOnce(wk, 'balance', '⚠️ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPayer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; this week needs ' + polStr(total + gas) + ' POL (' + polStr(total) + ' payouts + up to ' + polStr(gas) + ' gas). Nothing was sent. Fund it and it pays on the next check (or press Pay this week now).'); return { week: wk, held: 'balance' }; }
|
||||||
|
putWeek(wk, { state: 'paying', heldWhy: '' });
|
||||||
|
let sent = 0;
|
||||||
|
for (const r0 of rows) {
|
||||||
|
if (!await claim('pay:' + wk + ':' + r0.memberId)) continue; // another copy owns this row
|
||||||
|
const r = getRow(wk, r0.memberId); if (!r || r.state !== 'pending') continue;
|
||||||
|
try { await p.preflight(r.memberId, r.amountWei); }
|
||||||
|
catch (e) { putRow(wk, r.memberId, { state: 'carried', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent, carried to next week' }); continue; }
|
||||||
|
putRow(wk, r.memberId, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
|
||||||
|
let tx;
|
||||||
|
try { tx = await p.send(r.memberId, r.amountWei, fees); }
|
||||||
|
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
|
||||||
|
putRow(wk, r.memberId, { state: 'sent', txHash: tx.hash });
|
||||||
|
console.log('override: week ' + wk + ' #' + r.memberId + ' ' + polStr(r.amountWei) + ' POL tx ' + tx.hash);
|
||||||
|
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putRow(wk, r.memberId, { state: 'paid', paidAt: now() }); sent++; } else putRow(wk, r.memberId, { state: 'failed', note: 'reverted on chain (no POL moved except gas); needs review' }); }
|
||||||
|
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
|
||||||
|
}
|
||||||
|
return Object.assign(await finishWeek(wk), { sentNow: sent });
|
||||||
|
}
|
||||||
|
async function finishWeek(wk) {
|
||||||
|
// a send that stopped halfway (no answer in 15 minutes) is never retried: it becomes review
|
||||||
|
for (const r of rowsOf(wk)) {
|
||||||
|
if (r.state === 'sending' && now() - (r.sendingAt || r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'the app stopped during the send; it may or may not have gone out' });
|
||||||
|
if (r.state === 'sent' && now() - (r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'sent, no receipt and not in the chain index after 15 minutes' });
|
||||||
|
}
|
||||||
|
reconcile(wk, (payerOverride || keyHex()) ? payer() : null);
|
||||||
|
const rows = rowsOf(wk); const open = rows.filter(r => ['pending', 'sending', 'sent', 'review', 'failed'].includes(r.state));
|
||||||
|
if (open.length) {
|
||||||
|
const stuck = open.filter(r => r.state === 'review' || r.state === 'failed'); // in-flight rows of another copy are not stuck
|
||||||
|
if (stuck.length) await alertOnce(wk, 'review', '\u{1F50E} <b>Level-4 override needs review</b> · ' + BRAND + ' · week of ' + wk + '\n' + stuck.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL: ' + r.state + (r.txHash ? ' ' + txLink(r.txHash) : '') + ' ' + (r.note || '')).join('\n') + '\nNothing is re-sent automatically. Check the payer wallet on the explorer, then resolve it in admin.');
|
||||||
|
return { week: wk, state: (getWeek(wk) || {}).state, open: open.length };
|
||||||
|
}
|
||||||
|
const w = putWeek(wk, { state: 'paid', done: now() });
|
||||||
|
await summaryPaid(wk);
|
||||||
|
return { week: wk, state: w.state };
|
||||||
|
}
|
||||||
|
const txLink = h => { const c = chain.getConfig(); return (c.explorer ? c.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + h; };
|
||||||
|
async function alertOnce(wk, kind, text) { if (!notify) return; if (!await claim('tg:' + wk + ':' + kind)) return; await notify(text, null).catch(() => {}); }
|
||||||
|
async function summaryPaid(wk) {
|
||||||
|
if (!notify || !await claim('tg:' + wk + ':paid')) return;
|
||||||
|
const w = getWeek(wk) || {}, rows = rowsOf(wk), paid = rows.filter(r => r.state === 'paid'), carried = rows.filter(r => r.state === 'carried');
|
||||||
|
const tot = paid.reduce((n, r) => n + BigInt(r.amountWei), 0n), usd = paid.reduce((n, r) => n + (r.usd || 0), 0);
|
||||||
|
await notify('\u{1F4B8} <b>Level-4 override PAID</b> · ' + BRAND + ' · week of ' + wk + '\n' + (w.purchases || 0) + ' purchases, $' + Number(w.salesUsd || 0).toFixed(2) + ' sales\n'
|
||||||
|
+ 'Paid ' + polStr(tot) + ' POL (about $' + usd.toFixed(2) + ' at purchase prices) to ' + paid.length + ' member' + (paid.length === 1 ? '' : 's') + '; company keeps $' + Number(w.companyKeepsUsd || 0).toFixed(2) + ' of the 3%.\n'
|
||||||
|
+ (paid.map(r => '#' + r.memberId + ': ' + polStr(r.amountWei) + ' POL ($' + (r.usd || 0).toFixed(2) + ') <a href="' + txLink(r.txHash) + '">tx</a>').join('\n') || 'Nobody qualified this week.')
|
||||||
|
+ (carried.length ? '\nCarried to next week (under the minimum or the wallet refused): ' + carried.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL').join(', ') : '')
|
||||||
|
+ '\nDetails: ' + SITE_URL + '/api/admin/override?week=' + wk, null).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// weeks the live payer is responsible for: from the go-live week to the last closed one, in order
|
||||||
|
function dueWeeks(force) {
|
||||||
|
const c = cfg(); if (!c.goLive) return [];
|
||||||
|
const out = []; let wk = weekOf(c.goLive);
|
||||||
|
while (true) { const b = weekBounds(wk); if (now() < b.to) break; if (!force && now() < payableAt(wk)) break; out.push(wk); wk = addDays(wk, 7); if (out.length > 520) break; }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// settle every due week in order; stop at the first one that is not fully paid
|
||||||
|
async function payDue(opts) {
|
||||||
|
const o = opts || {}; const results = [];
|
||||||
|
if (!liveState().ready) return { ready: false, why: liveState().why, results };
|
||||||
|
for (const wk of dueWeeks(o.force)) {
|
||||||
|
if (o.week && wk > o.week) break;
|
||||||
|
let w = getWeek(wk);
|
||||||
|
if (!w) w = await plan(wk);
|
||||||
|
if (!w) { results.push({ week: wk, why: ['not planned yet: ' + (lastError.msg || 'waiting')] }); break; }
|
||||||
|
if (w.state === 'paid') { await summaryPaid(wk); results.push({ week: wk, state: 'paid' }); continue; }
|
||||||
|
const r = await pay(wk); results.push(r);
|
||||||
|
if ((getWeek(wk) || {}).state !== 'paid') break;
|
||||||
|
}
|
||||||
|
return { ready: true, results };
|
||||||
|
}
|
||||||
|
|
||||||
|
function weekStatus(wk) {
|
||||||
|
const w = getWeek(wk); if (!w) return { week: wk, state: claimed('plan:' + wk) ? 'planning' : 'not planned' };
|
||||||
|
const rows = rowsOf(wk);
|
||||||
|
return { week: wk, state: w.state, heldWhy: w.heldWhy || '', totalWei: w.totalWei, totalPol: w.totalWei ? polStr(w.totalWei) : '0',
|
||||||
|
rows: rows.map(r => ({ memberId: r.memberId, pol: polStr(r.amountWei), amountWei: r.amountWei, usd: r.usd, purchases: r.purchases, state: r.state, txHash: r.txHash || '', tx: r.txHash ? txLink(r.txHash) : '', note: r.note || '', carriedFrom: r.carriedFrom || [], rolledInto: r.rolledInto || '' })) };
|
||||||
|
}
|
||||||
|
async function payerStatus() {
|
||||||
|
const c = cfg(), live = liveState(); const out = { mode: c.mode, ready: live.ready, why: live.why, goLive: c.goLive || 0, capPol: polStr(c.capWei), dustPol: polStr(c.dustWei), house: c.house, keyPresent: !!(payerOverride || keyHex()), lastError: lastError.msg ? lastError : null };
|
||||||
|
const p = (payerOverride || keyHex()) ? payer() : null;
|
||||||
|
if (p) { out.address = p.address; try { out.balancePol = polStr(await p.balance()); } catch (e) { out.balanceError = e.message; } }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// AwardPaid txs this payer made (for the Earnings label and the payout email): tx -> { week, memberId }
|
||||||
|
let txCache = { at: 0, map: new Map() };
|
||||||
|
function overrideTxs(fresh) {
|
||||||
|
if (!fresh && now() - txCache.at < 30000) return txCache.map;
|
||||||
|
const m = new Map(); for (const wk of plannedWeeks()) for (const r of rowsOf(wk)) if (r.txHash) m.set(String(r.txHash).toLowerCase(), { week: wk, memberId: r.memberId });
|
||||||
|
txCache = { at: now(), map: m }; return m;
|
||||||
|
}
|
||||||
|
const txInfo = tx => { return overrideTxs(true).get(String(tx || '').toLowerCase()) || null; };
|
||||||
|
|
||||||
|
// ---- the scheduler: every 30 minutes ----
|
||||||
|
async function tick() {
|
||||||
|
const c = cfg(); if (c.mode === 'off') return;
|
||||||
|
const live = liveState();
|
||||||
|
if (live.ready) { try { await payDue(); } catch (e) { lastError.at = now(); lastError.msg = 'payDue: ' + e.message; console.error('override pay', e.message); } return; }
|
||||||
|
// dry run (or 'live' that is not ready): the Monday report, once per week across every copy of the app
|
||||||
|
const parts = Object.fromEntries(CT_HOUR.formatToParts(new Date(now())).map(p => [p.type, p.value]));
|
||||||
|
if (parts.weekday !== 'Mon' || Number(parts.hour) < 9 || !notify) return;
|
||||||
|
const r = await week(); if (r.readFailures) return; // try again in 30 minutes rather than report a partial week
|
||||||
|
if (!await claim('tg:' + r.week + ':dry')) return;
|
||||||
|
let st = {}; try { st = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 'utf8')); } catch (e) {}
|
||||||
|
st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } });
|
||||||
|
try { fs.writeFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 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} <b>Level-4 override, DRY RUN</b> · ' + BRAND + ' · 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' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Monday morning: the dry-run summary to Marty's private Telegram, once per week, and a copy on the volume
|
const main = create();
|
||||||
const STATE = () => path.join(DATA_DIR, 'override-dryrun.json');
|
module.exports = Object.assign(main, { create, weekOf, ctMidnight, weekBounds, payableAt, polStr, toWei, PCT, MIN_BUYERS, HOP_CAP, LEVEL, GAS_LIMIT });
|
||||||
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} <b>Level-4 override, DRY RUN</b> · 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 };
|
|
||||||
|
|||||||
@@ -8,6 +8,9 @@
|
|||||||
// 2. GET <bridge>?a=ptc_served -> [{iapId, received}] (cumulative visits PD delivered per campaign). Delivery is READ
|
// 2. GET <bridge>?a=ptc_served -> [{iapId, received}] (cumulative visits PD delivered per campaign). Delivery is READ
|
||||||
// from PD, never derived: the delta since our last read is applied through ads.applyExternalVisits, which bumps
|
// from PD, never derived: the delta since our last read is applied through ads.applyExternalVisits, which bumps
|
||||||
// imps and closes the pack when the ordered count is reached. Our last-read counters live in DATA_DIR/pdsync.json.
|
// imps and closes the pack when the ordered count is reached. Our last-read counters live in DATA_DIR/pdsync.json.
|
||||||
|
// SYNDICATED RATE (Marty 2026-10-27, 4:1): N = ads.synRateDivisor() partner visits use up ONE visit of the pack
|
||||||
|
// (floor(now/N) - floor(prev/N) on the cumulative count, so fractions carry exactly); every partner visit is still
|
||||||
|
// counted in the campaign's syn_imps for the member's stats, and PD is offered (visits left) x N.
|
||||||
//
|
//
|
||||||
// FEATURE-FLAGGED: inert unless PD_BRIDGE_URL and PD_BRIDGE_SECRET are set. Geo-restricted campaigns are not sent
|
// FEATURE-FLAGGED: inert unless PD_BRIDGE_URL and PD_BRIDGE_SECRET are set. Geo-restricted campaigns are not sent
|
||||||
// (PassiveDrip's audience is worldwide).
|
// (PassiveDrip's audience is worldwide).
|
||||||
@@ -16,6 +19,7 @@ const fs = require('fs'), path = require('path'), http = require('http'), https
|
|||||||
|
|
||||||
let X = null, FILE = null, S = { served: {}, last: null }, running = false;
|
let X = null, FILE = null, S = { served: {}, last: null }, running = false;
|
||||||
function enabled() { return !!(process.env.PD_BRIDGE_URL && process.env.PD_BRIDGE_SECRET); }
|
function enabled() { return !!(process.env.PD_BRIDGE_URL && process.env.PD_BRIDGE_SECRET); }
|
||||||
|
const synN = () => { try { return (X && X.ads && X.ads.synRateDivisor) ? X.ads.synRateDivisor() : 1; } catch (e) { return 1; } };
|
||||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'pdsync.json'); try { S = Object.assign(S, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) {} }
|
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'pdsync.json'); try { S = Object.assign(S, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) {} }
|
||||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||||
|
|
||||||
@@ -37,7 +41,7 @@ function bridge(action, method, body) {
|
|||||||
async function listing() {
|
async function listing() {
|
||||||
const all = await X.ads.adminList(2000);
|
const all = await X.ads.adminList(2000);
|
||||||
return all.filter(c => c.type === 'visits' && c.status === 'active' && !c.doorOnly && !c.geo && !(c.starts && c.starts > Date.now()) && /^https?:\/\//.test(c.targetUrl || ''))
|
return all.filter(c => c.type === 'visits' && c.status === 'active' && !c.doorOnly && !c.geo && !(c.starts && c.starts > Date.now()) && /^https?:\/\//.test(c.targetUrl || ''))
|
||||||
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) }))
|
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) * synN() }))
|
||||||
.filter(c => c.visitsLeft > 0);
|
.filter(c => c.visitsLeft > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +58,8 @@ async function sync() {
|
|||||||
const id = String(row.iapId); const now = Number(row.received) || 0; const prev = Number(S.served[id] || 0);
|
const id = String(row.iapId); const now = Number(row.received) || 0; const prev = Number(S.served[id] || 0);
|
||||||
if (now <= prev) { if (now < prev) S.served[id] = now; continue; } // PD's counter reset (row recreated): re-baseline, never charge backwards
|
if (now <= prev) { if (now < prev) S.served[id] = now; continue; } // PD's counter reset (row recreated): re-baseline, never charge backwards
|
||||||
if (process.env.PD_SYNC_APPLY === '0') { S.served[id] = now; t.ignored = (t.ignored || 0) + (now - prev); continue; } // staging bridge: test views are read and baselined, never counted as delivery
|
if (process.env.PD_SYNC_APPLY === '0') { S.served[id] = now; t.ignored = (t.ignored || 0) + (now - prev); continue; } // staging bridge: test views are read and baselined, never counted as delivery
|
||||||
try { const res = await X.ads.applyExternalVisits(Number(id), now - prev, 'PassiveDrip'); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
|
const N = synN(); const units = Math.floor(now / N) - Math.floor(prev / N); // pack visits these partner visits use up
|
||||||
|
try { const res = await X.ads.applyExternalVisits(Number(id), units, 'PassiveDrip', now - prev); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
|
||||||
catch (e) { console.error('pdsync apply', id, e.message); } // one bad row never stops the others; its delta is retried next sync
|
catch (e) { console.error('pdsync apply', id, e.message); } // one bad row never stops the others; its delta is retried next sync
|
||||||
}
|
}
|
||||||
save();
|
save();
|
||||||
|
|||||||
+73
-4
@@ -61,6 +61,14 @@
|
|||||||
.kv-row .k{font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}
|
.kv-row .k{font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}
|
||||||
.kv-row input[type=checkbox]{width:auto;justify-self:start}
|
.kv-row input[type=checkbox]{width:auto;justify-self:start}
|
||||||
@media(max-width:700px){.kv-row{grid-template-columns:1fr}}
|
@media(max-width:700px){.kv-row{grid-template-columns:1fr}}
|
||||||
|
.gpt-note{margin:0 0 10px;padding:8px 12px;border-radius:8px;background:#fde68a;color:#7c2d12;font-size:13px}
|
||||||
|
.gpt-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
|
||||||
|
.gpt-tier{border:1px dashed var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
|
||||||
|
.gpt-tier.on{border-style:solid;border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
|
||||||
|
.gpt-tier h4{margin:0;font-size:16px;display:flex;gap:6px;align-items:center;flex-wrap:wrap}
|
||||||
|
.gpt-tier .gpt-price{margin:0;font-size:18px;font-weight:700}
|
||||||
|
.gpt-tier ul{margin:4px 0;padding-left:18px;font-size:13px}
|
||||||
|
.gpt-tier .gpt-acts{display:flex;gap:6px;flex-wrap:wrap;margin-top:auto;padding-top:6px}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="bo-body">
|
<body class="bo-body">
|
||||||
@@ -97,6 +105,7 @@
|
|||||||
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10"/></svg>All campaigns</button>
|
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10"/></svg>All campaigns</button>
|
||||||
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
|
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
|
||||||
<button data-pane="support" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Support<span class="pill" id="supBadge" hidden></span></button>
|
<button data-pane="support" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Support<span class="pill" id="supBadge" hidden></span></button>
|
||||||
|
<button data-pane="kb" type="button"><svg viewBox="0 0 24 24"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/><path d="M4 20.5A2.5 2.5 0 0 0 6.5 21H20v-3"/><path d="M9 8h7M9 11.5h5"/></svg>Knowledge base</button>
|
||||||
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
|
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
|
||||||
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
|
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
|
||||||
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
|
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
|
||||||
@@ -231,6 +240,11 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pane" id="pane-campaigns" hidden>
|
<div class="pane" id="pane-campaigns" hidden>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Login-ad line</h3><span class="sub" id="lqSub">paid reservations waiting for a slot</span></div>
|
||||||
|
<p class="small muted" style="margin:0 0 10px">When every member slot is taken, a member can pay now to reserve the next one. The oldest paid reservation starts the moment a slot frees (on expiry, on a pause, and on a one-minute check), before any paused slot can come back. Estimated starts assume every live slot runs its full term. Cancel gives the full price back as purchased credits.</p>
|
||||||
|
<div class="tablewrap"><table class="adm-table" id="lqTable"></table></div>
|
||||||
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
|
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
|
||||||
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
|
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
|
||||||
@@ -264,6 +278,13 @@
|
|||||||
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
|
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
|
||||||
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
|
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
|
||||||
|
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
|
||||||
|
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
|
||||||
|
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
|
||||||
|
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
|
||||||
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
|
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
|
||||||
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
|
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
|
||||||
@@ -295,6 +316,27 @@
|
|||||||
<div id="spView" hidden></div>
|
<div id="spView" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="pane" id="pane-kb" hidden>
|
||||||
|
<div id="kbList">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Knowledge base</h3><span class="sub" id="kbSub">what the chat assistant answers from</span></div>
|
||||||
|
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
|
||||||
|
<input id="kbQ" class="small" placeholder="Search title, questions, answer, tags" style="flex:1;min-width:200px">
|
||||||
|
<select id="kbSrc" class="small"><option value="">All sources</option><option value="canned">From the code</option><option value="faq">FAQ</option><option value="ticket">From tickets</option><option value="admin">Added here</option></select>
|
||||||
|
<button type="button" class="btn small" id="kbNew">+ New entry</button>
|
||||||
|
</p>
|
||||||
|
<div class="tablewrap"><table class="adm-table" id="kbTable"></table></div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Try a question</h3><span class="sub">which entry answers it, and what the AI is given</span></div>
|
||||||
|
<p style="display:flex;gap:8px;flex-wrap:wrap;margin:0"><input id="kbTry" class="small" placeholder="Ask it the way a member would" style="flex:1;min-width:200px"><button type="button" class="btn small sec" id="kbTryGo">Test</button></p>
|
||||||
|
<div id="kbTryOut" class="small"></div>
|
||||||
|
</div>
|
||||||
|
<p class="small muted">Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. In a ticket, "Save as KB entry" under your reply turns it into a draft here. Entries from the code follow chatbot.js and kb-seed.js until you edit them.</p>
|
||||||
|
</div>
|
||||||
|
<div id="kbEdit" class="card" hidden></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="pane" id="pane-reports" hidden>
|
<div class="pane" id="pane-reports" hidden>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head"><h3>Counters audit</h3><span class="sub" id="audSub">views vs delivery logs, charges vs shows</span></div>
|
<div class="card-head"><h3>Counters audit</h3><span class="sub" id="audSub">views vs delivery logs, charges vs shows</span></div>
|
||||||
@@ -505,6 +547,13 @@
|
|||||||
<p class="small" id="burnerLine">…</p>
|
<p class="small" id="burnerLine">…</p>
|
||||||
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
|
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Level 4 override</h3><span class="sub">3% of each purchase to the qualified 4th upline, paid weekly from the payer wallet</span></div>
|
||||||
|
<p class="small" id="ovPayer">…</p>
|
||||||
|
<div id="ovWeeks" class="small"></div>
|
||||||
|
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
|
||||||
|
<div id="ovOut" class="small"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="pane" id="pane-gamepass" hidden>
|
<div class="pane" id="pane-gamepass" hidden>
|
||||||
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
|
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
|
||||||
@@ -523,14 +572,33 @@
|
|||||||
<div class="card-head"><h3>By pass tier</h3><span class="sub" id="gpTiersSub"></span></div>
|
<div class="card-head"><h3>By pass tier</h3><span class="sub" id="gpTiersSub"></span></div>
|
||||||
<div id="gpTiers" class="small">…</div>
|
<div id="gpTiers" class="small">…</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card" id="gpTestCard">
|
||||||
|
<div class="card-head"><h3>Tier test and preview</h3><span class="sub" id="gpTestSub">admin only · your own account</span></div>
|
||||||
|
<div id="gpTest" class="small">…</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head"><h3>Pass sales</h3><span class="sub" id="gpSalesSub"></span></div>
|
||||||
|
<div id="gpSales" class="small">…</div>
|
||||||
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass period, recorded as no sale</span></div>
|
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass period, recorded as no sale</span></div>
|
||||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><select id="gpCompTier"><option value="weekly">Game Pass (weekly)</option><option value="explorer">Explorer (monthly)</option><option value="champion">Champion (monthly)</option></select><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass period</button><button class="btn small sec" id="gpRevoke" type="button">End this tier now (refund)</button></p>
|
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><select id="gpCompTier"><option value="weekly">Game Pass (weekly)</option><option value="explorer">Explorer (monthly)</option><option value="champion">Champion (monthly)</option><option value="sovereign">Sovereign (monthly)</option><option value="legend">Legend (yearly)</option></select><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass period</button><button class="btn small sec" id="gpRevoke" type="button">End this tier now (refund)</button></p>
|
||||||
</div>
|
</div>
|
||||||
<p class="small muted">Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Monthly tiers: sovTiers (1/0, the Explorer + Champion sale switch; off = only the admin account sees them), gamePassExplorerEnabled / gamePassChampionEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (4000), gamePassExplorerDays / gamePassChampionDays (30), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
|
<p class="small muted">Every pass is paid by a new package purchase of at least its price (since 2026-10-22; credits never buy a pass). The *PriceCredits settings are the pass price in cents. Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Tiers above weekly: sovTiers (1/0, the sale switch for all of them; off = members never see them and the admin tests them in Tier test and preview above, never on the member card), gamePassExplorerEnabled / gamePassChampionEnabled / gamePassSovereignEnabled / gamePassLegendEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (5000), gamePassSovereignPriceCredits (10000), gamePassLegendPriceCredits (25000); since 2026-10-25 every tier price equals a one-click package ($5, $20, $50, $100, $250), gamePassExplorerDays / gamePassChampionDays / gamePassSovereignDays (30), gamePassLegendDays (365), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="pane" id="pane-settings" hidden>
|
<div class="pane" id="pane-settings" hidden>
|
||||||
|
<div class="card" id="kitCard">
|
||||||
|
<div class="card-head"><h3>Refuel Kit</h3><span class="sub" id="kitSub">monthly members-only banners: unlocked by a counted refuel (needs refuelStreak on)</span></div>
|
||||||
|
<p class="small muted">Five base images per month for this site's own program: 728x90, 300x250, 468x60, 160x600, 1200x630. Each member's @name and a QR to their own link are drawn on top: keep the right end clear on 728x90 and 468x60 (QR) with room for the name left of it, the bottom-right corner on 300x250 and 1200x630, and the bottom 170 px on 160x600. No income claims in any banner. Release on the 1st; a member unlocks the month's kit with their next counted refuel.</p>
|
||||||
|
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><input id="kitMonth" placeholder="YYYY-MM" style="max-width:110px"><input id="kitTheme" placeholder="Theme (e.g. Harvest)" style="max-width:240px">
|
||||||
|
<button class="btn small" id="kitSave" type="button">Save kit</button><button class="btn small sec" id="kitPlaceholder" type="button">Use placeholder art (public/banners)</button></p>
|
||||||
|
<div id="kitSizes"></div>
|
||||||
|
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">Preview <select id="kitPrevSize"></select><input id="kitPrevName" placeholder="username" style="max-width:160px"><label class="small"><input type="checkbox" id="kitPrevGif" style="width:auto"> animated</label><button class="btn small sec" id="kitPreview" type="button">Preview</button></p>
|
||||||
|
<div id="kitPrevBox"></div>
|
||||||
|
<div id="kitList" class="small"></div>
|
||||||
|
<div id="kitBox"></div>
|
||||||
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
|
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
|
||||||
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
|
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
|
||||||
@@ -571,7 +639,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/admin.js?v=20261018tiers"></script>
|
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||||
|
<script src="/assets/admin.js?v=20261027nr"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
|
||||||
|
// entries the chat assistant answers from, try a question against them, and take a support reply
|
||||||
|
// straight into a new entry (admin.js calls IAPKB.compose from a ticket's "Save as KB entry").
|
||||||
|
(function () {
|
||||||
|
const $ = IAP.$;
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
async function api(path, body, method) {
|
||||||
|
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
|
||||||
|
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
|
||||||
|
const r = await (await fetch(path, opts)).json();
|
||||||
|
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
|
||||||
|
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
|
||||||
|
let entries = [], filter = { q: '', src: '' }, wired = false;
|
||||||
|
|
||||||
|
function wire() {
|
||||||
|
if (wired) return; wired = true;
|
||||||
|
let t = null;
|
||||||
|
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
|
||||||
|
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
|
||||||
|
$('kbNew').addEventListener('click', () => compose({}));
|
||||||
|
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
|
||||||
|
const go = async () => {
|
||||||
|
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
|
||||||
|
const r = await api('/api/admin/kb/test', { question: q });
|
||||||
|
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
|
||||||
|
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
|
||||||
|
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
|
||||||
|
};
|
||||||
|
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
|
||||||
|
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
|
||||||
|
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
wire();
|
||||||
|
$('kbEdit').hidden = true; $('kbList').hidden = false;
|
||||||
|
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
|
||||||
|
entries = r.entries || [];
|
||||||
|
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
|
||||||
|
draw();
|
||||||
|
}
|
||||||
|
function draw() {
|
||||||
|
const rows = entries.filter(e => !filter.src || e.source === filter.src);
|
||||||
|
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
|
||||||
|
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
|
||||||
|
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
|
||||||
|
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
|
||||||
|
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
|
||||||
|
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
|
||||||
|
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
|
||||||
|
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
|
||||||
|
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
|
||||||
|
function compose(e) {
|
||||||
|
wire();
|
||||||
|
e = e || {};
|
||||||
|
const isNew = !e.id;
|
||||||
|
$('kbList').hidden = true; $('kbEdit').hidden = false;
|
||||||
|
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
|
||||||
|
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
|
||||||
|
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
|
||||||
|
+ '<div style="display:grid;gap:10px">'
|
||||||
|
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
|
||||||
|
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
|
||||||
|
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
|
||||||
|
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
|
||||||
|
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
|
||||||
|
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
|
||||||
|
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
|
||||||
|
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
|
||||||
|
+ '</div>'
|
||||||
|
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
|
||||||
|
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
|
||||||
|
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
|
||||||
|
$('kbSave').addEventListener('click', async () => {
|
||||||
|
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
|
||||||
|
try {
|
||||||
|
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
|
||||||
|
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
|
||||||
|
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
|
||||||
|
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
|
||||||
|
await load();
|
||||||
|
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
|
||||||
|
});
|
||||||
|
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
|
||||||
|
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
|
||||||
|
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
|
||||||
|
});
|
||||||
|
$('kbTitle').focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
|
||||||
|
function fromTicket(t, question, reply) {
|
||||||
|
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
|
||||||
|
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
|
||||||
|
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
|
||||||
|
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
|
||||||
|
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
|
||||||
|
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
|
||||||
|
}
|
||||||
|
|
||||||
|
window.IAPKB = { load: () => load(), compose, fromTicket };
|
||||||
|
})();
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// Admin > Settings > Refuel Kit (2026-10-24). The SAME file ships in InstantAdPay and LinkSpin. Upload one month's base art
|
||||||
|
// (five sizes, this site's own program), preview the personalization (@name + QR to the member's link), then release it.
|
||||||
|
// Keep the QR corner and the name strip clear in the art (see the layout note on the card).
|
||||||
|
(function () {
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
if (!$('kitBox')) return;
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
const say = m => { $('kitSub').textContent = m; };
|
||||||
|
const api = async (url, opt) => { const r = await fetch(url, Object.assign({ cache: 'no-store' }, opt || {})); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
|
||||||
|
const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
||||||
|
const nextMonth = () => { const d = new Date(); const ct = new Date(d.toLocaleString('en-US', { timeZone: 'America/Chicago' })); ct.setDate(1); ct.setMonth(ct.getMonth() + 1); return ct.getFullYear() + '-' + String(ct.getMonth() + 1).padStart(2, '0'); };
|
||||||
|
let sizes = [];
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
const d = await api('/api/admin/kits'); sizes = d.sizes;
|
||||||
|
if (!$('kitMonth').value) $('kitMonth').value = nextMonth();
|
||||||
|
$('kitList').innerHTML = d.kits.length ? d.kits.map(k => '<div style="border:1px solid var(--line,#ccd);border-radius:8px;padding:10px;margin:8px 0">'
|
||||||
|
+ '<b>' + esc(k.label) + '</b> ' + (k.theme ? '· ' + esc(k.theme) + ' ' : '') + '<span class="small muted">(' + esc(k.month) + ')</span> '
|
||||||
|
+ (k.released ? '<span class="badge">released</span>' : '<span class="badge amber">draft</span>') + '<div class="small" style="margin:6px 0">'
|
||||||
|
+ k.sizes.map(s => s.size + ': ' + (s.ready ? 'ready' : '<b>missing</b>')).join(' · ') + '</div>'
|
||||||
|
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small sec" type="button" data-kedit="' + esc(k.month) + '" data-theme="' + esc(k.theme) + '">Edit</button>'
|
||||||
|
+ '<button class="btn small' + (k.released ? ' sec' : '') + '" type="button" data-krel="' + esc(k.month) + '" data-on="' + (k.released ? '0' : '1') + '"' + (!k.complete && !k.released ? ' disabled title="upload all five sizes first"' : '') + '>' + (k.released ? 'Unrelease' : 'Release to members') + '</button></div></div>').join('') : '<p class="small muted">No kits yet.</p>';
|
||||||
|
$('kitList').querySelectorAll('[data-kedit]').forEach(b => b.addEventListener('click', () => { $('kitMonth').value = b.dataset.kedit; $('kitTheme').value = b.dataset.theme; say('editing ' + b.dataset.kedit); }));
|
||||||
|
$('kitList').querySelectorAll('[data-krel]').forEach(b => b.addEventListener('click', async () => { try { await post('/api/admin/kits', { month: b.dataset.krel, released: b.dataset.on === '1' }); load(); } catch (e) { say(e.message); } }));
|
||||||
|
$('kitSizes').innerHTML = sizes.map(s => '<label class="small" style="display:block;margin:4px 0">' + s + ' <input type="file" accept="image/png,image/jpeg,image/gif" data-ksize="' + s + '"></label>').join('');
|
||||||
|
$('kitSizes').querySelectorAll('[data-ksize]').forEach(inp => inp.addEventListener('change', async () => {
|
||||||
|
const f = inp.files && inp.files[0]; if (!f) return; const m = $('kitMonth').value.trim();
|
||||||
|
try { await api('/api/admin/kits/upload?month=' + encodeURIComponent(m) + '&size=' + inp.dataset.ksize, { method: 'POST', headers: { 'Content-Type': f.type }, body: f }); say(inp.dataset.ksize + ' uploaded for ' + m); load(); } catch (e) { say(e.message); }
|
||||||
|
}));
|
||||||
|
$('kitPrevSize').innerHTML = sizes.map(s => '<option>' + s + '</option>').join('');
|
||||||
|
} catch (e) { say('Could not load: ' + e.message); }
|
||||||
|
}
|
||||||
|
$('kitSave').addEventListener('click', async () => { try { await post('/api/admin/kits', { month: $('kitMonth').value.trim(), theme: $('kitTheme').value }); say('saved'); load(); } catch (e) { say(e.message); } });
|
||||||
|
$('kitPlaceholder').addEventListener('click', async () => { try { const r = await post('/api/admin/kits/placeholder', { month: $('kitMonth').value.trim() }); say('placeholder art: ' + r.sizes.join(', ')); load(); } catch (e) { say(e.message); } });
|
||||||
|
$('kitPreview').addEventListener('click', () => {
|
||||||
|
const q = 'month=' + encodeURIComponent($('kitMonth').value.trim()) + '&size=' + encodeURIComponent($('kitPrevSize').value) + '&username=' + encodeURIComponent($('kitPrevName').value || 'yourname') + ($('kitPrevGif').checked ? '&variant=gif' : '') + '&t=' + Date.now();
|
||||||
|
$('kitPrevBox').innerHTML = '<img alt="preview" style="max-width:100%;border:1px solid #ccd" src="/api/admin/kits/preview?' + q + '">';
|
||||||
|
});
|
||||||
|
load();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
|
||||||
|
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
|
||||||
|
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
|
||||||
|
(function () {
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
if (!$('scRun')) return;
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||||
|
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||||
|
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit' };
|
||||||
|
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||||
|
function side(f) {
|
||||||
|
if (!f) return '<span class="muted">no account</span>';
|
||||||
|
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
|
||||||
|
const how = [];
|
||||||
|
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
|
||||||
|
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
|
||||||
|
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
|
||||||
|
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
|
||||||
|
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
|
||||||
|
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
|
||||||
|
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
|
||||||
|
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
|
||||||
|
}
|
||||||
|
let last = null;
|
||||||
|
async function run() {
|
||||||
|
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
|
||||||
|
try {
|
||||||
|
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
|
||||||
|
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||||
|
last = r;
|
||||||
|
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
|
||||||
|
const differ = r.rows.filter(x => x.kind === 'differ').length;
|
||||||
|
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
|
||||||
|
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
|
||||||
|
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
|
||||||
|
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
|
||||||
|
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
|
||||||
|
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
|
||||||
|
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
|
||||||
|
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
|
||||||
|
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
|
||||||
|
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
|
||||||
|
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
|
||||||
|
finally { $('scRun').disabled = false; }
|
||||||
|
}
|
||||||
|
$('scRun').addEventListener('click', run);
|
||||||
|
document.addEventListener('click', async e => {
|
||||||
|
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
|
||||||
|
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
|
||||||
|
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
|
||||||
|
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
|
||||||
|
let ok = false;
|
||||||
|
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
|
||||||
|
if (!ok) return;
|
||||||
|
b.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
|
||||||
|
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||||
|
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
|
||||||
|
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
|
||||||
|
});
|
||||||
|
})();
|
||||||
+122
-8
@@ -44,8 +44,8 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ── panes ──
|
// ── panes ──
|
||||||
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
|
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
|
||||||
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
|
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
|
||||||
function setPane(name) {
|
function setPane(name) {
|
||||||
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email)
|
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email)
|
||||||
if (!TITLES[name]) name = 'overview';
|
if (!TITLES[name]) name = 'overview';
|
||||||
@@ -256,10 +256,31 @@
|
|||||||
// ── all campaigns ──
|
// ── all campaigns ──
|
||||||
let allCamps = [];
|
let allCamps = [];
|
||||||
async function loadCampaigns() {
|
async function loadCampaigns() {
|
||||||
|
loadLoginLine().catch(e => IAP.status(e.message, 'bad'));
|
||||||
const r = await api('/api/admin/campaigns');
|
const r = await api('/api/admin/campaigns');
|
||||||
allCamps = r.campaigns || [];
|
allCamps = r.campaigns || [];
|
||||||
drawCamps();
|
drawCamps();
|
||||||
}
|
}
|
||||||
|
// prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time.
|
||||||
|
const lqWhen = ts => ts ? esc(ctWhen(ts)) : '<span class="muted">unknown</span>'; // ctWhen (below) prints Central time
|
||||||
|
async function loadLoginLine() {
|
||||||
|
const d = await api('/api/admin/login-queue');
|
||||||
|
$('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open';
|
||||||
|
$('lqTable').innerHTML = '<tr><th>Place</th><th>ID</th><th>Owner</th><th>Campaign</th><th>Paid</th><th>Queued at</th><th>Estimated start</th><th></th></tr>'
|
||||||
|
+ (d.queue.length ? d.queue.map(c => '<tr><td><b>#' + c.place + '</b></td><td>#' + c.id + '</td><td><span class="trunc" title="' + esc(c.owner) + '">' + esc(c.owner) + '</span></td>'
|
||||||
|
+ '<td>' + esc(c.name) + '<div><a class="small trunc" href="' + esc(c.targetUrl) + '" target="_blank" rel="noopener">' + esc(c.targetUrl) + '</a></div></td>'
|
||||||
|
+ '<td class="mono small">' + Number(c.paid || 0).toLocaleString() + '</td><td class="small muted">' + lqWhen(c.queuedAt) + '</td><td class="small">' + lqWhen(c.estStart) + '</td>'
|
||||||
|
+ '<td class="act"><button class="btn small sec" data-lqcancel="' + c.id + '" data-lqowner="' + esc(c.owner) + '" data-lqpaid="' + Number(c.paid || 0) + '">Cancel + refund</button></td></tr>').join('')
|
||||||
|
: '<tr><td colspan="8" class="muted">Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.</td></tr>');
|
||||||
|
}
|
||||||
|
document.addEventListener('click', async e => {
|
||||||
|
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
|
||||||
|
const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' });
|
||||||
|
if (!ok) return;
|
||||||
|
b.disabled = true;
|
||||||
|
try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); }
|
||||||
|
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
|
||||||
|
});
|
||||||
function drawCamps() {
|
function drawCamps() {
|
||||||
const q = ($('campFilter').value || '').trim().toLowerCase();
|
const q = ($('campFilter').value || '').trim().toLowerCase();
|
||||||
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
|
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
|
||||||
@@ -273,8 +294,13 @@
|
|||||||
async function loadTank() {
|
async function loadTank() {
|
||||||
try {
|
try {
|
||||||
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
|
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
|
||||||
$('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window';
|
const nReady = r.waiting.filter(w => w.ready).length;
|
||||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>');
|
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members held ' + (r.holdHours || 24) + ' h, then auto-assigned in rotation';
|
||||||
|
// ready = wallet linked: activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
|
||||||
|
const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; };
|
||||||
|
const rb = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e">Ready to activate · ' + left(w) + '</span>' : '';
|
||||||
|
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
|
||||||
|
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (LinkSpin) instead of the tank</th></tr>' + r.aligned.slice(0, 15).map(x => '<tr><td>' + esc(x.email) + '</td><td>' + esc(x.toName || x.to) + '</td><td class="when">' + when(x.at) + '</td><td class="muted">' + esc(x.via || '') + '</td></tr>').join('') : '');
|
||||||
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
@@ -432,7 +458,7 @@
|
|||||||
h += '<div><h4 style="margin:0 0 6px">Payouts received</h4><div class="tablewrap"><table class="adm-table"><tr><th>When</th><th>From</th><th>Tier</th><th>Amount</th></tr>'
|
h += '<div><h4 style="margin:0 0 6px">Payouts received</h4><div class="tablewrap"><table class="adm-table"><tr><th>When</th><th>From</th><th>Tier</th><th>Amount</th></tr>'
|
||||||
+ (d.received.length ? d.received.map(r => '<tr><td class="small">' + when(r.ts) + '</td><td>#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '</td><td>' + r.tier + '</td><td>' + polOf(r.amountWei) + ' POL</td></tr>').join('') : '<tr><td colspan="4" class="muted">Nothing received yet.</td></tr>') + '</table></div></div></div>';
|
+ (d.received.length ? d.received.map(r => '<tr><td class="small">' + when(r.ts) + '</td><td>#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '</td><td>' + r.tier + '</td><td>' + polOf(r.amountWei) + ' POL</td></tr>').join('') : '<tr><td colspan="4" class="muted">Nothing received yet.</td></tr>') + '</table></div></div></div>';
|
||||||
h += '<h4 style="margin:18px 0 6px">Campaigns (' + d.campaigns.length + ')</h4><div class="tablewrap"><table class="adm-table"><tr><th>#</th><th>Type</th><th>Status</th><th>Budget</th><th>Spent</th><th>Views</th><th>Clicks</th><th>Created</th></tr>'
|
h += '<h4 style="margin:18px 0 6px">Campaigns (' + d.campaigns.length + ')</h4><div class="tablewrap"><table class="adm-table"><tr><th>#</th><th>Type</th><th>Status</th><th>Budget</th><th>Spent</th><th>Views</th><th>Clicks</th><th>Created</th></tr>'
|
||||||
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + Number(c.views || 0).toLocaleString() + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
|
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + (c.pack ? Number(c.views || 0).toLocaleString() + ' <span class="muted small">of ' + Number(c.pack).toLocaleString() + ' visits</span>' : Number(c.views || 0).toLocaleString()) + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
|
||||||
$('mcBody').innerHTML = h;
|
$('mcBody').innerHTML = h;
|
||||||
if (location.hash !== '#members') history.replaceState(null, '', '#members');
|
if (location.hash !== '#members') history.replaceState(null, '', '#members');
|
||||||
loadTrace(d);
|
loadTrace(d);
|
||||||
@@ -730,6 +756,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadPnl() {
|
async function loadPnl() {
|
||||||
|
loadOverride().catch(() => {}); // its own request: does not wait for the chain reads below
|
||||||
const r = await api('/api/admin/pnl?days=' + pnlDays);
|
const r = await api('/api/admin/pnl?days=' + pnlDays);
|
||||||
const px = r.polUsd || 0;
|
const px = r.polUsd || 0;
|
||||||
const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px;
|
const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px;
|
||||||
@@ -843,6 +870,29 @@
|
|||||||
});
|
});
|
||||||
document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); }));
|
document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); }));
|
||||||
if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
||||||
|
// Level 4 override (2026-10-23): week status from /api/admin/override; the pay button exists only while the live payer is ready
|
||||||
|
const OV_STATE = { 'not planned': 'not planned', planning: 'planning', planned: 'pending', paying: 'paying', held: 'held', paid: 'paid' };
|
||||||
|
async function loadOverride(week) {
|
||||||
|
if (!$('ovPayer')) return;
|
||||||
|
let r; try { r = await (await fetch('/api/admin/override' + (week ? '?week=' + encodeURIComponent(week) : ''), { cache: 'no-store' })).json(); } catch (e) { $('ovPayer').textContent = 'Could not read the override: ' + e.message; return; }
|
||||||
|
const pz = r.payer || {};
|
||||||
|
$('ovPayer').textContent = 'Mode: ' + (pz.mode || '?') + (pz.ready ? ' · PAYING automatically each Monday after 9 AM CT' : ' · not paying (' + (pz.why || []).join('; ') + ')')
|
||||||
|
+ (pz.address ? ' · payer wallet ' + pz.address + ' holds ' + (pz.balancePol || '?') + ' POL' : '') + ' · weekly cap ' + (pz.capPol || '?') + ' POL · minimum ' + (pz.dustPol || '?') + ' POL'
|
||||||
|
+ (pz.goLive ? ' · purchases from ' + new Date(pz.goLive).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : '') + (pz.lastError ? ' · last error: ' + pz.lastError.msg : '');
|
||||||
|
$('ovPay').hidden = !pz.ready;
|
||||||
|
const sel = $('ovWeek'); if (!sel.options.length) { const now = new Date(); for (let i = 0; i < 10; i++) { const d = new Date(now.getTime() - i * 7 * 86400000); const v = d.toISOString().slice(0, 10); sel.innerHTML += '<option value="' + v + '">week containing ' + v + '</option>'; } sel.selectedIndex = 1; }
|
||||||
|
$('ovWeeks').innerHTML = (r.dueWeeks || []).length ? '<table><tr><th>Week of</th><th>Status</th><th>Total</th></tr>' + r.dueWeeks.map(w => '<tr><td>' + esc(w.week) + '</td><td>' + esc(OV_STATE[w.state] || w.state) + (w.heldWhy ? ' <span class="muted">(' + esc(w.heldWhy) + ')</span>' : '') + '</td><td class="mono">' + esc(w.totalPol || '0') + ' POL</td></tr>').join('') + '</table>' : '';
|
||||||
|
const st = r.status || {}; const t = r.totals || {};
|
||||||
|
$('ovOut').innerHTML = '<p>Week of ' + esc(r.week || '') + ': ' + (r.purchases || 0) + ' purchases, $' + Number(t.salesUsd || 0).toFixed(2) + ' sales. Override due: $' + Number(t.wouldPayUsd || 0).toFixed(2) + ' (' + Number(t.wouldPayPol || 0).toFixed(4) + ' POL) to ' + (r.recipients || []).length + ' members; company keeps $' + Number(t.companyKeepsUsd || 0).toFixed(2) + '. Payout status: <b>' + esc(OV_STATE[st.state] || st.state || '?') + '</b>' + (st.heldWhy ? ' (' + esc(st.heldWhy) + ')' : '') + '.</p>'
|
||||||
|
+ ((st.rows || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Status</th><th></th></tr>' + st.rows.map(x => '<tr><td>#' + x.memberId + '</td><td class="mono">' + esc(x.pol) + '</td><td class="mono">$' + Number(x.usd || 0).toFixed(2) + '</td><td>' + esc(x.state) + (x.note ? ' <span class="muted">' + esc(x.note) + '</span>' : '') + '</td><td>' + (x.tx ? '<a target="_blank" rel="noopener" href="' + esc(x.tx) + '">tx</a>' : '') + '</td></tr>').join('') + '</table>'
|
||||||
|
: (r.recipients || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Buys</th></tr>' + r.recipients.map(x => '<tr><td>#' + x.recipientId + '</td><td class="mono">' + Number(x.pol).toFixed(4) + '</td><td class="mono">$' + Number(x.usd).toFixed(2) + '</td><td>' + x.purchases + '</td></tr>').join('') + '</table>' : '');
|
||||||
|
}
|
||||||
|
if ($('ovShow')) $('ovShow').addEventListener('click', () => loadOverride($('ovWeek').value));
|
||||||
|
if ($('ovPay')) $('ovPay').addEventListener('click', async () => {
|
||||||
|
const wk = $('ovWeek').value;
|
||||||
|
if (!await IAP.confirmBox('This sends real POL from the payer wallet for every closed week up to the week containing ' + wk + ' that is not paid yet. Each member is paid once; anything already paid is skipped.', { title: 'Pay the override now?', ok: 'Pay now' })) return;
|
||||||
|
try { const r = await api('/api/admin/override/pay', { week: wk }); IAP.status('Override: ' + (r.results || []).map(x => x.week + ' ' + (x.state || x.held || (x.why || []).join(', '))).join(' · '), 'ok'); loadOverride(wk); } catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
|
});
|
||||||
if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
||||||
async function loadAudit() {
|
async function loadAudit() {
|
||||||
if (!$('audTable')) return;
|
if (!$('audTable')) return;
|
||||||
@@ -916,6 +966,7 @@
|
|||||||
+ v.messages.map(m => '<div style="border:1px solid ' + (m.internal ? 'rgba(242,201,76,.55)' : m.author === 'admin' ? 'rgba(67,232,195,.45)' : 'var(--line)') + ';background:' + (m.internal ? 'rgba(242,201,76,.07)' : m.author === 'admin' ? 'rgba(67,232,195,.05)' : 'transparent') + ';border-radius:12px;padding:10px 14px;margin:8px 0">'
|
+ v.messages.map(m => '<div style="border:1px solid ' + (m.internal ? 'rgba(242,201,76,.55)' : m.author === 'admin' ? 'rgba(67,232,195,.45)' : 'var(--line)') + ';background:' + (m.internal ? 'rgba(242,201,76,.07)' : m.author === 'admin' ? 'rgba(67,232,195,.05)' : 'transparent') + ';border-radius:12px;padding:10px 14px;margin:8px 0">'
|
||||||
+ '<div class="small muted" style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '</b><span>' + esc(ctWhen(m.created)) + '</span></div>'
|
+ '<div class="small muted" style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '</b><span>' + esc(ctWhen(m.created)) + '</span></div>'
|
||||||
+ '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:6px">' + spLink(m.body) + '</div>'
|
+ '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:6px">' + spLink(m.body) + '</div>'
|
||||||
|
+ (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '<p style="margin:8px 0 0"><button type="button" class="btn small sec" data-kbsave="' + m.id + '">Save as KB entry</button></p>' : '')
|
||||||
+ (m.bodyEn ? '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:8px;padding:8px 10px;border-left:3px solid var(--accent,#43e8c3);background:rgba(67,232,195,.07);border-radius:6px"><span class="small muted">🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)</span>\n' + spLink(m.bodyEn) + '</div>' : '')
|
+ (m.bodyEn ? '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:8px;padding:8px 10px;border-left:3px solid var(--accent,#43e8c3);background:rgba(67,232,195,.07);border-radius:6px"><span class="small muted">🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)</span>\n' + spLink(m.bodyEn) + '</div>' : '')
|
||||||
+ ((m.attachments || []).length ? '<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment" style="max-width:180px;max-height:140px;border-radius:8px;border:1px solid var(--line)"></a>').join('') + '</div>' : '') + '</div>').join('')
|
+ ((m.attachments || []).length ? '<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment" style="max-width:180px;max-height:140px;border-radius:8px;border:1px solid var(--line)"></a>').join('') + '</div>' : '') + '</div>').join('')
|
||||||
+ '</div>'
|
+ '</div>'
|
||||||
@@ -925,6 +976,12 @@
|
|||||||
+ '<p style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin:10px 0 0"><label class="small"><input type="checkbox" id="spInternal"> Internal note (only you see it, nothing is sent)</label>'
|
+ '<p style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin:10px 0 0"><label class="small"><input type="checkbox" id="spInternal"> Internal note (only you see it, nothing is sent)</label>'
|
||||||
+ '<label class="small muted">Then set status ' + sel('spAfter', stOpts, 'waiting_on_member') + '</label>'
|
+ '<label class="small muted">Then set status ' + sel('spAfter', stOpts, 'waiting_on_member') + '</label>'
|
||||||
+ '<button type="button" class="btn small" id="spSend">Send reply</button></p></div>';
|
+ '<button type="button" class="btn small" id="spSend">Send reply</button></p></div>';
|
||||||
|
$('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20)
|
||||||
|
const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return;
|
||||||
|
const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal);
|
||||||
|
const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body);
|
||||||
|
await setPane('kb'); window.IAPKB.compose(draft);
|
||||||
|
}));
|
||||||
$('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
$('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
||||||
const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } };
|
const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } };
|
||||||
$('spSt').addEventListener('change', () => patch({ status: $('spSt').value }));
|
$('spSt').addEventListener('change', () => patch({ status: $('spSt').value }));
|
||||||
@@ -1046,6 +1103,7 @@
|
|||||||
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
|
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
|
||||||
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
|
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
|
||||||
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
|
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
|
||||||
|
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
|
||||||
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
||||||
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
||||||
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
||||||
@@ -1161,10 +1219,19 @@
|
|||||||
+ (Q.byGame && Object.keys(Q.byGame).length ? '<p class="muted" style="margin:8px 0 0">By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '</p>' : '');
|
+ (Q.byGame && Object.keys(Q.byGame).length ? '<p class="muted" style="margin:8px 0 0">By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '</p>' : '');
|
||||||
// per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month
|
// per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month
|
||||||
const TS = r.tiers || {}, TC = S.tiers || {};
|
const TS = r.tiers || {}, TC = S.tiers || {};
|
||||||
$('gpTiersSub').textContent = 'Explorer + Champion sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' monthly sales';
|
$('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales';
|
||||||
$('gpTiers').innerHTML = '<table class="adm-table"><tr><th>Tier</th><th>Price</th><th class="num">Active</th><th class="num">Sold week</th><th class="num">Sold month</th><th class="num">All time</th><th class="num">Renewals 30d</th><th class="num">Ending in 7 days</th><th class="num">Comped</th><th class="num">Waiting</th></tr>'
|
$('gpTiers').innerHTML = '<table class="adm-table"><tr><th>Tier</th><th>Price</th><th class="num">Active</th><th class="num">Sold week</th><th class="num">Sold month</th><th class="num">All time</th><th class="num">Renewals 30d</th><th class="num">Ending in 7 days</th><th class="num">Comped</th><th class="num">Waiting</th></tr>'
|
||||||
+ ['weekly', 'explorer', 'champion'].map(k => { const x = TS[k] || {}, c = TC[k] || {}; return '<tr><td style="white-space:nowrap">' + esc(x.name || k) + (c.sale ? '' : '<br><span class="chip flat">not on sale</span>') + '</td><td style="white-space:nowrap">' + (c.price || 0) + ' cr · ' + (c.days || 0) + ' d</td><td class="num">' + (x.active || 0) + '</td><td class="num">' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '</td><td class="num">' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '</td><td class="num">' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '</td><td class="num">' + (x.renewals30d || 0) + '</td><td class="num">' + (x.expiring7d || 0) + '</td><td class="num">' + (x.comped || 0) + '</td><td class="num">' + (x.waitingOrders || 0) + '</td></tr>'; }).join('')
|
+ (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return '<tr><td style="white-space:nowrap">' + esc(x.name || k) + (c.sale ? '' : '<br><span class="chip flat">not on sale</span>') + '</td><td style="white-space:nowrap">' + (c.price || 0) + ' cr<br>' + (c.days || 0) + ' d</td><td class="num">' + (x.active || 0) + '</td><td class="num">' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '</td><td class="num">' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '</td><td class="num">' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '</td><td class="num">' + (x.renewals30d || 0) + '</td><td class="num">' + (x.expiring7d || 0) + '</td><td class="num">' + (x.comped || 0) + '</td><td class="num">' + (x.waitingOrders || 0) + '</td></tr>'; }).join('')
|
||||||
+ '</table><p class="muted" style="margin:8px 0 0">Every tier gets the same pass caps (no extra POL). Monthly tiers add Shards of Valor islands and looks only.</p>';
|
+ '</table><p class="muted" style="margin:8px 0 0">Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).</p>';
|
||||||
|
// pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled)
|
||||||
|
const PM = P.pay || {}, SL = r.sales || [];
|
||||||
|
$('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')'
|
||||||
|
+ ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')';
|
||||||
|
const txLink = h => h ? '<a href="/tx/' + esc(h) + '" target="_blank" rel="noopener">' + esc(String(h).slice(0, 10)) + '…</a>' : '';
|
||||||
|
$('gpSales').innerHTML = !SL.length ? '<p class="muted">No pass sold yet.</p>' : '<table class="adm-table"><tr><th>When</th><th>Member</th><th>Pass</th><th>Paid by</th><th class="num">Pass</th><th class="num">Package</th><th>Package tx</th></tr>'
|
||||||
|
+ SL.map(x => '<tr><td style="white-space:nowrap">' + when(x.ts) + '</td><td>' + esc(x.email) + '</td><td>' + esc(x.name || x.tier) + '</td><td>' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + '</td><td class="num">' + usd(x.usd) + '</td><td class="num">' + (x.packageUsd ? usd(x.packageUsd) : '') + '</td><td>' + txLink(x.tx) + '</td></tr>').join('')
|
||||||
|
+ '</table>';
|
||||||
|
await loadGpTest();
|
||||||
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
|
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
|
||||||
const L = T.last;
|
const L = T.last;
|
||||||
$('gpTour').innerHTML = !L ? '<p class="muted">No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).</p>'
|
$('gpTour').innerHTML = !L ? '<p class="muted">No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).</p>'
|
||||||
@@ -1172,6 +1239,53 @@
|
|||||||
+ (L.winners && L.winners.length ? '<table class="adm-table">' + L.winners.map(w => '<tr><td>#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '</td><td>' + w.score + ' plays</td><td class="num">' + pol(w.pol) + ' POL</td><td>' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '</td></tr>').join('') + '</table>' : '<p class="muted">No pass holder reported any plays that week.</p>')
|
+ (L.winners && L.winners.length ? '<table class="adm-table">' + L.winners.map(w => '<tr><td>#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '</td><td>' + w.score + ' plays</td><td class="num">' + pol(w.pol) + ' POL</td><td>' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '</td></tr>').join('') + '</table>' : '<p class="muted">No pass holder reported any plays that week.</p>')
|
||||||
+ ((T.history || []).length > 1 ? '<p class="muted" style="margin:8px 0 0">Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '</p>' : '');
|
+ ((T.history || []).length > 1 ? '<p class="muted" style="margin:8px 0 0">Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '</p>' : '');
|
||||||
}
|
}
|
||||||
|
// Tier test and preview (2026-10-25, Marty): the member Games card shows the admin exactly what a member sees, so every tier test lives
|
||||||
|
// here. Every action touches ONLY the signed-in admin's own account; a test buy opens the same waiting order a member gets (a fresh
|
||||||
|
// package on /my fulfils it, sponsors paid as usual), a test comp starts the tier at once with no sale recorded.
|
||||||
|
async function loadGpTest() {
|
||||||
|
const box = $('gpTest'); if (!box) return;
|
||||||
|
let g; try { g = await api('/api/admin/gamepass/preview'); } catch (e) { box.innerHTML = '<p class="muted">' + esc(e.message) + '</p>'; return; }
|
||||||
|
const ct = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
|
||||||
|
const len = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
|
||||||
|
const rows = g.passes || [];
|
||||||
|
$('gpTestSub').textContent = 'TEST / PREVIEW · admin only · acts on your own account: ' + g.email;
|
||||||
|
const card = r => {
|
||||||
|
const sale = r.tier === 'weekly' ? !!g.enabled : !!r.sale;
|
||||||
|
const st = r.active ? '<b>Your account: active until ' + esc(ct(r.until)) + '</b>' : r.waiting ? '<b>Your account: test order waiting for a $' + r.package + ' package</b>' : 'Your account: not active';
|
||||||
|
const acts = (r.waiting ? '<a class="btn small" href="/my?from=gamepass#buy" target="_blank" rel="noopener">Buy the $' + r.package + ' package on /my</a><button class="btn small sec" type="button" data-gpt-cancel="' + esc(r.tier) + '">Cancel test order</button>'
|
||||||
|
: '<button class="btn small" type="button" data-gpt-buy="' + esc(r.tier) + '">Test buy (real order, $' + r.package + ' package)</button>')
|
||||||
|
+ '<button class="btn small sec" type="button" data-gpt-comp="' + esc(r.tier) + '">Give my account ' + esc(r.name) + ' now (test)</button>'
|
||||||
|
+ (r.active ? '<button class="btn small sec" type="button" data-gpt-end="' + esc(r.tier) + '">End my ' + esc(r.name) + ' now</button>' : '');
|
||||||
|
return '<div class="gpt-tier' + (r.active ? ' on' : '') + '"><h4>' + esc(r.name) + ' <span class="chip flat">' + (sale ? 'on sale: members see it' : 'hidden from members') + '</span></h4>'
|
||||||
|
+ '<p class="gpt-price">$' + r.usd + ' <span class="small muted">for ' + len(r.days) + '</span></p>'
|
||||||
|
+ '<ul>' + (r.perks || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
|
||||||
|
+ '<p class="small" style="margin:4px 0">' + st + '</p><div class="gpt-acts">' + acts + '</div></div>';
|
||||||
|
};
|
||||||
|
box.innerHTML = '<p class="gpt-note"><b>Test / preview, admin only.</b> ' + (g.tierPreview ? 'The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings (it stays off until the paid tiers launch). ' : '')
|
||||||
|
+ 'These are the tier cards as members will see them. Every button here acts on your own account (' + esc(g.email) + ') and nobody else’s. The member Games card on /my shows you exactly what a member sees: while you hold a test tier it shows that tier the way it would for any member who holds one.</p>'
|
||||||
|
+ '<div class="gpt-grid">' + rows.map(card).join('') + '</div>'
|
||||||
|
+ '<p class="muted" style="margin:10px 0 0"><b>Test buy</b> opens the same waiting order a member gets: a fresh package of at least the price, bought on /my by one of your positions, starts it (sponsors paid as usual). Cancel a test order you will not pay, or a later real package of that size fulfils it. <b>Give my account</b> starts one pass period at once, recorded as comped (no sale); <b>End</b> stops it. '
|
||||||
|
+ 'To test it in game, open <b>Shards of Valor > Passes</b> (key P) after signing in to the game again from /my Games: the game reads your highest tier from InstantAdPay at sign-in.</p>';
|
||||||
|
const tierName = k => (rows.find(r => r.tier === k) || {}).name || k;
|
||||||
|
box.querySelectorAll('[data-gpt-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||||
|
const k = b.dataset.gptBuy; const r = rows.find(x => x.tier === k);
|
||||||
|
if (!(await IAP.confirmBox('Open a TEST order for ' + tierName(k) + ' on your own account (' + g.email + ')? It starts when a fresh $' + r.package + ' or bigger package from one of your positions settles on chain. Members still cannot see or buy this tier.', { title: 'Test buy: ' + tierName(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
|
||||||
|
const x = await api('/api/admin/gamepass/test-buy', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
|
||||||
|
})));
|
||||||
|
box.querySelectorAll('[data-gpt-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||||
|
const k = b.dataset.gptCancel; await api('/api/admin/gamepass/test-cancel', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' cancelled.', 'ok'); await loadGpTest();
|
||||||
|
})));
|
||||||
|
box.querySelectorAll('[data-gpt-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||||
|
const k = b.dataset.gptComp;
|
||||||
|
if (!(await IAP.confirmBox('Give your own account (' + g.email + ') one ' + tierName(k) + ' period now, for testing? It is recorded as comped (no sale) and shows in the game the next time you sign in to it.', { title: 'Test ' + tierName(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
|
||||||
|
const x = await api('/api/admin/gamepass/test-comp', { tier: k }); IAP.status(tierName(k) + ' on your account until ' + when(x.until) + ' (test).', 'ok'); await loadGamePass();
|
||||||
|
})));
|
||||||
|
box.querySelectorAll('[data-gpt-end]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||||
|
const k = b.dataset.gptEnd;
|
||||||
|
if (!(await IAP.confirmBox('End ' + tierName(k) + ' on your own account now?', { title: 'End test tier', ok: 'End it now', cancel: 'Keep it' }))) return;
|
||||||
|
await api('/api/admin/gamepass/revoke', { email: g.email, tier: k, why: 'admin tier test' }); IAP.status(tierName(k) + ' on your account ended.', 'ok'); await loadGamePass();
|
||||||
|
})));
|
||||||
|
}
|
||||||
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
|
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
|
||||||
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
|
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
|
||||||
$('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => {
|
$('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => {
|
||||||
|
|||||||
+12
-1
@@ -93,7 +93,7 @@ window.IAP = (function () {
|
|||||||
case 'AdminPaid': return '🏛 platform fee settled: ' + pol(ev.amountWei);
|
case 'AdminPaid': return '🏛 platform fee settled: ' + pol(ev.amountWei);
|
||||||
case 'BuyerCounted': return '⭐ ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)';
|
case 'BuyerCounted': return '⭐ ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)';
|
||||||
case 'MemberActivated': return '👤 ' + nm(ev.id) + ' activated a payout wallet';
|
case 'MemberActivated': return '👤 ' + nm(ev.id) + ' activated a payout wallet';
|
||||||
case 'AwardPaid': return '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
|
case 'AwardPaid': return ev.override ? '🏅 Level 4 override' + (ev.overrideWeek ? ' (week of ' + ev.overrideWeek + ')' : '') + ': ' + pol(ev.amountWei) + ' → ' + nm(ev.toId) : '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
|
||||||
case 'CreditsConsumed': return '📣 ' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits';
|
case 'CreditsConsumed': return '📣 ' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits';
|
||||||
case 'PriceCached': return '🔮 oracle price refreshed';
|
case 'PriceCached': return '🔮 oracle price refreshed';
|
||||||
case 'FallbackPriceUsed': return '🔮 cached price bridged an oracle gap';
|
case 'FallbackPriceUsed': return '🔮 cached price bridged an oracle gap';
|
||||||
@@ -284,3 +284,14 @@ window.IAP = (function () {
|
|||||||
if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; }
|
if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||||
}, true);
|
}, true);
|
||||||
})();
|
})();
|
||||||
|
// Level 4 override copy (2026-10-23): blocks marked data-when="override-live" stay hidden until the site setting
|
||||||
|
// overrideMode is 'live' and overrideGoLive is set; [data-ov-start] gets the start date in Central time
|
||||||
|
(function () {
|
||||||
|
var els = document.querySelectorAll('[data-when="override-live"]'); if (!els.length || !window.IAP) return;
|
||||||
|
IAP.getConfig().then(function (c) {
|
||||||
|
if (String(c.overrideMode || '') !== 'live' || !Number(c.overrideGoLive)) return;
|
||||||
|
var d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' });
|
||||||
|
document.querySelectorAll('[data-ov-start]').forEach(function (e) { e.textContent = d; });
|
||||||
|
els.forEach(function (e) { e.hidden = false; });
|
||||||
|
}).catch(function () {});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// Conversion tracking guide (/conversion-tracking, 2026-10-24): the Copy buttons on the code examples. Copies the text of
|
||||||
|
// the <pre> in the same box (placeholders included). Frame handling (traffic exchanges) is common.js's, like every page.
|
||||||
|
(function () {
|
||||||
|
function flash(b, t) { var o = b.getAttribute('data-label') || b.textContent; b.setAttribute('data-label', o); b.textContent = t; setTimeout(function () { b.textContent = o; }, 1600); }
|
||||||
|
document.querySelectorAll('[data-copy]').forEach(function (b) {
|
||||||
|
b.addEventListener('click', function () {
|
||||||
|
var box = b.closest('.cg-code'); var pre = box && box.querySelector('pre'); if (!pre) return;
|
||||||
|
var text = pre.textContent;
|
||||||
|
var done = function () { flash(b, 'Copied'); };
|
||||||
|
var fallback = function () {
|
||||||
|
try { var r = document.createRange(); r.selectNodeContents(pre); var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); var ok = document.execCommand && document.execCommand('copy'); flash(b, ok ? 'Copied' : 'Selected'); }
|
||||||
|
catch (e) { flash(b, 'Select and copy'); }
|
||||||
|
};
|
||||||
|
try { if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fallback); else fallback(); } catch (e) { fallback(); }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// The Engine Room (2026-10-24). The SAME file ships in InstantAdPay (Members > Engine Room) and LinkSpin (Ads screen panel).
|
||||||
|
// Plain dials, real numbers, colour only for warnings. Renders into #erRoot from /api/my/engine; hidden while the
|
||||||
|
// refuelStreak switch is off. Unlocked by the first counted refuel, greyed "Refuel to start your engine" until then.
|
||||||
|
(function () {
|
||||||
|
const root = document.getElementById('erRoot'); if (!root) return;
|
||||||
|
const host = document.getElementById(root.dataset.host || 'erPanel');
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||||
|
// a link on this site becomes a plain path; a link to the other site carries ?from=<this site>&task=<job> so the other
|
||||||
|
// site opens with an arrival strip naming the job and its first step (2026-10-25, Marty lost the thread on LinkSpin)
|
||||||
|
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
||||||
|
let FROM = 'iap';
|
||||||
|
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
||||||
|
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return u.href; } catch (e) { return url; } };
|
||||||
|
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
||||||
|
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
||||||
|
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
||||||
|
return ' <a href="' + esc(go(url, 'refuel')) + '">Refuel ' + m[1] + (ext(url) ? ' ↗' : '') + '</a>'; };
|
||||||
|
const ext = url => { try { const u = new URL(url); return u.host !== location.host && siteOf(u) !== FROM; } catch (e) { return false; } };
|
||||||
|
const css = '.er{display:grid;gap:14px}.er-locked{opacity:.45;filter:grayscale(1);pointer-events:none}.er-dials{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr));gap:12px}'
|
||||||
|
+ '.er-dial{border:1px solid rgba(127,127,127,.3);border-radius:10px;padding:10px 12px;text-align:center;min-width:0}.er-dial svg{width:100%;max-width:200px;height:auto;display:block;margin:0 auto}'
|
||||||
|
+ '.er-dial .v{font-size:22px;font-weight:700;margin-top:-6px}.er-dial .c{font-size:12px;opacity:.8}.er-row{display:flex;flex-wrap:wrap;gap:8px}'
|
||||||
|
+ '.er-light{display:flex;gap:6px;align-items:center;border:1px solid rgba(127,127,127,.3);border-radius:999px;padding:4px 10px;font-size:12.5px}.er-dot{width:10px;height:10px;border-radius:50%;background:rgba(127,127,127,.45);flex:none}'
|
||||||
|
+ '.er-dot.on{background:#e8a317}.er-dot.green{background:#2fa36b}.er-dot.amber{background:#e8a317}.er-dot.grey{background:rgba(127,127,127,.45)}.er-parts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:8px}'
|
||||||
|
+ '.er-part{border:1px solid rgba(127,127,127,.3);border-radius:8px;padding:8px 10px;font-size:13px;display:grid;gap:3px;min-width:0}.er-part b{display:flex;flex-wrap:wrap;gap:2px 6px;align-items:center}.er-next{border:1px solid rgba(127,127,127,.4);border-radius:10px;padding:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}'
|
||||||
|
+ '.er-next .w{flex:1 1 220px;font-size:13px}.er-h{font-size:12px;letter-spacing:.06em;text-transform:uppercase;opacity:.75;margin:0}.er-streak{font-size:13.5px;line-height:1.5}.er-goal{display:flex;gap:6px;align-items:center;justify-content:center;margin-top:6px;font-size:12px}.er-goal input{width:70px}';
|
||||||
|
if (!document.getElementById('erCss')) { const st = document.createElement('style'); st.id = 'erCss'; st.textContent = css; document.head.appendChild(st); }
|
||||||
|
// a plain 180-degree dial; pct null = no reading
|
||||||
|
function dial(pct, value, caption, aria, warn) {
|
||||||
|
const p = pct == null ? 0 : Math.max(0, Math.min(100, pct));
|
||||||
|
const a = Math.PI * (1 - p / 100); const x = 100 + 80 * Math.cos(a), y = 100 - 80 * Math.sin(a);
|
||||||
|
const col = warn ? '#e8a317' : 'currentColor';
|
||||||
|
return '<div class="er-dial" role="img" aria-label="' + esc(aria) + '"><svg viewBox="0 0 200 112" aria-hidden="true"><path d="M20 100 A80 80 0 0 1 180 100" fill="none" stroke="rgba(127,127,127,.3)" stroke-width="14" stroke-linecap="round"/>'
|
||||||
|
+ (pct == null ? '' : '<path d="M20 100 A80 80 0 0 1 ' + x.toFixed(1) + ' ' + y.toFixed(1) + '" fill="none" stroke="' + col + '" stroke-width="14" stroke-linecap="round"/>') + '</svg>'
|
||||||
|
+ '<div class="v">' + esc(value) + '</div><div class="c">' + caption + '</div></div>';
|
||||||
|
}
|
||||||
|
function view(d) {
|
||||||
|
const f = d.fuel, c = d.clicks, g = d.goals, s = d.streak;
|
||||||
|
const fuelCap = (f.refuelCredits ? n(f.left) + ' of ' + n(f.refuelCredits) + ' credits this cycle' : n(f.left) + ' credits on both sites') + (f.daysLeft != null ? '<br>about ' + n(f.daysLeft) + ' days at your burn (' + n(f.burnPerDay) + ' a day)' : '');
|
||||||
|
const fuelAria = 'Fuel left: ' + n(f.left) + ' credits' + (f.pct != null ? ', ' + f.pct + ' percent of this cycle’s refuel' : '') + (f.daysLeft != null ? ', about ' + f.daysLeft + ' days at your current burn' : '');
|
||||||
|
const clickCap = (c.prevWeek ? 'last week: ' + n(c.prevWeek) + ' (half way = the same)<br>' : '') + (c.per1000 != null ? n(c.per1000) + ' clicks per 1,000 credits' : 'clicks per 1,000 credits: not enough delivery yet') + '<br>all ads, both sites';
|
||||||
|
const goalCap = (g.month == null ? 'LinkSpin did not answer' : g.tracking ? (g.target ? 'goal: ' + n(g.target) + ' this month' : 'set a goal for the month') : 'set up conversion tracking') + '<span class="er-goal"><label>goal <input type="number" min="0" max="100000" data-er-goal value="' + (g.target || '') + '" aria-label="Your goal for this month"></label><button class="btn small sec" type="button" data-er-save>Save</button></span>';
|
||||||
|
const dials = '<div class="er-dials">'
|
||||||
|
+ dial(f.pct, f.pct != null ? f.pct + '%' : n(f.left), 'Fuel left<br>' + fuelCap, fuelAria, f.daysLeft != null && f.daysLeft < 5)
|
||||||
|
+ dial(c.pct, n(c.week), 'Clicks this week<br>' + clickCap, 'Clicks this week: ' + n(c.week) + (c.prevWeek ? ', last week ' + n(c.prevWeek) : '') + (c.per1000 != null ? ', ' + c.per1000 + ' per 1,000 credits' : ''), false)
|
||||||
|
+ dial(g.pct, g.month == null ? '?' : n(g.month), 'Goals this month<br>' + goalCap, 'Goals this month: ' + (g.month == null ? 'unknown' : g.month) + (g.target ? ' of ' + g.target : ''), false) + '</div>';
|
||||||
|
const streak = '<div class="er-streak"><p class="er-h">Streak</p>' + (s.active ? '<b>' + s.months + ' month' + (s.months === 1 ? '' : 's') + '</b>' + (s.both ? ', both engines this cycle' : '') + '. Refuel day <b>' + esc(s.refuelDay) + '</b>, grace to ' + esc(s.graceEnd) + ' (Central).'
|
||||||
|
+ (typeof s.note === 'string' ? (s.note ? ' ' + esc(s.note) + otherBuy(s.note) : '') : s.next ? (s.windowOpen ? ' Window open: next refuel +' + s.next.single + '% (+' + s.next.both + '% on each with both).' : s.both ? ' Both engines fueled this cycle.' : s.next.secondEngine ? ' Refuel the other site this cycle for +' + s.next.secondEngine + '% on both.' : '') : '') // s.note from engine.js (2026-10-24: no 'refuel the other site' once both are done)
|
||||||
|
+ (s.pitStop ? ' Pit Stop: +' + s.pitStop.pct + '% ' + (s.pitStop.iap || s.pitStop.linkspin ? 'available' : 'used') + ' this cycle.' : '') + (s.best > s.months ? ' Best: ' + s.best + '.' : '') : 'Not started.') + '</div>';
|
||||||
|
const warns = '<div><p class="er-h">Warning lights</p><div class="er-row">' + d.warnings.map(w => '<span class="er-light" title="' + esc(w.note) + '"><span class="er-dot' + (w.on ? ' on' : '') + '" aria-hidden="true"></span>' + esc(w.label) + ': ' + (w.on ? '<b>on</b>' : 'off') + '<span class="sr" style="position:absolute;left:-9999px"> (' + esc(w.note) + ')</span></span>').join('') + '</div></div>';
|
||||||
|
const parts = '<div><p class="er-h">The six parts</p><div class="er-parts">' + d.parts.map(p => '<div class="er-part"><b><span class="er-dot ' + p.state + '" aria-hidden="true"></span>' + esc(p.label) + ' <span style="font-weight:400;opacity:.75">(' + (p.state === 'green' ? 'working' : p.state === 'amber' ? 'needs attention' : 'not started') + ')</span></b><span>' + esc(p.note) + '</span>'
|
||||||
|
+ (p.state !== 'green' && p.link ? '<a href="' + esc(go(p.link, p.key)) + '">' + (p.state === 'grey' ? 'Set it up' : 'Fix it') + (ext(p.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') + ' ↗' : '') + '</a>' : '') + '</div>').join('') + '</div></div>';
|
||||||
|
const nextLink = go(d.next.link, TASK[d.next.key]);
|
||||||
|
const next = '<div class="er-next"><div class="w"><p class="er-h">Next move</p><b>' + esc(d.next.label) + '</b><br>' + esc(d.next.why)
|
||||||
|
+ (d.next.guide ? '<br><a href="' + esc(d.next.guide) + '" target="_blank" rel="noopener" style="font-size:12.5px">' + (d.next.key === 'tracking' ? 'Step-by-step setup guide' : 'How the Refuel streak works') + '</a>' : '') + '</div>'
|
||||||
|
+ '<a class="btn' + (d.locked ? '' : ' pri') + '" href="' + esc(nextLink) + '">' + esc(d.next.label) + (ext(d.next.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') : '') + '</a></div>';
|
||||||
|
const how = d.next.guide === '/refuel' ? '' : '<p style="margin:0;font-size:12.5px"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
|
||||||
|
if (d.locked) return '<div class="er">' + next + how + '<div class="er-locked" aria-hidden="true">' + dials + warns + parts + '</div></div>';
|
||||||
|
return '<div class="er">' + next + dials + streak + how + warns + parts + '<p class="small muted" style="margin:0;font-size:12px;opacity:.75">Numbers cover InstantAdPay and LinkSpin together' + (d.sites && (!d.sites.iap || !d.sites.linkspin) ? ' (one site did not answer just now)' : '') + '. Credits buy ad delivery only.</p></div>';
|
||||||
|
}
|
||||||
|
async function load(fresh) {
|
||||||
|
try {
|
||||||
|
const d = await (await fetch('/api/my/engine' + (fresh ? '?fresh=1' : ''), { cache: 'no-store' })).json();
|
||||||
|
window.FUEL = window.FUEL || {}; window.FUEL.engine = d;
|
||||||
|
if (!d || !d.on) { if (host) host.hidden = true; return; }
|
||||||
|
if (host) host.hidden = false;
|
||||||
|
if (d.error) { root.innerHTML = '<p class="small muted">' + esc(d.error) + '</p>'; return; }
|
||||||
|
FROM = d.site === 'linkspin' ? 'linkspin' : 'iap';
|
||||||
|
root.innerHTML = view(d);
|
||||||
|
const save = root.querySelector('[data-er-save]');
|
||||||
|
if (save) save.addEventListener('click', async () => {
|
||||||
|
const v = root.querySelector('[data-er-goal]').value; save.disabled = true;
|
||||||
|
try { const r = await (await fetch('/api/my/engine/goal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ goal: Number(v) || 0 }) })).json(); if (r.error) throw new Error(r.error); load(true); }
|
||||||
|
catch (e) { save.disabled = false; save.textContent = 'Try again'; }
|
||||||
|
});
|
||||||
|
} catch (e) { if (host) host.hidden = true; }
|
||||||
|
}
|
||||||
|
window.ENGINE_ROOM = { load };
|
||||||
|
load(); setInterval(() => { if (!document.hidden) load(); }, 120000);
|
||||||
|
window.addEventListener('cr:signedin', () => load(true)); // LinkSpin's in-shell sign-in: the panel loaded signed out
|
||||||
|
})();
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// Fuel Your Offers (2026-10-24): the Refuel card on the Overview. Hidden while the refuelStreak switch is off
|
||||||
|
// (/api/my/refuel answers { on:false }). Everything here is ad credits, never cash.
|
||||||
|
(function () {
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||||
|
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||||
|
const goBuy = () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); else location.hash = '#buy'; };
|
||||||
|
window.FUEL = window.FUEL || {};
|
||||||
|
const HOW = '<p class="small" style="margin:8px 0 0"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
|
||||||
|
|
||||||
|
function siteLine(name, s, minUsd) {
|
||||||
|
if (s && s.refueled) return '<li><b>' + name + '</b>: refueled ' + esc(s.dayLabel ? 'on ' + s.dayLabel : '') + ', +' + s.pct + '% (' + n(s.bonus) + ' bonus credits)</li>';
|
||||||
|
return '<li><b>' + name + '</b>: not yet this cycle (a $' + minUsd + '+ package counts)</li>';
|
||||||
|
}
|
||||||
|
function cardHtml(v) {
|
||||||
|
const head = '<div class="card-head"><h3>⛽ Monthly Refuel</h3><span class="sub">' + (v.active ? 'streak: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') : 'not started') + '</span></div>';
|
||||||
|
if (!v.active) {
|
||||||
|
const lapsed = v.started ? '<p>Your last streak ended' + (v.misses && v.misses[0] ? ' after ' + esc(v.misses[0].day) : '') + '. Your next package of $' + v.minUsd.iap + '+ here (or $' + v.minUsd.linkspin + '+ on LinkSpin) starts it again at month 1.</p>' : '';
|
||||||
|
return head + (lapsed || '<p>Refuel your ads every month and the bonus grows. A package of <b>$' + v.minUsd.iap + ' or more</b> here, or $' + v.minUsd.linkspin + ' or more on LinkSpin, starts your streak and sets your own refuel day.</p>')
|
||||||
|
+ '<p class="small">Month 1 <b>+' + v.ladder.single[0] + '%</b> bonus ad credits, month 2 +' + v.ladder.single[1] + '%, month 3 +' + v.ladder.single[2] + '%, month 4 and up +' + v.ladder.single[3] + '%. Refuel both InstantAdPay and LinkSpin in the same cycle and each gets +' + v.ladder.both.join('%, +') + '%. It stacks on Five Dollar Friday and Wired Wednesday.</p>'
|
||||||
|
+ '<button class="btn" type="button" data-fuel-buy>Start my streak</button>' + HOW;
|
||||||
|
}
|
||||||
|
const c = v.cycle || {};
|
||||||
|
const when = v.windowOpen
|
||||||
|
? '<p><b>Your refuel window is open.</b> Refuel day: <b>' + esc(v.refuelDayLabel) + '</b>, grace to ' + esc(v.graceLabel) + ' (Central time). Your next refuel earns <b>+' + v.next.single + '%</b>, or +' + v.next.both + '% on each site when you refuel both.</p>'
|
||||||
|
: '<p>Next refuel day: <b>' + esc(v.refuelDayLabel) + '</b> (Central time). The window opens ' + esc(v.opensLabel) + ' and the grace runs to ' + esc(v.graceLabel) + '.</p>';
|
||||||
|
const sites = c.month ? '<p class="small" style="margin-bottom:2px">This cycle (month ' + c.month + (c.both ? ', both engines' : '') + '):</p><ul class="small" style="margin-top:0">' + siteLine('InstantAdPay', c.iap, v.minUsd.iap) + siteLine('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</ul>' : '';
|
||||||
|
let twin = '';
|
||||||
|
if (!v.windowOpen && c.month && !c.both) twin = '<p class="small">Refuel ' + (c.iap && c.iap.refueled ? 'LinkSpin ($' + v.minUsd.linkspin + '+)' : 'InstantAdPay ($' + v.minUsd.iap + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to <b>+' + v.next.secondEngine + '%</b>; the one you already refueled is topped up to match.'
|
||||||
|
// the second engine is on the other site: a direct way there (2026-10-25), landing on LinkSpin's Refuel panel with an arrival strip
|
||||||
|
+ (c.iap && c.iap.refueled ? ' <a href="https://linkspin.app/credits?from=iap&task=refuel#refuel" target="_blank" rel="noopener">Refuel LinkSpin ↗</a> (same email signs you in)' : '') + '</p>';
|
||||||
|
let pit = '';
|
||||||
|
if (v.pitStop) {
|
||||||
|
const here = v.pitStop.iap ? 'available here (+' + v.pitStop.pct + '% on a $' + v.minUsd.iap + '+ top-up, once this cycle)' : v.pitStop.usedIap ? 'used here this cycle' : null;
|
||||||
|
if (here) pit = '<p class="small"><b>Pit Stop:</b> ' + here + '. It keeps your ads running between refuel days; it does not count as your refuel.</p>';
|
||||||
|
}
|
||||||
|
const miss = '<p class="small muted">' + (v.freeMiss.available ? 'You have one free miss this year: if a grace passes, your streak is kept once.' : 'Your free miss for this year is used.') + (v.best > v.streak ? ' Best streak: ' + v.best + ' months.' : '') + '</p>';
|
||||||
|
return head + when + sites + twin + pit + miss + '<button class="btn" type="button" data-fuel-buy>' + (v.windowOpen ? 'Refuel now' : 'Buy a package') + '</button>' + HOW;
|
||||||
|
}
|
||||||
|
async function loadRefuelCard() {
|
||||||
|
const card = $('rfCard'); if (!card) return;
|
||||||
|
try {
|
||||||
|
const v = await (await fetch('/api/my/refuel', { cache: 'no-store' })).json();
|
||||||
|
window.FUEL.refuel = v;
|
||||||
|
if (!v || !v.on) { card.hidden = true; return; }
|
||||||
|
card.innerHTML = cardHtml(v); card.hidden = false;
|
||||||
|
card.querySelectorAll('[data-fuel-buy]').forEach(b => b.addEventListener('click', goBuy));
|
||||||
|
} catch (e) { card.hidden = true; }
|
||||||
|
}
|
||||||
|
window.FUEL.loadRefuelCard = loadRefuelCard;
|
||||||
|
loadRefuelCard(); setInterval(loadRefuelCard, 300000);
|
||||||
|
|
||||||
|
// ---- the Refuel Kit (Promo tools): this month's members-only banners, with your @name and a QR to your link ----
|
||||||
|
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||||
|
const IAP_SIZES = ['728x90', '300x250', '468x60', '160x600'];
|
||||||
|
let kitData = null;
|
||||||
|
async function render(month, size, variant) {
|
||||||
|
const r = await (await fetch('/api/my/kits/render', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ month, size, variant }) })).json();
|
||||||
|
if (r.error) throw new Error(r.error);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
// prefill the banner form under Campaigns with the kit image and the member's own link
|
||||||
|
function useInCampaign(r, month) {
|
||||||
|
const m = document.querySelector('.bo-menu [data-pane="campaigns"]'); if (m) m.click();
|
||||||
|
setTimeout(() => {
|
||||||
|
const set = (id, v, ev) => { const el = $(id); if (!el) return; el.value = v; el.dispatchEvent(new Event(ev || 'input', { bubbles: true })); };
|
||||||
|
set('cType', 'banner', 'change'); set('cSize', r.size, 'change');
|
||||||
|
set('cName', 'Refuel Kit ' + month + ' ' + r.size); set('cImage', r.abs); if (kitData && kitData.link) set('cTarget', kitData.link);
|
||||||
|
const el = $('cName'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
say('Banner form filled with your kit banner and your link. Set a budget and launch.', 'ok');
|
||||||
|
}, 250);
|
||||||
|
}
|
||||||
|
function kitHtml(k, d) {
|
||||||
|
const head = '<div class="card-head"><h3>Refuel Kit: ' + esc(k.label) + (k.theme ? ' · ' + esc(k.theme) : '') + '</h3><span class="sub">' + (k.unlocked ? 'yours' : 'locked') + '</span></div>';
|
||||||
|
if (!k.unlocked) return head + '<p class="small">Members-only banners for ' + esc(k.label) + '. Your next counted refuel unlocks them: a package of $20+ here, or $25+ on LinkSpin' + (d.nextRefuel ? ' (your refuel day: ' + esc(d.nextRefuel) + ')' : '') + '.</p>';
|
||||||
|
return head + '<p class="small">Five banners with your ' + esc(d.name || 'name') + ' and a QR code to your own link drawn on each one. They stay yours after the month ends.' + (k.gif ? ' Your streak also unlocks the animated version.' : '') + '</p>'
|
||||||
|
+ '<div class="kit-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px">'
|
||||||
|
+ k.sizes.filter(s => s.ready).map(s => '<div class="kit-cell" data-month="' + esc(k.month) + '" data-size="' + s.size + '" style="border:1px solid var(--line,#2a4650);border-radius:8px;padding:8px;min-width:0">'
|
||||||
|
+ '<div class="small muted">' + s.size + (s.size === '1200x630' ? ' (social posts)' : '') + '</div><div class="kit-img" style="margin:6px 0;min-height:30px"></div>'
|
||||||
|
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small" type="button" data-kit="make">Make mine</button>'
|
||||||
|
+ (k.gif && s.size !== '1200x630' ? '<button class="btn small sec" type="button" data-kit="gif">Animated</button>' : '') + '</div></div>').join('')
|
||||||
|
+ '</div>';
|
||||||
|
}
|
||||||
|
function cellReady(cell, r, month) {
|
||||||
|
const box = cell.querySelector('.kit-img');
|
||||||
|
box.innerHTML = '<img src="' + esc(r.url) + '" alt="Your ' + esc(r.size) + ' Refuel Kit banner" style="max-width:100%;height:auto;display:block">'
|
||||||
|
+ '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:6px"><a class="btn small sec" href="' + esc(r.url) + '" download>Download</a>'
|
||||||
|
+ '<button class="btn small sec" type="button" data-kit="copy">Copy image link</button>'
|
||||||
|
+ (IAP_SIZES.includes(r.size) ? '<button class="btn small" type="button" data-kit="use">Use in an IAP banner campaign</button>' : '') + '</div>';
|
||||||
|
box.querySelector('[data-kit="copy"]').addEventListener('click', () => { try { navigator.clipboard.writeText(r.abs); say('Image link copied.', 'ok'); } catch (e) { say(r.abs); } });
|
||||||
|
const u = box.querySelector('[data-kit="use"]'); if (u) u.addEventListener('click', () => useInCampaign(r, month));
|
||||||
|
}
|
||||||
|
async function loadKitCard() {
|
||||||
|
const card = $('rkCard'); if (!card) return;
|
||||||
|
try {
|
||||||
|
const d = await (await fetch('/api/my/kits', { cache: 'no-store' })).json();
|
||||||
|
kitData = d;
|
||||||
|
if (!d || !d.on || !d.kits || !d.kits.length) { card.hidden = true; return; }
|
||||||
|
card.innerHTML = d.kits.slice(0, 3).map(k => '<div class="rk-kit" style="margin-bottom:14px">' + kitHtml(k, d) + '</div>').join('')
|
||||||
|
+ (d.customNote ? '<p class="small"><b>Custom banners credit:</b> ' + esc(d.customNote) + '</p>' : '')
|
||||||
|
+ '<p class="small muted">Ad credits buy delivery only. No banner may promise income.</p>';
|
||||||
|
card.hidden = false;
|
||||||
|
card.querySelectorAll('.kit-cell button[data-kit]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
const cell = b.closest('.kit-cell'); b.disabled = true; const was = b.textContent; b.textContent = 'Drawing your banner...';
|
||||||
|
try { cellReady(cell, await render(cell.dataset.month, cell.dataset.size, b.dataset.kit === 'gif' ? 'gif' : 'still'), cell.dataset.month); }
|
||||||
|
catch (e) { say(e.message, 'err'); }
|
||||||
|
b.disabled = false; b.textContent = was;
|
||||||
|
}));
|
||||||
|
} catch (e) { card.hidden = true; }
|
||||||
|
}
|
||||||
|
window.FUEL.loadKitCard = loadKitCard;
|
||||||
|
loadKitCard();
|
||||||
|
})();
|
||||||
@@ -45,7 +45,7 @@
|
|||||||
IAP.status('Confirm the purchase in your wallet…');
|
IAP.status('Confirm the purchase in your wallet…');
|
||||||
// resolve the sponsor at buy time: a code referrer who activated since
|
// resolve the sponsor at buy time: a code referrer who activated since
|
||||||
// page load still gets locked in
|
// page load still gets locked in
|
||||||
const spNow = await (await fetch('/api/sponsor')).json();
|
const spNow = await (await fetch('/api/sponsor?intent=buy')).json(); // intent=buy: never held (Marty 2026-10-27)
|
||||||
const r = await IAPWallet.buy(Number(btn.dataset.id), spNow.sponsorId || 0, btn.dataset.cost);
|
const r = await IAPWallet.buy(Number(btn.dataset.id), spNow.sponsorId || 0, btn.dataset.cost);
|
||||||
if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
|
if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
|
||||||
IAP.status('Purchase settled on-chain. Credits are yours, payouts delivered. Watch it on the ledger.', 'ok');
|
IAP.status('Purchase settled on-chain. Credits are yours, payouts delivered. Watch it on the ledger.', 'ok');
|
||||||
|
|||||||
+344
-41
@@ -33,7 +33,51 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// holding tank activation hold (2026-10-27): no sponsor yet, so the activation waits for an adopter (24 hours at most)
|
||||||
|
let TANK_HOLD = null;
|
||||||
|
const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
|
||||||
|
function tankHoldText(h) {
|
||||||
|
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
|
||||||
|
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
// one-tap switch on payouts (2026-10-27): the tank assignment chat + emails link to /my?activate=1#wallet. The intent
|
||||||
|
// survives the sign-in and the wallet link (memory + sessionStorage) and runs the Activate button's own flow once.
|
||||||
|
const ACT_KEY = 'iap.activateIntent';
|
||||||
|
let ACT_INTENT = /[?&]activate=1(&|#|$)/.test(location.search);
|
||||||
|
try { if (ACT_INTENT) sessionStorage.setItem(ACT_KEY, String(Date.now())); else { const t = Number(sessionStorage.getItem(ACT_KEY)) || 0; ACT_INTENT = t > 0 && Date.now() - t < 3600000; } } catch (e) {}
|
||||||
|
function clearActIntent() {
|
||||||
|
ACT_INTENT = false; try { sessionStorage.removeItem(ACT_KEY); } catch (e) {}
|
||||||
|
try { if (/[?&]activate=1/.test(location.search)) { const q = location.search.replace(/([?&])activate=1(&|$)/, (m, a, b) => b ? a : '').replace(/^&/, '?').replace(/[?&]$/, ''); history.replaceState(null, '', location.pathname + q + location.hash); } } catch (e) {}
|
||||||
|
}
|
||||||
|
function actNote(text) {
|
||||||
|
let n = $('actIntentNote');
|
||||||
|
if (!n && text) { n = document.createElement('p'); n.id = 'actIntentNote'; n.className = 'small'; n.style.cssText = 'margin:8px 0;color:#22c55e;font-weight:600'; }
|
||||||
|
if (!n) return null;
|
||||||
|
n.hidden = !text; n.textContent = text || '';
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
async function runActivateIntent(me) {
|
||||||
|
if (!ACT_INTENT || runActivateIntent.started || !me || !me.signedIn) return;
|
||||||
|
if (me.memberId) { clearActIntent(); IAP.status('Your payouts are already switched on.', 'ok'); return; }
|
||||||
|
// never auto-start while the tank hold applies, a sponsor is blocked, or no real sponsor resolves (it would bind the fallback)
|
||||||
|
if (TANK_HOLD || me.tankHold || me.sponsorBlocked || !me.sponsorId || me.sponsorFallback || me.sponsorRouted) { clearActIntent(); return; }
|
||||||
|
const who = me.sponsorName || ('member #' + me.sponsorId);
|
||||||
|
setPane('wallet');
|
||||||
|
if (!me.address) { // link the wallet first; render() after the link comes back here and carries on
|
||||||
|
const n = actNote('Step 1: link your wallet (one free signature). Then switching on payouts with ' + who + ' starts by itself.');
|
||||||
|
if (n && $('linkBtn') && !n.isConnected) $('linkBtn').insertAdjacentElement('beforebegin', n);
|
||||||
|
if ($('linkCard')) $('linkCard').scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
runActivateIntent.started = true; clearActIntent();
|
||||||
|
const n = actNote('One free transaction switches on your payouts and locks ' + who + ' in as your sponsor. Confirm it in your wallet.');
|
||||||
|
if (n && !n.isConnected) $('activateBtn').insertAdjacentElement('beforebegin', n);
|
||||||
|
$('activateCard').scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
setTimeout(() => { if (!$('activateBtn').hidden && !$('activateBtn').disabled) $('activateBtn').click(); }, 400); // the Activate button's own flow (injected wallet, or the WalletConnect picker on a phone)
|
||||||
|
}
|
||||||
function nextMove(d) {
|
function nextMove(d) {
|
||||||
|
if (TANK_HOLD && d.address && !d.memberId) return tankHoldText(TANK_HOLD);
|
||||||
if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.';
|
if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.';
|
||||||
if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.';
|
if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.';
|
||||||
if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.';
|
if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $20 or more. Every direct pays you 50 percent from their very first package.';
|
||||||
@@ -81,7 +125,13 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
{ key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 },
|
{ key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 },
|
||||||
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 },
|
{ key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 },
|
||||||
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 },
|
{ key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 },
|
||||||
{ key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }
|
{ key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 },
|
||||||
|
{ key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 },
|
||||||
|
// Monthly Refuel badges (2026-10-24): final art, ribbon heights measured per image
|
||||||
|
{ key: 'refuelStart', label: 'Engine Started', sub: 'first monthly refuel', img: '/badges/badge-refuelstart.jpg?v=2', ribbonY: 0.735, earnedOnly: true },
|
||||||
|
{ key: 'refuel3', label: 'Refueled 3 months', sub: 'three monthly refuels in a row', img: '/badges/badge-refuel3.jpg?v=3', ribbonY: 0.783, earnedOnly: true },
|
||||||
|
{ key: 'refuel6', label: 'Refueled 6 months', sub: 'six monthly refuels in a row', img: '/badges/badge-refuel6.jpg?v=2', ribbonY: 0.716, earnedOnly: true },
|
||||||
|
{ key: 'refuel12', label: 'Refueled 12 months', sub: 'twelve monthly refuels in a row', img: '/badges/badge-refuel12.jpg?v=2', ribbonY: 0.744, earnedOnly: true }
|
||||||
];
|
];
|
||||||
let lastMilestones = [];
|
let lastMilestones = [];
|
||||||
function renderBadges(d) {
|
function renderBadges(d) {
|
||||||
@@ -90,7 +140,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
const strip = $('badgeStrip');
|
const strip = $('badgeStrip');
|
||||||
if (!strip) return;
|
if (!strip) return;
|
||||||
$('badgeCard').hidden = false;
|
$('badgeCard').hidden = false;
|
||||||
strip.innerHTML = BADGES.map(b => {
|
strip.innerHTML = BADGES.filter(b => !b.earnedOnly || reached.includes(b.key)).map(b => { // earnedOnly: shown once earned (refuel badges)
|
||||||
const got = reached.includes(b.key);
|
const got = reached.includes(b.key);
|
||||||
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
|
return '<div class="badge-a' + (got ? '' : ' locked') + '">'
|
||||||
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
|
+ '<img class="badge-img" src="' + b.img + '" alt="' + b.label + ' badge" loading="lazy">'
|
||||||
@@ -109,7 +159,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (d.milestonesGranted && d.milestonesGranted.length) {
|
if (d.milestonesGranted && d.milestonesGranted.length) {
|
||||||
const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0);
|
const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0);
|
||||||
const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', ');
|
const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', ');
|
||||||
IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok');
|
IAP.status('🏆 Achievement unlocked: ' + names + (total > 0 ? ': +' + total + ' bonus credits!' : '! See it in your badges.'), 'ok');
|
||||||
d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500));
|
d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -412,7 +462,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
}
|
}
|
||||||
bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({
|
bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({
|
||||||
v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6,
|
v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6,
|
||||||
label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1),
|
label: e.type === 'AwardPaid' ? (e.override ? 'L4' : 'award') : 'L' + (e.tier || 1),
|
||||||
tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' })));
|
tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' })));
|
||||||
if (!evs.length) $('chEarnSub').textContent = d.memberId
|
if (!evs.length) $('chEarnSub').textContent = d.memberId
|
||||||
? 'no payouts yet — share your link' : 'activate a package to start earning';
|
? 'no payouts yet — share your link' : 'activate a package to start earning';
|
||||||
@@ -636,8 +686,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')],
|
payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')],
|
||||||
package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)]
|
package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)]
|
||||||
}[cur.k];
|
}[cur.k];
|
||||||
$('gsNow').innerHTML = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p><button type="button" class="btn" id="gsGo">' + copy[2] + '</button>';
|
if (cur.k === 'payouts' && TANK_HOLD) { copy[0] = 'Matching you with a sponsor'; copy[1] = tankHoldText(TANK_HOLD); copy[2] = null; } // no activate button while held
|
||||||
$('gsGo').addEventListener('click', copy[3]);
|
$('gsNow').innerHTML = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p>' + (copy[2] ? '<button type="button" class="btn" id="gsGo">' + copy[2] + '</button>' : '');
|
||||||
|
if (copy[2]) $('gsGo').addEventListener('click', copy[3]);
|
||||||
card.hidden = false;
|
card.hidden = false;
|
||||||
}
|
}
|
||||||
// member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=<game>#buy.
|
// member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=<game>#buy.
|
||||||
@@ -685,6 +736,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
$('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString();
|
$('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString();
|
||||||
$('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : '');
|
$('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : '');
|
||||||
$('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0');
|
$('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0');
|
||||||
|
usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; });
|
||||||
$('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; }
|
$('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; }
|
||||||
$('dbTeam').textContent = (d.referrals || []).length;
|
$('dbTeam').textContent = (d.referrals || []).length;
|
||||||
// trend chips: only real, computable facts
|
// trend chips: only real, computable facts
|
||||||
@@ -751,7 +803,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
tn.hidden = !(tw && tw.count);
|
tn.hidden = !(tw && tw.count);
|
||||||
if (tw && tw.count) tn.innerHTML = '<b>' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank</b> \u00b7 '
|
if (tw && tw.count) tn.innerHTML = '<b>' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank</b> \u00b7 '
|
||||||
+ tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. <a href="#line">Adopt them from My line</a>'
|
+ tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. <a href="#line">Adopt them from My line</a>'
|
||||||
+ (tw.eligible ? '.' : ' (you need your own $20 package first).');
|
+ (tw.eligible ? '.' : ' (you need your own $20 package first).')
|
||||||
|
+ (tw.ready ? ' <b style="color:#22c55e">' + tw.ready + ' of them ' + (tw.ready === 1 ? 'has' : 'have') + ' linked a wallet and ' + (tw.ready === 1 ? 'is' : 'are') + ' ready to switch on payouts.</b>' : '');
|
||||||
}
|
}
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
// Share the presentation (2026-10-15): instantadpay.com/presentation?ref=<username> sets the same sponsor cookie as /join
|
// Share the presentation (2026-10-15): instantadpay.com/presentation?ref=<username> sets the same sponsor cookie as /join
|
||||||
@@ -789,13 +842,29 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── back-office menu: hash-routed panes ───────────────
|
// ── back-office menu: hash-routed panes ───────────────
|
||||||
const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile'];
|
const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile', 'engine']; // engine: the Engine Room (fuel.js, 2026-10-24)
|
||||||
const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns',
|
const TITLES = { engine: 'Engine Room', overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns',
|
||||||
earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games',
|
earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games',
|
||||||
wallet: 'Wallet & account', profile: 'Profile' };
|
wallet: 'Wallet & account', profile: 'Profile' };
|
||||||
|
// wait for a card that loads late, then scroll to it and flash it once (deep links from the Engine Room)
|
||||||
|
function focusCard(id, inputId) {
|
||||||
|
const t0 = Date.now();
|
||||||
|
const tick = () => {
|
||||||
|
const el = $(id);
|
||||||
|
if (!el || el.hidden || !el.offsetParent) { if (Date.now() - t0 < 20000) setTimeout(tick, 300); return; }
|
||||||
|
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||||
|
el.style.transition = 'box-shadow .4s'; el.style.boxShadow = '0 0 0 3px #45e3c4';
|
||||||
|
setTimeout(() => { el.style.boxShadow = ''; }, 2600);
|
||||||
|
const inp = inputId && $(inputId); if (inp && !inp.closest('[hidden]')) setTimeout(() => { try { inp.focus({ preventScroll: true }); } catch (e) {} }, 500);
|
||||||
|
};
|
||||||
|
setTimeout(tick, 150);
|
||||||
|
}
|
||||||
function setPane(name) {
|
function setPane(name) {
|
||||||
let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games)
|
let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games)
|
||||||
if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card
|
if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card
|
||||||
|
// /my#conversions (2026-10-25): the Engine Room's "Set up conversion tracking" opens Campaigns and lands ON the
|
||||||
|
// Conversion tracking card (it unhides once the campaign list has loaded), highlighted, with the goal name box focused
|
||||||
|
if (name === 'conversions') { name = 'campaigns'; focusCard('convCard', 'convName'); }
|
||||||
if (!PANES.includes(name)) name = 'overview';
|
if (!PANES.includes(name)) name = 'overview';
|
||||||
for (const p of PANES) {
|
for (const p of PANES) {
|
||||||
const el = $('pane-' + p);
|
const el = $('pane-' + p);
|
||||||
@@ -848,6 +917,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
$('memberArea').hidden = !signedIn;
|
$('memberArea').hidden = !signedIn;
|
||||||
if ($('mcFinish')) $('mcFinish').hidden = !walletOnly;
|
if ($('mcFinish')) $('mcFinish').hidden = !walletOnly;
|
||||||
if (!signedIn) return;
|
if (!signedIn) return;
|
||||||
|
TANK_HOLD = (!me.memberId && me.tankHold) || null;
|
||||||
if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL
|
if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL
|
||||||
if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews)
|
if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews)
|
||||||
// REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be
|
// REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be
|
||||||
@@ -862,6 +932,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }
|
if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }
|
||||||
if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02)
|
if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02)
|
||||||
if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13)
|
if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13)
|
||||||
|
if (me.returnTo === 'polminer' && !render.toGame) { render.toGame = true; location.href = '/api/my/polminer'; return; } // POL Miner sent them here to sign in (2026-10-28)
|
||||||
if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18)
|
if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18)
|
||||||
if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05)
|
if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05)
|
||||||
if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d);
|
if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d);
|
||||||
@@ -903,6 +974,10 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
loadPositions(me);
|
loadPositions(me);
|
||||||
$('linkCard').hidden = !!me.address;
|
$('linkCard').hidden = !!me.address;
|
||||||
$('activateCard').hidden = !(me.address && !me.memberId);
|
$('activateCard').hidden = !(me.address && !me.memberId);
|
||||||
|
{ let hn = $('tankHoldNote'); // held for an adopter: say so, and no activate button
|
||||||
|
if (!hn) { hn = document.createElement('p'); hn.id = 'tankHoldNote'; hn.className = 'small'; hn.style.cssText = 'margin:8px 0 0;color:#22c55e'; $('activateBtn').insertAdjacentElement('beforebegin', hn); }
|
||||||
|
hn.hidden = !TANK_HOLD; hn.textContent = TANK_HOLD ? tankHoldText(TANK_HOLD) : ''; $('activateBtn').hidden = !!TANK_HOLD; }
|
||||||
|
runActivateIntent(me).catch(() => {}); // arrived from the one-tap "Switch on payouts" link (tank assignment chat/email)
|
||||||
$('activityArea').hidden = !me.memberId;
|
$('activityArea').hidden = !me.memberId;
|
||||||
$('campGate').hidden = true; // earned credits fund campaigns for everyone
|
$('campGate').hidden = true; // earned credits fund campaigns for everyone
|
||||||
$('campaignCard').hidden = false;
|
$('campaignCard').hidden = false;
|
||||||
@@ -938,6 +1013,24 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here),
|
||||||
|
// shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day.
|
||||||
|
let USD = null;
|
||||||
|
async function usdRate() {
|
||||||
|
if (USD && Date.now() - USD.got < 120000) return USD;
|
||||||
|
try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; }
|
||||||
|
return USD;
|
||||||
|
}
|
||||||
|
function usdOf(wei, r) {
|
||||||
|
let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {}
|
||||||
|
const v = pol * ((r && r.usd) || 0);
|
||||||
|
return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
|
}
|
||||||
|
function usdNote(r) {
|
||||||
|
if (!r || !(r.usd > 0)) return '';
|
||||||
|
const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000));
|
||||||
|
return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.';
|
||||||
|
}
|
||||||
async function loadActivity() {
|
async function loadActivity() {
|
||||||
try {
|
try {
|
||||||
const c = await IAP.getConfig();
|
const c = await IAP.getConfig();
|
||||||
@@ -949,6 +1042,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
for (const ev of evs) el.appendChild(IAP.feedRow(ev, c));
|
for (const ev of evs) el.appendChild(IAP.feedRow(ev, c));
|
||||||
};
|
};
|
||||||
fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.');
|
fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.');
|
||||||
|
usdRate().then(r => {
|
||||||
|
const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r);
|
||||||
|
if (!(r.usd > 0)) return;
|
||||||
|
const rows = $('earnFeed').querySelectorAll('.row'); let i = 0;
|
||||||
|
for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); }
|
||||||
|
});
|
||||||
fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.');
|
fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.');
|
||||||
fill('buyFeed', a.purchases, 'No purchases from your wallet yet.');
|
fill('buyFeed', a.purchases, 'No purchases from your wallet yet.');
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
@@ -1037,11 +1136,109 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
pageList('credits', box, 'tbody tr');
|
pageList('credits', box, 'tbody tr');
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
|
// Campaigns > Conversion tracking (2026-10-23). Goals and counts come from LinkSpin through /api/my/conversions. Anything
|
||||||
|
// going wrong here only changes this card's own text: the campaign list never depends on it.
|
||||||
|
let convSel = null, convCamps = [];
|
||||||
|
const convFmt = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 1 });
|
||||||
|
function convSnips(host, g) {
|
||||||
|
const h = 'https://' + String(host || 'linkspin.app').replace(/^https?:\/\//, '').replace(/\/+$/, '');
|
||||||
|
const px = encodeURIComponent(g.px), goal = encodeURIComponent(g.name);
|
||||||
|
const val = Number(g.value) > 0 ? '&value=' + encodeURIComponent(g.value) : ''; // a goal with no default value (LinkSpin stores 0) adds nothing
|
||||||
|
return {
|
||||||
|
landing: '<script async src="' + h + '/t.js?px=' + px + '"></' + 'script>',
|
||||||
|
img: '<img src="' + h + '/cv.gif?px=' + px + '&goal=' + goal + val + '" width="1" height="1" alt="" style="display:none">',
|
||||||
|
js: '<script async src="' + h + '/cv.js?px=' + px + '&goal=' + goal + val + '"></' + 'script>'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const convBox = (id, label, text) => '<p class="small" style="margin:10px 0 4px"><b>' + label + '</b> <button class="btn small sec" type="button" data-convcopy="' + id + '">Copy</button></p>'
|
||||||
|
+ '<textarea id="' + id + '" readonly rows="2" style="width:100%;font-family:var(--mono);font-size:12px">' + esc(text) + '</textarea>';
|
||||||
|
function convCampLines(d) {
|
||||||
|
document.querySelectorAll('[data-convcamp]').forEach(el => { el.hidden = true; el.innerHTML = ''; });
|
||||||
|
if (!d || !d.ok || !(d.goals || []).length) return;
|
||||||
|
const by = d.byCampaign || {};
|
||||||
|
// cost per goal (30 days), 2026-10-26: goals are the last 30 days, so the spend is too. spend30 = credits each campaign
|
||||||
|
// spent in those days (credit activity log). A campaign started inside the window with no log rows uses its spend
|
||||||
|
// since it started (all of it is inside the window); otherwise no cost is shown rather than a lifetime figure.
|
||||||
|
const sp30 = d.spend30 || null, since = Number(d.spendSince) || (Date.now() - 30 * 86400000);
|
||||||
|
document.querySelectorAll('[data-convcamp]').forEach(el => {
|
||||||
|
const id = el.dataset.convcamp; const b = by[id]; const c = convCamps.find(x => String(x.id) === String(id)); if (!c) return;
|
||||||
|
let spent = null, basis = '';
|
||||||
|
if (sp30 && sp30[id] != null) { spent = Number(sp30[id]) || 0; basis = 'the credits it spent in the same 30 days'; }
|
||||||
|
else if (Number(c.created) >= since) { spent = Number(c.spent || 0); basis = 'the credits it spent since it started on ' + new Date(Number(c.created)).toLocaleDateString([], { month: 'short', day: 'numeric' }) + ', inside the 30 days'; }
|
||||||
|
const parts = d.goals.map(g => { const n = Number(b && b.conv && b.conv[g.px]) || 0;
|
||||||
|
return '<span>' + esc(g.name) + ' ' + n.toLocaleString() + (n > 0 && spent != null ? ' (' + convFmt(spent / n) + ' credits each)' : '') + '</span>'; });
|
||||||
|
el.innerHTML = '\u{1F3AF} <span class="muted">Goals and cost per goal (30 days):</span> ' + parts.join(' · ') + (spent == null ? ' <span class="muted">· no spend on record for these 30 days, so no cost per goal</span>' : '') + (b && b.clicks ? ' <span class="muted">· ' + Number(b.clicks).toLocaleString() + ' tracked clicks</span>' : '');
|
||||||
|
el.title = 'Goals counted for this campaign in the last 30 days. Cost per goal (30 days) = ' + (spent != null ? basis : 'the credits it spent in the same 30 days') + ', divided by those goals.';
|
||||||
|
el.hidden = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function loadConv(fresh) {
|
||||||
|
const card = $('convCard'); if (!card) return;
|
||||||
|
card.hidden = false;
|
||||||
|
let d = null;
|
||||||
|
try { d = await (await fetch('/api/my/conversions' + (fresh ? '?fresh=1' : ''))).json(); } catch (e) { d = { ok: false, error: 'Could not reach InstantAdPay just now. Try again in a minute.' }; }
|
||||||
|
convCampLines(d);
|
||||||
|
const st = $('convStatus'), list = $('convGoals'), snips = $('convSnips'), add = $('convAddRow');
|
||||||
|
if (!d || !d.ok) { st.textContent = (d && d.error) || 'Conversion tracking is not available right now.'; list.innerHTML = ''; snips.innerHTML = ''; add.hidden = !!(d && d.reason === 'off'); return; }
|
||||||
|
add.hidden = false;
|
||||||
|
const goals = d.goals || [];
|
||||||
|
const m = d.methods || {}; const mt = ['url', 'stored', 'cookie', 'soft'].reduce((s, k) => s + (Number(m[k]) || 0), 0);
|
||||||
|
const selfN = Number(d.selfTests) || 0; // own clicks (ads here, spin links and Banner Spins on LinkSpin), kept as tests
|
||||||
|
st.textContent = goals.length ? (mt ? 'How your conversions were matched (30 days): ' + ['url', 'stored', 'cookie', 'soft'].map(k => k + ' ' + Number(m[k] || 0).toLocaleString()).join(', ') + '.' : 'No conversions counted yet in the last 30 days.')
|
||||||
|
+ (selfN ? ' ' + selfN.toLocaleString() + ' from your own clicks, kept as tests and left out.' : '') : 'No goals yet. Add your first one below.';
|
||||||
|
if (!goals.length) { list.innerHTML = ''; snips.innerHTML = ''; return; }
|
||||||
|
if (!convSel || !goals.some(g => g.px === convSel)) convSel = goals[0].px;
|
||||||
|
const when = ts => ts ? new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : 'never';
|
||||||
|
list.innerHTML = '<div class="tablewrap"><table class="camp-table"><thead><tr><th>Goal</th><th class="num">Default value</th><th>Pixel id</th><th class="num">Conversions (30 days)</th><th>Last test</th><th></th></tr></thead><tbody>'
|
||||||
|
+ goals.map(g => '<tr' + (g.px === convSel ? ' style="background:rgba(120,160,255,.08)"' : '') + '><td data-l="Goal"><b>' + esc(g.name) + '</b></td>'
|
||||||
|
+ '<td class="num" data-l="Default value">' + (Number(g.value) > 0 ? esc(g.value) : '<span class="muted">none</span>') + '</td>'
|
||||||
|
+ '<td data-l="Pixel id" class="mono small">' + esc(g.px) + '</td>'
|
||||||
|
+ '<td class="num" data-l="Conversions (30 days)">' + Number(g.conv || 0).toLocaleString() + (g.lastAt ? '<div class="muted small">last ' + when(g.lastAt) + '</div>' : '') + '</td>'
|
||||||
|
+ '<td data-l="Last test" class="small">' + when(g.lastTest) + '</td>'
|
||||||
|
+ '<td class="act"><button class="btn small sec" type="button" data-convpick="' + esc(g.px) + '">Snippets</button> <button class="btn small sec" type="button" data-convtest="' + esc(g.px) + '">Send a test conversion</button> <button class="btn small quiet" type="button" data-convdel="' + esc(g.px) + '" data-convname="' + esc(g.name) + '">Remove</button></td></tr>').join('')
|
||||||
|
+ '</tbody></table></div>';
|
||||||
|
const g = goals.find(x => x.px === convSel); const sn = convSnips(d.host, g);
|
||||||
|
snips.innerHTML = '<h4 style="margin:14px 0 0">Snippets for <b>' + esc(g.name) + '</b></h4>'
|
||||||
|
+ convBox('convLanding', '1. Landing tag (the page your ad points to)', sn.landing)
|
||||||
|
+ convBox('convImg', '2. Goal pixel (your thank-you page)', sn.img)
|
||||||
|
+ '<details style="margin-top:8px"><summary class="small">Prefer the JS version of the goal pixel?</summary>'
|
||||||
|
+ '<p class="small muted" style="margin:6px 0 0">Use it where your page allows scripts. It also sends the click id the landing tag stored, which makes the count surer.</p>'
|
||||||
|
+ convBox('convJs', 'Goal pixel, JS version', sn.js) + '</details>';
|
||||||
|
list.querySelectorAll('[data-convpick]').forEach(b => b.addEventListener('click', () => { convSel = b.dataset.convpick; loadConv(); }));
|
||||||
|
// Send a test conversion (2026-10-26): loads the member's REAL pixel in test mode from this browser, the same request a
|
||||||
|
// thank-you page makes (LinkSpin answers X-LS-Result: test). If the browser blocks it, the signed partner call records the test.
|
||||||
|
list.querySelectorAll('[data-convtest]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
b.disabled = true; const px = b.dataset.convtest; let via = '';
|
||||||
|
const base = 'https://' + String(d.host || 'linkspin.app').replace(/^https?:\/\//, '').replace(/\/+$/, '');
|
||||||
|
try { const r = await fetch(base + '/cv.gif?px=' + encodeURIComponent(px) + '&test=1&r=' + Date.now(), { cache: 'no-store', mode: 'cors', credentials: 'omit' }); if (r.ok && /^test/.test(r.headers.get('X-LS-Result') || '')) via = 'pixel'; } catch (e) {}
|
||||||
|
if (!via) { try { await api('/api/my/conversions/test', { px }); via = 'relay'; } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; return; } }
|
||||||
|
IAP.status(via === 'pixel' ? 'Test conversion received by your real pixel. It shows under Last test and never counts in your numbers.' : 'Test conversion recorded through InstantAdPay (this browser did not load the pixel itself). It shows under Last test and never counts in your numbers.', 'ok');
|
||||||
|
await loadConv(true);
|
||||||
|
}));
|
||||||
|
list.querySelectorAll('[data-convdel]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
const yes = await IAP.confirmBox('Remove the goal "' + b.dataset.convname + '"? Its pixel stops counting. Pages that still carry it will simply be ignored.', { title: 'Remove goal', ok: 'Remove', cancel: 'Keep it' });
|
||||||
|
if (!yes) return; b.disabled = true;
|
||||||
|
try { await api('/api/my/conversions/goal', { op: 'remove', px: b.dataset.convdel }); IAP.status('Goal removed.', 'ok'); await loadConv(true); }
|
||||||
|
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
||||||
|
}));
|
||||||
|
snips.querySelectorAll('[data-convcopy]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
const ta = $(b.dataset.convcopy); try { await navigator.clipboard.writeText(ta.value); IAP.status('Copied. Paste it into your page.', 'ok'); } catch (e) { ta.select(); IAP.status('Selected. Press Ctrl+C (or long-press, Copy) to copy it.', 'ok'); }
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if ($('convAddBtn')) $('convAddBtn').addEventListener('click', async () => {
|
||||||
|
const b = $('convAddBtn'); const name = $('convName').value.trim(); const value = $('convValue').value.trim();
|
||||||
|
if (!name) { IAP.status('Give the goal a short name, like subscriber or sale.', 'bad'); return; }
|
||||||
|
b.disabled = true;
|
||||||
|
try { const r = await api('/api/my/conversions/goal', { op: 'create', name, value }); if (r.goal && r.goal.px) convSel = r.goal.px; $('convName').value = ''; $('convValue').value = ''; IAP.status('Goal added. Copy its two snippets below.', 'ok'); await loadConv(true); }
|
||||||
|
catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
|
b.disabled = false;
|
||||||
|
});
|
||||||
async function loadCampaigns() {
|
async function loadCampaigns() {
|
||||||
try {
|
try {
|
||||||
const r = await (await fetch('/api/my/campaigns')).json();
|
const r = await (await fetch('/api/my/campaigns')).json();
|
||||||
if (r.error) return;
|
if (r.error) return;
|
||||||
lastRates = r.rates;
|
lastRates = r.rates;
|
||||||
|
lastLoginLine = r.loginLine || null; loginLineHint();
|
||||||
if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.';
|
if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.';
|
||||||
// populate the banner-size dropdown once (ids map to NAS width/height)
|
// populate the banner-size dropdown once (ids map to NAS width/height)
|
||||||
if (r.bannerSizes && $('cSize') && !$('cSize').options.length)
|
if (r.bannerSizes && $('cSize') && !$('cSize').options.length)
|
||||||
@@ -1055,36 +1252,44 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if ($('spendNote')) $('spendNote').textContent = r.inCampaigns
|
if ($('spendNote')) $('spendNote').textContent = r.inCampaigns
|
||||||
? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.'
|
? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.'
|
||||||
: 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.';
|
: 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.';
|
||||||
$('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', r.rates.loginCreditsPerDay + ' cr / day'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '<span><b>' + x[0] + '</b> ' + x[1] + '</span>').join('');
|
$('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', Number(r.rates.loginSlotCredits || 1000).toLocaleString() + ' cr / ' + (r.rates.loginSlotDays || 30) + '-day slot'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].concat(Number(r.rates.synRateDivisor) > 1 ? [['Network', '1/' + Math.floor(Number(r.rates.synRateDivisor)) + ' of the rate']] : []).map(x => '<span><b>' + x[0] + '</b> ' + x[1] + '</span>').join('');
|
||||||
}
|
}
|
||||||
$('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString()
|
$('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString()
|
||||||
+ ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '')
|
+ ((r.earnedCredits || r.earnedReserved) ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + (r.earnedCredits || 0) + ' earned' + (r.earnedReserved ? ', ' + r.earnedReserved.toLocaleString() + ' more earned and bonus credits already working inside your live campaigns' : '') + ')' : '')
|
||||||
+ (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '')
|
+ (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '')
|
||||||
+ ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch
|
+ ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch
|
||||||
+ ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch
|
+ ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch
|
||||||
+ ' views, login ' + r.rates.loginCreditsPerDay + 'cr/day, solo '
|
+ ' views, login ' + Number(r.rates.loginSlotCredits || 1000).toLocaleString() + 'cr per ' + (r.rates.loginSlotDays || 30) + '-day slot, solo '
|
||||||
+ (r.rates.soloCostPerRecipient || 5) + 'cr/delivery';
|
+ (r.rates.soloCostPerRecipient || 5) + 'cr/delivery';
|
||||||
const el = $('campList');
|
const el = $('campList');
|
||||||
el.innerHTML = '';
|
el.innerHTML = '';
|
||||||
if (!r.campaigns.length) { el.innerHTML = '<p class="muted small">No campaigns yet. Launch your first below.</p>'; loadCreditActivity(el); return; }
|
convCamps = r.campaigns || [];
|
||||||
|
if (!r.campaigns.length) { el.innerHTML = '<p class="muted small">No campaigns yet. Launch your first below.</p>'; loadCreditActivity(el); loadConv(); return; }
|
||||||
const tbl = document.createElement('div');
|
const tbl = document.createElement('div');
|
||||||
tbl.className = 'tablewrap';
|
tbl.className = 'tablewrap';
|
||||||
tbl.innerHTML = '<table class="camp-table"><thead><tr><th>Name</th><th>Type</th><th class="num">Views here</th><th class="num" title="Impressions delivered by Network Ad Space across the wider network (banner and text ads only)">Network views</th><th class="num">Clicks</th>'
|
// syndicated rate (Marty, 2026-10-27, 4:1): network views and partner visits cost 1/N of a view or visit here
|
||||||
|
const synN = Math.max(1, Math.floor(Number(r.rates && r.rates.synRateDivisor) || 1));
|
||||||
|
const netCell = c => ['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() + (synN > 1 && c.impsNas ? ' <span class="muted small">at 1/' + synN + '</span>' : '')
|
||||||
|
: (c.type === 'visits' && c.impsSyn) ? c.impsSyn.toLocaleString() + ' <span class="muted small">partner visits' + (synN > 1 ? ', ' + synN + ' = 1 visit' : '') + '</span>'
|
||||||
|
: '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>';
|
||||||
|
if (synN > 1) { const n = document.createElement('p'); n.className = 'muted small'; n.textContent = 'Views and visits here on InstantAdPay use credits at the normal rate. Your ads also run on Network Ad Space and partner sites, and that delivery costs a ' + (synN === 4 ? 'quarter' : '1/' + synN) + ' of the rate: ' + synN + ' network views cost what 1 view here does, and ' + synN + ' partner visits use up 1 visit of your pack. Your budget goes further and every credit still buys real delivery.'; el.appendChild(n); }
|
||||||
|
tbl.innerHTML = '<table class="camp-table"><thead><tr><th>Name</th><th>Type</th><th class="num">Views here</th><th class="num" title="Impressions delivered by Network Ad Space across the wider network (banner and text ads), and visits from partner sites (visit packs)' + (synN > 1 ? ', at 1/' + synN + ' of the rate here' : '') + '">Network views</th><th class="num">Clicks</th>'
|
||||||
+ '<th class="num">Spent</th><th class="num">Budget</th><th>Status</th><th></th></tr></thead><tbody>'
|
+ '<th class="num">Spent</th><th class="num">Budget</th><th>Status</th><th></th></tr></thead><tbody>'
|
||||||
+ r.campaigns.map(c => '<tr><td data-l="Campaign"><b>' + c.name + '</b>' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '</td>'
|
+ r.campaigns.map(c => '<tr><td data-l="Campaign"><b>' + c.name + '</b>' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '<div class="muted small conv-line" data-convcamp="' + c.id + '" hidden></div></td>'
|
||||||
+ '<td data-l="Type">' + c.type + (c.type === 'banner' && c.width ? ' <span class="muted small">' + c.width + '×' + c.height + '</span>' : '') + (c.dailyCap ? ' <span class="muted small" title="daily cap: ' + c.dailyCap + ' credits, ' + (c.daySpent || 0) + ' spent today">cap ' + c.dailyCap + '/day</span>' : '') + (c.geo ? ' <span class="muted small" title="shown only to viewers in these country tiers">tier ' + esc(c.geo.replace(/,/g, '+')) + '</span>' : '') + schedChips(c)
|
+ '<td data-l="Type">' + c.type + (c.type === 'banner' && c.width ? ' <span class="muted small">' + c.width + '×' + c.height + '</span>' : '') + (c.dailyCap ? ' <span class="muted small" title="daily cap: ' + c.dailyCap + ' credits, ' + (c.daySpent || 0) + ' spent today">cap ' + c.dailyCap + '/day</span>' : '') + (c.geo ? ' <span class="muted small" title="shown only to viewers in these country tiers">tier ' + esc(c.geo.replace(/,/g, '+')) + '</span>' : '') + schedChips(c)
|
||||||
+ (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' <span class="badge' + (c.placement === 'golden' ? ' amber' : '') + '" title="' + (c.doorOnly ? 'runs only in Spooky Doors until the season ends, then any doors left run as normal visits' : 'the Spooky Doors season is over, so any doors left run as normal visits') + '">' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '</span>' : '') + '</td>'
|
+ (c.type === 'visits' && (c.placement === 'golden' || c.placement === 'doors') ? ' <span class="badge' + (c.placement === 'golden' ? ' amber' : '') + '" title="' + (c.doorOnly ? 'runs only in Spooky Doors until the season ends, then any doors left run as normal visits' : 'the Spooky Doors season is over, so any doors left run as normal visits') + '">' + (c.placement === 'golden' ? 'Golden Door' : 'Spooky Doors') + '</span>' : '') + '</td>'
|
||||||
+ '<td class="num" data-l="Views here">' + c.imps.toLocaleString() + '</td>'
|
+ '<td class="num" data-l="Views here">' + c.imps.toLocaleString() + '</td>'
|
||||||
+ '<td class="num" data-l="Network views">' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : '<span class="muted small" title="only banner and text ads syndicate to the network">n/a</span>') + '</td>'
|
+ '<td class="num" data-l="Network views">' + netCell(c) + '</td>'
|
||||||
+ '<td class="num" data-l="Clicks">' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '<div class="muted small clk-src" title="where the clicks happened">' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '<span>' + esc(k) + ' ' + v + '</span>').join('') + (c.impsNas ? ' · network: see Network views' : '') + '</div>' : '') + '</td>'
|
+ '<td class="num" data-l="Clicks">' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '<div class="muted small clk-src" title="where the clicks happened">' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '<span>' + esc(k) + ' ' + v + '</span>').join('') + (c.impsNas ? ' · network: see Network views' : '') + '</div>' : '') + '</td>'
|
||||||
+ (c.type === 'visits' ? '<td class="num" data-l="Spent"><span class="muted small" title="visit packs are paid in full when created; nothing more is charged as visits arrive">paid up front</span></td><td class="num" data-l="Delivered"><b>' + c.imps.toLocaleString() + '</b> of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits')
|
+ (c.type === 'visits' ? '<td class="num" data-l="Spent"><span class="muted small" title="visit packs are paid in full when created; nothing more is charged as visits arrive">paid up front</span></td><td class="num" data-l="Delivered"><b>' + c.imps.toLocaleString() + '</b> of ' + Number(c.body || 0).toLocaleString() + (c.placement === 'golden' || c.placement === 'doors' ? ' doors' : ' visits')
|
||||||
+ (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '<div class="muted small" title="Spooky Doors: every door opened on this pack, and how many different players opened one">\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '</div>')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '</td>'
|
+ (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '<div class="muted small" title="Spooky Doors: every door opened on this pack, and how many different players opened one">\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '</div>')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '</td>'
|
||||||
: c.type === 'featured' ? '<td class="num" data-l="Spent"><span class="muted small" title="featured runs are paid in full when booked (' + (r.rates.featuredPerDay || 40) + ' credits a day); nothing more is charged while the run is live">paid up front</span></td><td class="num" data-l="Run">' + featRun(c) + '</td>'
|
: c.type === 'featured' ? '<td class="num" data-l="Spent"><span class="muted small" title="featured runs are paid in full when booked (' + (r.rates.featuredPerDay || 40) + ' credits a day); nothing more is charged while the run is live">paid up front</span></td><td class="num" data-l="Run">' + featRun(c) + '</td>'
|
||||||
: '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>')
|
: '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>')
|
||||||
+ '<td data-l="Status">' + (c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
|
+ '<td data-l="Status">' + (c.status === 'queued' ? queuedCell(c) : c.status === 'cancelled' ? '<span class="muted" title="cancelled before it started; the full price came back to your balance">cancelled, refunded</span>' : c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
|
||||||
+ '<td class="act">' + (c.status === 'active' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="pause">Pause</button>'
|
+ '<td class="act">' + (c.status === 'active' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="pause">Pause</button>'
|
||||||
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>' : '')
|
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>'
|
||||||
+ (['paused', 'out', 'done'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
|
: c.status === 'queued' ? '<button class="btn small sec" data-qedit="' + c.id + '">Edit</button> <button class="btn small quiet" data-qcancel="' + c.id + '" data-qname="' + esc(c.name || ('#' + c.id)) + '" data-qpaid="' + Number(c.spent || 0) + '">Cancel and refund</button>' : '')
|
||||||
|
+ (['paused', 'out', 'done', 'cancelled'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
|
||||||
+ (c.type === 'featured' ? ' <button class="btn small sec" data-extend="' + c.id + '" title="book more days at the daily rate">Extend run</button>'
|
+ (c.type === 'featured' ? ' <button class="btn small sec" data-extend="' + c.id + '" title="book more days at the daily rate">Extend run</button>'
|
||||||
: c.type === 'visits' ? ' <button class="btn small sec" data-morevisits="' + c.id + '" data-vper="' + placeCost(c.doorOnly ? c.placement : 'all', r.rates) + '" data-vdoor="' + (c.doorOnly ? (c.placement === 'golden' ? 'golden' : 'doors') : '') + '">' + (c.doorOnly ? 'Buy more doors' : 'Buy more visits') + '</button>'
|
: c.type === 'visits' ? ' <button class="btn small sec" data-morevisits="' + c.id + '" data-vper="' + placeCost(c.doorOnly ? c.placement : 'all', r.rates) + '" data-vdoor="' + (c.doorOnly ? (c.placement === 'golden' ? 'golden' : 'doors') : '') + '">' + (c.doorOnly ? 'Buy more doors' : 'Buy more visits') + '</button>'
|
||||||
: c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up
|
: c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up
|
||||||
@@ -1092,6 +1297,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
+ '</td></tr>').join('') + '</tbody></table>';
|
+ '</td></tr>').join('') + '</tbody></table>';
|
||||||
el.appendChild(tbl);
|
el.appendChild(tbl);
|
||||||
pageList('camps', tbl, 'tbody tr');
|
pageList('camps', tbl, 'tbody tr');
|
||||||
|
loadConv();
|
||||||
renderArchived(el, r);
|
renderArchived(el, r);
|
||||||
const note = document.createElement('p'); note.className = 'muted small';
|
const note = document.createElement('p'); note.className = 'muted small';
|
||||||
note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.';
|
note.textContent = 'Credits you put into a campaign are set aside the moment you start it, so your Available number drops right away and the campaign spends from its own budget. Featured links and verified-visit packs are paid in full up front; a featured run is sold by the day, so use Extend run to keep it going. Whatever a campaign has not spent comes back to Available when it ends.';
|
||||||
@@ -1116,6 +1322,27 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
await loadCampaigns(); loadDashboard();
|
await loadCampaigns(); loadDashboard();
|
||||||
} catch (e) { IAP.status(e.message, 'bad'); }
|
} catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
}));
|
}));
|
||||||
|
// prepaid login-ad line (2026-10-23): a reservation can be edited for free and cancelled for the full price back until it starts
|
||||||
|
el.querySelectorAll('button[data-qcancel]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
const paid = Number(b.dataset.qpaid) || 0;
|
||||||
|
const ok = await IAP.confirmBox('You give up your place in line and the full ' + paid.toLocaleString() + ' credits come back to your balance right away, as purchased credits. You can reserve again later, at the back of the line.',
|
||||||
|
{ title: 'Cancel ' + b.dataset.qname + '?', ok: 'Cancel and refund', cancel: 'Keep my place' });
|
||||||
|
if (!ok) return;
|
||||||
|
b.disabled = true;
|
||||||
|
try { const x = await api('/api/my/campaigns/' + b.dataset.qcancel + '/cancel-reservation'); IAP.status('Reservation cancelled. ' + Number(x.refunded || 0).toLocaleString() + ' credits are back in your balance.', 'ok'); await loadCampaigns(); loadDashboard(); }
|
||||||
|
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; await loadCampaigns(); }
|
||||||
|
}));
|
||||||
|
el.querySelectorAll('button[data-qedit]').forEach(b => b.addEventListener('click', async () => {
|
||||||
|
const c = r.campaigns.find(x => x.id === Number(b.dataset.qedit)); if (!c) return;
|
||||||
|
const target = await IAP.ask({ title: 'Edit your reserved login ad', text: 'Target URL: the page members see when they sign in. Editing is free until the ad starts.', value: c.targetUrl || '', placeholder: 'https://', ok: 'Next' });
|
||||||
|
if (target === null) return;
|
||||||
|
const image = await IAP.ask({ title: 'Image (optional)', text: 'A direct image link (.png or .jpg) shown as the clickable creative. Leave it empty for a plain link card.', value: c.imageUrl || '', placeholder: 'https://', ok: 'Next' });
|
||||||
|
if (image === null) return;
|
||||||
|
const title = await IAP.ask({ title: 'Headline (optional)', text: 'Shown on the link card when there is no image. Up to 60 characters.', value: c.title || '', placeholder: 'Visit today\'s sponsor', ok: 'Save changes' });
|
||||||
|
if (title === null) return;
|
||||||
|
try { await api('/api/my/campaigns/' + c.id + '/edit-reservation', { targetUrl: target.trim(), imageUrl: image.trim(), title: title.trim() }); IAP.status('Saved. Your place in line is unchanged.', 'ok'); await loadCampaigns(); }
|
||||||
|
catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
|
}));
|
||||||
el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => {
|
el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => {
|
||||||
try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); }
|
try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); }
|
||||||
catch (e) { IAP.status(e.message, 'bad'); }
|
catch (e) { IAP.status(e.message, 'bad'); }
|
||||||
@@ -1152,6 +1379,28 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
let lastRates = null;
|
let lastRates = null;
|
||||||
|
let lastLoginLine = null; // { max, used, queued, free, credits, days, nextPlace, nextEstStart, mine: [{ id, place, estStart }] }
|
||||||
|
// every date about the login-ad line is shown in Central time, Marty's clock
|
||||||
|
function ctWhen(ts) { return new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; }
|
||||||
|
function queuedCell(c) {
|
||||||
|
const m = lastLoginLine && (lastLoginLine.mine || []).find(x => x.id === c.id);
|
||||||
|
return '<span class="badge amber" title="paid in full; it starts on its own when a slot frees">In line' + (m ? ' #' + m.place : '') + '</span>'
|
||||||
|
+ '<div class="muted small">' + (m && m.estStart ? 'Estimated start ' + esc(ctWhen(m.estStart)) : 'Start date not known yet') + '</div>';
|
||||||
|
}
|
||||||
|
// the Login ad form: open slots, or the paid line with this buyer's place and estimated start
|
||||||
|
function loginLineHint() {
|
||||||
|
const el = $('cLoginLine'); const isLogin = $('cType') && $('cType').value === 'login';
|
||||||
|
if (el) el.hidden = !isLogin || !lastLoginLine;
|
||||||
|
if ($('createCampBtn')) $('createCampBtn').textContent = isLogin && lastLoginLine && !lastLoginLine.free ? 'Reserve the next slot' : 'Launch campaign';
|
||||||
|
if (!el || !isLogin || !lastLoginLine) return;
|
||||||
|
const L = lastLoginLine;
|
||||||
|
el.textContent = L.free
|
||||||
|
? L.free + ' of ' + L.max + ' login-ad slots open now. Yours goes live the moment you launch: ' + Number(L.credits).toLocaleString() + ' purchased credits for ' + L.days + ' days.'
|
||||||
|
: 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ' and ' + L.queued + ' paid ' + (L.queued === 1 ? 'reservation is' : 'reservations are') + ' in line' : '') + '. You can reserve the next slot: you pay the same '
|
||||||
|
+ Number(L.credits).toLocaleString() + ' purchased credits now and take place #' + L.nextPlace + ' in line. Your ' + L.days + ' days start when your turn comes, not before.'
|
||||||
|
+ (L.nextEstStart ? ' Estimated start: ' + ctWhen(L.nextEstStart) + '. That is an estimate: a slot can end early if its owner archives it, which moves the line forward.' : '')
|
||||||
|
+ ' Until it starts you can edit it for free, or cancel it for every credit back.';
|
||||||
|
}
|
||||||
function soloHint() {
|
function soloHint() {
|
||||||
if (!lastRates || $('cType').value !== 'solo') return;
|
if (!lastRates || $('cType').value !== 'solo') return;
|
||||||
const cost = lastRates.soloCostPerRecipient || 5;
|
const cost = lastRates.soloCostPerRecipient || 5;
|
||||||
@@ -1215,6 +1464,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
// runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
|
// runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
|
||||||
function applyType() { // hoisted: loadCampaigns may run before this line is reached
|
function applyType() { // hoisted: loadCampaigns may run before this line is reached
|
||||||
whereHint();
|
whereHint();
|
||||||
|
loginLineHint();
|
||||||
const t = $('cType').value;
|
const t = $('cType').value;
|
||||||
$('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
|
$('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
|
||||||
if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner';
|
if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner';
|
||||||
@@ -1334,7 +1584,14 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
const t = $('cType').value;
|
const t = $('cType').value;
|
||||||
const isVideo = t === 'video', isFeat = t === 'featured';
|
const isVideo = t === 'video', isFeat = t === 'featured';
|
||||||
if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value);
|
if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value);
|
||||||
await api('/api/my/campaigns', { type: t, name: $('cName').value,
|
// login ad with every slot taken: pay now for a place in line (Marty, 2026-10-23), after one plain confirmation
|
||||||
|
const confirmReserve = async (place, est) => IAP.confirmBox('Every login-ad slot is taken right now. Reserving charges the full ' + Number((lastLoginLine && lastLoginLine.credits) || (lastRates && lastRates.loginSlotCredits) || 0).toLocaleString()
|
||||||
|
+ ' purchased credits now and puts you at place #' + place + ' in line. Your ad starts on its own when a slot frees, and runs its full ' + ((lastLoginLine && lastLoginLine.days) || 30) + ' days from then.'
|
||||||
|
+ (est ? '\n\nEstimated start: ' + ctWhen(est) + '. That is an estimate: a slot can end early if its owner archives it.' : '')
|
||||||
|
+ '\n\nUntil it starts you can edit it for free, or cancel it and get every credit back.', { title: 'Reserve the next login-ad slot?', ok: 'Pay now and reserve', cancel: 'Not now' });
|
||||||
|
let reserve = false;
|
||||||
|
if (t === 'login' && lastLoginLine && !lastLoginLine.free) { if (!(await confirmReserve(lastLoginLine.nextPlace, lastLoginLine.nextEstStart))) return; reserve = true; }
|
||||||
|
const sendCamp = extra => api('/api/my/campaigns', Object.assign({ type: t, name: $('cName').value,
|
||||||
targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value,
|
targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value,
|
||||||
title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value,
|
title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value,
|
||||||
body: t === 'solo' ? soloBody : $('cBody').value,
|
body: t === 'solo' ? soloBody : $('cBody').value,
|
||||||
@@ -1347,9 +1604,18 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0,
|
startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0,
|
||||||
endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0,
|
endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0,
|
||||||
ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value,
|
ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value,
|
||||||
budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) });
|
budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }, extra || {}));
|
||||||
|
let res;
|
||||||
|
try { res = await sendCamp({ reserve }); }
|
||||||
|
catch (e) { // the last slot went while the form was open: offer the line instead of a dead end
|
||||||
|
if (!(t === 'login' && e.data && e.data.full)) throw e;
|
||||||
|
if (!(await confirmReserve(e.data.place, e.data.estStart))) { await loadCampaigns(); return; }
|
||||||
|
res = await sendCamp({ reserve: true });
|
||||||
|
}
|
||||||
const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null;
|
const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null;
|
||||||
IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
|
if (res && res.queued) IAP.status('Reserved and paid. You are #' + res.place + ' in line' + (res.estStart ? ', estimated start ' + ctWhen(res.estStart) : '') + '. We will tell you on site and by email the moment it goes live.', 'ok');
|
||||||
|
else if (t === 'login' && reserve) IAP.status('A slot opened up while you were deciding, so your login ad is live now.', 'ok');
|
||||||
|
else IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
|
||||||
// clear EVERY field so no target/creative carries into the next campaign
|
// clear EVERY field so no target/creative carries into the next campaign
|
||||||
['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel',
|
['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel',
|
||||||
'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt']
|
'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt']
|
||||||
@@ -1629,10 +1895,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
}
|
}
|
||||||
function renderTank(el, r) {
|
function renderTank(el, r) {
|
||||||
const rows = listApply('tank', r.waiting);
|
const rows = listApply('tank', r.waiting).sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0)); // ready to activate always on top (stable: the chosen order stays inside each group)
|
||||||
el.innerHTML = '';
|
el.innerHTML = '';
|
||||||
el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on
|
el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on
|
||||||
el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + '</span>'
|
const readyBadge = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e" title="Wallet linked. If nobody adopts them, the site assigns them to the next eligible adopter when the time runs out.">Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '</span>' : '';
|
||||||
|
el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + readyBadge(w) + '</span>'
|
||||||
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
|
+ '<span class="em">joined ' + ago(w.joined) + '<span class="sp wrap">' + memberChips(w) + '</span></span>'
|
||||||
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
|
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
|
||||||
+ (r.eligible ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('')
|
+ (r.eligible ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('')
|
||||||
@@ -1696,17 +1963,23 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
}
|
}
|
||||||
loadWednesdayCard(); setInterval(loadWednesdayCard, 120000);
|
loadWednesdayCard(); setInterval(loadWednesdayCard, 120000);
|
||||||
|
|
||||||
// ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all nine games. More game, never "earn more". ----
|
// ---- Game Pass (2026-10-16, docs/GAME-PASS.md): $5 for 7 days across all ten games. More game, never "earn more". ----
|
||||||
const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
|
const gpDate = ms => new Date(Number(ms)).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
|
||||||
const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, '');
|
const gpPol = n => Number(n || 0).toFixed(2).replace(/\.?0+$/, '');
|
||||||
// Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add
|
// Pass tiers (2026-10-18, Marty approved the safe form): weekly Game Pass, monthly Explorer and Champion side by side. Paid tiers add
|
||||||
// islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time.
|
// islands and looks in Shards of Valor, never power and never more POL; the main story is free. End dates in Central time.
|
||||||
|
// 2026-10-22 (Dallas's structure): + Sovereign (monthly) and Legend (yearly). Names and what each includes come from the server
|
||||||
|
// (gamepass.js TIER_DEFS, row.perks); GP_TIER_PERKS is only the fallback for an older server answer.
|
||||||
const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
|
const gpCT = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
|
||||||
const GP_TIER_PERKS = {
|
const GP_TIER_PERKS = {
|
||||||
weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'],
|
weekly: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and the Weekly look'],
|
||||||
explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'],
|
explorer: ['Everything in the Game Pass, in every game', 'Shards of Valor: up to 4 bonus islands you pick (1 swap a month)', 'Explorer outfits and gear styles for your character'],
|
||||||
champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'],
|
champion: ['Everything in Explorer', 'Shards of Valor: every bonus island, now and future', 'Champion outfits and gear styles for your character'],
|
||||||
};
|
};
|
||||||
|
// 2026-10-25 (Marty): every pass price equals a one-click package ($5, $20, $50, $100, $250), so the pass comes with exactly that
|
||||||
|
// package's ad credits (the base credits per package, same table as Buy packages; day bonuses can add more)
|
||||||
|
const GP_PKG_CREDITS = { 5: 500, 10: 1000, 20: 2000, 50: 5500, 100: 12000, 250: 32500, 500: 70000 };
|
||||||
|
const gpLen = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
|
||||||
function renderPassTiers(card, gp, highlight) {
|
function renderPassTiers(card, gp, highlight) {
|
||||||
const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier);
|
const rows = gp.passes || []; const top = rows.find(r => r.tier === gp.tier);
|
||||||
const state = top ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '</span>'
|
const state = top ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">' + esc(top.name) + ' active · until ' + esc(gpCT(top.until)) + '</span>'
|
||||||
@@ -1715,30 +1988,30 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
const capsLine = caps.enforced ? 'Today: <b>' + gpPol(caps.used && caps.used.total) + '</b> of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : '';
|
const capsLine = caps.enforced ? 'Today: <b>' + gpPol(caps.used && caps.used.total) + '</b> of ' + gpPol(caps.total) + ' POL used across the games (' + gpPol(caps.used && caps.used.daily) + ' of ' + gpPol(caps.daily) + ' on daily play).' : '';
|
||||||
const box = r => {
|
const box = r => {
|
||||||
const btn = r.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + r.package + ' package</button>'
|
const btn = r.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + r.package + ' package</button>'
|
||||||
: r.open ? '<button class="btn small" type="button" data-gp-tier="' + esc(r.tier) + '">' + (r.active ? 'Extend ' + r.days + ' more days' : 'Get ' + esc(r.name)) + ' · ' + r.price + ' credits</button>'
|
: r.open ? '<button class="btn small" type="button" data-gp-tier="' + esc(r.tier) + '">' + (r.active ? 'Extend ' + gpLen(r.days) + ' more' : 'Get ' + esc(r.name)) + ' · ' + '$' + r.package + ' package</button>'
|
||||||
: '<span class="small muted">Not on sale right now. Your pass keeps running.</span>';
|
: '<span class="small muted">Not on sale right now. Your pass keeps running.</span>';
|
||||||
return '<div class="gp-tier' + (r.tier === gp.tier ? ' on' : '') + '"><h4>' + esc(r.name) + '</h4>'
|
return '<div class="gp-tier' + (r.tier === gp.tier ? ' on' : '') + '"><h4>' + esc(r.name) + '</h4>'
|
||||||
+ '<p class="gp-price">$' + r.usd + ' <span class="small muted">for ' + r.days + ' days</span></p>'
|
+ '<p class="gp-price">$' + r.usd + ' <span class="small muted">for ' + gpLen(r.days) + '</span></p>'
|
||||||
+ '<ul>' + (GP_TIER_PERKS[r.tier] || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
|
+ '<p class="small muted" style="margin:0 0 6px">Comes with the $' + r.package + ' package and its ' + (GP_PKG_CREDITS[r.package] ? GP_PKG_CREDITS[r.package].toLocaleString('en-US') + ' ' : '') + 'ad credits.</p>'
|
||||||
|
+ '<ul>' + (r.perks || GP_TIER_PERKS[r.tier] || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
|
||||||
+ '<p class="small" style="margin:6px 0">' + (r.active ? '<b>Active until ' + esc(gpCT(r.until)) + '</b>' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '</p>'
|
+ '<p class="small" style="margin:6px 0">' + (r.active ? '<b>Active until ' + esc(gpCT(r.until)) + '</b>' : r.waiting ? 'Waiting for a $' + r.package + ' package' : 'Not active') + '</p>'
|
||||||
+ btn + '</div>';
|
+ btn + '</div>';
|
||||||
};
|
};
|
||||||
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
|
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
|
||||||
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}️ Game Passes</h3><span class="sub">weekly or monthly · every game</span></div>'
|
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}️ Game Passes</h3><span class="sub">weekly, monthly or yearly · every game</span></div>'
|
||||||
+ (gp.tierPreview ? '<p class="small" style="margin:0 0 8px;padding:6px 10px;border-radius:8px;background:#fde68a;color:#7c2d12"><b>Admin preview.</b> Explorer and Champion are hidden from members until sovTiers is switched on in Settings.</p>' : '')
|
|
||||||
+ '<p style="margin:0 0 8px">' + state + '</p>'
|
+ '<p style="margin:0 0 8px">' + state + '</p>'
|
||||||
+ '<p>Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. The monthly passes add islands to explore and looks in Shards of Valor. <b>Paid passes never make you stronger than players who earn their gear</b>, and they never pay more POL.</p>'
|
+ '<p>Free play pays real POL every day, and the main story of Shards of Valor is free for everyone. Every pass gives the same higher POL caps in every game. Each higher pass includes everything below it and adds more of Shards of Valor: weapons, gear, bonus islands, heroes and a higher level cap. <b>Paid passes add heroes, islands, a higher level cap and new looks.</b> Pass gear is never better than gear players can earn, and passes never pay more POL.</p>'
|
||||||
+ '<div class="gp-tiers">' + rows.map(box).join('') + '</div>'
|
+ '<div class="gp-tiers">' + rows.map(box).join('') + '</div>'
|
||||||
+ (capsLine ? '<p class="small muted" style="margin-top:10px">' + capsLine + '</p>' : '')
|
+ (capsLine ? '<p class="small muted" style="margin-top:10px">' + capsLine + '</p>' : '')
|
||||||
+ '<p class="small muted" style="margin:10px 0 0">Paid with purchased credits from your packages (earned credits never buy a pass). Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.</p>';
|
+ '<p class="small muted" style="margin:10px 0 0">Every pass is paid by a new package purchase of at least its price, so your sponsor and team are paid; you keep the package credits for your ads. Credits you already hold never buy a pass. Passes run side by side: a higher pass shows first, and the one underneath keeps its own end date. No auto-renew: buy again any time and that pass extends from its end date. When a pass ends, nothing you earned in a game is taken away.</p>';
|
||||||
card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => {
|
card.querySelectorAll('[data-gp-tier]').forEach(b => b.addEventListener('click', async () => {
|
||||||
const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return;
|
const r = rows.find(x => x.tier === b.dataset.gpTier); if (!r) return;
|
||||||
const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + r.days + ' days' : 'Get ' + r.name + ' for ' + r.days + ' days') + ' for ' + r.price + ' purchased credits ($' + r.usd + ')? It starts at once. Islands and looks only: no extra power, no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' });
|
const yes = await IAP.confirmBox((r.active ? 'Extend your ' + r.name + ' by ' + gpLen(r.days) : 'Get ' + r.name + ' for ' + gpLen(r.days)) + ' ($' + r.usd + ')? Every pass is paid by a new package purchase of $' + r.package + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the pass starts the moment it settles. Credits you already hold never buy a pass. The same POL caps as every pass: no extra POL.', { title: r.name, ok: r.active ? 'Extend' : 'Get ' + r.name, cancel: 'Not now' });
|
||||||
if (!yes) return;
|
if (!yes) return;
|
||||||
b.disabled = true;
|
b.disabled = true;
|
||||||
try {
|
try {
|
||||||
const x = await api('/api/my/gamepass/buy', { tier: r.tier });
|
const x = await api('/api/my/gamepass/buy', { tier: r.tier });
|
||||||
if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; }
|
if (x.needPay) { IAP.status(x.message || 'Buy a package and the pass starts when it settles.', 'ok'); setPane('buy'); return; }
|
||||||
IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok');
|
IAP.status(r.name + ' active until ' + gpCT(x.until) + '. Have fun out there.', 'ok');
|
||||||
await loadGamePassCard(true);
|
await loadGamePassCard(true);
|
||||||
} catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
} catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
||||||
@@ -1746,11 +2019,36 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy')));
|
card.querySelectorAll('[data-gp-go]').forEach(b => b.addEventListener('click', () => setPane('buy')));
|
||||||
if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} }
|
if (highlight) { try { card.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (e) {} }
|
||||||
}
|
}
|
||||||
|
// What the Pass adds in each game (Marty, 2026-10-22: members must see what they are buying). Keep in step with the games' perks.
|
||||||
|
const GP_PERKS = [
|
||||||
|
['PolHunter', '5 missions a day instead of 3, plus 2 Ad Detective cases a day'],
|
||||||
|
['Gem Kingdom', 'one free continue every day'],
|
||||||
|
['Spooky Doors', 'one extra door every day'],
|
||||||
|
['ClutterHunt', '2 bonus hints every day'],
|
||||||
|
['SpellWheel', 'daily streak pays 0.30 POL instead of 0.15, plus 1 free hint a day'],
|
||||||
|
['PolyBreak', 'daily gem limit 1.5 POL instead of 0.5, plus an extra paddle every round'],
|
||||||
|
['POL Miner', 'daily crystal limit 1.5 POL instead of 0.5, plus one free supply crate every day'],
|
||||||
|
['PolyWarriors', 'a 4th daily mission, and defense pays 25 Circuits instead of 15'],
|
||||||
|
['Drip Runner', 'a free shield at the start of every run'],
|
||||||
|
['Road Agent', '2 patrols a day and 25% more scrap']
|
||||||
|
];
|
||||||
|
function gpPerksHtml() {
|
||||||
|
return '<div class="gp-perks"><p style="margin:10px 0 6px"><b>What you get</b></p>'
|
||||||
|
+ '<table class="gp-tbl"><tr><td>Every game</td><td>Daily POL caps of 1.50 a day on repeatable rewards (free play 0.30) and 5 a day in all (free play 2), counted across all ten games</td></tr>'
|
||||||
|
+ '<tr><td>Weekly</td><td>A seat in the Pass Tournament, POL prizes from 5% of pass sales, paid Mondays</td></tr>'
|
||||||
|
+ '<tr><td>Badge</td><td>The gold Game Pass badge with your name, to share or post</td></tr></table>'
|
||||||
|
+ '<p style="margin:10px 0 6px"><b>In each game</b></p><table class="gp-tbl">'
|
||||||
|
+ GP_PERKS.map(p => '<tr><td>' + p[0] + '</td><td>' + p[1] + '</td></tr>').join('') + '</table>'
|
||||||
|
+ '<p class="small muted" style="margin:6px 0 0">The Pass never changes how much a reward pays: it lets you play and collect more each day.</p></div>';
|
||||||
|
}
|
||||||
async function loadGamePassCard(highlight) {
|
async function loadGamePassCard(highlight) {
|
||||||
const card = $('gpCard'); if (!card) return;
|
const card = $('gpCard'); if (!card) return;
|
||||||
let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {}
|
let gp = null; try { gp = await (await fetch('/api/my/gamepass')).json(); } catch (e) {}
|
||||||
if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; }
|
if (!gp || !(gp.enabled || gp.show)) { card.hidden = true; return; }
|
||||||
if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight); // Explorer / Champion on sale (or admin preview, or a holder)
|
if ((gp.passes || []).some(r => r.tier !== 'weekly')) return renderPassTiers(card, gp, highlight);
|
||||||
|
// Five Dollar Friday + the pass (Marty 2026-10-23): the package that starts the pass also gets the Friday bonus, so say so on Fridays
|
||||||
|
let fdf = ''; try { const f = await (await fetch('/api/friday')).json(); if (f && f.on && f.live) { const base = gp.price || 500, got = Math.round(base * (1 + (Number(f.pct) || 20) / 100));
|
||||||
|
fdf = '<p style="margin:0 0 10px;padding:8px 10px;border-radius:8px;background:rgba(226,176,74,.12);border:1px solid rgba(226,176,74,.35)">\u{1F383} <b>It\u2019s Five Dollar Friday.</b> The $' + (gp.usd || 5) + ' package that starts your pass gets +' + (Number(f.pct) || 20) + '% too, so you get the ' + (gp.days || 7) + '-day pass <b>and keep ' + got.toLocaleString() + ' ad credits</b>. Tap Get the Pass first, then buy the package.</p>'; } } catch (e) {} // the tier boxes above show only when a tier above weekly is on sale or the member holds one (never an admin-only view: tier tests live in Admin > Game Pass)
|
||||||
const caps = gp.caps || {}; const price = gp.price || 500;
|
const caps = gp.caps || {}; const price = gp.price || 500;
|
||||||
const state = gp.active ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '</span>'
|
const state = gp.active ? '<span class="badge" style="background:var(--gold,#e2b04a);color:#111">Pass active \u00b7 until ' + esc(gpDate(gp.until)) + '</span>'
|
||||||
: gp.waiting ? '<span class="badge amber">Waiting for a $' + (gp.usd || 5) + ' package</span>' : '<span class="badge">Not active</span>';
|
: gp.waiting ? '<span class="badge amber">Waiting for a $' + (gp.usd || 5) + ' package</span>' : '<span class="badge">Not active</span>';
|
||||||
@@ -1759,23 +2057,26 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
: gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.'
|
: gp.capsStart ? 'Account-wide caps start on ' + esc(gpDate(Date.parse(gp.capsStart + 'T17:00:00Z'))) + ': free play ' + gpPol(caps.daily) + ' POL a day on repeatable rewards, 2 POL a day in all; with the Pass 1.50 and 5.'
|
||||||
: 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.';
|
: 'Account-wide caps are not switched on yet; the games\u2019 own caps stand for now.';
|
||||||
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
|
card.hidden = false; card.classList.toggle('gp-hl', !!highlight);
|
||||||
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F Game Pass</h3><span class="sub">$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all nine games</span></div>'
|
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F Game Pass</h3><span class="sub">$' + (gp.usd || 5) + ' for ' + (gp.days || 7) + ' days \u00b7 all ten games</span></div>'
|
||||||
+ '<p style="margin:0 0 8px">' + state + '</p>'
|
+ '<p style="margin:0 0 8px">' + state + '</p>'
|
||||||
|
+ fdf
|
||||||
+ '<p>Free play pays real POL every day. The Pass plays <b>more</b>: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly <b>Pass Tournament</b> with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.</p>'
|
+ '<p>Free play pays real POL every day. The Pass plays <b>more</b>: higher daily POL caps across every game (1.50 a day on repeatable rewards instead of 0.30, 5 a day in all instead of 2), a seat in the weekly <b>Pass Tournament</b> with POL prizes from ' + (gp.tournament && gp.tournament.pct || 5) + '% of pass sales, extra plays and perks in each game, and the Pass badge. One pass covers your whole account, linked positions included.</p>'
|
||||||
|
+ gpPerksHtml()
|
||||||
+ '<p class="small muted">' + capsLine + '</p>'
|
+ '<p class="small muted">' + capsLine + '</p>'
|
||||||
+ (gp.waiting ? '<p class="small">Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.</p>' : '')
|
+ (gp.waiting ? '<p class="small">Your pass is waiting: buy a $' + (gp.usd || 5) + ' package and it starts the moment the purchase settles. You keep every credit of the package for your ads.</p>' : '')
|
||||||
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:10px 0 0">'
|
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:10px 0 0">'
|
||||||
+ (gp.waiting ? '<button class="btn" type="button" id="gpGoBuy">Buy a $' + (gp.usd || 5) + ' package</button>' : '<button class="btn" type="button" id="gpBuy">' + (gp.active ? 'Extend ' + (gp.days || 7) + ' more days' : 'Get the Pass') + ' \u00b7 ' + price + ' credits</button>')
|
+ (gp.waiting ? '<button class="btn" type="button" id="gpGoBuy">Buy a $' + (gp.usd || 5) + ' package</button>' : '<button class="btn" type="button" id="gpBuy">' + (gp.active ? 'Extend ' + (gp.days || 7) + ' more days' : 'Get the Pass') + ' \u00b7 buy a $' + (gp.usd || 5) + ' package</button>')
|
||||||
+ '<span class="small muted">Paid with purchased credits from your packages (earned credits never buy a pass). Short? A $' + (gp.usd || 5) + ' package starts it the moment it settles.</span></p>';
|
+ '<span class="small muted">Paid by a new $' + (gp.usd || 5) + ' or bigger package, so your sponsor and team are paid. You keep the package credits for your ads; credits you already hold never buy a pass.</span></p>';
|
||||||
const b = $('gpBuy'); if (b) b.addEventListener('click', async () => {
|
const b = $('gpBuy'); if (b) b.addEventListener('click', async () => {
|
||||||
const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + ' for ' + price + ' purchased credits? Higher daily caps across all nine games, the weekly Pass Tournament and the Pass perks start at once.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' });
|
const yes = await IAP.confirmBox((gp.active ? 'Extend your Game Pass by ' + (gp.days || 7) + ' days' : 'Get the Game Pass for ' + (gp.days || 7) + ' days') + '? The Pass is paid by a new package purchase of $' + (gp.usd || 5) + ' or more: your sponsor and team are paid from it as usual, you keep all its credits for your ads, and the Pass starts the moment it settles. Credits you already hold never buy a pass.', { title: 'Game Pass', ok: gp.active ? 'Extend the Pass' : 'Get the Pass', cancel: 'Not now' });
|
||||||
if (!yes) return;
|
if (!yes) return;
|
||||||
b.disabled = true;
|
b.disabled = true;
|
||||||
try {
|
try {
|
||||||
const r = await api('/api/my/gamepass/buy');
|
const r = await api('/api/my/gamepass/buy');
|
||||||
if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'bad'); await loadGamePassCard(true); return; }
|
if (r.needPay) { IAP.status(r.message || 'Buy a $5 package and the pass starts when it settles.', 'ok'); setPane('buy'); return; }
|
||||||
IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok');
|
IAP.status('Game Pass active until ' + gpDate(r.until) + '. Have fun out there.', 'ok');
|
||||||
await loadGamePassCard(true);
|
await loadGamePassCard(true);
|
||||||
|
try { await loadDashboard(); } catch (e) {} // unlocks the Game Pass badge at once (toast + team post)
|
||||||
} catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
} catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; }
|
||||||
});
|
});
|
||||||
const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy'));
|
const g = $('gpGoBuy'); if (g) g.addEventListener('click', () => setPane('buy'));
|
||||||
@@ -1790,7 +2091,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
|
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent' };
|
||||||
card.hidden = false;
|
card.hidden = false;
|
||||||
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '</h3><span class="sub">free play keeps paying; the Pass plays more</span></div>'
|
card.innerHTML = '<div class="card-head"><h3>\u{1F39F}\uFE0F You reached today\u2019s free cap in ' + esc(NAMES[gp.lastCapHit.game] || 'the games') + '</h3><span class="sub">free play keeps paying; the Pass plays more</span></div>'
|
||||||
+ '<p>Every member earns real POL in the games up to the daily cap. The <b>Game Pass</b> raises the caps across all nine games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with purchased credits), adds the weekly Pass Tournament and a perk in every game.</p>'
|
+ '<p>Every member earns real POL in the games up to the daily cap. The <b>Game Pass</b> raises the caps across all ten games for ' + (gp.days || 7) + ' days ($' + (gp.usd || 5) + ', paid with a new package), adds the weekly Pass Tournament and a perk in every game.</p>'
|
||||||
+ '<button class="btn" type="button" id="gpNudgeGo">See the Game Pass</button>';
|
+ '<button class="btn" type="button" id="gpNudgeGo">See the Game Pass</button>';
|
||||||
$('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1'));
|
$('gpNudgeGo').addEventListener('click', () => setPane('games?pass=1'));
|
||||||
try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day
|
try { localStorage.setItem('iap-hide-gpnudge', String(Date.now())); } catch (e) {} // once a day
|
||||||
@@ -2688,7 +2989,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.');
|
if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.');
|
||||||
}
|
}
|
||||||
const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy');
|
const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy');
|
||||||
if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company
|
if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), spNow.sponsorBlocked === 'tankHold' ? 'ok' : 'bad'); return; } // first activation must not hand a sponsored member to the company
|
||||||
if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok');
|
if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok');
|
||||||
// pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any
|
// pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any
|
||||||
// transaction that spends most of the balance ("drain your wallet"), so Trust users
|
// transaction that spends most of the balance ("drain your wallet"), so Trust users
|
||||||
@@ -2938,10 +3239,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
|||||||
const who = sp.sponsorName || 'your sponsor';
|
const who = sp.sponsorName || 'your sponsor';
|
||||||
if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.';
|
if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.';
|
||||||
if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.';
|
if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.';
|
||||||
|
if (sp.sponsorBlocked === 'tankHold') return tankHoldText(sp.tankHold);
|
||||||
return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.';
|
return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.';
|
||||||
}
|
}
|
||||||
$('activateBtn').addEventListener('click', busy($('activateBtn'), async () => {
|
$('activateBtn').addEventListener('click', busy($('activateBtn'), async () => {
|
||||||
const me = await (await fetch('/api/me')).json();
|
const me = await (await fetch('/api/me')).json();
|
||||||
|
if (me.tankHold || me.sponsorBlocked === 'tankHold') { TANK_HOLD = me.tankHold || {}; IAP.status(tankHoldText(me.tankHold), 'ok'); await render(); return; } // never bound under the company
|
||||||
if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; }
|
if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; }
|
||||||
IAP.status('Confirm the free activation in your wallet…');
|
IAP.status('Confirm the free activation in your wallet…');
|
||||||
const r = await IAPWallet.activate(me.sponsorId || 0);
|
const r = await IAPWallet.activate(me.sponsorId || 0);
|
||||||
|
|||||||
@@ -295,6 +295,13 @@ window.IAPPromo = (function () {
|
|||||||
{ name: 'Short post', text: 'Every game in the InstantAdPay network on one page: a word puzzle, a hidden-object hunt, a match-3, a runner, a scavenger hunt, a cyberpunk battler. Free to play, and they pay POL to the wallet on your account. {L}' },
|
{ name: 'Short post', text: 'Every game in the InstantAdPay network on one page: a word puzzle, a hidden-object hunt, a match-3, a runner, a scavenger hunt, a cyberpunk battler. Free to play, and they pay POL to the wallet on your account. {L}' },
|
||||||
{ name: 'Friendly post', text: 'If you like small games that actually pay something, this is the page I send people. Eight games, all free, all paying POL on Polygon for first clears, levels and daily puzzles. Pick one: {L}' },
|
{ name: 'Friendly post', text: 'If you like small games that actually pay something, this is the page I send people. Eight games, all free, all paying POL on Polygon for first clears, levels and daily puzzles. Pick one: {L}' },
|
||||||
{ name: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {L}' }] },
|
{ name: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {L}' }] },
|
||||||
|
// POL Miner (2026-10-28): shows once 'polminer' is in gamesLive (the public games list), like PolyBreak
|
||||||
|
{ slug: 'polminer', name: 'POL Miner', link: 'https://polminer.com/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polminer/og-polminer.jpg', sub: 'mining game that pays Polygon',
|
||||||
|
posts: [
|
||||||
|
{ name: 'Short post', text: 'POL Miner is a free mining game. Dig down through the layers, haul ore up to sell, upgrade your pick, lamp and cart, and beat a drill boss every 30 m. The rare pink Polygon crystals pay Polygon to the wallet on your InstantAdPay account. {L}' },
|
||||||
|
{ name: 'Friendly post', text: 'This one is easy to lose an hour in. POL Miner is free, it plays fine on a phone, and you sign in with your InstantAdPay account. Each pink Polygon crystal you dig out pays Polygon, and so does each drill boss the first time you beat it. Give it a dig: {L}' },
|
||||||
|
{ name: 'Crystal angle', text: 'Somewhere under the gravel there is a pink glow. In POL Miner the rare Polygon crystals pay Polygon when you dig them out. Free to play: {L}' },
|
||||||
|
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: POL Miner. Free mining game, the pink Polygon crystals pay Polygon: {L}' }] },
|
||||||
{ slug: 'polybreak', name: 'PolyBreak', link: 'https://polybreak.app/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak.jpg', sub: 'brick breaker that pays Polygon',
|
{ slug: 'polybreak', name: 'PolyBreak', link: 'https://polybreak.app/?ref=', img: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/polybreak/og-polybreak.jpg', sub: 'brick breaker that pays Polygon',
|
||||||
posts: [
|
posts: [
|
||||||
{ name: 'Short post', text: 'PolyBreak is a free brick breaker in the old Amiga arcade style. Smash a wall of glass jewel bricks, grab the capsules, and catch the purple Polygon gem when it drops. Your first clear of each round pays Polygon to the wallet on your InstantAdPay account. {L}' },
|
{ name: 'Short post', text: 'PolyBreak is a free brick breaker in the old Amiga arcade style. Smash a wall of glass jewel bricks, grab the capsules, and catch the purple Polygon gem when it drops. Your first clear of each round pays Polygon to the wallet on your InstantAdPay account. {L}' },
|
||||||
@@ -333,7 +340,7 @@ window.IAPPromo = (function () {
|
|||||||
{ slug: 'spookydoors', name: 'Spooky Doors', link: 'https://spookydoors.com/?ref=', kit: 'promo-spookydoors', seasonal: true },
|
{ slug: 'spookydoors', name: 'Spooky Doors', link: 'https://spookydoors.com/?ref=', kit: 'promo-spookydoors', seasonal: true },
|
||||||
{ slug: 'polhunter', name: 'PolHunter', link: 'https://polhunter.com/?r=', kit: 'promo-polhunter' }];
|
{ slug: 'polhunter', name: 'PolHunter', link: 'https://polhunter.com/?r=', kit: 'promo-polhunter' }];
|
||||||
const SIZES = [['728x90', 'Leaderboard'], ['468x60', 'Banner'], ['320x50', 'Mobile banner'], ['300x250', 'Medium rectangle'], ['336x280', 'Large rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Wide skyscraper'], ['120x600', 'Skyscraper'], ['300x600', 'Half page'], ['600x300', 'Traffic exchange / splash page']];
|
const SIZES = [['728x90', 'Leaderboard'], ['468x60', 'Banner'], ['320x50', 'Mobile banner'], ['300x250', 'Medium rectangle'], ['336x280', 'Large rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Wide skyscraper'], ['120x600', 'Skyscraper'], ['300x600', 'Half page'], ['600x300', 'Traffic exchange / splash page']];
|
||||||
const avail = { spookydoors: false, roadagent: !preLaunch(2026, 10, 15), polybreak: false }; // PolyBreak joins once it is in gamesLive (public games list) // seasonal: the Spooky Doors kit says whether its season is showing; Road Agent joins the list on its launch day
|
const avail = { spookydoors: false, roadagent: !preLaunch(2026, 10, 15), polybreak: false, polminer: false }; // PolyBreak joins once it is in gamesLive (public games list) // seasonal: the Spooky Doors kit says whether its season is showing; Road Agent joins the list on its launch day
|
||||||
const list = () => GAMES.filter(g => avail[g.slug] !== false);
|
const list = () => GAMES.filter(g => avail[g.slug] !== false);
|
||||||
let cur = null; try { cur = localStorage.getItem('iap.gmGame'); } catch (e) {}
|
let cur = null; try { cur = localStorage.getItem('iap.gmGame'); } catch (e) {}
|
||||||
const draw = () => {
|
const draw = () => {
|
||||||
@@ -369,7 +376,7 @@ window.IAPPromo = (function () {
|
|||||||
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(copyBtn(src, 'Copy image URL')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); grid.appendChild(d); }
|
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(copyBtn(src, 'Copy image URL')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); grid.appendChild(d); }
|
||||||
};
|
};
|
||||||
window.__gmAvail = (slug, on) => { avail[slug] = !!on; draw(); };
|
window.__gmAvail = (slug, on) => { avail[slug] = !!on; draw(); };
|
||||||
fetch('/api/public/games').then(r => r.json()).then(d => { if ((d.games || []).some(g => g.slug === 'polybreak')) window.__gmAvail('polybreak', true); }).catch(() => {});
|
fetch('/api/public/games').then(r => r.json()).then(d => { for (const sl of ['polybreak', 'polminer']) if ((d.games || []).some(g => g.slug === sl)) window.__gmAvail(sl, true); }).catch(() => {});
|
||||||
$('gmPick').addEventListener('click', e => { const b = e.target.closest('[data-gm]'); if (!b) return; cur = b.dataset.gm; draw(); });
|
$('gmPick').addEventListener('click', e => { const b = e.target.closest('[data-gm]'); if (!b) return; cur = b.dataset.gm; draw(); });
|
||||||
draw();
|
draw();
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 276 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 247 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 226 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 207 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
@@ -142,7 +142,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/contract.js?v=20260908p"></script>
|
<script src="/assets/contract.js?v=20260908p"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,268 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Conversion tracking: see which ad brings sign-ups and sales | InstantAdPay</title>
|
||||||
|
<meta name="description" content="How to set up conversion tracking on InstantAdPay: create a goal, put the landing tag on the page your ad points to and the goal pixel on your thank-you page, then read conversions and cost per goal in credits for every campaign. Copy-paste examples for HTML, WordPress, page builders, Aweber and GetResponse.">
|
||||||
|
<meta name="theme-color" content="#043b2f">
|
||||||
|
<link rel="canonical" href="https://instantadpay.com/conversion-tracking">
|
||||||
|
<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">
|
||||||
|
<meta property="og:title" content="Conversion tracking: see which ad brings sign-ups and sales">
|
||||||
|
<meta property="og:description" content="Clicks tell you who looked. Conversion tracking tells you which ad, page and source actually brought a subscriber or a sale, with a cost per goal in credits. Free for every member. Set it up in four steps.">
|
||||||
|
<meta property="og:url" content="https://instantadpay.com/conversion-tracking">
|
||||||
|
<meta name="twitter:card" content="summary">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||||
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
|
<link rel="stylesheet" href="/assets/site.css?v=20260912b">
|
||||||
|
<style>
|
||||||
|
.rg{max-width:900px}
|
||||||
|
.rg .hero{padding:44px 0 10px}
|
||||||
|
.rg h2{font-size:26px;margin:38px 0 6px}
|
||||||
|
.rg h3{font-size:17px;margin:0 0 6px}
|
||||||
|
.rg-eye{font-family:var(--mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--amber);font-weight:700;margin:38px 0 0}
|
||||||
|
.rg-eye + h2{margin-top:6px}
|
||||||
|
.rg-cta{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:6px 0 10px}
|
||||||
|
.rg-cta .btn.big{font-size:17px;padding:14px 22px}
|
||||||
|
.rg-two{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:14px;margin:14px 0 0}
|
||||||
|
.rg-box{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);min-width:0}
|
||||||
|
.rg-box p{margin:0;font-size:14.5px;color:var(--muted)}
|
||||||
|
.rg-box p + p{margin-top:8px}
|
||||||
|
.rg-note{font-size:14.5px;color:var(--muted);margin:8px 0 0}
|
||||||
|
/* the flow: across on a wide screen, down on a phone */
|
||||||
|
.cg-flow{list-style:none;margin:16px 0 8px;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:26px}
|
||||||
|
.cg-flow li{position:relative;border:1px solid var(--line-strong);border-radius:12px;padding:12px 13px;background:rgba(255,255,255,.02);font-size:13.5px;line-height:1.45;color:var(--muted);min-width:0}
|
||||||
|
.cg-flow li b{display:block;font-family:var(--disp);font-size:14.5px;color:var(--ink);margin-bottom:4px}
|
||||||
|
.cg-flow li .k{display:inline-grid;place-items:center;width:24px;height:24px;border-radius:50%;font-family:var(--mono);font-size:12px;font-weight:700;margin-bottom:6px;background:var(--ink);color:#04120e}
|
||||||
|
.cg-flow li code{font-family:var(--mono);font-size:12px;color:var(--mint);overflow-wrap:anywhere}
|
||||||
|
.cg-flow li.f-ad{border-color:rgba(84,204,255,.55);background:rgba(84,204,255,.07)}
|
||||||
|
.cg-flow li.f-tag{border-color:rgba(67,232,195,.6);background:rgba(67,232,195,.08)}
|
||||||
|
.cg-flow li.f-px{border-color:rgba(255,178,56,.7);background:rgba(255,178,56,.09)}
|
||||||
|
.cg-flow li.f-win{border-color:var(--mint);background:var(--mint-soft)}
|
||||||
|
.cg-flow li:not(:last-child)::after{content:"";position:absolute;right:-20px;top:50%;margin-top:-7px;border:7px solid transparent;border-left:9px solid var(--line-strong);border-right:0}
|
||||||
|
@media (max-width:820px){
|
||||||
|
.cg-flow{grid-template-columns:1fr;gap:24px}
|
||||||
|
.cg-flow li:not(:last-child)::after{right:auto;left:26px;top:auto;bottom:-19px;margin-top:0;border:7px solid transparent;border-top:9px solid var(--line-strong);border-bottom:0}
|
||||||
|
}
|
||||||
|
/* steps */
|
||||||
|
.rg-route{list-style:none;counter-reset:s;margin:12px 0 0;padding:0;display:grid;gap:14px}
|
||||||
|
.rg-route > li{counter-increment:s;display:grid;grid-template-columns:42px minmax(0,1fr);gap:14px;align-items:start;border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:rgba(255,255,255,.02);min-width:0}
|
||||||
|
.rg-route > li::before{content:counter(s);font-family:var(--disp);font-weight:800;font-size:20px;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--amber);color:#1b1203}
|
||||||
|
.rg-route > li > div{min-width:0}
|
||||||
|
.rg-route p{margin:0 0 8px;font-size:14.5px;color:var(--muted)}
|
||||||
|
.rg-where{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px}
|
||||||
|
.rg-chip{font-size:12.5px;font-weight:600;padding:3px 10px;border-radius:999px;background:var(--mint-soft);color:var(--mint);border:1px solid rgba(67,232,195,.35)}
|
||||||
|
.rg-chip.ls{background:rgba(84,204,255,.08);color:var(--cyan);border-color:rgba(84,204,255,.35)}
|
||||||
|
/* code */
|
||||||
|
.cg-code{position:relative;margin:8px 0 10px;border:1px solid var(--line-strong);border-radius:10px;background:#02100b;padding:12px 14px 12px;min-width:0}
|
||||||
|
.cg-code pre{margin:0;font-family:var(--mono);font-size:12.5px;line-height:1.6;color:var(--mint-hi);white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
|
||||||
|
.cg-code .cg-lbl{display:flex;justify-content:space-between;align-items:center;gap:8px;font-family:var(--mono);font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin:0 0 6px}
|
||||||
|
.cg-copy{font:600 12px var(--disp);background:transparent;color:var(--mint);border:1px solid rgba(67,232,195,.5);border-radius:999px;padding:3px 12px;cursor:pointer}
|
||||||
|
.cg-copy:hover{background:rgba(67,232,195,.1)}
|
||||||
|
.cg-ph{color:var(--amber);font-weight:700}
|
||||||
|
.cg-ex{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);margin:14px 0 0;min-width:0}
|
||||||
|
.cg-ex > p,.cg-ex li{font-size:14.5px;color:var(--muted)}
|
||||||
|
.cg-ex > p{margin:0 0 8px}
|
||||||
|
.cg-ex ol,.cg-ex ul{margin:0 0 8px;padding-left:20px;display:grid;gap:4px}
|
||||||
|
.rg code.i{font-family:var(--mono);font-size:13px;color:var(--mint);background:rgba(67,232,195,.08);padding:1px 5px;border-radius:4px;overflow-wrap:anywhere}
|
||||||
|
/* report table */
|
||||||
|
.rg-tbl{border:1px solid var(--line);border-radius:14px;overflow:hidden;margin:10px 0 8px}
|
||||||
|
.rg-tbl table{width:100%;border-collapse:collapse;font-size:14.5px;table-layout:fixed}
|
||||||
|
.rg-tbl th,.rg-tbl td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
|
||||||
|
.rg-tbl th{font-family:var(--mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);font-weight:600}
|
||||||
|
.rg-tbl td:first-child{width:34%;font-weight:700}
|
||||||
|
.rg-tbl td .muted{font-weight:400;font-size:12.5px}
|
||||||
|
.rg-tbl tr:last-child td{border-bottom:0}
|
||||||
|
/* checklist */
|
||||||
|
.cg-check{list-style:none;margin:12px 0 0;padding:0;display:grid;gap:10px}
|
||||||
|
.cg-check li{position:relative;padding:12px 14px 12px 44px;border:1px solid var(--line);border-radius:12px;background:rgba(255,255,255,.02);font-size:14.5px;color:var(--muted)}
|
||||||
|
.cg-check li::before{content:"";position:absolute;left:14px;top:14px;width:16px;height:16px;border-radius:4px;border:2px solid var(--mint)}
|
||||||
|
.cg-check li b{color:var(--ink)}
|
||||||
|
.rg-faq{display:grid;gap:14px;margin:12px 0 0}
|
||||||
|
.rg-faq dt{font-family:var(--disp);font-weight:700}
|
||||||
|
.rg-faq dd{margin:4px 0 0;color:var(--muted);font-size:14.5px}
|
||||||
|
.rg-rule{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:14px 18px;border-radius:0 12px 12px 0;margin:30px 0 22px;font-size:14.5px}
|
||||||
|
.rg-warn{border-left:4px solid var(--amber);background:rgba(255,178,56,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:12px 0 0;font-size:14.5px}
|
||||||
|
@media (max-width:640px){.rg .hero h1{font-size:30px}.cg-ex,.rg-box{padding:14px}.rg-route > li{grid-template-columns:34px minmax(0,1fr);gap:10px;padding:12px}.rg-route > li::before{width:34px;height:34px;font-size:17px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap rg">
|
||||||
|
<section class="hero">
|
||||||
|
<p class="eyebrow">InstantAdPay + LinkSpin · free for every member</p>
|
||||||
|
<h1>Conversion tracking: <em>see which ad</em> actually brings sign-ups and sales.</h1>
|
||||||
|
<p class="lead">Clicks tell you who looked. Conversion tracking tells you which ad, which page and which traffic source brought a subscriber or a sale, and what each one cost you in credits. You paste two small tags on your own site, one time. After that, every campaign in your dashboard shows its goals next to its clicks.</p>
|
||||||
|
</section>
|
||||||
|
<video src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/conversion-tracking-iap.mp4?v=20261026" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/conversion-tracking-iap.jpg?v=20261026" controls playsinline preload="metadata" width="1200" height="675" style="display:block;width:100%;height:auto;max-width:860px;background:#000;border-radius:16px;border:1px solid var(--line);margin:18px 0 14px" aria-label="Video: Marty walks through setting up conversion tracking, about 3 minutes"></video>
|
||||||
|
<div class="rg-cta">
|
||||||
|
<a class="btn big" href="/my#campaigns">Open Conversion tracking</a>
|
||||||
|
<a class="btn sec" href="/join">Not a member yet? Join free by email</a>
|
||||||
|
</div>
|
||||||
|
<p class="rg-note">In your dashboard it lives under <b>Campaigns</b>, in the <b>Conversion tracking</b> card below your campaign list. The counting is done by LinkSpin, our sister site, under the same email, so the same goals also show in your LinkSpin Control Room under <b>Conversions</b>.</p>
|
||||||
|
|
||||||
|
<p class="rg-eye">Why it matters</p>
|
||||||
|
<h2>Why track conversions</h2>
|
||||||
|
<div class="rg-two">
|
||||||
|
<div class="rg-box"><h3>Clicks are not sign-ups</h3><p>One ad can get lots of clicks from people who never sign up. Another gets fewer clicks and brings you subscribers. Without tracking, both look the same, or the wrong one looks better.</p></div>
|
||||||
|
<div class="rg-box"><h3>Find the winner</h3><p>Every goal is counted against the ad that sent the visitor. You see which campaign, which landing page and which traffic source produced the sign-up or the sale.</p></div>
|
||||||
|
<div class="rg-box"><h3>A cost per goal, in credits</h3><p>Each campaign shows its goals and what each one cost: the credits the campaign spent in the last 30 days, divided by its goals in those 30 days. Lower is better. Compare two ads on the same offer and you know which to keep.</p></div>
|
||||||
|
<div class="rg-box"><h3>Put next month's fuel behind it</h3><p>This is the "your numbers get useful" part of <a href="/refuel">Fuel Your Offers</a>. Run your ads all month, let the goals come in, then put next month's refuel behind the ad and the page that convert, instead of guessing.</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="rg-eye">The flow</p>
|
||||||
|
<h2>How a conversion gets counted</h2>
|
||||||
|
<ol class="cg-flow" aria-label="How a conversion gets counted, step by step">
|
||||||
|
<li class="f-ad"><span class="k">1</span><b>Someone clicks your ad</b>The click gets a random id, added to your page's address as <code>?lsclk=i2f9…</code></li>
|
||||||
|
<li class="f-tag"><span class="k">2</span><b>They land on your page</b>The landing tag keeps that id on your own site for 30 days.</li>
|
||||||
|
<li><span class="k">3</span><b>They sign up or buy</b>On your page, through your form or your checkout. Nothing changes for them.</li>
|
||||||
|
<li class="f-px"><span class="k">4</span><b>Your thank-you page loads</b>The goal pixel there reads the kept id and sends it to LinkSpin.</li>
|
||||||
|
<li class="f-win"><span class="k">5</span><b>Counted on your campaign</b>The goal shows on the ad that sent them, with its cost per goal in credits.</li>
|
||||||
|
</ol>
|
||||||
|
<p class="rg-note">The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere.</p>
|
||||||
|
|
||||||
|
<p class="rg-eye">Set it up</p>
|
||||||
|
<h2>Four steps, one time</h2>
|
||||||
|
<ol class="rg-route">
|
||||||
|
<li><div>
|
||||||
|
<h3>Create a goal</h3>
|
||||||
|
<p>A goal is one thing you want counted: <b>subscriber</b>, <b>sale</b>, <b>signup</b>. Type a short name (letters, numbers and dashes) and press Add goal. The default value is optional: put what a sale is worth, like 19.95, and it is recorded with each conversion. You can have up to 20 goals.</p>
|
||||||
|
<p>Each goal gets its own pixel id: <b>px</b> plus 10 letters and numbers. It is not a secret. It can only ever count clicks on your own ads, so it is safe to paste on any page.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay: Campaigns, Conversion tracking</span><span class="rg-chip ls">LinkSpin: Control Room, Conversions</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Put the landing tag on the page your ad points to</h3>
|
||||||
|
<p>Press <b>Snippets</b> on your goal and copy <b>1. Landing tag</b>. Paste it once on your landing page (the address your ad sends people to), just before <code class="i"></body></code>. It keeps the click id on your site, fills any hidden form field named <code class="i">lsclk</code>, and adds the id to links that stay on your site.</p>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>Landing tag</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre><script async src="https://linkspin.app/t.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>"></script></pre></div>
|
||||||
|
<p>It is fine to put it on every page of your site (in a site-wide footer). It never slows or breaks the page, even if LinkSpin cannot be reached.</p>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Put the goal pixel on your thank-you page</h3>
|
||||||
|
<p>Copy <b>2. Goal pixel</b> and paste it on the page people see only after they sign up or buy. Use the script version wherever your page allows scripts: it reads the id the landing tag kept, which is the surest match. Use the image version where scripts are not allowed.</p>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>Goal pixel, script version (surest)</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre><script async src="https://linkspin.app/cv.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&goal=<span class="cg-ph">subscriber</span>"></script></pre></div>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>Goal pixel, image version</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre><img src="https://linkspin.app/cv.gif?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&goal=<span class="cg-ph">subscriber</span>" width="1" height="1" alt="" style="display:none"></pre></div>
|
||||||
|
<p>Recording a sale amount? Add <code class="i">&value=19.95</code> to the end of the pixel address. Without it, the goal's default value is used.</p>
|
||||||
|
<div class="rg-warn"><b>Only on the thank-you page.</b> Never put the goal pixel on your landing page. Everyone who lands would count as a goal.</div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Send a test conversion</h3>
|
||||||
|
<p>Press <b>Send a test conversion</b> on your goal. It loads your real pixel in test mode, the same request your thank-you page makes. It shows under <b>Last test</b> and never counts in your numbers. That proves your pixel id is live.</p>
|
||||||
|
<p>To check the pixel on your real thank-you page, add <code class="i">&test=1</code> to the end of the pixel address, open your thank-you page once, and reload your dashboard a minute later: Last test updates. Then take <code class="i">&test=1</code> back out. Last, click one of your own ads and look at the address bar on your landing page: you should see <code class="i">lsclk=</code> in it. That click is yours, so anything you finish after it is kept as a test, never counted.</p>
|
||||||
|
</div></li>
|
||||||
|
</ol>
|
||||||
|
<p class="rg-note">Your own clicks are kept as tests: on your ads here, and on your spin links and Banner Spins on LinkSpin, whether you are signed in on that browser or it is one you sign in from. They never show in your numbers, so a full run-through of your own funnel will not inflate anything. The card says how many of your own clicks were kept as tests.</p>
|
||||||
|
|
||||||
|
<p class="rg-eye">Copy and paste</p>
|
||||||
|
<h2>Where the code goes, by platform</h2>
|
||||||
|
<p class="rg-note">In every example, replace <span class="cg-ph" style="font-family:var(--mono)">YOUR_PIXEL_ID</span> with your goal's pixel id and <span class="cg-ph" style="font-family:var(--mono)">subscriber</span> with your goal's name. The Snippets button in your dashboard gives you both lines with these already filled in.</p>
|
||||||
|
|
||||||
|
<div class="cg-ex">
|
||||||
|
<h3>A plain HTML page</h3>
|
||||||
|
<p>Landing page: paste the landing tag right before the closing body tag.</p>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>landing.html</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre> ...your page...
|
||||||
|
<script async src="https://linkspin.app/t.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>"></script>
|
||||||
|
</body></pre></div>
|
||||||
|
<p>Thank-you page: the landing tag (optional, harmless) and the goal pixel.</p>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>thank-you.html</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre> ...your thank-you message...
|
||||||
|
<script async src="https://linkspin.app/cv.js?px=<span class="cg-ph">YOUR_PIXEL_ID</span>&goal=<span class="cg-ph">subscriber</span>"></script>
|
||||||
|
</body></pre></div>
|
||||||
|
<p>Have your own form on the landing page? Add a hidden field and the landing tag fills it with the click id, so your own system can keep it with the lead:</p>
|
||||||
|
<div class="cg-code"><div class="cg-lbl"><span>hidden field</span><button class="cg-copy" type="button" data-copy>Copy</button></div><pre><input type="hidden" name="lsclk" value=""></pre></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cg-ex">
|
||||||
|
<h3>WordPress</h3>
|
||||||
|
<ol>
|
||||||
|
<li><b>Landing tag, site-wide:</b> with a header and footer plugin (WPCode, for example), paste the landing tag into the <b>footer</b> box and save. It now runs on every page, landing page included.</li>
|
||||||
|
<li><b>Goal pixel, thank-you page only:</b> edit your thank-you page, add a <b>Custom HTML</b> block, paste the goal pixel into it, and update the page. Do not put the goal pixel in the site-wide footer.</li>
|
||||||
|
<li>If your WordPress plan or theme strips scripts out of blocks (some hosted plans do), use the image version of the goal pixel in the Custom HTML block instead.</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cg-ex">
|
||||||
|
<h3>Funnel and page builders</h3>
|
||||||
|
<p>Most builders that allow custom code give you one of two places, and either works:</p>
|
||||||
|
<ul>
|
||||||
|
<li>A <b>tracking code</b> or <b>footer code</b> box in the page or funnel settings. Put the landing tag in your landing page's box, and the goal pixel in your thank-you page's box.</li>
|
||||||
|
<li>A <b>custom HTML</b> or <b>code</b> element you drop onto the page. Drop one on each page and paste the matching line.</li>
|
||||||
|
</ul>
|
||||||
|
<p>If the builder only accepts images and no scripts on a page, use the image version of the goal pixel there. Keep the landing page and the thank-you page on the same domain (see the checklist below).</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cg-ex">
|
||||||
|
<h3>Autoresponders: Aweber, GetResponse and others</h3>
|
||||||
|
<p>If your list provider shows its own thank-you page after someone subscribes, you cannot paste the pixel there. Point the provider at a thank-you page on <b>your</b> site instead, and put the goal pixel on that page.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>Aweber:</b> open your sign-up form's settings, set <b>Thank You Page</b> to a custom page, and paste your own page's address.</li>
|
||||||
|
<li><b>GetResponse:</b> in the form or landing page settings, set the <b>thank-you page</b> to a custom URL, and paste your own page's address.</li>
|
||||||
|
<li><b>Any other provider:</b> look for "thank-you page", "success page" or "redirect after sign-up" and give it your own page's address.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Your own thank-you page needs only your message and the goal pixel. Put the form on your landing page (where the landing tag runs), and use the same domain for both pages.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cg-ex">
|
||||||
|
<h3>What if I can't put code on the thank-you page?</h3>
|
||||||
|
<p>Best fix: send people to a thank-you page you control, as above. If that is not possible:</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>The pixel can go on the thank-you page, but it is on another domain, or only images are allowed there.</b> Use the image version. It cannot read the id your landing tag kept, so it counts through LinkSpin's cookie or the 24-hour match (the same network and browser within a day of the click). Both work, just less surely, and your report labels them so you can tell.</li>
|
||||||
|
<li><b>No code of any kind after the sign-up.</b> Then nothing can tell LinkSpin the sign-up happened. You can still keep the click id with each lead: add the hidden <code class="i">lsclk</code> field to your form, and if your provider keeps custom fields, the id is stored with the subscriber.</li>
|
||||||
|
<li><b>Your page signs people up without leaving the page</b> (a pop-up form). With the landing tag on that page, your page's own code can count the goal with one line after a successful sign-up: <code class="i">if (window.LinkSpin) LinkSpin.goal('YOUR_PIXEL_ID', 'subscriber');</code></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="rg-eye">Your numbers</p>
|
||||||
|
<h2>How to read the report</h2>
|
||||||
|
<p class="rg-note">On InstantAdPay, each campaign row under Campaigns gets a goal line, for example <b>subscriber 4 (35 credits each) · 61 tracked clicks</b>. The Conversion tracking card lists your goals with their conversions in the last 30 days, the last test, and how your conversions were matched. Numbers refresh about once a minute.</p>
|
||||||
|
<div class="rg-tbl">
|
||||||
|
<table>
|
||||||
|
<thead><tr><th>You see</th><th>What it means</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><td>Conversions (30 days)</td><td>Goals counted for this goal in the last 30 days, tests and your own clicks left out.</td></tr>
|
||||||
|
<tr><td>Cost per goal (30 days), in credits</td><td>The credits the campaign spent in the last 30 days, divided by its goals in the same 30 days, so an older campaign reads the same way as a new one. Spend comes from your credit activity (Campaigns, Credit activity). It is in ad credits, never dollars.</td></tr>
|
||||||
|
<tr><td>url <span class="muted">(LinkSpin: Address)</span></td><td>Surest. The thank-you page's own address still carried the click id.</td></tr>
|
||||||
|
<tr><td>stored <span class="muted">(LinkSpin: Kept)</span></td><td>Very sure. The landing tag kept the click id on your site and the goal pixel read it back.</td></tr>
|
||||||
|
<tr><td>cookie <span class="muted">(LinkSpin: Cookie)</span></td><td>Fairly sure. Matched through LinkSpin's own cookie in the visitor's browser. Some browsers block it.</td></tr>
|
||||||
|
<tr><td>soft <span class="muted">(LinkSpin: 24 h match)</span></td><td>Least sure. The same network and browser within 24 hours of a click on your ad. A good guess, not proof.</td></tr>
|
||||||
|
<tr><td>Last test</td><td>When your last test conversion arrived. Tests are recorded apart and never counted.</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div class="rg-two">
|
||||||
|
<div class="rg-box"><h3>The counting rules</h3><p>Each goal counts once per click, so one person signing up twice from one click is one goal. A goal counts only within 30 days of a real click, and only for clicks on your own ads. Your own clicks are kept as tests, never counted.</p></div>
|
||||||
|
<div class="rg-box"><h3>More detail on LinkSpin</h3><p>Sign in to LinkSpin with the same email and open <b>Conversions</b> in the Control Room for the full breakdown: by ad campaign (both sites), by destination page and by traffic source, a 7, 30 or 90 day range, and a CSV download.</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="rg-eye">Not counting?</p>
|
||||||
|
<h2>Troubleshooting checklist</h2>
|
||||||
|
<ul class="cg-check">
|
||||||
|
<li><b>Is the pixel id right?</b> It is <code class="i">px</code> plus 10 letters and numbers, copied from Snippets. A removed goal's pixel stops counting.</li>
|
||||||
|
<li><b>Did the test arrive?</b> Press Send a test conversion. If Last test updates, the goal is live. If the <code class="i">&test=1</code> check on your real page does not update it, the pixel is not on that page or the page strips it.</li>
|
||||||
|
<li><b>Does the click id reach your page?</b> Click your own ad: your landing page's address should show <code class="i">lsclk=</code>. If it does not, something between the ad and your page (a redirect or a link shortener) is dropping it. Point the ad straight at the page with the landing tag.</li>
|
||||||
|
<li><b>Is the landing tag on the page the ad points to?</b> Exactly that address, not another page of your site.</li>
|
||||||
|
<li><b>Same domain for both pages?</b> The landing tag keeps the id on one domain. If the landing page is on <code class="i">www.yoursite.com</code> and the thank-you page on <code class="i">yoursite.com</code> (or another site), the script pixel cannot read it and only the cookie or 24-hour match is left.</li>
|
||||||
|
<li><b>Goal pixel only on the thank-you page?</b> Not in a site-wide footer, not on the landing page.</li>
|
||||||
|
<li><b>Scripts stripped?</b> Some builders and hosted blogs remove scripts. Use the image version of the goal pixel there.</li>
|
||||||
|
<li><b>Testing with your own clicks?</b> Your own clicks on your ads (and on your LinkSpin spin links and Banner Spins) are kept as tests and never show in the counts. Use Send a test conversion and the <code class="i">&test=1</code> check above instead.</li>
|
||||||
|
<li><b>Older than 30 days, or the same click twice?</b> A sign-up more than 30 days after the click does not count, and each click counts once per goal.</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<p class="rg-eye">Quick answers</p>
|
||||||
|
<h2>Questions members ask</h2>
|
||||||
|
<dl class="rg-faq">
|
||||||
|
<div><dt>Does it cost anything?</dt><dd>No. Conversion tracking is free for every member. It does not use credits.</dd></div>
|
||||||
|
<div><dt>Will the tags slow down or break my page?</dt><dd>No. Both load in the background, never stop your page from showing, and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.</dd></div>
|
||||||
|
<div><dt>Do I need a separate goal for each ad?</dt><dd>No. One goal covers all your ads. Each conversion is counted against whichever ad sent that visitor.</dd></div>
|
||||||
|
<div><dt>Do my ads get the click id automatically?</dt><dd>Yes. Every click through your InstantAdPay ads carries one. Your page address keeps all its own parameters; the click id is added to the end.</dd></div>
|
||||||
|
<div><dt>Is any personal data sent?</dt><dd>No. The click id is random. No name or email from your page is read or sent.</dd></div>
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<div class="rg-rule"><b>What a credit is.</b> One credit is one cent of ad delivery across the network. Credits are not money and cannot be withdrawn. Cost per goal is shown in credits for that reason.</div>
|
||||||
|
<p class="muted small" style="margin-top:10px">Conversion tracking shows what your own ads and pages produce. It does not promise any number of sign-ups or sales. No income is guaranteed; any commissions depend on real purchases in your line and on your own effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.</p>
|
||||||
|
<footer>
|
||||||
|
<div>InstantAdPay · <a href="/">Home</a> · <a href="/refuel">Fuel Your Offers</a> · <a href="/earning">How earning works</a> · <a href="https://linkspin.app/conversion-tracking">The LinkSpin side</a></div>
|
||||||
|
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||||
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
<script src="/assets/common.js?v=20261023ov"></script>
|
||||||
|
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
|
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+13
-1
@@ -72,6 +72,18 @@
|
|||||||
<li><b>Level 2 opens at two qualifying buyers, level 3 at five.</b> A qualifying buyer is a direct referral who bought a package of $20 or more. Qualification never expires and cannot be bought. It is counted at the block the purchase happens in, so a buy that lands forty minutes before you qualify is passed up, not held.</li>
|
<li><b>Level 2 opens at two qualifying buyers, level 3 at five.</b> A qualifying buyer is a direct referral who bought a package of $20 or more. Qualification never expires and cannot be bought. It is counted at the block the purchase happens in, so a buy that lands forty minutes before you qualify is passed up, not held.</li>
|
||||||
<li><b>Passed-up shares go to the next qualified person above.</b> That is why the people who qualify early collect what the people below them are not yet set up to receive.</li>
|
<li><b>Passed-up shares go to the next qualified person above.</b> That is why the people who qualify early collect what the people below them are not yet set up to receive.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
<div data-when="override-live" hidden><!-- Level 4 override: shown only when overrideMode is live (common.js) -->
|
||||||
|
<h3>The Level 4 override: 3% from deeper in your line</h3>
|
||||||
|
<p>On top of the three levels the contract pays in the same transaction, the company pays a <b>3% override</b> on every package bought four levels below you. It goes to the 4th sponsor up from the buyer, as long as that member has <b>5 or more qualifying buyers</b>, the same bar that opens level 3.</p>
|
||||||
|
<ul>
|
||||||
|
<li><b>It hunts upward.</b> If the 4th sponsor up does not have 5 qualifying buyers yet, the override moves up the line to the next member who does, up to 25 steps. Each purchase pays one override to one person, never more.</li>
|
||||||
|
<li><b>Paid weekly in POL.</b> Every Monday after 9 AM Central, the company wallet sends the override for the Monday to Sunday week before through the contract's award function, so every payment has its own Polygon link. It shows in your Earnings as "Level 4 override".</li>
|
||||||
|
<li><b>Small amounts wait.</b> A weekly total under 0.01 POL carries over to the next week.</li>
|
||||||
|
<li><b>From the start date on.</b> It counts purchases made from <span data-ov-start>the start date</span> forward. Earlier purchases are not paid.</li>
|
||||||
|
<li><b>The company pays it, not the contract.</b> It comes out of the platform's 20% share, so the 50/20/10 split does not change for anyone.</li>
|
||||||
|
</ul>
|
||||||
|
<p>What it rewards: building wide, and bringing in people who actually want traffic. Five qualifying buyers of your own opens it. Members who advertise again and again are what keep it coming.</p>
|
||||||
|
</div>
|
||||||
<h3>Who is your sponsor</h3>
|
<h3>Who is your sponsor</h3>
|
||||||
<p>The invite link you opened most recently before creating your account sets your sponsor, and it locks the moment the account exists. Linked positions from Qualified Start count toward your badges, and their purchases pay your main position at level 1.</p>
|
<p>The invite link you opened most recently before creating your account sets your sponsor, and it locks the moment the account exists. Linked positions from Qualified Start count toward your badges, and their purchases pay your main position at level 1.</p>
|
||||||
<h3>Where to see it</h3>
|
<h3>Where to see it</h3>
|
||||||
@@ -84,6 +96,6 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+6
-1
@@ -112,6 +112,11 @@
|
|||||||
</table></div>
|
</table></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="card" data-when="override-live" hidden><!-- shown only when overrideMode is live (common.js) -->
|
||||||
|
<h3>Level 4 override (company paid)</h3>
|
||||||
|
<p class="muted small">Since <span data-ov-start>the start date</span> the company pays a weekly override of 3% of every package purchase to the buyer's 4th upline on the contract's sponsor line, if that member has 5 or more qualifying buyers. If not, it goes to the next qualified upline, up to 25 steps; if none is found, or the company account is reached first, the company keeps it. One override per purchase. It is paid in POL every Monday after 9 AM Central for the previous Monday to Sunday week, from a company wallet through the contract's public award function, and amounts under 0.01 POL carry to the next week. It is funded from the platform's 20% share; the contract split is unchanged. Purchases before the start date are not included.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>What InstantAdPay is not</h3>
|
<h3>What InstantAdPay is not</h3>
|
||||||
<ul class="muted small">
|
<ul class="muted small">
|
||||||
@@ -121,7 +126,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script>
|
<script src="/assets/common.js?v=20261023ov"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -55,7 +55,7 @@
|
|||||||
|
|
||||||
<div class="fr-steps">
|
<div class="fr-steps">
|
||||||
<div class="fr-step"><div class="n">Step 1</div><h3>Join free, by email.</h3><p>Email first, wallet later, inside your account. Nothing to install to look around.</p></div>
|
<div class="fr-step"><div class="n">Step 1</div><h3>Join free, by email.</h3><p>Email first, wallet later, inside your account. Nothing to install to look around.</p></div>
|
||||||
<div class="fr-step"><div class="n">Step 2</div><h3>Buy any pack from $5 on a Friday.</h3><p>Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log.</p></div>
|
<div class="fr-step"><div class="n">Step 2</div><h3>Buy any pack from $5 on a Friday.</h3><p>Central time, midnight to midnight. The 20% bonus is added to your credits the moment the purchase settles, and labelled in your credit log. You also get a free 7-day Game Pass for all ten games.</p></div>
|
||||||
<div class="fr-step"><div class="n">Step 3</div><h3>Your pack pays the line above you. Theirs pays you.</h3><p>Every package is one Polygon transaction that splits to the sponsor line instantly. Public ledger, nothing held, nothing pending.</p></div>
|
<div class="fr-step"><div class="n">Step 3</div><h3>Your pack pays the line above you. Theirs pays you.</h3><p>Every package is one Polygon transaction that splits to the sponsor line instantly. Public ledger, nothing held, nothing pending.</p></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -71,6 +71,6 @@
|
|||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/friday.js?v=20260925a"></script>
|
<script src="/assets/friday.js?v=20260925a"></script>
|
||||||
<script src="/assets/common.js?v=20261016n"></script>
|
<script src="/assets/common.js?v=20261023ov"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -78,6 +78,6 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+7
-2
@@ -472,6 +472,11 @@
|
|||||||
The 5 dollar package mints 500 credits, and the bigger packages mint bonus credits on top, up to
|
The 5 dollar package mints 500 credits, and the bigger packages mint bonus credits on top, up to
|
||||||
70,000 on the 500 dollar package. That is the product, plain and simple. Your earnings come from
|
70,000 on the 500 dollar package. That is the product, plain and simple. Your earnings come from
|
||||||
referring people who also buy real ad delivery, and the contract splits every purchase automatically.</p></details>
|
referring people who also buy real ad delivery, and the contract splits every purchase automatically.</p></details>
|
||||||
|
<details><summary>Can I see which ads bring me subscribers or sales?</summary>
|
||||||
|
<p>Yes. Campaigns > Conversion tracking in your dashboard gives you two small tags for your own site:
|
||||||
|
a landing tag for the page your ad points to and a goal pixel for your thank-you page. Each subscriber
|
||||||
|
or sale is counted against the ad that sent the visitor, once per click, within 30 days, and every
|
||||||
|
campaign shows its cost per goal in credits.</p></details>
|
||||||
|
|
||||||
<div class="closer">
|
<div class="closer">
|
||||||
<div>
|
<div>
|
||||||
@@ -500,9 +505,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/wallet.js?v=20260909c"></script>
|
<script src="/assets/wallet.js?v=20260909c"></script>
|
||||||
<script src="/assets/home.js?v=20261016p"></script>
|
<script src="/assets/home.js?v=20261027tb"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -157,7 +157,7 @@
|
|||||||
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
|
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/join.js?v=20261016p"></script>
|
<script src="/assets/join.js?v=20261016p"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -105,7 +105,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/launch.js?v=20260915b"></script>
|
<script src="/assets/launch.js?v=20260915b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2
-2
@@ -32,7 +32,7 @@
|
|||||||
<div class="card" style="padding:0">
|
<div class="card" style="padding:0">
|
||||||
<div data-ph-slot="0" style="margin:0 0 10px"></div>
|
<div data-ph-slot="0" style="margin:0 0 10px"></div>
|
||||||
<div class="feed" id="feed"><div class="row muted">Loading recent history…</div></div>
|
<div class="feed" id="feed"><div class="row muted">Loading recent history…</div></div>
|
||||||
<div class="nas-zone" style="max-width:728px;margin:22px auto 0;overflow:hidden;text-align:center"><!-- nas-ledger --><script src="https://www.networkadspace.com/showadss.php?w=728&h=90&n=1&bw=728&bh=90&c=999"></script></div>
|
<div class="nas-zone" style="max-width:728px;margin:22px auto 0;overflow:hidden;text-align:center"><!-- nas-ledger --><iframe title="Advertisement" width="728" height="90" scrolling="no" loading="lazy" style="border:0;max-width:100%;display:block;margin:0 auto;background:transparent" srcdoc="<!doctype html><base target="_blank"><style>html,body{margin:0;padding:0;overflow:hidden;background:transparent}</style><script src="https://www.networkadspace.com/showadss.php?w=728&h=90&n=1&bw=728&bh=90&c=999"></script>"></iframe><!-- framed 2026-10-24: a dead ad server must never block the page --></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card small" id="adSlotText" hidden></div>
|
<div class="card small" id="adSlotText" hidden></div>
|
||||||
<footer>
|
<footer>
|
||||||
@@ -40,7 +40,7 @@
|
|||||||
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/ledger.js?v=20260906m"></script>
|
<script src="/assets/ledger.js?v=20260906m"></script>
|
||||||
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
|
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
|
|||||||
+44
-5
@@ -139,6 +139,7 @@
|
|||||||
<button data-pane="pipeline" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="5" height="16" rx="1.2"/><rect x="9.5" y="4" width="5" height="11" rx="1.2"/><rect x="16" y="4" width="5" height="7" rx="1.2"/></svg>Pipeline<span class="pill" id="pipeBadge" hidden></span></button>
|
<button data-pane="pipeline" type="button"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="5" height="16" rx="1.2"/><rect x="9.5" y="4" width="5" height="11" rx="1.2"/><rect x="16" y="4" width="5" height="7" rx="1.2"/></svg>Pipeline<span class="pill" id="pipeBadge" hidden></span></button>
|
||||||
<button data-pane="buy" type="button"><svg viewBox="0 0 24 24"><circle cx="9" cy="20" r="1.6"/><circle cx="17" cy="20" r="1.6"/><path d="M3 4h2l2.4 11.2A2 2 0 0 0 9.4 17h8.2a2 2 0 0 0 2-1.6L21 8H6"/></svg>Buy packages</button>
|
<button data-pane="buy" type="button"><svg viewBox="0 0 24 24"><circle cx="9" cy="20" r="1.6"/><circle cx="17" cy="20" r="1.6"/><path d="M3 4h2l2.4 11.2A2 2 0 0 0 9.4 17h8.2a2 2 0 0 0 2-1.6L21 8H6"/></svg>Buy packages</button>
|
||||||
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>Campaigns</button>
|
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>Campaigns</button>
|
||||||
|
<button data-pane="engine" id="engineNav" type="button" hidden><svg viewBox="0 0 24 24"><path d="M4 16a8 8 0 1 1 16 0"/><path d="M12 16l4-5"/><circle cx="12" cy="16" r="1.4"/></svg>Engine Room</button>
|
||||||
<button data-pane="earn" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v9M9 10c0-1.1 1.3-1.8 3-1.8s3 .7 3 1.8-1.3 1.6-3 1.8-3 .7-3 1.8 1.3 1.8 3 1.8 3-.7 3-1.8"/></svg>Earn credits<span class="pill" id="inboxBadge" hidden></span></button>
|
<button data-pane="earn" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v9M9 10c0-1.1 1.3-1.8 3-1.8s3 .7 3 1.8-1.3 1.6-3 1.8-3 .7-3 1.8 1.3 1.8 3 1.8 3-.7 3-1.8"/></svg>Earn credits<span class="pill" id="inboxBadge" hidden></span></button>
|
||||||
<button data-pane="earnings" type="button"><svg viewBox="0 0 24 24"><path d="M4 17l5-5 4 3 7-8"/><path d="M14 7h6v6"/></svg>Earnings</button>
|
<button data-pane="earnings" type="button"><svg viewBox="0 0 24 24"><path d="M4 17l5-5 4 3 7-8"/><path d="M14 7h6v6"/></svg>Earnings</button>
|
||||||
<button data-pane="promo" type="button"><svg viewBox="0 0 24 24"><path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/></svg>Promo tools</button>
|
<button data-pane="promo" type="button"><svg viewBox="0 0 24 24"><path d="M7 10s5-1 9-5v14c-4-4-9-5-9-5H5a2 2 0 0 1-2-2v0a2 2 0 0 1 2-2h2z"/><path d="M8 15l1 5h2l-1-5"/></svg>Promo tools</button>
|
||||||
@@ -183,6 +184,7 @@
|
|||||||
<div class="card" id="phLaunch" hidden></div>
|
<div class="card" id="phLaunch" hidden></div>
|
||||||
<div class="card" id="fdfCard" hidden></div>
|
<div class="card" id="fdfCard" hidden></div>
|
||||||
<div class="card" id="wwCard" hidden></div>
|
<div class="card" id="wwCard" hidden></div>
|
||||||
|
<div class="card" id="rfCard" hidden aria-live="polite"></div>
|
||||||
<div class="card" id="gpNudge" hidden></div>
|
<div class="card" id="gpNudge" hidden></div>
|
||||||
<div class="card gs" id="gsCard" hidden>
|
<div class="card gs" id="gsCard" hidden>
|
||||||
<div class="card-head"><h3>Getting started</h3><span class="sub" id="gsSub"></span></div>
|
<div class="card-head"><h3>Getting started</h3><span class="sub" id="gsSub"></span></div>
|
||||||
@@ -196,7 +198,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="statx c-cyan">
|
<div class="statx c-cyan">
|
||||||
<div class="pl"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><circle cx="16.5" cy="14.5" r="1.4"/></svg></div>
|
<div class="pl"><svg viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><circle cx="16.5" cy="14.5" r="1.4"/></svg></div>
|
||||||
<div><div class="nv mono" id="dbEarned">0</div><div class="lb">POL earned</div><span class="chip" id="dbEarnedChip" hidden></span></div>
|
<div><div class="nv mono" id="dbEarned">0</div><div class="lb">POL earned <span class="muted" id="dbEarnedUsd"></span></div><span class="chip" id="dbEarnedChip" hidden></span></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="statx c-violet">
|
<div class="statx c-violet">
|
||||||
<div class="pl"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg></div>
|
<div class="pl"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg></div>
|
||||||
@@ -528,6 +530,7 @@
|
|||||||
<option value="visits">Verified visits (guaranteed unique)</option>
|
<option value="visits">Verified visits (guaranteed unique)</option>
|
||||||
</select></p>
|
</select></p>
|
||||||
<p class="small muted" id="cWhere" style="margin:-4px 0 10px"></p>
|
<p class="small muted" id="cWhere" style="margin:-4px 0 10px"></p>
|
||||||
|
<p class="small" id="cLoginLine" hidden style="grid-column:1/-1;margin:-4px 0 10px"></p>
|
||||||
<p><input id="cName" placeholder="Campaign name" style="width:100%"></p>
|
<p><input id="cName" placeholder="Campaign name" style="width:100%"></p>
|
||||||
<p id="cBudgetRow"><input id="cBudget" type="number" placeholder="Budget (credits)" min="10" style="width:100%"></p>
|
<p id="cBudgetRow"><input id="cBudget" type="number" placeholder="Budget (credits)" min="10" style="width:100%"></p>
|
||||||
<p id="cCapRow" style="grid-column:1/-1"><input id="cDailyCap" type="number" placeholder="Daily cap in credits (optional) — paces the budget across days" min="10" style="width:100%">
|
<p id="cCapRow" style="grid-column:1/-1"><input id="cDailyCap" type="number" placeholder="Daily cap in credits (optional) — paces the budget across days" min="10" style="width:100%">
|
||||||
@@ -617,6 +620,34 @@
|
|||||||
</div>
|
</div>
|
||||||
<button class="btn" id="createCampBtn">Launch campaign</button>
|
<button class="btn" id="createCampBtn">Launch campaign</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card" id="convCard" hidden>
|
||||||
|
<h3>Conversion tracking</h3>
|
||||||
|
<p class="small" style="margin:0 0 6px"><a href="/conversion-tracking" target="_blank" rel="noopener">How to set it up: the step-by-step guide with copy-paste examples</a></p>
|
||||||
|
<p class="muted small">See which of your ads bring subscribers and sales, not just clicks. Every click on your ad carries a click id. Put two small tags on your own site and each goal is counted against the ad that sent the visitor, with a cost per goal in credits on each campaign above. The counting is done by LinkSpin, our sister site, under this same email.</p>
|
||||||
|
<ol class="small" style="margin:6px 0 10px 18px;padding:0">
|
||||||
|
<li>Add a goal below, for example <b>subscriber</b> or <b>sale</b>.</li>
|
||||||
|
<li>Put the <b>landing tag</b> on the page your ad sends people to (once per page, just before </body>).</li>
|
||||||
|
<li>Put the <b>goal pixel</b> on your thank-you page, the page people see after they sign up or buy.</li>
|
||||||
|
</ol>
|
||||||
|
<p class="small" id="convStatus"></p>
|
||||||
|
<div id="convGoals"></div>
|
||||||
|
<div id="convAddRow" class="grid c3" style="margin-top:10px">
|
||||||
|
<p><input id="convName" maxlength="32" placeholder="Goal name, like subscriber or sale" style="width:100%"></p>
|
||||||
|
<p><input id="convValue" type="number" min="0" step="0.01" placeholder="Default value (optional), like 19.95" style="width:100%"></p>
|
||||||
|
<p><button class="btn small" id="convAddBtn" type="button">Add goal</button></p>
|
||||||
|
</div>
|
||||||
|
<div id="convSnips"></div>
|
||||||
|
<h4 style="margin:14px 0 4px">Your autoresponder's thank-you page</h4>
|
||||||
|
<p class="small muted" style="margin:0">Set your autoresponder's thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose 'Thank You Page: custom page' and paste your page's address. GetResponse: in the form or landing page settings, pick 'Thank-you page: custom URL' and paste your page's address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely.</p>
|
||||||
|
<h4 style="margin:14px 0 4px">How sure is each count</h4>
|
||||||
|
<ul class="small muted" id="convLegend" style="margin:0 0 0 18px;padding:0">
|
||||||
|
<li><b>Click id in the address</b> (url): surest. The thank-you page address still carried the click id from your ad.</li>
|
||||||
|
<li><b>Stored by the landing tag</b> (stored): very sure. The landing tag kept the click id on your site and the goal pixel read it back.</li>
|
||||||
|
<li><b>LinkSpin cookie</b> (cookie): fairly sure. Matched through LinkSpin's own cookie in the visitor's browser. Some browsers block it.</li>
|
||||||
|
<li><b>24-hour match</b> (soft): least sure. Same connection and browser within 24 hours of a click. A good guess, not a proof.</li>
|
||||||
|
</ul>
|
||||||
|
<p class="small muted" style="margin:8px 0 0">Each goal counts once per click, only within 30 days of a real click on one of your ads. Your own clicks (on your ads here, and on your LinkSpin spin links and Banner Spins) and the test button count as tests, never in your numbers. Send a test conversion loads your real pixel in test mode. Cost per goal (30 days) = the credits a campaign spent in the same 30 days, divided by its goals.</p>
|
||||||
|
</div>
|
||||||
<div class="card ad-foot" id="adSlotPane-campaigns" hidden></div>
|
<div class="card ad-foot" id="adSlotPane-campaigns" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -745,6 +776,7 @@
|
|||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>Earnings</h3>
|
<h3>Earnings</h3>
|
||||||
<p class="muted small">Every payout the contract has sent to your wallet. Each line links to the transaction.</p>
|
<p class="muted small">Every payout the contract has sent to your wallet. Each line links to the transaction.</p>
|
||||||
|
<p class="muted small" id="earnUsdNote" style="margin-top:-4px"></p>
|
||||||
<div class="feed" id="earnFeed"><div class="row muted">Nothing yet.</div></div>
|
<div class="feed" id="earnFeed"><div class="row muted">Nothing yet.</div></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
@@ -767,7 +799,11 @@
|
|||||||
<div class="card ad-foot" id="adSlotPane-earnings" hidden></div>
|
<div class="card ad-foot" id="adSlotPane-earnings" hidden></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="pane" id="pane-engine" hidden>
|
||||||
|
<div class="card"><div class="card-head"><h3>Engine Room</h3><span class="sub">InstantAdPay and LinkSpin at a glance</span></div><div id="erRoot" data-host="engineNav" aria-live="polite"></div></div>
|
||||||
|
</div>
|
||||||
<div class="pane" id="pane-promo" hidden>
|
<div class="pane" id="pane-promo" hidden>
|
||||||
|
<div class="card" id="rkCard" hidden aria-live="polite"></div>
|
||||||
<div class="card" id="promoLinks">
|
<div class="card" id="promoLinks">
|
||||||
<div class="card-head"><h3>Your links</h3><span class="sub">one invite link, eight front doors</span></div>
|
<div class="card-head"><h3>Your links</h3><span class="sub">one invite link, eight front doors</span></div>
|
||||||
<div class="promo-strip" style="padding:0 0 12px">
|
<div class="promo-strip" style="padding:0 0 12px">
|
||||||
@@ -786,7 +822,7 @@
|
|||||||
<span><button class="btn small sec" id="promoWallCopy" type="button">Copy wall link</button> <a class="btn small sec" id="promoWallOpen" href="#" target="_blank" rel="noopener">Open</a></span>
|
<span><button class="btn small sec" id="promoWallCopy" type="button">Copy wall link</button> <a class="btn small sec" id="promoWallOpen" href="#" target="_blank" rel="noopener">Open</a></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="chips promo-pills" role="tablist" aria-label="Promo tools sections">
|
<div class="chips promo-pills" role="tablist" aria-label="Promo tools sections">
|
||||||
<button class="chip-t" data-promo="toolkit" type="button" role="tab">✨ AI Copy Engine</button>
|
<button class="chip-t" data-promo="toolkit" type="button" role="tab">✨ Your toolkit</button>
|
||||||
<button class="chip-t on" data-promo="posts" type="button" role="tab">Social posts</button>
|
<button class="chip-t on" data-promo="posts" type="button" role="tab">Social posts</button>
|
||||||
<button class="chip-t" data-promo="text" type="button" role="tab">Text a friend</button>
|
<button class="chip-t" data-promo="text" type="button" role="tab">Text a friend</button>
|
||||||
<button class="chip-t" data-promo="swipe" type="button" role="tab">Email swipes</button>
|
<button class="chip-t" data-promo="swipe" type="button" role="tab">Email swipes</button>
|
||||||
@@ -1093,6 +1129,7 @@
|
|||||||
.game-card .btn{margin-top:auto;text-align:center}
|
.game-card .btn{margin-top:auto;text-align:center}
|
||||||
.game-card{position:relative}
|
.game-card{position:relative}
|
||||||
#gpCard.gp-hl{outline:2px solid var(--gold,#e2b04a);outline-offset:2px}
|
#gpCard.gp-hl{outline:2px solid var(--gold,#e2b04a);outline-offset:2px}
|
||||||
|
.gp-tbl{width:100%;border-collapse:collapse;font-size:13px}.gp-tbl td{padding:5px 8px;border-top:1px solid var(--line,#e5e7eb);vertical-align:top}.gp-tbl td:first-child{font-weight:700;white-space:nowrap;width:1%}
|
||||||
.gp-tiers{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-top:10px}
|
.gp-tiers{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-top:10px}
|
||||||
.gp-tier{border:1px solid var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
|
.gp-tier{border:1px solid var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
|
||||||
.gp-tier.on{border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
|
.gp-tier.on{border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
|
||||||
@@ -1182,11 +1219,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||||
<script src="/assets/promo.js?v=20261016p"></script>
|
<script src="/assets/promo.js?v=20261028p"></script>
|
||||||
<script src="/assets/support.js?v=20261016a"></script>
|
<script src="/assets/support.js?v=20261016a"></script>
|
||||||
<script src="/assets/my.js?v=20261020share"></script>
|
<script src="/assets/my.js?v=20261028pp"></script>
|
||||||
|
<script src="/assets/fuel.js?v=20261025ff"></script>
|
||||||
|
<script src="/assets/engine-room.js?v=20261025ff"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -130,7 +130,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/partners.js?v=20260914a"></script>
|
<script src="/assets/partners.js?v=20260914a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -193,7 +193,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/plays.js?v=20260910b"></script>
|
<script src="/assets/plays.js?v=20260910b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -86,6 +86,6 @@
|
|||||||
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+4
-2
@@ -10,7 +10,7 @@
|
|||||||
<body>
|
<body>
|
||||||
<div id="nav"></div>
|
<div id="nav"></div>
|
||||||
<section><div class="wrap" style="max-width:820px">
|
<section><div class="wrap" style="max-width:820px">
|
||||||
<div class="sectionhead" style="text-align:left"><h2>Privacy Policy</h2><p class="muted small">Last updated: September 2026</p></div>
|
<div class="sectionhead" style="text-align:left"><h2>Privacy Policy</h2><p class="muted small">Last updated: October 2026</p></div>
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<h3>What we collect</h3>
|
<h3>What we collect</h3>
|
||||||
<p class="muted small">A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. Campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.</p>
|
<p class="muted small">A minimal set: the email you sign up with, a username and any profile details you choose to add (avatar, bio, social links), and, only if you link one, your public wallet address. Campaign content you create and reports you submit are stored to run the service. We also read on-chain activity that is already public on the blockchain.</p>
|
||||||
@@ -21,6 +21,8 @@
|
|||||||
<h3>Cookies</h3>
|
<h3>Cookies</h3>
|
||||||
<p class="muted small">We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, and a browser identifier cookie used only to enforce one account per person. No third-party ad-tracking cookies.</p>
|
<p class="muted small">We use a session cookie to keep you signed in, a referral cookie to credit the sponsor whose link you arrived through, and a browser identifier cookie used only to enforce one account per person. No third-party ad-tracking cookies.</p>
|
||||||
<p class="muted small"><strong>Abuse prevention.</strong> When you create an account and when you sign in we record your IP address, browser type and the browser identifier. We use them to detect duplicate accounts and self-referral, which the Terms prohibit, and for nothing else. They are visible to the site administrator only and are not sold or shared.</p>
|
<p class="muted small"><strong>Abuse prevention.</strong> When you create an account and when you sign in we record your IP address, browser type and the browser identifier. We use them to detect duplicate accounts and self-referral, which the Terms prohibit, and for nothing else. They are visible to the site administrator only and are not sold or shared.</p>
|
||||||
|
<h3>Conversion tracking on ad links</h3>
|
||||||
|
<p class="muted small">When you click an ad here, the link to the advertiser's site gets a random click id added to its address (it looks like <code>lsclk=i3f9a0c1b2d4e</code>). The id says nothing about you. We record which ad it belongs to, the time, your country, phone or computer, and the page the click came from, and pass that to LinkSpin, our sister site, which counts the advertiser's results. If the advertiser has added the LinkSpin landing tag to their own site, that tag keeps the click id on their site (in the browser's local storage and a first-party cookie of their site). If you later sign up or buy there, their goal pixel on the thank-you page tells LinkSpin that one goal happened for that click. Nothing personal is sent: no name, no email, no wallet. Your IP address is never stored; it is only used in hashed form, together with your browser type, for a match within 24 hours of the click when the click id is missing.</p>
|
||||||
<h3>Sharing</h3>
|
<h3>Sharing</h3>
|
||||||
<p class="muted small">Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.</p>
|
<p class="muted small">Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.</p>
|
||||||
<h3>Your choices</h3>
|
<h3>Your choices</h3>
|
||||||
@@ -29,7 +31,7 @@
|
|||||||
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
|
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -0,0 +1,265 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>Fuel Your Offers: the Monthly Refuel guide | InstantAdPay</title>
|
||||||
|
<meta name="description" content="How the Monthly Refuel streak works on InstantAdPay and LinkSpin: refuel your ads every month with a $20+ package here or $25+ on LinkSpin, and your bonus ad credits climb from +10% to +40%. The flow, the numbers and the member steps.">
|
||||||
|
<meta name="theme-color" content="#043b2f">
|
||||||
|
<link rel="canonical" href="https://instantadpay.com/refuel">
|
||||||
|
<meta property="og:type" content="website"><meta property="og:site_name" content="InstantAdPay">
|
||||||
|
<meta property="og:title" content="Fuel Your Offers: refuel every month, watch your bonus climb">
|
||||||
|
<meta property="og:description" content="The Monthly Refuel streak on InstantAdPay and LinkSpin: bonus ad credits from +10% up to +40% when you refuel your ads every month. Here is how it works, step by step.">
|
||||||
|
<meta property="og:image" content="https://instantadpay.com/banners/fuel-your-offers-1200x675.jpg">
|
||||||
|
<meta property="og:image:width" content="1200"><meta property="og:image:height" content="675">
|
||||||
|
<meta property="og:url" content="https://instantadpay.com/refuel">
|
||||||
|
<meta name="twitter:card" content="summary_large_image">
|
||||||
|
<meta name="twitter:image" content="https://instantadpay.com/banners/fuel-your-offers-1200x675.jpg">
|
||||||
|
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||||
|
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||||
|
<link rel="stylesheet" href="/assets/site.css?v=20260912b">
|
||||||
|
<style>
|
||||||
|
.rg{max-width:900px}
|
||||||
|
.rg .hero{padding:44px 0 10px}
|
||||||
|
.rg-banner{display:block;width:100%;height:auto;border-radius:16px;border:1px solid var(--line);margin:18px 0 14px}
|
||||||
|
.rg h2{font-size:26px;margin:38px 0 6px}
|
||||||
|
.rg h3{font-size:17px;margin:0 0 6px}
|
||||||
|
.rg-eye{font-family:var(--mono);font-size:11px;letter-spacing:.14em;text-transform:uppercase;color:var(--amber);font-weight:700;margin:38px 0 0}
|
||||||
|
.rg-eye + h2{margin-top:6px}
|
||||||
|
.rg-gauge{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:8px 0 18px}
|
||||||
|
.rg-gauge div{border:1px solid var(--line);border-radius:12px;padding:12px;background:rgba(255,255,255,.02);min-width:0}
|
||||||
|
.rg-gauge b{display:block;font-family:var(--mono);font-size:22px;color:var(--amber);font-variant-numeric:tabular-nums}
|
||||||
|
.rg-gauge span{font-size:13px;color:var(--muted)}
|
||||||
|
.rg-gauge div:last-child{border-color:rgba(255,178,56,.55);background:rgba(255,178,56,.08)}
|
||||||
|
.rg-cta{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin:6px 0 10px}
|
||||||
|
.rg-cta .btn.big{font-size:17px;padding:14px 22px}
|
||||||
|
/* the flow: one spine down the page, decisions open into branch cards that stack on a phone */
|
||||||
|
.rg-flow{list-style:none;margin:14px 0 8px;padding:0;display:grid;gap:0}
|
||||||
|
.rg-flow > li{display:grid;gap:10px;position:relative;padding-bottom:30px}
|
||||||
|
.rg-flow > li:not(:last-child)::after{content:"";position:absolute;left:22px;bottom:4px;width:2px;height:22px;background:var(--line-strong)}
|
||||||
|
.rg-flow > li:not(:last-child)::before{content:"";position:absolute;left:17px;bottom:0;border:6px solid transparent;border-top-color:var(--line-strong);border-bottom:0}
|
||||||
|
.rg-n{border:1px solid var(--line-strong);border-radius:12px;padding:11px 14px;font-size:14.5px;line-height:1.45;background:rgba(255,255,255,.02);min-width:0}
|
||||||
|
.rg-n b{display:block;font-family:var(--disp);font-size:15px;color:var(--ink);margin-bottom:2px}
|
||||||
|
.rg-n .k{display:inline-grid;place-items:center;width:24px;height:24px;border-radius:50%;font-family:var(--mono);font-size:12px;font-weight:700;margin-right:6px;vertical-align:1px;background:var(--ink);color:#04120e}
|
||||||
|
.rg-n.start{border-color:var(--mint);background:var(--mint-soft)}
|
||||||
|
.rg-n.ask{border-style:dashed;border-color:rgba(238,247,243,.45)}
|
||||||
|
.rg-n.go{border-color:rgba(67,232,195,.6);background:rgba(67,232,195,.08)}
|
||||||
|
.rg-n.fuel{border-color:rgba(255,178,56,.7);background:rgba(255,178,56,.09)}
|
||||||
|
.rg-n.stop{border-color:rgba(139,166,156,.45);background:rgba(139,166,156,.07);color:var(--muted)}
|
||||||
|
.rg-n .to{display:block;margin-top:4px;font-family:var(--mono);font-size:12px;color:var(--muted)}
|
||||||
|
.rg-br{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,230px),1fr));gap:10px;padding-left:18px;border-left:2px solid var(--line-strong);margin-left:22px}
|
||||||
|
.rg-b{display:grid;gap:6px;align-content:start;min-width:0}
|
||||||
|
.rg-e{font-family:var(--mono);font-size:11.5px;letter-spacing:.04em;color:var(--mint);font-weight:700}
|
||||||
|
.rg-b .rg-br{margin-left:4px;padding-left:12px}
|
||||||
|
.rg-legend{display:flex;flex-wrap:wrap;gap:8px 18px;font-size:13px;color:var(--muted);margin:0 0 6px}
|
||||||
|
.rg-legend i{display:inline-block;width:12px;height:12px;border-radius:3px;margin-right:6px;vertical-align:-1px;border:1px solid}
|
||||||
|
/* the numbers */
|
||||||
|
.rg-tbl{border:1px solid var(--line);border-radius:14px;overflow:hidden;margin:10px 0 8px}
|
||||||
|
.rg-tbl table{width:100%;border-collapse:collapse;font-size:15px}
|
||||||
|
.rg-tbl th,.rg-tbl td{padding:10px 12px;text-align:left;border-bottom:1px solid var(--line)}
|
||||||
|
.rg-tbl th{font-family:var(--mono);font-size:11px;letter-spacing:.1em;text-transform:uppercase;color:var(--muted);font-weight:600}
|
||||||
|
.rg-tbl td.n,.rg-tbl th.n{text-align:right;font-family:var(--mono);font-variant-numeric:tabular-nums}
|
||||||
|
.rg-tbl td.both{color:var(--amber);font-weight:700}
|
||||||
|
.rg-tbl tr:last-child td{border-bottom:0}
|
||||||
|
.rg-note{font-size:14.5px;color:var(--muted);margin:8px 0 0}
|
||||||
|
/* member route */
|
||||||
|
.rg-route{list-style:none;counter-reset:s;margin:12px 0 0;padding:0;display:grid;gap:14px}
|
||||||
|
.rg-route li{counter-increment:s;display:grid;grid-template-columns:42px minmax(0,1fr);gap:14px;align-items:start;border:1px solid var(--line);border-radius:14px;padding:14px 16px;background:rgba(255,255,255,.02)}
|
||||||
|
.rg-route li::before{content:counter(s);font-family:var(--disp);font-weight:800;font-size:20px;width:42px;height:42px;border-radius:50%;display:grid;place-items:center;background:var(--amber);color:#1b1203}
|
||||||
|
.rg-route p{margin:0 0 8px;font-size:14.5px;color:var(--muted)}
|
||||||
|
.rg-where{display:flex;flex-wrap:wrap;gap:6px}
|
||||||
|
.rg-chip{font-size:12.5px;font-weight:600;padding:3px 10px;border-radius:999px;background:var(--mint-soft);color:var(--mint);border:1px solid rgba(67,232,195,.35)}
|
||||||
|
.rg-chip.ls{background:rgba(84,204,255,.08);color:var(--cyan);border-color:rgba(84,204,255,.35)}
|
||||||
|
.rg-two{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,300px),1fr));gap:14px;margin:30px 0 0}
|
||||||
|
.rg-box{border:1px solid var(--line);border-radius:14px;padding:16px 18px;background:rgba(255,255,255,.02);min-width:0}
|
||||||
|
.rg-box p{margin:0;font-size:14.5px;color:var(--muted)}
|
||||||
|
.rg-coach{border-left:4px solid var(--amber);background:rgba(255,178,56,.07);padding:16px 18px;border-radius:0 14px 14px 0;margin:30px 0 0}
|
||||||
|
.rg-coach ul{margin:8px 0 0;padding-left:20px;display:grid;gap:6px;font-size:14.5px}
|
||||||
|
.rg-faq{display:grid;gap:14px;margin:12px 0 0}
|
||||||
|
.rg-faq dt{font-family:var(--disp);font-weight:700}
|
||||||
|
.rg-faq dd{margin:4px 0 0;color:var(--muted);font-size:14.5px}
|
||||||
|
.rg-rule{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:14px 18px;border-radius:0 12px 12px 0;margin:30px 0 22px;font-size:14.5px}
|
||||||
|
@media (max-width:640px){.rg-gauge{grid-template-columns:repeat(2,minmax(0,1fr))}.rg .hero h1{font-size:30px}.rg-br{margin-left:10px;padding-left:12px}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="wrap rg">
|
||||||
|
<section class="hero">
|
||||||
|
<p class="eyebrow">InstantAdPay + LinkSpin · live since October 24, 2026</p>
|
||||||
|
<h1>Fuel Your Offers: <em>refuel every month</em>, watch your bonus climb.</h1>
|
||||||
|
<p class="lead">Your ads run on fuel. Refuel them every month with a new package and the Monthly Refuel streak adds bonus ad credits that climb each month, a fresh Refuel Kit lands with your name on it, and the Engine Room tells you the next move. Either site keeps your streak going. Refuel both in the same cycle and the bonus is bigger on both.</p>
|
||||||
|
</section>
|
||||||
|
<video class="rg-banner" src="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/refuel-iap.mp4?v=20261024" poster="https://coolify-saasytop.nyc3.digitaloceanspaces.com/training/refuel-iap.jpg?v=20261024" controls playsinline preload="metadata" width="1200" height="675" style="background:#000" aria-label="Video: Marty walks through Fuel Your Offers on InstantAdPay, 3 minutes"></video>
|
||||||
|
|
||||||
|
<div class="rg-gauge" aria-label="Bonus when you refuel both sites, by streak month">
|
||||||
|
<div><b>+15%</b><span>Month 1, both engines</span></div>
|
||||||
|
<div><b>+20%</b><span>Month 2</span></div>
|
||||||
|
<div><b>+30%</b><span>Month 3</span></div>
|
||||||
|
<div><b>+40%</b><span>Month 4 and on, + 100 Featured credits</span></div>
|
||||||
|
</div>
|
||||||
|
<div class="rg-cta">
|
||||||
|
<a class="btn big" href="/join">Join free by email</a>
|
||||||
|
<a class="btn sec" href="/my#buy">Already a member? Buy a package</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="rg-eye">Why it matters</p>
|
||||||
|
<h2>Why keep refueling</h2>
|
||||||
|
<p class="lead" style="margin:0 0 14px">Traffic is what makes an offer work, and traffic stops the day your credits run out. An ad that runs for a week and then goes dark gives people one look. Most people don't act on the first look. They act after they've seen your offer a few times, over days and weeks. Refueling every month keeps your offer in front of people the whole month, not just the week you bought.</p>
|
||||||
|
<div class="rg-two" style="margin-top:0">
|
||||||
|
<div class="rg-box"><h3 style="margin:0 0 6px">Steady beats bursts</h3><p>One big push, then nothing, means every new visitor sees you once. A monthly refuel keeps your ads running every day, so the people who saw you last week see you again this week. That repeat exposure is what turns a click into a sign-up.</p></div>
|
||||||
|
<div class="rg-box"><h3 style="margin:0 0 6px">Your numbers get useful</h3><p>With ads running all month you collect enough clicks and goals to see which ad actually works. The Engine Room and conversion tracking show you the winner, and next month's fuel goes behind it instead of guessing.</p></div>
|
||||||
|
<div class="rg-box"><h3 style="margin:0 0 6px">Fresh creative every month</h3><p>The Refuel Kit gives you new banners with your name and QR code each month, so the same audience sees something new instead of tuning out the ad they've already passed ten times.</p></div>
|
||||||
|
<div class="rg-box"><h3 style="margin:0 0 6px">Each month buys more</h3><p>The bonus climbs the longer you keep the streak, so the same package delivers more ads in month four than in month one. Refuel both sites and it climbs faster.</p></div>
|
||||||
|
</div>
|
||||||
|
<p style="margin:14px 0 30px;font-size:15px;color:var(--muted)">The bonus isn't the point. It just makes the habit cheaper. The point is that your offer never goes dark.</p>
|
||||||
|
|
||||||
|
<p class="rg-eye">The flow</p>
|
||||||
|
<h2>What happens when you buy a package</h2>
|
||||||
|
<div class="rg-legend">
|
||||||
|
<span><i style="background:rgba(67,232,195,.15);border-color:#43e8c3"></i>Streak moves forward</span>
|
||||||
|
<span><i style="background:rgba(255,178,56,.18);border-color:#ffb238"></i>Bonus boost</span>
|
||||||
|
<span><i style="background:rgba(139,166,156,.12);border-color:#8ba69c"></i>No refuel bonus</span>
|
||||||
|
<span><i style="border-style:dashed;border-color:#eef7f3"></i>A question</span>
|
||||||
|
</div>
|
||||||
|
<ol class="rg-flow" aria-label="Refuel flow, step by step">
|
||||||
|
<li><div class="rg-n start"><b><span class="k">1</span>You buy a new ad package on either site</b>InstantAdPay or LinkSpin, paid from your own wallet.</div></li>
|
||||||
|
<li>
|
||||||
|
<div class="rg-n ask"><b><span class="k">2</span>Does it meet that site's minimum?</b>InstantAdPay package: $20 or more. LinkSpin package: $25 or more. Bought by you or one of your own linked positions.</div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n stop"><b>Normal purchase</b>No refuel bonus.</div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Keep going</b><span class="to">down to the next question</span></div></div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<div class="rg-n ask"><b><span class="k">3</span>Are you already on a streak?</b></div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">No: your first refuel, or your streak ended</span><div class="rg-n go"><b>Streak starts at month 1</b>Today becomes your refuel day. Your very first one also earns the Engine Started badge.<span class="to">then step 5</span></div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Keep going</b><span class="to">down to the next question</span></div></div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<div class="rg-n ask"><b><span class="k">4</span>When is it, against your refuel day?</b></div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">Inside the window: 5 days before to 5 days after</span><div class="rg-n go"><b>Counted refuel</b>Your streak moves up a month.<span class="to">then step 5</span></div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">After the 5-day grace</span>
|
||||||
|
<div class="rg-n ask"><b>Free miss left in the last 365 days?</b></div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n go"><b>Streak kept</b>This package counts as your next month.<span class="to">then step 5</span></div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n go"><b>Streak starts over at month 1</b>Today becomes your new refuel day.<span class="to">then step 5</span></div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="rg-b"><span class="rg-e">More than 5 days before</span>
|
||||||
|
<div class="rg-n ask"><b>Already refueled on this site this cycle?</b></div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">No</span><div class="rg-n fuel"><b>Second engine</b>This is the other site's refuel for the same cycle: both-engines rate here, and the first site is topped up to match (step 6). Your refuel day stays put.</div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">Yes</span><div class="rg-n fuel"><b>Pit Stop</b>Half your current rate, once per site per cycle. Not a refuel, so your refuel day stays put. A second top-up on the same site is a normal purchase.</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="rg-n go"><b><span class="k">5</span>Bonus credits land at your month's rate</b>One engine: +10% in month 1, +15% in month 2, +20% in month 3, +25% from month 4. Added on the site where you bought.</div></li>
|
||||||
|
<li>
|
||||||
|
<div class="rg-n ask"><b><span class="k">6</span>Later this cycle: refuel the other site too, before your next window opens?</b></div>
|
||||||
|
<div class="rg-br">
|
||||||
|
<div class="rg-b"><span class="rg-e">Yes: both engines</span><div class="rg-n fuel"><b>Higher rate on both sites</b>+15%, +20%, +30%, then +40% from month 4. The first site is topped up to match. From month 4 you also get 100 Featured bonus credits on InstantAdPay.</div></div>
|
||||||
|
<div class="rg-b"><span class="rg-e">No: one engine</span><div class="rg-n go"><b>One-engine rate</b>Your streak still counts. Either site keeps it going.</div></div>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
<li><div class="rg-n go"><b><span class="k">7</span>This month's Refuel Kit unlocks</b>Badges at 3, 6 and 12 months in a row.</div></li>
|
||||||
|
<li><div class="rg-n go"><b><span class="k">8</span>Next refuel day = 30 days after this one</b>Reminders 5 days before, on the day, and a last call at the end of your grace. Then it is back to step 1 next month.</div></li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<p class="rg-eye">The numbers</p>
|
||||||
|
<h2>The bonus climbs</h2>
|
||||||
|
<div class="rg-tbl"><table>
|
||||||
|
<thead><tr><th>Months in a row</th><th class="n">One engine</th><th class="n">Both engines</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><td>Month 1</td><td class="n">+10%</td><td class="n both">+15%</td></tr>
|
||||||
|
<tr><td>Month 2</td><td class="n">+15%</td><td class="n both">+20%</td></tr>
|
||||||
|
<tr><td>Month 3</td><td class="n">+20%</td><td class="n both">+30%</td></tr>
|
||||||
|
<tr><td>Month 4 and on</td><td class="n">+25%</td><td class="n both">+40% each</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<p class="rg-note">A percent of the package's credits, added as bonus ad credits on the site where you bought. One engine means you refueled one site this cycle; both engines means InstantAdPay and LinkSpin in the same cycle. From month 4 with both engines you also get 100 Featured bonus credits on InstantAdPay. A Pit Stop pays half your current rate. The refuel bonus is its own grant, so it stacks on Five Dollar Friday (+20% on $5+ packages) and Wired Wednesday (+25% on $20+ packages). Bonus credits buy ad delivery only. They are never cash.</p>
|
||||||
|
|
||||||
|
<p class="rg-eye">Member guide</p>
|
||||||
|
<h2>Your route, step by step</h2>
|
||||||
|
<ol class="rg-route">
|
||||||
|
<li><div>
|
||||||
|
<h3>Start your engine</h3>
|
||||||
|
<p>Buy a new package of $20 or more here, or $25 or more on LinkSpin. Today becomes your refuel day, your first bonus lands right away, and you earn the Engine Started badge. Buying from one of your linked positions counts too, and so do Game Pass packages of $20 or more.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay: Buy packages</span><span class="rg-chip ls">LinkSpin: Credits</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Find your Refuel card</h3>
|
||||||
|
<p>It shows your refuel day, your streak month, the bonus your next refuel earns, which sites you refueled this cycle, and whether your Pit Stop is still open.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay: Overview</span><span class="rg-chip ls">LinkSpin: Credits and Ads</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Put this month's Refuel Kit to work</h3>
|
||||||
|
<p>Your refuel unlocks the month's members-only banners in five sizes (728x90, 468x60, 300x250, 160x600 and 1200x630 for social posts) with your @name and a QR code to your own link. Tap Make mine, then send one straight into an InstantAdPay banner campaign, or load the set into your Banner Spin on LinkSpin. From a 3-month streak you also get an animated version. Kits you unlock stay yours after the month ends.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay: Promo tools</span><span class="rg-chip ls">LinkSpin: Ads</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Check the Engine Room</h3>
|
||||||
|
<p>Your first refuel opens it. Three dials: fuel left across both sites, clicks this week against last week, and goals this month against a goal you set. Warning lights flag ads running low or out, a refuel day coming, or a login slot opening. Then press the one next-move button.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay: Engine Room tab</span><span class="rg-chip ls">LinkSpin: top of Ads</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Refuel inside your window every month</h3>
|
||||||
|
<p>The window opens 5 days before your refuel day and stays open 5 days after it (Central time). You get an email and an on-site notice 5 days before, on the day, and a last call. Your next refuel day is 30 days after the day you actually refuel, so it moves with you.</p>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Light up the second engine</h3>
|
||||||
|
<p>Refuel on both sites in the same cycle and both get the higher rate. Buy on one site, then the other, in either order, before your next window opens. The first site is topped up automatically to match.</p>
|
||||||
|
<div class="rg-where"><span class="rg-chip">InstantAdPay $20+</span><span class="rg-chip ls">LinkSpin $25+</span></div>
|
||||||
|
</div></li>
|
||||||
|
<li><div>
|
||||||
|
<h3>Running low early? Take a Pit Stop</h3>
|
||||||
|
<p>Another package on a site you already refueled this cycle, bought before your window opens, is a Pit Stop: half your current rate, once per site per cycle. It keeps your ads running. Your monthly refuel is still due on your refuel day.</p>
|
||||||
|
</div></li>
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
<div class="rg-two">
|
||||||
|
<div class="rg-box">
|
||||||
|
<h3>If you miss a month</h3>
|
||||||
|
<p>You get one free miss in any 365 days. Miss your window once and the streak holds: your next qualifying package counts as the next month. Miss again inside the year and the streak starts over at month 1, with a new refuel day.</p>
|
||||||
|
</div>
|
||||||
|
<div class="rg-box">
|
||||||
|
<h3>What counts and what doesn't</h3>
|
||||||
|
<p>Counts: a new package at or above the minimum, bought by you or one of your own linked positions, Game Pass packages included. Doesn't count: smaller packages, or credits you earned by viewing ads.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rg-coach">
|
||||||
|
<h3>For leaders: how to coach it</h3>
|
||||||
|
<ul>
|
||||||
|
<li>When someone in your line buys their first package, help them pick a refuel day they can keep every month.</li>
|
||||||
|
<li>Show them the Refuel card and the Engine Room on day one, so they know where to look.</li>
|
||||||
|
<li>Teach both engines. One package on each site per cycle earns the higher rate on both.</li>
|
||||||
|
<li>Use your own Refuel Kit in a live campaign, so they see it working before they try it.</li>
|
||||||
|
<li>Repeat ad spend keeps every level of your line active, so this is the habit to build.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="rg-eye">Quick answers</p>
|
||||||
|
<h2>Questions members ask</h2>
|
||||||
|
<dl class="rg-faq">
|
||||||
|
<div><dt>Do I have to use both sites?</dt><dd>No. Either site keeps your streak going at the one-engine rate. Refueling both in the same cycle earns the bigger bonus on both.</dd></div>
|
||||||
|
<div><dt>Is the bonus cash?</dt><dd>No. Bonus credits are purchased-grade ad credits that run on any format, login ads included. They show in your credit log by name.</dd></div>
|
||||||
|
<div><dt>Does the bonus stack with Friday and Wednesday?</dt><dd>Yes. They are separate grants, so a Friday refuel gets both.</dd></div>
|
||||||
|
<div><dt>I refueled early. Did I lose my place?</dt><dd>Inside the 5-day window it counts as your refuel and your next date moves to 30 days after it. Earlier than that it is a Pit Stop (or your second engine, if it is the other site's first package this cycle), and your refuel day stays put.</dd></div>
|
||||||
|
<div><dt>When does the Refuel Kit change?</dt><dd>Each month gets its own kit. A counted refuel unlocks that month's kit, and kits you unlocked stay yours.</dd></div>
|
||||||
|
<div><dt>Is anything billed automatically?</dt><dd>No. You choose every package. Nothing renews on its own.</dd></div>
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<div class="rg-rule"><b>What a credit is.</b> One credit is one cent of ad delivery across the network. Credits are not money and cannot be withdrawn. Fuel Your Offers runs on InstantAdPay and LinkSpin.</div>
|
||||||
|
<p class="muted small" style="margin-top:10px">No income is guaranteed. Any commissions depend on real purchases in your line and on your own effort. Cryptocurrency involves risk of loss. InstantAdPay sells advertising; it is not an investment product.</p>
|
||||||
|
<footer>
|
||||||
|
<div>InstantAdPay · <a href="/">Home</a> · <a href="/friday">Five Dollar Friday</a> · <a href="/wednesday">Wired Wednesday</a> · <a href="/earning">How earning works</a> · <a href="https://linkspin.app/refuel">The LinkSpin side</a></div>
|
||||||
|
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||||
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
<script src="/assets/common.js?v=20261023ov"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+1
-1
@@ -19,7 +19,7 @@
|
|||||||
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
|
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
|
||||||
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
|
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
<script src="/assets/support.js?v=20261016a"></script>
|
<script src="/assets/support.js?v=20261016a"></script>
|
||||||
<script src="/assets/chat.js?v=20261016n"></script>
|
<script src="/assets/chat.js?v=20261016n"></script>
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@
|
|||||||
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>. Questions: the <a href="/support">support page</a> or <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>.</p>
|
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>. Questions: the <a href="/support">support page</a> or <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>.</p>
|
||||||
</div>
|
</div>
|
||||||
</div></section>
|
</div></section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/legal.js?v=20260908a"></script>
|
<script src="/assets/legal.js?v=20260908a"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -34,7 +34,7 @@
|
|||||||
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
|
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/tx.js?v=20260906m"></script>
|
<script src="/assets/tx.js?v=20260906m"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/wall.js?v=20260911v"></script>
|
<script src="/assets/wall.js?v=20260911v"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+1
-1
@@ -122,7 +122,7 @@
|
|||||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.</div>
|
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
<script src="/assets/common.js?v=20261023ov"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||||
<script src="/assets/wallets.js?v=20260911b"></script>
|
<script src="/assets/wallets.js?v=20260911b"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -64,6 +64,6 @@
|
|||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
<script src="/assets/wednesday.js?v=20260929c"></script>
|
<script src="/assets/wednesday.js?v=20260929c"></script>
|
||||||
<script src="/assets/common.js?v=20261016n"></script>
|
<script src="/assets/common.js?v=20261023ov"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -76,7 +76,8 @@ const WANT = {
|
|||||||
PIF: /PIF is a gift/,
|
PIF: /PIF is a gift/,
|
||||||
PRICE: /Five packages, priced/,
|
PRICE: /Five packages, priced/,
|
||||||
EARN: /Every package splits the same way/,
|
EARN: /Every package splits the same way/,
|
||||||
TANK: /The holding tank is where free members/
|
TANK: /The holding tank is where free members/,
|
||||||
|
GAMEPOL: /Game POL is paid to the wallet linked/
|
||||||
};
|
};
|
||||||
const ROUTES = [
|
const ROUTES = [
|
||||||
['PIF', 'should I pif someone from the holding tank'], ['PIF', 'what is pif'],
|
['PIF', 'should I pif someone from the holding tank'], ['PIF', 'what is pif'],
|
||||||
@@ -89,7 +90,9 @@ const ROUTES = [
|
|||||||
['PRICE', 'how much does it cost'],
|
['PRICE', 'how much does it cost'],
|
||||||
['EARN', 'how much do I earn'], ['EARN', 'how much can i make'],
|
['EARN', 'how much do I earn'], ['EARN', 'how much can i make'],
|
||||||
['EARN', 'what will i get paid'], ['EARN', 'what is the commission'],
|
['EARN', 'what will i get paid'], ['EARN', 'what is the commission'],
|
||||||
['TANK', 'how does the holding tank work'], ['TANK', 'can I adopt someone from the tank']
|
['TANK', 'how does the holding tank work'], ['TANK', 'can I adopt someone from the tank'],
|
||||||
|
['GAMEPOL', 'my gem kingdom pol was never sent'], ['GAMEPOL', 'it says 1.50 POL is waiting for your wallet'],
|
||||||
|
['GAMEPOL', 'do I need to switch on payouts to get my game pol']
|
||||||
];
|
];
|
||||||
for (const [want, q] of ROUTES) {
|
for (const [want, q] of ROUTES) {
|
||||||
const reply = await ask(q);
|
const reply = await ask(q);
|
||||||
|
|||||||
+11
-3
@@ -1,6 +1,10 @@
|
|||||||
// Chatbot knowledge guard (Marty, 2026-09-16: "ensure the chatbot is completely current, and keep it that way").
|
// Chatbot knowledge guard (Marty, 2026-09-16: "ensure the chatbot is completely current, and keep it that way").
|
||||||
// Compares chatbot.js KNOWLEDGE_DATE with the newest public release note. If a note is newer, the
|
// Compares chatbot.js KNOWLEDGE_DATE with the newest public release note. If a note is newer, the
|
||||||
// chatbot was not brought up to date with that change: fix chatbot.js (canned + prompt), bump the date.
|
// chatbot was not brought up to date with that change: fix chatbot.js (canned + prompt), bump the date.
|
||||||
|
// Since the knowledge base (2026-10-20, kb.js) the assistant also answers from Admin > Knowledge base, so a
|
||||||
|
// KB change made after a release counts too: the guard takes the later of KNOWLEDGE_DATE and the site's
|
||||||
|
// newest KB edit by a person (/api/chat/kb-stamp, a Central-time day; seed refreshes from the code do not count). Either way a release must be followed by a
|
||||||
|
// knowledge update, in the code or in the admin pane.
|
||||||
// node qa/chatbot-sync.mjs (checks the live site's /api/releases)
|
// node qa/chatbot-sync.mjs (checks the live site's /api/releases)
|
||||||
// LOCAL=http://127.0.0.1:8796 node qa/chatbot-sync.mjs
|
// LOCAL=http://127.0.0.1:8796 node qa/chatbot-sync.mjs
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
@@ -8,14 +12,18 @@ const B = process.env.LOCAL || 'https://instantadpay.com';
|
|||||||
const src = fs.readFileSync(new URL('../chatbot.js', import.meta.url), 'utf8');
|
const src = fs.readFileSync(new URL('../chatbot.js', import.meta.url), 'utf8');
|
||||||
const m = /KNOWLEDGE_DATE = '(\d{4}-\d{2}-\d{2})'/.exec(src);
|
const m = /KNOWLEDGE_DATE = '(\d{4}-\d{2}-\d{2})'/.exec(src);
|
||||||
if (!m) { console.log('[bug] chatbot.js has no KNOWLEDGE_DATE constant'); process.exit(1); }
|
if (!m) { console.log('[bug] chatbot.js has no KNOWLEDGE_DATE constant'); process.exit(1); }
|
||||||
const known = m[1];
|
let known = m[1], via = 'chatbot.js KNOWLEDGE_DATE';
|
||||||
|
try {
|
||||||
|
const st = await (await fetch(B + '/api/chat/kb-stamp')).json();
|
||||||
|
if (st && /^\d{4}-\d{2}-\d{2}$/.test(st.updated || '') && st.updated > known) { known = st.updated; via = 'knowledge base (' + st.count + ' entries)'; }
|
||||||
|
} catch (e) { console.log('[warn] no knowledge-base stamp from ' + B + ' (' + e.message + '), using KNOWLEDGE_DATE only'); }
|
||||||
let notes = [];
|
let notes = [];
|
||||||
try { const r = await (await fetch(B + '/api/releases')).json(); notes = r.notes || []; } catch (e) { console.log('[warn] could not read ' + B + '/api/releases: ' + e.message); process.exit(0); }
|
try { const r = await (await fetch(B + '/api/releases')).json(); notes = r.notes || []; } catch (e) { console.log('[warn] could not read ' + B + '/api/releases: ' + e.message); process.exit(0); }
|
||||||
const newer = notes.filter(n => (n.date || '') > known);
|
const newer = notes.filter(n => (n.date || '') > known);
|
||||||
if (newer.length) {
|
if (newer.length) {
|
||||||
console.log('[bug] chatbot knowledge date ' + known + ' is older than ' + newer.length + ' release note(s):');
|
console.log('[bug] chatbot knowledge date ' + known + ' is older than ' + newer.length + ' release note(s):');
|
||||||
for (const n of newer) console.log(' ' + n.date + ' ' + n.title);
|
for (const n of newer) console.log(' ' + n.date + ' ' + n.title);
|
||||||
console.log(' -> update chatbot.js (canned answers + systemPrompt) for each, then bump KNOWLEDGE_DATE.');
|
console.log(' -> update chatbot.js (canned answers + systemPrompt) or the entries in Admin > Knowledge base for each, then bump KNOWLEDGE_DATE.');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
console.log('chatbot knowledge date ' + known + ' covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')');
|
console.log('chatbot knowledge date ' + known + ' (' + via + ') covers all ' + notes.length + ' release notes (newest ' + (notes[0] ? notes[0].date : 'none') + ')');
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
// Conversion pixel, InstantAdPay half (2026-10-23), end to end against a LOCAL copy and a MOCK LinkSpin.
|
||||||
|
// node qa/convpixel.test.mjs (or: bash qa/run.sh convpixel)
|
||||||
|
// Boots server.js on its own port with a throwaway DATA_DIR seeded with two advertisers and a few campaigns (JSON store,
|
||||||
|
// DATABASE_URL blank, no mail key, devCode sign-in, a minimal environment so no live secret can leak in), LS_URL pointing at a
|
||||||
|
// mock LinkSpin on localhost that verifies the HMAC on every call, records the pushed clicks and answers op summary.
|
||||||
|
// Nothing touches production or a real member. Checks: lsclk on the 302 (existing params and #hash kept, a LinkSpin /r/ link
|
||||||
|
// gets it, an existing lsclk is never replaced, an unparsable target goes out unchanged), the click rows pushed with a valid
|
||||||
|
// signature and the contract fields, the owner's own click flagged self=1 and not counted, the proxies, the Campaigns pane
|
||||||
|
// showing goals and cost per goal (300 credits / 4 = 75), LinkSpin down: pane still loads, panel says so, rows kept and
|
||||||
|
// pushed once it is back. 2026-10-26: own soft keys pushed as owners and an own-browser click flagged self (billing
|
||||||
|
// unchanged), Send a test conversion loads the real pixel in test mode (routed in the browser, nothing leaves the machine)
|
||||||
|
// with the partner call as fallback, the own-click test count on the card, cost per goal (30 days) from the credit log.
|
||||||
|
// Exit code 1 on any failure.
|
||||||
|
import http from 'node:http';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const PORT = Number(process.env.CONV_PORT || 8831), MPORT = PORT + 1;
|
||||||
|
const B = 'http://127.0.0.1:' + PORT, MOCK = 'http://127.0.0.1:' + MPORT;
|
||||||
|
const SECRET = 'qa-convpixel-' + crypto.randomBytes(24).toString('hex'); // throwaway, 32+ chars
|
||||||
|
const ADMIN = 'localtest';
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-conv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
|
const OUT = path.join(SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
||||||
|
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 15000)) { try { const v = await fn(); if (v) return v; } catch (e) {} await sleep(400); } return null; }
|
||||||
|
|
||||||
|
// ---- seed: two advertisers, campaigns with every target shape ----
|
||||||
|
const now = Date.now();
|
||||||
|
const acct = (email, username, code) => ({ email, pass: null, sponsorRef: '', code, username, address: null, created: now - 5 * 86400000, lastSeen: now - 3600000, memberId: 0 });
|
||||||
|
const A1 = 'qa-adv@example.com', A2 = 'qa-adv2@example.com';
|
||||||
|
{ const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
|
||||||
|
for (const a of [acct(A1, 'qaadv', 'cqaadv1'), acct(A2, 'qaadvtwo', 'cqaadv2')]) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
|
||||||
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(db)); }
|
||||||
|
const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://example.com/b.png', title: null, body: null,
|
||||||
|
budget: 1000, spent, accrued: 0, imps: 50, clicks: 0, batchImps: 0, width: 468, height: 60, status: 'paused', created: now - 86400000 });
|
||||||
|
const T1 = 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world#top';
|
||||||
|
const CAMPS = [camp(1, A1, 'QA landing', T1, 300), camp(2, A1, 'QA spin link', 'https://linkspin.app/r/abc12', 120),
|
||||||
|
camp(3, A1, 'QA has lsclk', 'https://adv.example/p?lsclk=keepme', 0), camp(4, A1, 'QA odd target', 'adv.example/no-scheme', 0), camp(5, A2, 'QA other', 'https://other.example/', 50),
|
||||||
|
Object.assign(camp(6, A1, 'QA old no log', 'https://adv.example/old', 500), { created: now - 60 * 86400000 }), Object.assign(camp(7, A1, 'QA new no log', 'https://adv.example/new', 90), { created: now - 3 * 86400000 })];
|
||||||
|
// cost per goal (30 days): campaign 1 spent 150 today + 50 five days ago inside the window, 100 forty days ago outside it
|
||||||
|
const ctd = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||||
|
const cl = (t, delta, ref) => ({ email: A1, ts: t, day: ctd(t), delta, kind: 'delivery', note: 'Ad views: QA landing', ref: String(ref) });
|
||||||
|
fs.writeFileSync(path.join(DATA, 'credit-log.json'), JSON.stringify({ items: [cl(now - 40 * 86400000, -100, 1), cl(now - 5 * 86400000, -50, 1), cl(now - 60000, -150, 1), Object.assign(cl(now - 60000, -999, 1), { email: A2 })] }));
|
||||||
|
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 6, campaigns: CAMPS, burnsPending: [] }));
|
||||||
|
|
||||||
|
// ---- mock LinkSpin ----
|
||||||
|
const PX1 = 'px0123456789', PX2 = 'pxabcdef0123';
|
||||||
|
const mock = { clicks: new Map(), owners: [], badSig: 0, calls: [], down: false, goals: { [A1]: [{ px: PX1, name: 'subscriber', value: null, created: now - 86400000, conv: 6, convDays: 30, lastAt: now - 3600000, lastTest: null }, { px: PX2, name: 'sale', value: 19.95, created: now - 86400000, conv: 1, convDays: 30, lastAt: now - 7200000, lastTest: null }] } };
|
||||||
|
const verify = (ts, sig, raw) => { if (!ts || !sig || Math.abs(Date.now() - Number(ts)) > 300000) return false; const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); return want.length === String(sig).length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(String(sig))); };
|
||||||
|
const send = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
|
||||||
|
function mockHandler(req, res) {
|
||||||
|
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
||||||
|
if (mock.down) { res.writeHead(503); return res.end('down'); }
|
||||||
|
if (req.method !== 'POST') return send(res, 404, { error: 'not found' });
|
||||||
|
if (!verify(req.headers['x-ls-ts'], req.headers['x-ls-sig'], raw)) { mock.badSig++; return send(res, 401, { error: 'bad signature' }); }
|
||||||
|
const b = JSON.parse(raw || '{}');
|
||||||
|
if (req.url === '/api/partner/clicks') { for (const c of b.clicks || []) mock.clicks.set(c.id, c); for (const o of b.owners || []) mock.owners.push(o); return send(res, 200, { ok: true, n: (b.clicks || []).length, owners: (b.owners || []).length }); }
|
||||||
|
if (req.url === '/api/partner/conv') {
|
||||||
|
mock.calls.push(b); const email = String(b.email || '');
|
||||||
|
const goals = mock.goals[email] || (mock.goals[email] = []);
|
||||||
|
if (b.op === 'summary') return send(res, 200, { ok: true, goals, byCampaign: email === A1 ? { 1: { clicks: 9, conv: { [PX1]: 4, [PX2]: 1 }, value: { [PX2]: 19.95 } }, 2: { clicks: 3, conv: {} }, 6: { clicks: 4, conv: { [PX1]: 2 } }, 7: { clicks: 5, conv: { [PX1]: 3 } } } : {}, methods: { url: 2, stored: 2, cookie: 1, soft: 1 }, selfTests: email === A1 ? 3 : 0, host: 'linkspin.app' });
|
||||||
|
if (b.op === 'create') { const g = { px: 'px' + crypto.randomBytes(5).toString('hex'), name: b.name, value: b.value == null ? null : b.value, created: Date.now(), conv: 0, convDays: 30, lastAt: null, lastTest: null }; goals.push(g); return send(res, 200, { ok: true, goal: g }); }
|
||||||
|
if (b.op === 'remove') { const i = goals.findIndex(g => g.px === b.px); if (i < 0) return send(res, 404, { error: 'No such goal.' }); goals.splice(i, 1); return send(res, 200, { ok: true }); }
|
||||||
|
if (b.op === 'test') { const g = goals.find(x => x.px === b.px); if (!g) return send(res, 404, { error: 'No such goal.' }); g.lastTest = Date.now(); return send(res, 200, { ok: true, at: g.lastTest }); }
|
||||||
|
return send(res, 400, { error: 'unknown op' });
|
||||||
|
}
|
||||||
|
return send(res, 404, { error: 'not found' }); // registry sync and anything else: ignored
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mockSrv = http.createServer(mockHandler); await new Promise(r => mockSrv.listen(MPORT, '127.0.0.1', r));
|
||||||
|
|
||||||
|
// ---- the local copy, minimal environment (no live secrets can ride along) ----
|
||||||
|
const ENV = {};
|
||||||
|
for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k];
|
||||||
|
Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, DATABASE_URL: '', LS_SYNC_SECRET: SECRET, LS_URL: MOCK });
|
||||||
|
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||||
|
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
|
||||||
|
let browser = null;
|
||||||
|
const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} try { mockSrv.close(); } catch (e) {} await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
|
||||||
|
|
||||||
|
try {
|
||||||
|
const up = await waitFor(async () => (await fetch(B + '/api/config')).ok, 30000);
|
||||||
|
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
|
||||||
|
const api = async (p, body, hdr) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: body ? JSON.stringify(body) : undefined }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
|
||||||
|
const click = async (id, hdr) => { const r = await fetch(B + '/api/ads/click/' + id, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148', Referer: 'https://instantadpay.com/ledger?secret=1' }, hdr || {}) }); return { status: r.status, loc: r.headers.get('location') }; };
|
||||||
|
async function signIn(email) {
|
||||||
|
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000, fage: 5000 });
|
||||||
|
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
|
||||||
|
return (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
|
||||||
|
}
|
||||||
|
const ID = /lsclk=(i[0-9a-f]{11})(?=$|[&#])/;
|
||||||
|
|
||||||
|
// 1. click ids on the redirect
|
||||||
|
const c1 = await click(1);
|
||||||
|
const id1 = (ID.exec(c1.loc || '') || [])[1];
|
||||||
|
ok(c1.status === 302 && !!id1, 'click -> 302 with lsclk=i+11 hex', c1.status + ' ' + c1.loc);
|
||||||
|
ok(c1.loc === 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world&lsclk=' + id1 + '#top', 'existing params kept byte for byte, lsclk before the #hash', c1.loc);
|
||||||
|
const c2 = await click(2); const id2 = (ID.exec(c2.loc || '') || [])[1];
|
||||||
|
ok(!!id2 && c2.loc === 'https://linkspin.app/r/abc12?lsclk=' + id2, 'a LinkSpin /r/ spin link gets lsclk', c2.loc);
|
||||||
|
const c3 = await click(3);
|
||||||
|
ok(c3.loc === 'https://adv.example/p?lsclk=keepme', 'an existing lsclk is never replaced', c3.loc);
|
||||||
|
const c4 = await click(4);
|
||||||
|
ok(c4.status === 302 && c4.loc === 'adv.example/no-scheme', 'an unparsable target redirects unchanged', c4.status + ' ' + c4.loc);
|
||||||
|
const c1b = await click(1); const id1b = (ID.exec(c1b.loc || '') || [])[1];
|
||||||
|
ok(id1b && id1b !== id1, 'every click gets its own id');
|
||||||
|
|
||||||
|
// 2. pushed to the mock, signed, with the contract fields
|
||||||
|
const got = await waitFor(() => mock.clicks.has(id1) && mock.clicks.has(id2) && mock.clicks.has(id1b), 15000);
|
||||||
|
ok(!!got, 'click rows pushed to LinkSpin /api/partner/clicks within ~3 s', [...mock.clicks.keys()].join(','));
|
||||||
|
ok(mock.badSig === 0, 'every push carried a valid HMAC signature', 'bad: ' + mock.badSig);
|
||||||
|
const r1 = mock.clicks.get(id1) || {};
|
||||||
|
ok(r1.camp === 1 && r1.cname === 'QA landing' && r1.type === 'banner' && r1.owner === A1, 'row: camp, cname, type, owner', JSON.stringify(r1));
|
||||||
|
ok(r1.spent === 300 && r1.self === 0 && r1.target === T1, 'row: spent 300, self 0, target', JSON.stringify(r1));
|
||||||
|
ok(/^s:[0-9a-f]{20}$/.test(r1.sk || '') && r1.dv === 'mobile' && r1.pl === 'instantadpay.com/ledger' && Math.abs(r1.ts - Date.now()) < 120000, 'row: soft key, device, placement (query dropped), ts', JSON.stringify(r1));
|
||||||
|
const ip = '127.0.0.1', ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148';
|
||||||
|
const sks = ['s:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20), 's:' + crypto.createHash('sha256').update('::ffff:127.0.0.1|' + ua).digest('hex').slice(0, 20)];
|
||||||
|
ok(sks.includes(r1.sk), 'soft key = sha256(ip|ua) first 20 hex, no raw IP in the row', r1.sk);
|
||||||
|
ok(!JSON.stringify([...mock.clicks.values()]).includes('127.0.0.1'), 'no raw IP anywhere in the pushed rows');
|
||||||
|
ok(!mock.clicks.has('keepme') && [...mock.clicks.values()].filter(r => r.camp === 3).length === 1, 'the click on the lsclk target is still recorded (its own id), the URL untouched');
|
||||||
|
|
||||||
|
// 3. the owner's own click: still an id, flagged self, not counted as a click
|
||||||
|
const ck1 = await signIn(A1);
|
||||||
|
const before = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
|
||||||
|
const clicksBefore = ((before && before.campaigns) || []).find(c => c.id === 1);
|
||||||
|
const own = await click(1, { Cookie: ck1 }); const idOwn = (ID.exec(own.loc || '') || [])[1];
|
||||||
|
ok(!!idOwn, 'own click still gets a click id (so the owner can test)', own.loc);
|
||||||
|
ok(!!(await waitFor(() => mock.clicks.get(idOwn), 10000)) && mock.clicks.get(idOwn).self === 1, 'own click pushed with self=1', JSON.stringify(mock.clicks.get(idOwn)));
|
||||||
|
const after = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
|
||||||
|
const clicksAfter = ((after && after.campaigns) || []).find(c => c.id === 1);
|
||||||
|
ok(clicksBefore && clicksAfter && clicksAfter.clicks === clicksBefore.clicks && clicksBefore.clicks === 2, 'own click not counted (clicks stay 2)', JSON.stringify([clicksBefore && clicksBefore.clicks, clicksAfter && clicksAfter.clicks]));
|
||||||
|
// fix 1 (2026-10-26): the soft keys the owner signs in from go to LinkSpin as owners; a click from that browser while
|
||||||
|
// signed out is flagged self for conversions (billing unchanged: it is still a counted click)
|
||||||
|
const skNode = ['127.0.0.1', '::ffff:127.0.0.1'].map(x => 's:' + crypto.createHash('sha256').update(x + '|node').digest('hex').slice(0, 20));
|
||||||
|
ok(!!(await waitFor(() => mock.owners.some(o => o.owner === A1 && skNode.includes(o.sk)), 10000)), "owner's session soft key pushed to LinkSpin as owners (no raw IP)", JSON.stringify(mock.owners));
|
||||||
|
ok(!JSON.stringify(mock.owners).includes('127.0.0.1'), 'no raw IP in the owners rows');
|
||||||
|
const ownSk = await click(1, { 'User-Agent': 'node' }); const idOwnSk = (ID.exec(ownSk.loc || '') || [])[1];
|
||||||
|
ok(!!(await waitFor(() => mock.clicks.get(idOwnSk), 10000)) && mock.clicks.get(idOwnSk).self === 1, "a click from the owner's own browser, signed out, is pushed self=1", JSON.stringify(mock.clicks.get(idOwnSk)));
|
||||||
|
const strangerC = await click(1, { 'User-Agent': 'Mozilla/5.0 Stranger QA' }); const idStr = (ID.exec(strangerC.loc || '') || [])[1];
|
||||||
|
ok(!!(await waitFor(() => mock.clicks.get(idStr), 10000)) && mock.clicks.get(idStr).self === 0, "a stranger's click is still self=0");
|
||||||
|
const nOwners = mock.owners.length; await api('/api/my/campaigns', null, { Cookie: ck1 }); await sleep(3500);
|
||||||
|
ok(mock.owners.length === nOwners, 'the same session soft key is not pushed again within 6 h');
|
||||||
|
|
||||||
|
// 4. proxies
|
||||||
|
const sum = await api('/api/my/conversions', null, { Cookie: ck1 });
|
||||||
|
ok(sum.j && sum.j.ok === true && sum.j.goals.length === 2 && sum.j.byCampaign['1'].conv[PX1] === 4, 'GET /api/my/conversions relays the LinkSpin summary', JSON.stringify(sum.j).slice(0, 200));
|
||||||
|
ok(sum.j && sum.j.spend30 && sum.j.spend30['1'] === 200 && sum.j.spend30['6'] == null && sum.j.spend30['7'] == null && sum.j.spendSince > Date.now() - 31 * 86400000, 'spend30 from the credit log: campaign 1 = 150 + 50 inside the 30 days (the 100 from 40 days ago and another member\'s row left out)', JSON.stringify(sum.j && sum.j.spend30));
|
||||||
|
const lastSum = mock.calls.filter(c => c.op === 'summary').pop();
|
||||||
|
ok(lastSum && lastSum.email === A1 && lastSum.days === 30, 'summary asked for the signed-in email, 30 days', JSON.stringify(lastSum));
|
||||||
|
const nSum = mock.calls.filter(c => c.op === 'summary').length; await api('/api/my/conversions', null, { Cookie: ck1 });
|
||||||
|
ok(mock.calls.filter(c => c.op === 'summary').length === nSum, 'summary cached (second call within 60 s does not hit LinkSpin)');
|
||||||
|
ok((await api('/api/my/conversions')).status === 401, 'signed out: 401');
|
||||||
|
const bad = await api('/api/my/conversions/goal', { op: 'create', name: ' ' }, { Cookie: ck1 });
|
||||||
|
ok(bad.status === 400, 'create without a name refused locally');
|
||||||
|
const cr = await api('/api/my/conversions/goal', { op: 'create', name: 'Free Report', value: '7.5' }, { Cookie: ck1 });
|
||||||
|
ok(cr.j && cr.j.ok && cr.j.goal && /^px[0-9a-f]{10}$/.test(cr.j.goal.px) && cr.j.goal.name === 'free-report' && cr.j.goal.value === 7.5, 'create relays op create (name normalized, value number)', JSON.stringify(cr.j));
|
||||||
|
const ts = await api('/api/my/conversions/test', { px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
|
||||||
|
ok(ts.j && ts.j.ok && ts.j.at, 'test relays op test', JSON.stringify(ts.j));
|
||||||
|
const rm = await api('/api/my/conversions/goal', { op: 'remove', px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
|
||||||
|
ok(rm.j && rm.j.ok, 'remove relays op remove');
|
||||||
|
const rm2 = await api('/api/my/conversions/goal', { op: 'remove', px: 'px9999999999' }, { Cookie: ck1 });
|
||||||
|
ok(rm2.status === 400 && rm2.j && rm2.j.error === 'No such goal.', 'LinkSpin plain-words error passed through as 400', JSON.stringify(rm2));
|
||||||
|
ok(mock.calls.every(c => c.email === A1), 'every conv call carried only the signed-in email');
|
||||||
|
|
||||||
|
// 5. the Campaigns pane in a real browser
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
browser = await chromium.launch();
|
||||||
|
async function pane(cookie, shot) {
|
||||||
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
|
||||||
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
||||||
|
const [k, v] = cookie.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
|
||||||
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
||||||
|
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
|
||||||
|
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
|
||||||
|
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
|
||||||
|
const st = await page.evaluate(() => ({
|
||||||
|
rows: document.querySelectorAll('#campList .camp-table tbody tr').length,
|
||||||
|
line1: (document.querySelector('[data-convcamp="1"]') || {}).textContent || '', line1Hidden: !!(document.querySelector('[data-convcamp="1"]') || {}).hidden,
|
||||||
|
line5Hidden: (document.querySelector('[data-convcamp="5"]') || { hidden: true }).hidden,
|
||||||
|
line6: (document.querySelector('[data-convcamp="6"]') || {}).textContent || '', line7: (document.querySelector('[data-convcamp="7"]') || {}).textContent || '', title1: (document.querySelector('[data-convcamp="1"]') || {}).title || '',
|
||||||
|
card: !document.getElementById('convCard').hidden, status: document.getElementById('convStatus').textContent,
|
||||||
|
goals: document.querySelectorAll('#convGoals tbody tr').length, convCells: [...document.querySelectorAll('#convGoals td[data-l="Conversions (30 days)"]')].map(td => (td.firstChild && td.firstChild.textContent || '').trim()), landing: (document.getElementById('convLanding') || {}).value || '', img: (document.getElementById('convImg') || {}).value || '',
|
||||||
|
js: (document.getElementById('convJs') || {}).value || '', tip: document.getElementById('convCard').textContent }));
|
||||||
|
await page.screenshot({ path: path.join(OUT, shot), fullPage: true }).catch(() => {});
|
||||||
|
await ctx.close(); return { st, errs };
|
||||||
|
}
|
||||||
|
const p1 = await pane(ck1, 'convpixel-pane.png');
|
||||||
|
ok(p1.st.rows >= 4 && p1.st.card, 'Campaigns pane loads with the Conversion tracking card', JSON.stringify(p1.st).slice(0, 200));
|
||||||
|
ok(!p1.st.line1Hidden && /cost per goal \(30 days\)/.test(p1.st.line1) && /subscriber 4 \(50 credits each\)/.test(p1.st.line1) && /sale 1 \(200 credits each\)/.test(p1.st.line1), 'campaign row: cost per goal (30 days) = 200 credits spent in the 30 days / 4 = 50 (not lifetime 300 / 4 = 75)', p1.st.line1);
|
||||||
|
ok(/same 30 days/.test(p1.st.title1), 'its tooltip says the spend is the same 30 days', p1.st.title1);
|
||||||
|
ok(/subscriber 2/.test(p1.st.line6) && !/credits each/.test(p1.st.line6) && /no spend on record/.test(p1.st.line6), 'an older campaign with no spend in the log shows no cost per goal rather than a lifetime figure', p1.st.line6);
|
||||||
|
ok(/subscriber 3 \(30 credits each\)/.test(p1.st.line7), 'a campaign started inside the window with no log rows uses its spend since start (90 / 3 = 30)', p1.st.line7);
|
||||||
|
ok(/3 from your own clicks, kept as tests/.test(p1.st.status), 'card shows the own-click test count (selfTests from LinkSpin)', p1.st.status);
|
||||||
|
ok(!/\$/.test(p1.st.line1), 'cost per goal is in credits, never dollars');
|
||||||
|
ok(JSON.stringify(p1.st.convCells) === '["6","1"]', 'goal rows show the conversion count, not the 30-day window (convDays is the window length)', JSON.stringify(p1.st.convCells));
|
||||||
|
ok(p1.st.goals === 2 && p1.st.landing === '<script async src="https://linkspin.app/t.js?px=' + PX1 + '"></script>', 'goal list + landing tag snippet', p1.st.landing);
|
||||||
|
ok(p1.st.img === '<img src="https://linkspin.app/cv.gif?px=' + PX1 + '&goal=subscriber" width="1" height="1" alt="" style="display:none">' && p1.st.js === '<script async src="https://linkspin.app/cv.js?px=' + PX1 + '&goal=subscriber"></script>', 'goal pixel image + JS snippets match the contract', p1.st.img + ' | ' + p1.st.js);
|
||||||
|
ok(/Thank You Page: custom page/.test(p1.st.tip) && /Thank-you page: custom URL/.test(p1.st.tip) && /24-hour match/.test(p1.st.tip), 'autoresponder advice + match legend present');
|
||||||
|
ok(/url 2, stored 2, cookie 1, soft 1/.test(p1.st.status), 'match methods line', p1.st.status);
|
||||||
|
ok(!p1.errs.length, 'no page errors', p1.errs.join(' | '));
|
||||||
|
// fix 2 (2026-10-26): Send a test conversion loads the REAL pixel in test mode. The browser's request to linkspin.app is
|
||||||
|
// routed here (nothing leaves the machine): PX1 answers X-LS-Result: test like LinkSpin; PX2 answers unknown, so the
|
||||||
|
// card falls back to the signed partner call (op test).
|
||||||
|
{
|
||||||
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
|
||||||
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
||||||
|
const [k, v] = ck1.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
|
||||||
|
const pixelHits = [];
|
||||||
|
await ctx.route(/^https:\/\/linkspin\.app\/cv\.gif/, route => { const u = new URL(route.request().url()); pixelHits.push(u.search); const px = u.searchParams.get('px'); const g = (mock.goals[A1] || []).find(x => x.px === px);
|
||||||
|
const good = px === PX1 && u.searchParams.get('test') === '1' && g; if (good) g.lastTest = Date.now();
|
||||||
|
return route.fulfill({ status: 200, headers: { 'Content-Type': 'image/gif', 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-LS-Result': good ? 'test' : 'unknown' }, body: Buffer.from('R0lGODlhAQABAAAAACw=', 'base64') }); });
|
||||||
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
||||||
|
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
|
||||||
|
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
|
||||||
|
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
|
||||||
|
const testsBefore = mock.calls.filter(c => c.op === 'test').length;
|
||||||
|
await page.click('[data-convtest="' + PX1 + '"]'); await page.waitForTimeout(2000);
|
||||||
|
const msg1 = await page.evaluate(() => document.body.innerText);
|
||||||
|
const last1 = await page.evaluate(px => { const b = document.querySelector('[data-convtest="' + px + '"]'); const tr = b && b.closest('tr'); const td = tr && tr.querySelector('td[data-l="Last test"]'); return td ? td.textContent.trim() : ''; }, PX1);
|
||||||
|
ok(pixelHits.some(q => q.includes('px=' + PX1) && q.includes('test=1')), 'Send a test conversion loads the real pixel cv.gif?px=..&test=1 from the browser', JSON.stringify(pixelHits));
|
||||||
|
ok(/received by your real pixel/.test(msg1) && last1 && last1 !== 'never' && mock.calls.filter(c => c.op === 'test').length === testsBefore, 'pixel answered test: Last test updates, no partner fallback needed', last1);
|
||||||
|
await page.click('[data-convtest="' + PX2 + '"]'); await page.waitForTimeout(2000);
|
||||||
|
const msg2 = await page.evaluate(() => document.body.innerText);
|
||||||
|
const tcall = mock.calls.filter(c => c.op === 'test').pop();
|
||||||
|
ok(pixelHits.some(q => q.includes('px=' + PX2)) && tcall && tcall.px === PX2 && /recorded through InstantAdPay/.test(msg2), 'pixel did not confirm: falls back to the signed partner call (op test)', JSON.stringify(tcall));
|
||||||
|
ok(!errs.length, 'no page errors during the tests', errs.join(' | '));
|
||||||
|
await page.screenshot({ path: path.join(OUT, 'convpixel-test-button.png'), fullPage: true }).catch(() => {});
|
||||||
|
await ctx.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. LinkSpin down: the pane still loads, the panel says so, campaign rows omit the goal line; clicks are kept and pushed later
|
||||||
|
mock.down = true;
|
||||||
|
const ck2 = await signIn(A2);
|
||||||
|
const down = await api('/api/my/conversions', null, { Cookie: ck2 });
|
||||||
|
ok(down.j && down.j.ok === false && down.j.reason === 'down' && /did not answer/.test(down.j.error), 'proxy says LinkSpin is down in plain words', JSON.stringify(down.j));
|
||||||
|
const p2 = await pane(ck2, 'convpixel-down.png');
|
||||||
|
ok(p2.st.rows >= 1 && p2.st.card && /did not answer/.test(p2.st.status) && p2.st.line5Hidden, 'LinkSpin down: Campaigns pane still loads, no goal line, panel explains', JSON.stringify(p2.st).slice(0, 220));
|
||||||
|
ok(!p2.errs.length, 'no page errors while LinkSpin is down', p2.errs.join(' | '));
|
||||||
|
const cd = await click(5); const idDown = (ID.exec(cd.loc || '') || [])[1];
|
||||||
|
ok(!!idDown, 'clicks still get ids while LinkSpin is down');
|
||||||
|
await sleep(4000);
|
||||||
|
ok(!mock.clicks.has(idDown), 'nothing marked pushed while LinkSpin refuses');
|
||||||
|
mock.down = false;
|
||||||
|
ok(!!(await waitFor(() => mock.clicks.has(idDown), 30000)), 'row kept and pushed once LinkSpin is back (retry with backoff)');
|
||||||
|
const adm = await api('/api/admin/lssync', null, { Authorization: 'Bearer ' + ADMIN });
|
||||||
|
ok(adm.j && adm.j.conv && adm.j.conv.on === true && adm.j.conv.pushed >= 5, 'admin lssync view carries conv push stats', JSON.stringify(adm.j && adm.j.conv));
|
||||||
|
} catch (e) { ok(false, 'run', e.stack); }
|
||||||
|
finally {
|
||||||
|
await cleanup();
|
||||||
|
fs.writeFileSync(path.join(OUT, 'convpixel-server.log'), srvLog);
|
||||||
|
console.log(fails ? fails + ' FAILED' : 'all passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
}
|
||||||
+28
-13
@@ -71,24 +71,39 @@ try {
|
|||||||
g = (await api('/api/my/gamepass', null, hA)).j;
|
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||||
ok(g && g.enabled === true && g.caps && g.caps.enforced === false && g.caps.daily === 0.3 && g.caps.total === 2, 'pass ON: GET shows free caps 0.30 / 2 and enforced false (no capsStartDate)', JSON.stringify(g.caps));
|
ok(g && g.enabled === true && g.caps && g.caps.enforced === false && g.caps.daily === 0.3 && g.caps.total === 2, 'pass ON: GET shows free caps 0.30 / 2 and enforced false (no capsStartDate)', JSON.stringify(g.caps));
|
||||||
|
|
||||||
// 2. buy without purchased credits -> waiting order; a $5 package fulfils it
|
// 2. buy (2026-10-22: no pass is ever bought with credits) -> waiting order; only a FRESH package by the member's own position fulfils it.
|
||||||
|
// A's purchases are stamped Sun Oct 18 (week of Oct 12) and B's Tue Oct 20 (week of Oct 19), so the tournament below sees one sale.
|
||||||
|
const SUN = Date.parse('2026-10-18T17:00:00Z'), TUE = Date.parse('2026-10-20T17:00:00Z');
|
||||||
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
||||||
ok(r.status === 200 && r.j && r.j.needPay === true && r.j.payUrl === '/my?from=gamepass#buy' && r.j.order, 'buy with no purchased credits -> needPay + payUrl + waiting order', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, need: r.j.need }));
|
ok(r.status === 200 && r.j && r.j.needPay === true && r.j.payUrl === '/my?from=gamepass#buy' && r.j.order && r.j.package === 5 && /package/.test(r.j.message || ''), 'buy -> needPay + payUrl + waiting order (never a credit charge)', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, pkg: r.j.package }));
|
||||||
const order1 = r.j && r.j.order;
|
const order1 = r.j && r.j.order, order1Ts = r.j && r.j.orderTs;
|
||||||
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
|
||||||
ok(r.j && r.j.order === order1, 'a second buy attempt reuses the same waiting order', r.j && r.j.order);
|
ok(r.j && r.j.order === order1 && r.j.needPay === true && !r.j.ok, 'a second buy (even with the retired devPaid flag) reuses the same waiting order, no pass', r.j && r.j.order);
|
||||||
g = (await api('/api/my/gamepass', null, hA)).j; ok(g.waiting === true && g.active === false, 'GET shows waiting: true', '');
|
g = (await api('/api/my/gamepass', null, hA)).j; ok(g.waiting === true && g.active === false, 'GET shows waiting: true', '');
|
||||||
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, minedAt: order1Ts - 10 * 60000 } });
|
||||||
ok(r.j && r.j.order && r.j.order.order === order1, 'a $5 package purchase event fulfils the waiting order', JSON.stringify(r.j));
|
ok(r.j && r.j.order === null, 'a package mined BEFORE the order was opened does not fulfil it', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 200 } });
|
||||||
|
ok(r.j && r.j.order === null, 'a $2 package does not fulfil a $5 pass order', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 500 } });
|
||||||
|
ok(r.j && r.j.order === null, 'another member’s package does not fulfil A’s order', JSON.stringify(r.j));
|
||||||
|
const tx1 = '0x' + crypto.randomBytes(32).toString('hex');
|
||||||
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
|
||||||
|
ok(r.j && r.j.order && r.j.order.order === order1, 'a fresh $5 package by A fulfils the waiting order', JSON.stringify(r.j));
|
||||||
g = (await api('/api/my/gamepass', null, hA)).j; const until1 = g.until;
|
g = (await api('/api/my/gamepass', null, hA)).j; const until1 = g.until;
|
||||||
ok(g.active === true && g.waiting === false && near(g.until, Date.now() + 7 * 86400000, 60000) && g.bought === 1, 'pass active for 7 days, waiting cleared', new Date(g.until).toISOString());
|
ok(g.active === true && g.waiting === false && g.until === SUN + 7 * 86400000 && g.bought === 1, 'pass active for 7 days from the purchase, waiting cleared', new Date(g.until).toISOString());
|
||||||
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
|
||||||
ok(r.j && r.j.order === null, 'another package with no waiting order does nothing', JSON.stringify(r.j));
|
ok(r.j && r.j.order === null, 'another package with no waiting order does nothing', JSON.stringify(r.j));
|
||||||
// 3. buy while active -> extends from the current until (charge stubbed: devPaid, local only)
|
// 3. buy while active -> a new order; the same tx again is refused, a new package extends from the current until
|
||||||
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
|
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
|
||||||
ok(r.status === 200 && r.j.ok && near(r.j.until, until1 + 7 * 86400000, 1000) && r.j.paid === 'credits', 'buy while active extends by 7 days from the current until', new Date(r.j.until).toISOString());
|
ok(r.j && r.j.needPay && r.j.order && r.j.order !== order1, 'buy while active opens a new waiting order', r.j && r.j.order);
|
||||||
r = await api('/api/my/gamepass/buy', { data: { devPaid: true, devDay: '2026-10-20' } }, hB);
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
|
||||||
ok(r.status === 200 && r.j.ok && r.j.active === true, 'member B: buy -> active (sale stamped in the week of Oct 19 for the tournament)', '');
|
ok(r.j && r.j.order === null, 'replaying a purchase tx that already paid a pass does nothing (each tx once)', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, now: SUN } });
|
||||||
|
ok(r.j && r.j.order && near(r.j.order.until, until1 + 7 * 86400000, 1000), 'a fresh package while active extends by 7 days from the current until', r.j && r.j.order && new Date(r.j.order.until).toISOString());
|
||||||
|
r = await api('/api/my/gamepass/buy', { data: {} }, hB);
|
||||||
|
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 1000, now: TUE } });
|
||||||
|
g = (await api('/api/my/gamepass', null, hB)).j;
|
||||||
|
ok(r.j && r.j.order && g.active === true, 'member B: order + a $10 package -> active (sale stamped in the week of Oct 19 for the tournament)', JSON.stringify(r.j));
|
||||||
|
|
||||||
// 4. partner auth + /api/partner/player
|
// 4. partner auth + /api/partner/player
|
||||||
let pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: A }, A, GK);
|
let pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: A }, A, GK);
|
||||||
|
|||||||
+130
@@ -0,0 +1,130 @@
|
|||||||
|
// Knowledge-base chat, end to end against a LOCAL copy (2026-10-20).
|
||||||
|
// node qa/kb-chat.mjs (or: bash qa/run.sh kb)
|
||||||
|
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB) and a mock OpenRouter that
|
||||||
|
// records every request and answers from the "Knowledge base" block it was given. Nothing touches production:
|
||||||
|
// OPENROUTER_URL points at the mock and the key is a throwaway string.
|
||||||
|
// Covers: the Coinbase question answered from the KB through the AI path, the CANNED fast path served from the
|
||||||
|
// KB (no AI call), an off-topic question told to say "I'm not sure, ask support", admin create / edit / test /
|
||||||
|
// delete, an admin edit to a canned entry changing the instant answer, and /api/chat/kb-stamp. Exit 1 on failure.
|
||||||
|
import http from 'node:http';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
|
||||||
|
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const PORT = Number(process.env.KB_PORT || 8799), MOCK = PORT + 100;
|
||||||
|
const B = 'http://127.0.0.1:' + PORT;
|
||||||
|
const ADMIN = 'localtest';
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kb-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
|
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
|
||||||
|
// -- the mock OpenRouter: answers with the first KB answer it was handed, or the not-sure line
|
||||||
|
const calls = [];
|
||||||
|
const mock = http.createServer((req, res) => {
|
||||||
|
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
||||||
|
let body = {}; try { body = JSON.parse(raw); } catch (e) {}
|
||||||
|
calls.push({ url: req.url, auth: req.headers.authorization, body });
|
||||||
|
const sys = ((body.messages || [])[0] || {}).content || '';
|
||||||
|
const m = /\nAnswer: ([^\n]+)/.exec(sys.slice(sys.indexOf('KNOWLEDGE BASE')));
|
||||||
|
const content = m ? m[1] : "I'm not sure, ask support: open Help at https://instantadpay.com/my#help.";
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||||
|
res.end('\n\n' + JSON.stringify({ choices: [{ message: { content } }] })); // keepalive padding first, like the real thing
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise(r => mock.listen(MOCK, '127.0.0.1', r));
|
||||||
|
|
||||||
|
let srv = null, srvLog = '';
|
||||||
|
async function boot() {
|
||||||
|
srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN,
|
||||||
|
OPENROUTER_API_KEY: 'qa-throwaway', OPENROUTER_URL: 'http://127.0.0.1:' + MOCK + '/api/v1/chat/completions', DATABASE_URL: '' }) });
|
||||||
|
srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
|
||||||
|
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(B + '/api/config')).ok; } catch (e) { await sleep(500); } }
|
||||||
|
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
|
||||||
|
}
|
||||||
|
async function halt() { if (!srv) return; const s = srv; srv = null; s.kill(); await new Promise(r => { s.once('exit', r); setTimeout(r, 3000); }); await sleep(300); }
|
||||||
|
const cleanup = async () => { try { await halt(); } catch (e) {} try { mock.close(); } catch (e) {} try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
|
||||||
|
|
||||||
|
try {
|
||||||
|
await boot();
|
||||||
|
const api = async (p, data, method, hdr) => { const r = await fetch(B + p, data !== undefined || method ? { method: method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: data === undefined ? undefined : JSON.stringify(data) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
|
||||||
|
const adminH = { Authorization: 'Bearer ' + ADMIN };
|
||||||
|
const chat = message => api('/api/chat', { message }, 'POST'); // six questions in all, under the 10-a-minute chat limit
|
||||||
|
|
||||||
|
// 1. seeds landed in DATA_DIR/kb.json
|
||||||
|
await sleep(300);
|
||||||
|
const list0 = await api('/api/admin/kb', undefined, undefined, adminH);
|
||||||
|
const ids = (list0.j && list0.j.entries || []).map(e => e.id);
|
||||||
|
ok(ids.includes('f-coinbase') && ids.includes('c-withdraw') && ids.length >= 55, 'KB seeded from CANNED + FAQ + the Coinbase ticket', ids.length + ' entries');
|
||||||
|
ok(fs.existsSync(path.join(DATA, 'kb.json')), 'JSON store at DATA_DIR/kb.json');
|
||||||
|
|
||||||
|
// 2. the Coinbase question goes to the AI with the Coinbase entry in its knowledge base
|
||||||
|
let n = calls.length;
|
||||||
|
const cb = await chat('Can I use my regular Coinbase account?');
|
||||||
|
const sys = calls[n] && calls[n].body.messages[0].content || '';
|
||||||
|
ok(cb.status === 200 && calls.length === n + 1, 'Coinbase question goes to the AI path (one call)', 'status ' + cb.status);
|
||||||
|
ok(sys.includes('KNOWLEDGE BASE') && sys.includes('Coinbase is an exchange') && sys.indexOf('[1] Can I use my regular Coinbase account?') > 0, 'system prompt carries the Coinbase entry first');
|
||||||
|
ok(sys.includes('NEVER promise or estimate income') && sys.includes('No em dashes'), 'compliance rules still in the prompt');
|
||||||
|
ok(calls[n] && calls[n].body.reasoning && calls[n].body.reasoning.enabled === false, 'reasoning stays off');
|
||||||
|
ok(cb.j && /Coinbase is an exchange/.test(cb.j.reply) && (cb.j.kb || [])[0] === 'f-coinbase', 'reply drawn from the KB entry', JSON.stringify(cb.j).slice(0, 140));
|
||||||
|
|
||||||
|
// 3. the CANNED fast path, now served from the KB: no AI call
|
||||||
|
n = calls.length;
|
||||||
|
const wd = await chat('how do I withdraw my money');
|
||||||
|
ok(wd.j && wd.j.canned && wd.j.kb === 'c-withdraw' && /no withdrawals here/.test(wd.j.reply) && calls.length === n, 'canned answer served from the KB, no AI call', JSON.stringify(wd.j).slice(0, 100));
|
||||||
|
const sup = await chat('I want to talk to a real person');
|
||||||
|
ok(sup.j && sup.j.handoff && sup.j.kb === 'c-support', 'support hand-off flag kept on the instant answer');
|
||||||
|
|
||||||
|
// 4. nothing fits: the prompt says so and the reply hands off
|
||||||
|
n = calls.length;
|
||||||
|
const off = await chat('What is the capital of Mongolia?');
|
||||||
|
const sys2 = calls[n] && calls[n].body.messages[0].content || '';
|
||||||
|
ok(/no entry matches this question/.test(sys2) && /I'm not sure, ask support/.test(sys2), 'off-topic: prompt tells the AI to say it is not sure');
|
||||||
|
ok(off.j && off.j.handoff, 'off-topic reply offers "Send this to support"');
|
||||||
|
|
||||||
|
// 5. admin: create, find, test, edit, delete
|
||||||
|
const cr = await api('/api/admin/kb', { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?', 'Do you take PayPal'], answer: 'No. Packages are paid in POL on Polygon only — PayPal is not accepted.', tags: 'paypal, payment' }, 'POST', adminH);
|
||||||
|
ok(cr.j && cr.j.ok && cr.j.entry.answer.indexOf('—') < 0, 'admin creates an entry (em dash cleaned)', cr.j && cr.j.entry && cr.j.entry.answer);
|
||||||
|
const kid = cr.j && cr.j.entry && cr.j.entry.id;
|
||||||
|
const noAuth = await api('/api/admin/kb', { title: 'x', answer: 'y' }, 'POST');
|
||||||
|
ok(noAuth.status === 401, 'KB admin routes need the admin');
|
||||||
|
const t = await api('/api/admin/kb/test', { question: 'do you accept paypal' }, 'POST', adminH);
|
||||||
|
ok(t.j && t.j.ranked[0] && t.j.ranked[0].id === kid && t.j.ranked[0].used, 'Try a question ranks the new entry first');
|
||||||
|
n = calls.length;
|
||||||
|
await chat('can I pay using paypal?');
|
||||||
|
ok(calls[n] && calls[n].body.messages[0].content.includes('PayPal is not accepted'), 'new entry reaches the AI prompt right away');
|
||||||
|
const ed = await api('/api/admin/kb/' + kid, { title: 'Can I pay with PayPal?', questions: ['Can I pay with PayPal?'], answer: 'No, PayPal is not accepted. Packages are paid in POL on Polygon.', tags: ['paypal'] }, 'PUT', adminH);
|
||||||
|
ok(ed.j && ed.j.ok && ed.j.entry.answer.startsWith('No, PayPal'), 'admin edits the entry');
|
||||||
|
const srch = await api('/api/admin/kb?q=paypal', undefined, undefined, adminH);
|
||||||
|
ok(srch.j && srch.j.entries[0] && srch.j.entries[0].id === kid, 'admin search finds it');
|
||||||
|
const bad = await api('/api/admin/kb', { title: 'x', answer: 'y', pattern: '(' }, 'POST', adminH);
|
||||||
|
ok(bad.status === 400, 'a broken instant-answer pattern is refused');
|
||||||
|
const del = await api('/api/admin/kb/' + kid, undefined, 'DELETE', adminH);
|
||||||
|
const gone = await api('/api/admin/kb/' + kid, undefined, undefined, adminH);
|
||||||
|
ok(del.j && del.j.ok && gone.status === 404, 'admin deletes it');
|
||||||
|
|
||||||
|
// 6. editing a canned entry changes the instant answer (one source)
|
||||||
|
const cw = (await api('/api/admin/kb/c-withdraw', undefined, undefined, adminH)).j.entry;
|
||||||
|
await api('/api/admin/kb/c-withdraw', Object.assign({}, cw, { answer: cw.answer + ' (edited in QA)' }), 'PUT', adminH);
|
||||||
|
const wd2 = await chat('how do I withdraw');
|
||||||
|
ok(wd2.j && /\(edited in QA\)$/.test(wd2.j.reply), 'admin edit to a canned entry is what the fast path serves');
|
||||||
|
|
||||||
|
// 7. the sync guard's stamp: today (Central), because a person just edited entries
|
||||||
|
const st = await api('/api/chat/kb-stamp');
|
||||||
|
const today = new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||||
|
ok(st.j && st.j.updated === today && st.j.count >= 55, '/api/chat/kb-stamp reports the newest human edit', JSON.stringify(st.j));
|
||||||
|
|
||||||
|
// 8. a restart (the seed sync runs again) keeps admin work and does not bring a deleted seed back
|
||||||
|
await api('/api/admin/kb/f-refunds', undefined, 'DELETE', adminH);
|
||||||
|
await halt(); await boot();
|
||||||
|
const after = await api('/api/admin/kb', undefined, undefined, adminH);
|
||||||
|
const aIds = (after.j && after.j.entries || []).map(e => e.id);
|
||||||
|
const cw2 = (after.j && after.j.entries || []).find(e => e.id === 'c-withdraw');
|
||||||
|
ok(!aIds.includes('f-refunds') && aIds.includes('f-coinbase'), 'restart: a deleted seed stays deleted');
|
||||||
|
ok(cw2 && /\(edited in QA\)$/.test(cw2.answer) && cw2.edited, 'restart: an admin edit to a seed is not overwritten by the code');
|
||||||
|
} catch (e) { ok(false, 'run', e.message); }
|
||||||
|
await cleanup();
|
||||||
|
console.log(fails ? fails + ' failure(s)' : 'all KB chat checks passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// Knowledge-base retrieval unit test (kb.js): the right entry must rank first for each sample question,
|
||||||
|
// scored over the real seeds (chatbot.js CANNED + kb-seed.js). No server, no network.
|
||||||
|
// node qa/kb-retrieval.cjs
|
||||||
|
const path = require('path');
|
||||||
|
const kb = require(path.join(__dirname, '..', 'kb.js'));
|
||||||
|
const chatbot = require(path.join(__dirname, '..', 'chatbot.js'));
|
||||||
|
const { buildIndex, rank, relevant, validate } = kb._pure;
|
||||||
|
|
||||||
|
const entries = chatbot.seeds();
|
||||||
|
const idx = buildIndex(entries);
|
||||||
|
const CASES = [
|
||||||
|
['Can I hook up my Coinbase account to pay for a package?', 'f-coinbase'],
|
||||||
|
['can i just use coinbase', 'f-coinbase'],
|
||||||
|
['Is my payment refundable if I change my mind?', 'f-refunds'],
|
||||||
|
['Can I give some of my credits to a friend?', 'f-credits-transfer'],
|
||||||
|
['Why does the amount of POL keep changing when I buy?', 'f-price-feed'],
|
||||||
|
['What is the smart contract address on polygonscan?', 'f-contract'],
|
||||||
|
['My video stopped playing when I switched tabs', 'f-active-viewing'],
|
||||||
|
['How many extra POL should I keep for gas fees?', 'f-how-much-pol'],
|
||||||
|
['My bank refused my card on MoonPay', 'f-moonpay-declined'],
|
||||||
|
['Trust wallet says this will drain my wallet', 'c-trust-drain'],
|
||||||
|
['How do I adopt somebody from the holding tank?', 'c-holding-tank'],
|
||||||
|
['I keep getting signed out every few hours', 'c-session-4h'],
|
||||||
|
['Where does the 20 percent platform share go?', 'f-platform-share']
|
||||||
|
];
|
||||||
|
let bad = 0;
|
||||||
|
for (const [q, want] of CASES) {
|
||||||
|
const hits = rank(idx, q, 5), top = hits[0];
|
||||||
|
const ok = top && top.entry.id === want && relevant(hits).length > 0;
|
||||||
|
if (!ok) bad++;
|
||||||
|
console.log((ok ? 'ok ' : 'FAIL ') + q + ' -> ' + hits.slice(0, 3).map(h => h.entry.id + ' ' + h.score).join(', ') + (ok ? '' : ' (wanted ' + want + ')'));
|
||||||
|
}
|
||||||
|
// off-topic questions should bring nothing back, so the prompt says "I'm not sure, ask support"
|
||||||
|
for (const q of ['What is the weather in Paris tomorrow?', 'Recommend a good pizza recipe']) {
|
||||||
|
const r = relevant(rank(idx, q, 5));
|
||||||
|
if (r.length) bad++;
|
||||||
|
console.log((r.length ? 'FAIL ' : 'ok ') + 'off-topic: ' + q + ' -> ' + (r.map(h => h.entry.id + ' ' + h.score).join(', ') || 'nothing'));
|
||||||
|
}
|
||||||
|
// admin input hygiene: em dashes are turned into commas, a bad pattern is refused
|
||||||
|
const v = validate({ title: 'T', answer: 'One — two', questions: 'a\nb', tags: 'X, y' });
|
||||||
|
if (v.answer !== 'One, two' || v.questions.length !== 2 || v.tags[0] !== 'x') { bad++; console.log('FAIL validate', v); } else console.log('ok validate cleans em dashes, splits questions and tags');
|
||||||
|
if (!validate({ title: 'T', answer: 'a', pattern: '(' }).error) { bad++; console.log('FAIL validate accepted a broken pattern'); } else console.log('ok validate refuses a broken pattern');
|
||||||
|
// every CANNED regex still answers through the KB fast path in the same order
|
||||||
|
const ordered = entries.filter(e => e.pattern).sort((a, b) => a.order - b.order);
|
||||||
|
const first = msg => ordered.find(e => new RegExp(e.pattern, 'i').test(msg));
|
||||||
|
const canned = chatbot.CANNED.find(c => c.re.test('how do I withdraw'));
|
||||||
|
if (!first('how do I withdraw') || first('how do I withdraw').answer !== canned.a) { bad++; console.log('FAIL fast-path order'); } else console.log('ok fast path keeps CANNED order');
|
||||||
|
console.log(bad ? bad + ' failure(s)' : 'all retrieval checks passed');
|
||||||
|
process.exit(bad ? 1 : 0);
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
// Prepaid login-ad line, MySQL code path (2026-10-23).
|
||||||
|
// node qa/login-queue-sql.cjs
|
||||||
|
// There is no MySQL on the test machine, so this swaps db.js for an in-memory fake that understands exactly the SQL the
|
||||||
|
// line uses and runs each statement atomically after a random 0-3 ms wait, so concurrent callers interleave BETWEEN
|
||||||
|
// statements the way two app copies do during a deploy overlap. That tests the guard logic of the SQL path (the
|
||||||
|
// app_locks lease and the conditional UPDATE ... WHERE status='queued'), not MySQL itself: real InnoDB locking, the
|
||||||
|
// schema migration and mysql2's affectedRows semantics are not exercised here. Unknown SQL throws, so a statement
|
||||||
|
// this fake does not model fails the test instead of passing silently. Exit 1 on failure.
|
||||||
|
'use strict';
|
||||||
|
const path = require('path');
|
||||||
|
const DAY = 86400000;
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
|
||||||
|
// ---- the fake ----
|
||||||
|
const T = { campaigns: [], locks: {}, earned: {}, log: [] }; let nextId = 1;
|
||||||
|
const wait = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 4)));
|
||||||
|
const norm = s => String(s).replace(/\s+/g, ' ').trim();
|
||||||
|
const liveRows = now => T.campaigns.filter(c => c.type === 'login' && c.status === 'active' && c.house === 0 && (c.expires == null || c.expires > now));
|
||||||
|
async function q(sql, p) {
|
||||||
|
await wait();
|
||||||
|
const s = norm(sql); p = p || [];
|
||||||
|
let m;
|
||||||
|
if (s.startsWith('INSERT IGNORE INTO app_locks')) { if (!T.locks[p[0]]) T.locks[p[0]] = { holder: null, until: 0 }; return { affectedRows: 1 }; }
|
||||||
|
if (s === 'UPDATE app_locks SET holder=?, lease_until=? WHERE name=? AND (holder IS NULL OR lease_until<?)') {
|
||||||
|
const L = T.locks[p[2]]; if (L && (L.holder === null || L.until < p[3])) { L.holder = p[0]; L.until = p[1]; return { affectedRows: 1 }; } return { affectedRows: 0 };
|
||||||
|
}
|
||||||
|
if (s === 'UPDATE app_locks SET holder=NULL, lease_until=0 WHERE name=? AND holder=?') {
|
||||||
|
const L = T.locks[p[0]]; if (L && L.holder === p[1]) { L.holder = null; L.until = 0; return { affectedRows: 1 }; } return { affectedRows: 0 };
|
||||||
|
}
|
||||||
|
if (s === "SELECT COUNT(*) n FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return [{ n: liveRows(p[0]).length }];
|
||||||
|
if (s === "SELECT expires FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return liveRows(p[0]).map(c => ({ expires: c.expires }));
|
||||||
|
if ((m = /^SELECT \* FROM campaigns WHERE type='login' AND status='queued' AND house=0 ORDER BY queued_at ASC, id ASC( LIMIT (\d+))?$/.exec(s))) {
|
||||||
|
const rows = T.campaigns.filter(c => c.type === 'login' && c.status === 'queued' && c.house === 0).sort((a, b) => (a.queued_at - b.queued_at) || (a.id - b.id));
|
||||||
|
return (m[2] ? rows.slice(0, Number(m[2])) : rows).map(c => Object.assign({}, c));
|
||||||
|
}
|
||||||
|
if (s === "UPDATE campaigns SET status='active', starts=?, expires=?, body=? WHERE id=? AND type='login' AND status='queued'") {
|
||||||
|
const c = T.campaigns.find(x => x.id === p[3] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
|
||||||
|
c.status = 'active'; c.starts = p[0]; c.expires = p[1]; c.body = p[2]; return { affectedRows: 1 };
|
||||||
|
}
|
||||||
|
if (s === "UPDATE campaigns SET status='cancelled' WHERE id=? AND type='login' AND status='queued'") {
|
||||||
|
const c = T.campaigns.find(x => x.id === p[0] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
|
||||||
|
c.status = 'cancelled'; return { affectedRows: 1 };
|
||||||
|
}
|
||||||
|
if (s === 'SELECT * FROM campaigns WHERE id=?') return T.campaigns.filter(c => c.id === p[0]).map(c => Object.assign({}, c));
|
||||||
|
if (s === 'SELECT * FROM campaigns WHERE owner_email=? ORDER BY id DESC') return T.campaigns.filter(c => c.owner_email === p[0]).sort((a, b) => b.id - a.id).map(c => Object.assign({}, c));
|
||||||
|
if (s === 'UPDATE campaigns SET status=? WHERE id=? AND owner_email=?') { const c = T.campaigns.find(x => x.id === p[1] && x.owner_email === p[2]); if (!c) return { affectedRows: 0 }; c.status = p[0]; return { affectedRows: 1 }; }
|
||||||
|
if (s.startsWith('INSERT INTO earned_credits (email,balance,purchase_grade,granted_welcome,updated)')) {
|
||||||
|
const e = T.earned[p[0]] = T.earned[p[0]] || { balance: 0, grade: 0 }; e.balance += p[1]; e.grade += p[2]; return { affectedRows: 1 };
|
||||||
|
}
|
||||||
|
if (s.startsWith('INSERT INTO credit_log')) { T.log.push({ email: p[0], delta: p[3], kind: p[4], note: p[5], ref: p[6] }); return { affectedRows: 1 }; }
|
||||||
|
throw new Error('fake db: unmodelled SQL: ' + s);
|
||||||
|
}
|
||||||
|
const fake = { enabled: () => true, q, init: async () => true };
|
||||||
|
const dbPath = require.resolve(path.join(__dirname, '..', 'db.js'));
|
||||||
|
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: fake };
|
||||||
|
const fs = require('fs'); const os = require('os');
|
||||||
|
const ads = require('../ads');
|
||||||
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-sql-'));
|
||||||
|
ads.init({ dataDir, chain: { creditBalance: async () => 0 } });
|
||||||
|
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
|
||||||
|
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
|
||||||
|
|
||||||
|
const row = (o) => { const c = Object.assign({ id: nextId++, owner_email: 'x@qa.test', member_id: 1, house: 0, type: 'login', name: 'QA', target_url: 'https://example.com', image_url: null, title: null, body: '30', budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batch_imps: 0, status: 'active', created: Date.now(), expires: Date.now() + 10 * DAY, starts: Date.now(), queued_at: null }, o); T.campaigns.push(c); return c; };
|
||||||
|
const reset = () => { T.campaigns = []; T.locks = {}; T.earned = {}; T.log = []; notified.length = 0; };
|
||||||
|
const live = () => liveRows(Date.now()).length;
|
||||||
|
const tick = () => new Promise(r => setTimeout(r, 30));
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
// 1. one slot frees, two queued, five promoters at once: exactly one start, the oldest
|
||||||
|
for (let round = 0; round < 25; round++) {
|
||||||
|
reset();
|
||||||
|
const slots = []; for (let i = 0; i < 6; i++) slots.push(row({ owner_email: 's' + i + '@qa.test', expires: Date.now() + (i + 1) * DAY }));
|
||||||
|
const a = row({ owner_email: 'a@qa.test', status: 'queued', queued_at: 1000, expires: null, starts: null });
|
||||||
|
const b = row({ owner_email: 'b@qa.test', status: 'queued', queued_at: 2000, expires: null, starts: null });
|
||||||
|
slots[0].expires = Date.now() - 1000;
|
||||||
|
const res = await Promise.all([1, 2, 3, 4, 5].map(() => ads.promoteLoginQueue()));
|
||||||
|
await tick();
|
||||||
|
const started = res.flatMap(r => r.promoted.map(c => c.id));
|
||||||
|
const good = started.length === 1 && started[0] === a.id && a.status === 'active' && b.status === 'queued' && live() === 6 && notified.length === 1 && T.locks.login_queue.holder === null;
|
||||||
|
if (!good || round === 24) ok(good, 'round ' + (round + 1) + '/25: five concurrent promoters, one free slot -> exactly one start (the oldest), 6 live, one notice, lock released', JSON.stringify({ started, a: a.status, b: b.status, live: live(), notified, lock: T.locks.login_queue }));
|
||||||
|
if (!good) break;
|
||||||
|
}
|
||||||
|
// 2. two free slots, three queued, concurrent promoters: exactly two start, the two oldest, never over the cap
|
||||||
|
{
|
||||||
|
reset();
|
||||||
|
for (let i = 0; i < 4; i++) row({});
|
||||||
|
const q = [3000, 1000, 2000].map(t => row({ status: 'queued', queued_at: t, expires: null, starts: null }));
|
||||||
|
const res = await Promise.all([1, 2, 3].map(() => ads.promoteLoginQueue()));
|
||||||
|
const started = res.flatMap(r => r.promoted.map(c => c.id)).sort();
|
||||||
|
ok(started.length === 2 && started.join() === [q[1].id, q[2].id].sort().join() && q[0].status === 'queued' && live() === 6, 'two slots free: the two oldest start, the third waits, cap 6', JSON.stringify({ started, live: live() }));
|
||||||
|
}
|
||||||
|
// 3. a cancel racing a start: exactly one wins, the refund is paid only if the cancel won
|
||||||
|
{
|
||||||
|
let bad = 0;
|
||||||
|
for (let round = 0; round < 40; round++) {
|
||||||
|
reset();
|
||||||
|
for (let i = 0; i < 5; i++) row({});
|
||||||
|
const a = row({ owner_email: 'race@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||||
|
const [cn, pr] = await Promise.all([ads.cancelLoginReservation('race@qa.test', a.id), ads.promoteLoginQueue()]);
|
||||||
|
const refunded = (T.earned['race@qa.test'] || { balance: 0 }).balance;
|
||||||
|
const cancelWon = !!cn.ok, startWon = pr.promoted.length === 1;
|
||||||
|
if (cancelWon === startWon || (cancelWon && (a.status !== 'cancelled' || refunded !== 1000)) || (startWon && (a.status !== 'active' || refunded !== 0))) bad++;
|
||||||
|
}
|
||||||
|
ok(bad === 0, '40 rounds of cancel vs start on the same reservation: always exactly one winner, refund only when the cancel won', bad + ' bad rounds');
|
||||||
|
}
|
||||||
|
// 4. a lease held by the other app copy: the tick backs off; an expired lease is taken over
|
||||||
|
{
|
||||||
|
reset();
|
||||||
|
for (let i = 0; i < 5; i++) row({});
|
||||||
|
const a = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||||
|
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 10000 };
|
||||||
|
let r = await ads.promoteLoginQueue();
|
||||||
|
ok(r.busy === true && !r.promoted.length && a.status === 'queued' && T.locks.login_queue.holder === 'other-copy', 'lease held by the other copy: no start, the tick backs off, the lease is untouched', JSON.stringify(r));
|
||||||
|
T.locks.login_queue.until = Date.now() - 1; // that copy died holding it
|
||||||
|
r = await ads.promoteLoginQueue();
|
||||||
|
ok(r.promoted.length === 1 && a.status === 'active' && T.locks.login_queue.holder === null, 'an expired lease is taken over, the reservation starts, the lease is released', JSON.stringify({ n: r.promoted.length, lock: T.locks.login_queue }));
|
||||||
|
}
|
||||||
|
// 5. resume rule in SQL mode: a paused slot stays paused while the line is non-empty, even with a slot free
|
||||||
|
{
|
||||||
|
reset();
|
||||||
|
for (let i = 0; i < 4; i++) row({});
|
||||||
|
const p = row({ owner_email: 'pz@qa.test', status: 'paused' });
|
||||||
|
const w = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||||
|
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 60000 }; // keep the line from starting w during the check
|
||||||
|
const t0 = Date.now(); let r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||||
|
ok(r.error && /busy/.test(r.error) && p.status === 'paused' && Date.now() - t0 >= 3000, 'resume waits for the lease and gives up cleanly while another copy holds it', JSON.stringify(r));
|
||||||
|
T.locks.login_queue = { holder: null, until: 0 };
|
||||||
|
// 4 live + 1 waiting = 5 of 6: one place is open, so the paused slot may resume
|
||||||
|
r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||||
|
ok(r.ok && p.status === 'active', '4 live + 1 waiting of 6: a place is open, the paused slot resumes', JSON.stringify(r).slice(0, 100));
|
||||||
|
p.status = 'paused'; row({}); // now 5 live + 1 waiting = 6
|
||||||
|
r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||||
|
ok(r.error && /line goes first/.test(r.error) && p.status === 'paused', '5 live + 1 waiting of 6: resume refused, the line goes first', JSON.stringify(r));
|
||||||
|
r = await ads.setStatus(w.owner_email, w.id, 'active');
|
||||||
|
ok(r.error && /already in line/.test(r.error), 'a reservation cannot be "resumed" past the line', JSON.stringify(r));
|
||||||
|
}
|
||||||
|
// 6. cancel refunds once, at purchase grade, with the ledger line
|
||||||
|
{
|
||||||
|
reset();
|
||||||
|
const a = row({ owner_email: 'c@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null, spent: 600, accrued: 400 });
|
||||||
|
const r1 = await ads.cancelLoginReservation('c@qa.test', a.id), r2 = await ads.cancelLoginReservation('c@qa.test', a.id);
|
||||||
|
const e = T.earned['c@qa.test'];
|
||||||
|
ok(r1.ok && r1.refunded === 1000 && r2.error && e.balance === 1000 && e.grade === 1000, 'cancel: 1,000 back once (spent + accrued), purchased grade; the second cancel pays nothing', JSON.stringify({ r1, r2, e }));
|
||||||
|
ok(T.log.some(l => l.delta === 1000 && /^Login slot reservation cancelled: refund/.test(l.note) && l.kind === 'refund'), 'credit_log row "Login slot reservation cancelled: refund"', JSON.stringify(T.log));
|
||||||
|
const r3 = await ads.cancelLoginReservation('someone@else.test', a.id);
|
||||||
|
ok(r3.error === 'No such reservation.', 'another member cannot cancel it or learn its state', JSON.stringify(r3));
|
||||||
|
}
|
||||||
|
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||||
|
console.log(fails ? fails + ' FAILED' : 'ALL PASS');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})().catch(e => { console.error(e); process.exit(1); });
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// Prepaid login-ad line (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line").
|
||||||
|
// node qa/login-queue.cjs
|
||||||
|
// Store-level test of ads.js in JSON mode on a throwaway data dir (no server, no DB, no chain: a fake chain returns
|
||||||
|
// made-up on-chain balances for made-up members). Nothing here can reach production or a real member.
|
||||||
|
// Covers: fill 6 slots, a 7th buy is refused with the reserve offer, reserve 2 (balances drop at once, credit log lines),
|
||||||
|
// places + estimated starts, one slot expires -> two concurrent promoters start the first reservation exactly once
|
||||||
|
// (owner notified once, cap never exceeded), cancel the second -> full refund once, edit before start is free,
|
||||||
|
// a freed slot goes to the line before a paused slot, paused-resume blocked while the line is non-empty, earned credits
|
||||||
|
// never pay. Exit 1 on any failure.
|
||||||
|
'use strict';
|
||||||
|
delete process.env.DATABASE_URL; // JSON store, always
|
||||||
|
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||||
|
const ads = require('../ads');
|
||||||
|
const DAY = 86400000;
|
||||||
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-'));
|
||||||
|
const onchain = {}; // memberId -> on-chain credits (fake)
|
||||||
|
ads.init({ dataDir, chain: { creditBalance: async id => onchain[id] || 0 } });
|
||||||
|
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
|
||||||
|
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
|
||||||
|
const tick = () => new Promise(r => setTimeout(r, 30));
|
||||||
|
const M = n => ({ email: 'lq' + n + '@qa.test', id: 500 + n });
|
||||||
|
const avail = async n => (await ads.balances([M(n).id], M(n).email)).available;
|
||||||
|
const buy = (n, extra) => ads.createCampaign(M(n).email, M(n).id, Object.assign({ type: 'login', name: 'QA login ' + n, targetUrl: 'https://example.com/' + n, budget: 1000 }, extra || {}), [M(n).id]);
|
||||||
|
const row = async id => ads.campaignById(id); // JSON mode: the live row
|
||||||
|
const live = async () => (await ads.adminLoginQueue()).used;
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
for (let n = 1; n <= 14; n++) onchain[M(n).id] = 5000;
|
||||||
|
// 1. six slots fill and go live, each paid up front
|
||||||
|
const slot = {};
|
||||||
|
for (let n = 1; n <= 6; n++) { const r = await buy(n); slot[n] = r.campaign && r.campaign.id; ok(r.ok && r.campaign.status === 'active', 'slot ' + n + ' of 6 goes live', JSON.stringify(r).slice(0, 160)); }
|
||||||
|
ok(await avail(1) === 4000, 'a live slot drops the balance by 1,000', String(await avail(1)));
|
||||||
|
// give the six slots distinct end dates: slot n ends in n days
|
||||||
|
for (let n = 1; n <= 6; n++) (await row(slot[n])).expires = Date.now() + n * DAY;
|
||||||
|
// 2. the seventh buy is refused with the reserve offer, nothing charged
|
||||||
|
let r = await buy(7);
|
||||||
|
ok(r.error && r.full === true && r.place === 1 && /reserve the next slot/i.test(r.error), 'all 6 taken: plain buy refused with a reserve offer (place #1)', JSON.stringify(r).slice(0, 220));
|
||||||
|
ok(await avail(7) === 5000, 'the refused buy charged nothing', String(await avail(7)));
|
||||||
|
// 3. reserve two: paid now, status queued, no clock, credit log line
|
||||||
|
const q7 = await buy(7, { reserve: true }), q8 = await buy(8, { reserve: true });
|
||||||
|
ok(q7.ok && q7.queued && q7.place === 1 && q7.campaign.status === 'queued', 'member 7 reserves: queued, place #1', JSON.stringify(q7).slice(0, 200));
|
||||||
|
ok(q8.ok && q8.queued && q8.place === 2, 'member 8 reserves: place #2', JSON.stringify(q8).slice(0, 120));
|
||||||
|
ok(await avail(7) === 4000 && await avail(8) === 4000, 'both balances dropped by 1,000 at reserve time', (await avail(7)) + ' / ' + (await avail(8)));
|
||||||
|
const c7 = await row(q7.campaign.id);
|
||||||
|
ok(c7.status === 'queued' && !c7.expires && !c7.starts && c7.queuedAt > 0 && (c7.spent + (c7.accrued || 0)) === 1000, 'a reservation has no start/end yet, a queuedAt stamp, and is fully charged', JSON.stringify({ s: c7.status, e: c7.expires, st: c7.starts, q: c7.queuedAt, spent: c7.spent, acc: c7.accrued }));
|
||||||
|
const log7 = await ads.creditActivity(M(7).email);
|
||||||
|
ok(log7.some(i => /^Login slot reserved \(queue #1\)/.test(i.note) && i.delta === -1000), 'credit log: "Login slot reserved (queue #1)" -1000', JSON.stringify(log7.map(i => i.note + ' ' + i.delta)));
|
||||||
|
ok(await live() === 6, 'reservations do not count as live slots', String(await live()));
|
||||||
|
ok(!(await ads.serve('login', {})) || ![q7.campaign.id, q8.campaign.id].includes((await ads.serve('login', {})).id), 'a reservation never serves');
|
||||||
|
{ let served = new Set(); for (let i = 0; i < 60; i++) { const s = await ads.serve('login', {}); if (s) served.add(s.id); } ok(!served.has(q7.campaign.id) && !served.has(q8.campaign.id), 'sixty serves: never a queued ad', [...served].join(',')); }
|
||||||
|
// 4. places and estimated starts: #1 when slot 1 ends (1 day), #2 when slot 2 ends (2 days), a new one at slot 3 (3 days)
|
||||||
|
let A = await ads.adminLoginQueue();
|
||||||
|
const near = (a, b) => a && Math.abs(a - b) < 5000;
|
||||||
|
ok(A.queue.length === 2 && A.queue[0].id === q7.campaign.id && A.queue[0].place === 1 && A.queue[1].place === 2, 'admin view: the line in paid order', JSON.stringify(A.queue.map(x => [x.id, x.place])));
|
||||||
|
ok(near(A.queue[0].estStart, (await row(slot[1])).expires) && near(A.queue[1].estStart, (await row(slot[2])).expires), 'estimated starts follow the live slots\' end dates', JSON.stringify(A.queue.map(x => x.estStart)));
|
||||||
|
const V = await ads.loginQueueView(M(8).email);
|
||||||
|
ok(V.free === 0 && V.nextPlace === 3 && near(V.nextEstStart, (await row(slot[3])).expires) && V.mine.length === 1 && V.mine[0].place === 2 && !JSON.stringify(V).includes(M(7).email), 'member view: own place #2, next place #3 at slot 3\'s end, nobody else\'s email', JSON.stringify(V).slice(0, 260));
|
||||||
|
// estimator alone: 6 slots ending day 1..6, 8 waiting -> the 7th starts when the first reservation's 30 days end
|
||||||
|
{ const now = 1e12; const e = ads.estimateStarts(6, [1, 2, 3, 4, 5, 6].map(d => now + d * DAY), 8, now, 30 * DAY);
|
||||||
|
ok(e[0] === now + DAY && e[5] === now + 6 * DAY && e[6] === now + 31 * DAY && e[7] === now + 32 * DAY, 'estimator: a full round, then reservations wait on reservations', JSON.stringify(e.map(x => (x - now) / DAY))); }
|
||||||
|
// 5. edit before the start: free, place unchanged
|
||||||
|
const before = await avail(8);
|
||||||
|
r = await ads.editLoginReservation(M(8).email, q8.campaign.id, { targetUrl: 'https://example.org/new', title: 'New headline' });
|
||||||
|
ok(r.ok && (await row(q8.campaign.id)).targetUrl === 'https://example.org/new' && await avail(8) === before, 'edit a reservation: saved, nothing charged', JSON.stringify(r).slice(0, 120));
|
||||||
|
r = await ads.editLoginReservation(M(7).email, q8.campaign.id, { targetUrl: 'https://evil.example' });
|
||||||
|
ok(r.error, 'another member cannot edit it', JSON.stringify(r));
|
||||||
|
r = await ads.setStatus(M(7).email, q7.campaign.id, 'paused');
|
||||||
|
ok(r.error && /waiting in line/.test(r.error), 'a reservation cannot be paused', JSON.stringify(r));
|
||||||
|
// 6. slot 1 expires -> two promoters at once: the first reservation starts exactly once
|
||||||
|
(await row(slot[1])).expires = Date.now() - 1000;
|
||||||
|
const [p1, p2] = await Promise.all([ads.promoteLoginQueue(), ads.promoteLoginQueue()]);
|
||||||
|
await tick();
|
||||||
|
const started = [...p1.promoted, ...p2.promoted];
|
||||||
|
ok(started.length === 1 && started[0].id === q7.campaign.id, 'two concurrent promoters: exactly one start, the oldest paid', JSON.stringify([p1, p2]).slice(0, 200));
|
||||||
|
const s7 = await row(q7.campaign.id);
|
||||||
|
ok(s7.status === 'active' && Math.abs(s7.starts - Date.now()) < 5000 && Math.abs(s7.expires - (s7.starts + 30 * DAY)) < 5 && s7.body === '30', 'the started ad: active, starts now, ends in 30 days', JSON.stringify({ st: s7.status, starts: s7.starts, expires: s7.expires }));
|
||||||
|
ok(notified.length === 1 && notified[0] === q7.campaign.id, 'its owner is notified once', JSON.stringify(notified));
|
||||||
|
ok(await live() === 6, 'the cap holds: 6 live', String(await live()));
|
||||||
|
r = await ads.promoteLoginQueue(); ok(!r.promoted.length, 'a third promoter finds nothing to do (slots full)');
|
||||||
|
ok(await avail(7) === 4000, 'starting charged nothing more', String(await avail(7)));
|
||||||
|
// 7. cancel the second reservation: full refund, exactly once
|
||||||
|
r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id);
|
||||||
|
ok(r.ok && r.refunded === 1000, 'cancel before the start refunds the full 1,000', JSON.stringify(r));
|
||||||
|
ok(await avail(8) === 5000, 'member 8 balance back to 5,000', String(await avail(8)));
|
||||||
|
const sp8 = await ads.earnedSplit(M(8).email);
|
||||||
|
ok(sp8.grade === 1000, 'the refund is purchased-grade (same kind as paid)', JSON.stringify(sp8));
|
||||||
|
const log8 = await ads.creditActivity(M(8).email);
|
||||||
|
ok(log8.some(i => /^Login slot reservation cancelled: refund/.test(i.note) && i.delta === 1000), 'credit log: "Login slot reservation cancelled: refund" +1000', JSON.stringify(log8.map(i => i.note + ' ' + i.delta)));
|
||||||
|
r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id);
|
||||||
|
ok(r.error && await avail(8) === 5000, 'a second cancel refunds nothing', JSON.stringify(r));
|
||||||
|
r = await ads.cancelLoginReservation(M(7).email, q7.campaign.id);
|
||||||
|
ok(r.error && /already started/.test(r.error) && await avail(7) === 4000, 'a started ad cannot be cancelled for a refund', JSON.stringify(r));
|
||||||
|
ok((await row(q8.campaign.id)).status === 'cancelled', 'cancelled stays cancelled');
|
||||||
|
r = await ads.archive(M(8).email, q8.campaign.id); ok(r.ok && r.freed === 0, 'a cancelled reservation can be archived, freeing 0', JSON.stringify(r));
|
||||||
|
// 8. a freed slot goes to the line before a paused slot
|
||||||
|
const q9 = await buy(9, { reserve: true });
|
||||||
|
ok(q9.queued && q9.place === 1, 'member 9 reserves: place #1');
|
||||||
|
r = await ads.setStatus(M(2).email, slot[2], 'paused'); await tick();
|
||||||
|
ok(r.ok && (await row(q9.campaign.id)).status === 'active', 'pausing slot 2 hands its place to the line at once', (await row(q9.campaign.id)).status);
|
||||||
|
ok(notified.includes(q9.campaign.id), 'member 9 notified');
|
||||||
|
r = await ads.setStatus(M(2).email, slot[2], 'active');
|
||||||
|
ok(r.error && /taken/.test(r.error), 'slot 2 cannot resume while all 6 are live', JSON.stringify(r));
|
||||||
|
// 9. paused-resume blocked while the line is non-empty, even with a slot free
|
||||||
|
const q10 = await buy(10, { reserve: true });
|
||||||
|
(await row(slot[3])).expires = Date.now() - 1000; // slot 3 ends; no tick yet: 5 live, 1 waiting
|
||||||
|
ok(await live() === 5, 'slot 3 ended: 5 live, 1 waiting', String(await live()));
|
||||||
|
r = await ads.setStatus(M(2).email, slot[2], 'active');
|
||||||
|
ok(r.error && /line goes first/.test(r.error) && (await row(slot[2])).status === 'paused', 'resume refused while the line is non-empty (the line goes first)', JSON.stringify(r));
|
||||||
|
r = await buy(11);
|
||||||
|
// a new plain buy also respects the line: the freed slot went to member 10, member 11 is offered a reservation
|
||||||
|
ok((await row(q10.campaign.id)).status === 'active', 'a new buy first starts the waiting reservation (member 10 live)', (await row(q10.campaign.id)).status);
|
||||||
|
ok(r.error && r.full === true, 'and member 11 is offered the line, not the slot', JSON.stringify(r).slice(0, 160));
|
||||||
|
ok(await live() === 6, 'still 6 live', String(await live()));
|
||||||
|
// 10. with nobody waiting and a slot open, the paused slot resumes
|
||||||
|
(await row(slot[4])).expires = Date.now() - 1000;
|
||||||
|
r = await ads.setStatus(M(2).email, slot[2], 'active');
|
||||||
|
ok(r.ok && (await row(slot[2])).status === 'active' && await live() === 6, 'slot open and nobody waiting: the paused slot resumes', JSON.stringify(r).slice(0, 120));
|
||||||
|
// 11. earned (viewing) credits never pay for a reservation
|
||||||
|
await ads.addEarned(M(12).email, 5000); onchain[M(12).id] = 0;
|
||||||
|
r = await buy(12, { reserve: true });
|
||||||
|
ok(r.error && /purchased credits only/.test(r.error), 'earned credits cannot buy a reservation', JSON.stringify(r).slice(0, 160));
|
||||||
|
ok((await ads.adminLoginQueue()).queue.length === 0, 'nothing was queued for it');
|
||||||
|
// 12. admin cancel refunds the owner in full
|
||||||
|
const q13 = await buy(13, { reserve: true });
|
||||||
|
r = await ads.cancelLoginReservation(null, q13.campaign.id, { admin: true });
|
||||||
|
ok(r.ok && r.refunded === 1000 && await avail(13) === 5000, 'admin cancel: full refund to the owner', JSON.stringify(r));
|
||||||
|
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||||
|
console.log(fails ? fails + ' FAILED' : 'ALL PASS');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})().catch(e => { console.error(e); process.exit(1); });
|
||||||
+1
-1
@@ -27,7 +27,7 @@ t('same total as 30 days at the old daily rate',
|
|||||||
const src = require('fs').readFileSync(new URL('../ads.js', import.meta.url), 'utf8');
|
const src = require('fs').readFileSync(new URL('../ads.js', import.meta.url), 'utf8');
|
||||||
|
|
||||||
t('buying a slot charges the whole price up front',
|
t('buying a slot charges the whole price up front',
|
||||||
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, v\.c\.budget, 'Login-ad slot/.test(src));
|
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, (v\.)?c\.budget, 'Login-ad slot/.test(src));
|
||||||
t('a slot gets an end date at purchase',
|
t('a slot gets an end date at purchase',
|
||||||
/out\.expires = Date\.now\(\) \+ days \* 86400000/.test(src));
|
/out\.expires = Date\.now\(\) \+ days \* 86400000/.test(src));
|
||||||
t('the MySQL daily meter skips slot campaigns',
|
t('the MySQL daily meter skips slot campaigns',
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Syndicated rate (Marty, 2026-10-27, approved 4:1): delivery off instantadpay.com costs 1/synRateDivisor of the on-site rate.
|
||||||
|
// JSON store, NAS layer stubbed, throwaway data dir: no server, DB, chain, NAS or PassiveDrip. node qa/nas-ratio.mjs
|
||||||
|
// Covers: N=4 NAS views charge 1 credit per 20 banner views, fractions carried exactly, own credit-log line, budget is the
|
||||||
|
// limit (exhaustion stops the NAS ad with the true count), a lowered rate tops NAS up to what the budget now buys, N=1 is the
|
||||||
|
// old rule, on-site batches unchanged, PassiveDrip: 4 partner visits use 1 pack visit, all counted in synImps, PD offered x4.
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
delete process.env.DATABASE_URL;
|
||||||
|
const ok = [], bad = [];
|
||||||
|
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-ratio-'));
|
||||||
|
const nas = require('../nas.js');
|
||||||
|
const rows = {}; const calls = { topUp: [], deactivate: 0 };
|
||||||
|
nas.enabled = () => true;
|
||||||
|
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
|
||||||
|
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
|
||||||
|
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; calls.deactivate++; return { ok: true, served }; };
|
||||||
|
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp.push([id, add]); return { ok: true }; };
|
||||||
|
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; return { ok: true }; };
|
||||||
|
const ads = require('../ads.js');
|
||||||
|
const OWNER = 'ratio@qa.test', FILE = path.join(DATA, 'campaigns.json');
|
||||||
|
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
|
||||||
|
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
|
||||||
|
const visits = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'visits', name: 'QA visits ' + id, targetUrl: 'https://example.com/v', body: '100', budget: 300, spent: 300, accrued: 0, imps: 10, clicks: 0, status: 'active', created: Date.now() }, x || {});
|
||||||
|
const seed = camps => { fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: camps, burnsPending: [] })); ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } }); };
|
||||||
|
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
|
||||||
|
const used = c => (c.spent || 0) + (c.accrued || 0);
|
||||||
|
const deliver = (id, n) => { rows[id].remaining -= n; };
|
||||||
|
|
||||||
|
seed([banner(9001), visits(9101)]);
|
||||||
|
await ads.addEarned(OWNER, 100000);
|
||||||
|
t('default divisor is 4', ads.synRateDivisor() === 4, String(ads.synRateDivisor()));
|
||||||
|
rows[9001] = { assigned: 20000, remaining: 20000 }; rows[9002] = { assigned: 200, remaining: 200 };
|
||||||
|
deliver(9001, 1000); await ads.reconcileNas();
|
||||||
|
t('N=4: 1,000 network banner views charge 50 credits (1 per 20)', used(C(9001)) === 50, String(used(C(9001))));
|
||||||
|
deliver(9001, 10); await ads.reconcileNas();
|
||||||
|
t('10 more views: no whole credit yet', used(C(9001)) === 50, String(used(C(9001))));
|
||||||
|
deliver(9001, 10); await ads.reconcileNas();
|
||||||
|
t('10 more: the fraction completes one credit (exact)', used(C(9001)) === 51, String(used(C(9001))));
|
||||||
|
const log = (await ads.creditActivity(OWNER, 50)).filter(i => i.delta < 0);
|
||||||
|
t('credit log line names the network rate', log.some(i => /^Network views \(1\/4 rate\): /.test(i.note) && i.delta === -51), JSON.stringify(log.map(i => i.note + ' ' + i.delta)));
|
||||||
|
// on-site batches unchanged
|
||||||
|
for (let i = 0; i < 10; i++) await ads.serve('banner', { width: 728, height: 90 });
|
||||||
|
t('on-site: 10 views still charge 2 credits', used(C(9001)) === 53, String(used(C(9001))));
|
||||||
|
// budget is the limit
|
||||||
|
seed([C(9001), C(9101), banner(9002, { budget: 10 })]);
|
||||||
|
const onsite2 = used(C(9002));
|
||||||
|
deliver(9002, 200); await ads.reconcileNas();
|
||||||
|
const x = C(9002);
|
||||||
|
t('budget is the limit: the network charge stops at the budget', used(x) === 10 && x.status === 'out', JSON.stringify({ used: used(x), onsite2, st: x.status }));
|
||||||
|
t('exhaustion stops the NAS ad', calls.deactivate >= 1 && rows[9002].remaining === 0);
|
||||||
|
// rate lowered: NAS gets topped up to what the budget now buys
|
||||||
|
ads.setRates({ synRateDivisor: 1 });
|
||||||
|
rows[9003] = { assigned: 1000, remaining: 1000 };
|
||||||
|
seed([C(9001), C(9002), C(9101), banner(9003)]);
|
||||||
|
deliver(9003, 500); await ads.reconcileNas();
|
||||||
|
t('N=1 (old rule): 500 network views charge 100 credits', used(C(9003)) === 100, String(used(C(9003))));
|
||||||
|
ads.setRates({ synRateDivisor: 4 });
|
||||||
|
const before = calls.topUp.length; await ads.reconcileNas();
|
||||||
|
const tu = calls.topUp.slice(before).find(x => x[0] === 9003);
|
||||||
|
t('rate lowered to 1/4: NAS is topped up to what the 900 credits left now buy (18,000 views)', tu && rows[9003].remaining === 18000, JSON.stringify({ tu, row: rows[9003] }));
|
||||||
|
await ads.reconcileNas();
|
||||||
|
t('and not topped up again on the next pass', calls.topUp.slice(before).filter(x => x[0] === 9003).length === 1);
|
||||||
|
// PassiveDrip
|
||||||
|
let a = await ads.applyExternalVisits(9101, Math.floor(7 / 4) - Math.floor(0 / 4), 'PassiveDrip', 7);
|
||||||
|
let v = C(9101);
|
||||||
|
t('PD: 7 partner visits use up 1 pack visit', a.applied === 1 && v.imps === 11, JSON.stringify(a) + ' imps ' + v.imps);
|
||||||
|
t('PD: all 7 counted as partner visits', v.synImps === 7, String(v.synImps));
|
||||||
|
a = await ads.applyExternalVisits(9101, Math.floor(8 / 4) - Math.floor(7 / 4), 'PassiveDrip', 1);
|
||||||
|
v = C(9101);
|
||||||
|
t('PD: the 8th completes the second pack visit (fraction carried)', v.imps === 12 && v.synImps === 8, JSON.stringify({ imps: v.imps, syn: v.synImps }));
|
||||||
|
const pd = require('../pdsync.js'); pd.init({ dataDir: DATA, ads });
|
||||||
|
const L = (await pd.listing()).find(c => c.id === 9101);
|
||||||
|
t('pdsync offers PD the visits left x 4 (88 x 4 = 352)', L && L.visitsLeft === 352, JSON.stringify(L));
|
||||||
|
console.log('PASS ' + ok.length);
|
||||||
|
for (const b of bad) console.log('FAIL ' + b);
|
||||||
|
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
process.exit(bad.length ? 1 : 0);
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// NAS phantom delivery on resume / top-up (found 2026-10-27). stopNas zeroes `remaining` after recording the true served
|
||||||
|
// count. Resuming (or topping up) used a plain topUp, so assigned - remaining then read the zeroed remainder as served
|
||||||
|
// and the next reconcileNas CHARGED it. Fix: a stopped ad restarts from the true count (nas.restart).
|
||||||
|
// JSON store, NAS layer stubbed, throwaway data dir. node qa/nas-restart.mjs
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
delete process.env.DATABASE_URL;
|
||||||
|
const ok = [], bad = [];
|
||||||
|
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-restart-'));
|
||||||
|
const nas = require('../nas.js');
|
||||||
|
const rows = {}; const calls = { restart: 0, topUp: 0 };
|
||||||
|
nas.enabled = () => true;
|
||||||
|
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
|
||||||
|
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
|
||||||
|
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; return { ok: true, served }; };
|
||||||
|
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp++; return { ok: true }; };
|
||||||
|
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; calls.restart++; return { ok: true }; };
|
||||||
|
const ads = require('../ads.js');
|
||||||
|
const OWNER = 'restart@qa.test', FILE = path.join(DATA, 'campaigns.json');
|
||||||
|
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
|
||||||
|
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
|
||||||
|
fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: [banner(9001)], burnsPending: [] }));
|
||||||
|
ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } });
|
||||||
|
ads.setRates({ synRateDivisor: 1 }); // the restart logic at the on-site rate (qa/nas-ratio.mjs covers the network rate)
|
||||||
|
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
|
||||||
|
const used = c => (c.spent || 0) + (c.accrued || 0);
|
||||||
|
await ads.addEarned(OWNER, 10000);
|
||||||
|
rows[9001] = { assigned: 5000, remaining: 5000 };
|
||||||
|
rows[9001].remaining -= 1000; await ads.reconcileNas();
|
||||||
|
t('1,000 real NAS views charge 200 credits', used(C(9001)) === 200, String(used(C(9001))));
|
||||||
|
await ads.setStatus(OWNER, 9001, 'paused');
|
||||||
|
t('pause records the true 1,000 served', C(9001).nasServed === 1000, String(C(9001).nasServed));
|
||||||
|
const r0 = calls.restart; await ads.setStatus(OWNER, 9001, 'active');
|
||||||
|
t('resume restarts the stopped ad (not a plain top-up)', calls.restart === r0 + 1, String(calls.restart - r0));
|
||||||
|
t('resume books the budget left (800 credits x 5 = 4,000)', rows[9001].remaining === 4000 && rows[9001].assigned === 5000, JSON.stringify(rows[9001]));
|
||||||
|
await ads.reconcileNas();
|
||||||
|
t('no phantom charge after the resume', used(C(9001)) === 200, String(used(C(9001))));
|
||||||
|
rows[9001].remaining -= 500; await ads.reconcileNas();
|
||||||
|
t('real views after the resume still charge (500 views = 100)', used(C(9001)) === 300, String(used(C(9001))));
|
||||||
|
// a running ad that is topped up keeps a plain top-up
|
||||||
|
const tu = calls.topUp; await ads.topUpCampaign(OWNER, 0, 9001, 100);
|
||||||
|
t('top-up of a running ad is a plain top-up (+500)', calls.topUp === tu + 1 && rows[9001].remaining === 4000, JSON.stringify(rows[9001]));
|
||||||
|
// a stopped ad that is topped up restarts from the true count
|
||||||
|
await ads.setStatus(OWNER, 9001, 'paused'); const before = used(C(9001));
|
||||||
|
const r1 = calls.restart; await ads.topUpCampaign(OWNER, 0, 9001, 100); await ads.reconcileNas();
|
||||||
|
t('top-up of a stopped ad restarts it', calls.restart === r1 + 1, String(calls.restart - r1));
|
||||||
|
t('and charges nothing that was not served', used(C(9001)) === before, used(C(9001)) + ' vs ' + before);
|
||||||
|
console.log('PASS ' + ok.length);
|
||||||
|
for (const b of bad) console.log('FAIL ' + b);
|
||||||
|
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
process.exit(bad.length ? 1 : 0);
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
// Level-4 override payer tests (2026-10-23). Throwaway DATA_DIR in the OS temp folder, a FAKE chain, a FAKE signer and a
|
||||||
|
// FAKE database: nothing here touches Polygon, the production volume or a real member. Run: node qa/override.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs'), os = require('os'), path = require('path'), assert = require('assert');
|
||||||
|
const OV = require(path.join(__dirname, '..', 'override.js'));
|
||||||
|
const { create, weekOf, weekBounds, payableAt, polStr, toWei } = OV;
|
||||||
|
const E = 10n ** 18n;
|
||||||
|
let pass = 0, fail = 0;
|
||||||
|
async function test(name, fn) { try { await fn(); pass++; console.log(' ok ' + name); } catch (e) { fail++; console.log(' FAIL ' + name + '\n ' + (e && e.stack || e).toString().split('\n').slice(0, 3).join('\n ')); } }
|
||||||
|
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'ovtest-'));
|
||||||
|
const tickAsync = () => new Promise(r => setImmediate(r));
|
||||||
|
|
||||||
|
// ---- fakes ----
|
||||||
|
// tree: spec { id: [sponsorId, buyerCount] }
|
||||||
|
function fakeChain(tree, purchases, extraEvents) {
|
||||||
|
const events = purchases.map((p, i) => Object.assign({ type: 'Purchase', tx: '0xbuy' + i, li: 0, block: 1000 + i }, p)).concat(extraEvents || []);
|
||||||
|
return {
|
||||||
|
events,
|
||||||
|
member: async id => { await tickAsync(); const t = tree[id]; if (!t) return { sponsorId: 0, buyerCount: 0 }; return { sponsorId: t[0], buyerCount: t[1] }; },
|
||||||
|
recentEvents: () => events,
|
||||||
|
getConfig: () => ({ explorer: 'https://polygonscan.example', contract: '0xcontract', chainId: 137 }),
|
||||||
|
suggestedFees: async () => ({ maxPriorityFeePerGas: '0x' + (30n * 10n ** 9n).toString(16), maxFeePerGas: '0x' + (100n * 10n ** 9n).toString(16) })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function fakePayer(balanceWei, opts) {
|
||||||
|
const o = opts || {}; let n = 0;
|
||||||
|
const p = { address: '0x00000000000000000000000000000000000000aa', bal: BigInt(balanceWei), sends: [], opts: o,
|
||||||
|
balance: async () => { await tickAsync(); return p.bal; },
|
||||||
|
fees: async () => ({ maxFeePerGas: 100n * 10n ** 9n, maxPriorityFeePerGas: 30n * 10n ** 9n }),
|
||||||
|
preflight: async id => { await tickAsync(); if ((o.reject || []).includes(id)) throw Object.assign(new Error('execution reverted'), { reason: 'Send failed' }); },
|
||||||
|
send: async (id, wei) => {
|
||||||
|
await tickAsync(); await tickAsync();
|
||||||
|
if ((o.throwOn || []).includes(id)) throw new Error('server response 502');
|
||||||
|
p.sends.push({ id, wei: BigInt(wei) }); p.bal -= BigInt(wei); const hash = '0x' + (++n).toString(16).padStart(64, '0');
|
||||||
|
return { hash, wait: async () => { await tickAsync(); return { status: 1 }; } };
|
||||||
|
} };
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
function fakeDb(opts) {
|
||||||
|
const set = new Set(); const o = opts || {};
|
||||||
|
return { set, enabled: () => true, q: async (sql, params) => {
|
||||||
|
await tickAsync();
|
||||||
|
if (o.broken) throw new Error('connection lost');
|
||||||
|
if (/^INSERT IGNORE INTO event_marks/.test(sql)) { if (set.has(params[0])) return { affectedRows: 0 }; set.add(params[0]); return { affectedRows: 1 }; }
|
||||||
|
throw new Error('unexpected sql ' + sql);
|
||||||
|
} };
|
||||||
|
}
|
||||||
|
function instance(o) {
|
||||||
|
const ov = create(); const sent = [];
|
||||||
|
ov.init({ dataDir: o.dir, chain: o.chain, db: o.db || null, payer: o.payer, now: () => o.clock.t, siteConfig: () => o.site, notify: async t => { (o.tg || sent).push(t); return true; } });
|
||||||
|
return ov;
|
||||||
|
}
|
||||||
|
|
||||||
|
// a world: buyers under a qualified #10 (6 buyers) four levels up; #20 unqualified (2 buyers) is skipped once
|
||||||
|
const WK1 = '2026-10-26', WK2 = '2026-11-02';
|
||||||
|
const goLive = weekBounds(WK1).from;
|
||||||
|
const TREE = { 1: [0, 99], 10: [1, 6], 20: [10, 2], 30: [20, 0], 40: [30, 0], 50: [40, 0], 60: [50, 0],
|
||||||
|
// a short line under the company: 70 -> 71 -> 1
|
||||||
|
71: [1, 1], 70: [71, 0],
|
||||||
|
// #11 (qualified, 5 buyers) is the 4th upline of #81
|
||||||
|
11: [1, 5], 12: [11, 0], 13: [12, 0], 14: [13, 0], 81: [14, 0] };
|
||||||
|
const at = (wk, h) => weekBounds(wk).from + h * 3600000;
|
||||||
|
const buy = (buyerId, cents, pol, ts) => ({ buyerId, priceCents: cents, paidWei: (toWei(String(pol))).toString(), ts });
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
console.log('override.test: week math');
|
||||||
|
await test('weekOf: Sunday 11:30 PM CT belongs to the week before, Monday 12:30 AM CT to the new week', () => {
|
||||||
|
assert.strictEqual(weekOf(Date.parse('2026-10-26T04:30:00Z')), '2026-10-19'); // Sun 23:30 CDT
|
||||||
|
assert.strictEqual(weekOf(Date.parse('2026-10-26T05:30:00Z')), '2026-10-26'); // Mon 00:30 CDT
|
||||||
|
});
|
||||||
|
await test('week across the November DST change: Mon 00:00 CDT to Mon 00:00 CST (169 hours)', () => {
|
||||||
|
const b = weekBounds('2026-10-26');
|
||||||
|
assert.strictEqual(new Date(b.from).toISOString(), '2026-10-26T05:00:00.000Z');
|
||||||
|
assert.strictEqual(new Date(b.to).toISOString(), '2026-11-02T06:00:00.000Z');
|
||||||
|
assert.strictEqual((b.to - b.from) / 3600000, 169);
|
||||||
|
assert.strictEqual(weekOf(Date.parse('2026-11-02T05:30:00Z')), '2026-10-26'); // Sun 23:30 CST
|
||||||
|
});
|
||||||
|
await test('week across the March DST change: 167 hours', () => { const b = weekBounds('2027-03-08'); assert.strictEqual((b.to - b.from) / 3600000, 167); });
|
||||||
|
await test('payable from 9 AM Central the Monday after', () => { assert.strictEqual(new Date(payableAt('2026-10-19')).toISOString(), '2026-10-26T14:00:00.000Z'); assert.strictEqual(new Date(payableAt('2026-10-26')).toISOString(), '2026-11-02T15:00:00.000Z'); });
|
||||||
|
await test('polStr / toWei round trip', () => { assert.strictEqual(polStr(toWei('12.3456')), '12.3456'); assert.strictEqual(toWei('0.01'), 10n ** 16n); });
|
||||||
|
|
||||||
|
console.log('override.test: who gets it');
|
||||||
|
const clock = { t: payableAt(WK1) + 3600000 };
|
||||||
|
await test('hunt: 4th upline #20 (2 buyers) is skipped, #10 (6 buyers) gets it with 1 hop', async () => {
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
|
||||||
|
const r = await ov.recipientFor(60); // 60 -> 50, 40, 30, [20 skipped], 10
|
||||||
|
assert.strictEqual(r.recipientId, 10); assert.strictEqual(r.hops, 1); assert.deepStrictEqual(r.skipped, [{ id: 20, buyers: 2 }]);
|
||||||
|
});
|
||||||
|
await test('exactly 5 buyers qualifies (#11 for #81)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(81)).recipientId, 11); });
|
||||||
|
await test('house: a hunt that reaches #1 leaves it with the company', async () => {
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) });
|
||||||
|
const r = await ov.recipientFor(40); // 40 -> 30, 20, 10, 1 : 4th up is #1
|
||||||
|
assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /company account #1/);
|
||||||
|
});
|
||||||
|
await test('overrideHouseIds can add company positions (#10 as house)', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: { overrideHouseIds: '1,10' }, payer: fakePayer(0) }); assert.strictEqual((await ov.recipientFor(60)).recipientId, 0); });
|
||||||
|
await test('short line: company keeps it', async () => { const ov = instance({ dir: tmp(), chain: fakeChain(TREE, []), clock, site: {}, payer: fakePayer(0) }); assert.match((await ov.recipientFor(70)).reason, /shorter than 4/); });
|
||||||
|
await test('hunt cap: 30 unqualified uplines above the 4th, nobody within 25 hops', async () => {
|
||||||
|
const t = { 1: [0, 99] }; for (let i = 200; i < 240; i++) t[i] = [i + 1, 0]; t[240] = [1, 0]; t[199] = [200, 0];
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(t, []), clock, site: {}, payer: fakePayer(0) });
|
||||||
|
const r = await ov.recipientFor(199); assert.strictEqual(r.recipientId, 0); assert.match(r.reason, /within 25 hops/); assert.strictEqual(r.skipped.length, 25);
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('override.test: the payer');
|
||||||
|
const PUR = [buy(60, 2000, 200, at(WK1, 30)), buy(60, 5000, 500, at(WK1, 50)), buy(81, 2000, 200, at(WK1, 60)), buy(40, 2000, 200, at(WK1, 70)),
|
||||||
|
buy(60, 2000, 200, goLive - 3600000) /* before go-live: never paid */, buy(81, 500, 0.2, at(WK2, 10)) /* next week */];
|
||||||
|
const LIVE = { overrideMode: 'live', overrideGoLive: goLive };
|
||||||
|
|
||||||
|
await test('default mode is dry run: nothing planned, nothing sent', async () => {
|
||||||
|
const dir = tmp(), payer = fakePayer(1000n * E); const ov = instance({ dir, chain: fakeChain(TREE, PUR), clock, site: { overrideGoLive: goLive }, payer });
|
||||||
|
const r = await ov.payDue(); assert.strictEqual(r.ready, false); assert.match(r.why.join(), /dryrun/); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
assert.ok(!fs.existsSync(path.join(dir, 'override', 'weeks')));
|
||||||
|
});
|
||||||
|
await test('live without overrideGoLive is not ready', async () => { const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock, site: { overrideMode: 'live' }, payer }); assert.strictEqual(ov.liveState().ready, false); await ov.payDue(); assert.strictEqual(payer.sends.length, 0); });
|
||||||
|
await test('live without a payer key is not ready (real key path)', async () => { delete process.env.OVERRIDE_PAYER_KEY; const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => LIVE }); assert.match(ov.liveState().why.join(), /no payer key/); });
|
||||||
|
await test('a week is not planned before it closes, nor paid before Monday 9 AM CT', async () => {
|
||||||
|
const c2 = { t: weekBounds(WK1).to + 3600000 }; const payer = fakePayer(1000n * E); // Monday 1 AM
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), clock: c2, site: LIVE, payer });
|
||||||
|
assert.deepStrictEqual(ov.dueWeeks(), []); await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
assert.deepStrictEqual(ov.dueWeeks(true), [WK1]); // the admin's "pay this week now" may settle a closed week early
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('two payers at once (deploy overlap, shared DB + volume): each recipient paid exactly once', async () => {
|
||||||
|
const dir = tmp(), db = fakeDb(), payer = fakePayer(1000n * E), tg = [], chain = fakeChain(TREE, PUR);
|
||||||
|
const A = instance({ dir, chain, db, payer, clock, site: LIVE, tg }), B = instance({ dir, chain, db, payer, clock, site: LIVE, tg });
|
||||||
|
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
|
||||||
|
const by = {}; for (const s of payer.sends) by[s.id] = (by[s.id] || 0n) + s.wei;
|
||||||
|
assert.strictEqual(payer.sends.length, 2, 'two recipients, two sends: ' + JSON.stringify(payer.sends.map(s => s.id)));
|
||||||
|
assert.strictEqual(by[10], toWei('21')); // 3% of 200 + 500 POL (two buys by #60)
|
||||||
|
assert.strictEqual(by[11], toWei('6')); // 3% of 200 POL
|
||||||
|
const st = A.weekStatus(WK1); assert.strictEqual(st.state, 'paid'); assert.ok(st.rows.every(r => r.state === 'paid' && r.txHash));
|
||||||
|
assert.strictEqual(tg.filter(t => /PAID/.test(t)).length, 1, 'one paid summary'); assert.match(tg.find(t => /PAID/.test(t)), /polygonscan\.example\/tx\//);
|
||||||
|
await Promise.all([A.payDue(), B.payDue()]); assert.strictEqual(payer.sends.length, 2, 'a second pass sends nothing');
|
||||||
|
});
|
||||||
|
await test('two payers at once with NO database (LinkSpin JSON mode): file claims alone hold', async () => {
|
||||||
|
const dir = tmp(), payer = fakePayer(1000n * E), chain = fakeChain(TREE, PUR);
|
||||||
|
const A = instance({ dir, chain, payer, clock, site: LIVE }), B = instance({ dir, chain, payer, clock, site: LIVE });
|
||||||
|
await Promise.all([A.payDue(), B.payDue(), A.payDue(), B.payDue()]);
|
||||||
|
assert.strictEqual(payer.sends.length, 2);
|
||||||
|
});
|
||||||
|
await test('a database that errors fails closed: nothing is planned or sent', async () => {
|
||||||
|
const payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), db: fakeDb({ broken: true }), payer, clock, site: LIVE });
|
||||||
|
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'not planned');
|
||||||
|
});
|
||||||
|
await test('purchases before overrideGoLive are never paid (no back-pay)', async () => {
|
||||||
|
const payer = fakePayer(1000n * E); const late = { overrideMode: 'live', overrideGoLive: at(WK1, 55) }; // after #60's buys, before #81's
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: late });
|
||||||
|
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [11]);
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('dust: under 0.01 POL is carried, then rolled into the next week and paid', async () => {
|
||||||
|
const dir = tmp(), payer = fakePayer(1000n * E);
|
||||||
|
const P = [buy(81, 500, 0.2, at(WK1, 30)), buy(81, 2000, 200, at(WK2, 30))]; // week 1: 3% of 0.2 = 0.006 POL
|
||||||
|
const ck = { t: clock.t }; const ov = instance({ dir, chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
|
||||||
|
await ov.payDue(); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
const s1 = ov.weekStatus(WK1); assert.strictEqual(s1.state, 'paid'); assert.strictEqual(s1.rows[0].state, 'carried');
|
||||||
|
ck.t = payableAt(WK2) + 60000; await ov.payDue();
|
||||||
|
assert.strictEqual(payer.sends.length, 1); assert.strictEqual(payer.sends[0].wei, toWei('6.006'));
|
||||||
|
assert.strictEqual(ov.weekStatus(WK1).rows[0].state, 'rolled'); assert.deepStrictEqual(ov.weekStatus(WK2).rows[0].carriedFrom, [WK1]);
|
||||||
|
});
|
||||||
|
await test('a dust amount that stays under the minimum keeps carrying', async () => {
|
||||||
|
const payer = fakePayer(1000n * E), P = [buy(81, 500, 0.1, at(WK1, 30)), buy(81, 500, 0.1, at(WK2, 30))];
|
||||||
|
const ck = { t: payableAt(WK2) + 60000 }; const ov = instance({ dir: tmp(), chain: fakeChain(TREE, P), payer, clock: ck, site: LIVE });
|
||||||
|
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK2).rows[0].state, 'carried'); assert.strictEqual(ov.weekStatus(WK2).rows[0].amountWei, toWei('0.006').toString());
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('cap: a week over overridePayCapPol is held whole, nothing sent, one alert', async () => {
|
||||||
|
const tg = [], payer = fakePayer(1000n * E); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: Object.assign({ overridePayCapPol: 20 }, LIVE), tg });
|
||||||
|
await ov.payDue(); await ov.payDue();
|
||||||
|
assert.strictEqual(payer.sends.length, 0); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); assert.match(ov.weekStatus(WK1).heldWhy, /cap/);
|
||||||
|
assert.strictEqual(tg.filter(t => /HELD/.test(t)).length, 1);
|
||||||
|
});
|
||||||
|
await test('a held week stops the weeks after it', async () => {
|
||||||
|
const payer = fakePayer(1000n * E), ck = { t: payableAt(WK2) + 60000 };
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: Object.assign({ overridePayCapPol: 20 }, LIVE) });
|
||||||
|
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK2).state, 'not planned'); assert.strictEqual(payer.sends.length, 0);
|
||||||
|
});
|
||||||
|
await test('insufficient balance: held with a clear message, then pays once funded', async () => {
|
||||||
|
const tg = [], payer = fakePayer(26n * E); // needs 27 POL + gas
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE, tg });
|
||||||
|
await ov.payDue(); assert.strictEqual(payer.sends.length, 0); assert.match(ov.weekStatus(WK1).heldWhy, /holds 26\.0000 POL, needs 27\.0300/);
|
||||||
|
assert.match(tg.join(), /Fund it/);
|
||||||
|
payer.bal = 27n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 0, 'still short of the gas reserve');
|
||||||
|
payer.bal = 28n * E; await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
|
||||||
|
});
|
||||||
|
|
||||||
|
await test('a wallet that would refuse POL: pre-flight catches it, nothing sent, carried', async () => {
|
||||||
|
const payer = fakePayer(1000n * E, { reject: [11] }); const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock, site: LIVE });
|
||||||
|
await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id), [10]);
|
||||||
|
const r11 = ov.weekStatus(WK1).rows.find(r => r.memberId === 11); assert.strictEqual(r11.state, 'carried'); assert.match(r11.note, /Send failed/);
|
||||||
|
assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
|
||||||
|
});
|
||||||
|
await test('a send whose answer is lost becomes review, is never re-sent, and blocks later weeks until resolved', async () => {
|
||||||
|
const tg = [], payer = fakePayer(1000n * E, { throwOn: [11] }), ck = { t: payableAt(WK2) + 60000 };
|
||||||
|
const ov = instance({ dir: tmp(), chain: fakeChain(TREE, PUR), payer, clock: ck, site: LIVE, tg });
|
||||||
|
await ov.payDue(); await ov.payDue(); await ov.payDue();
|
||||||
|
assert.deepStrictEqual(payer.sends.map(s => s.id), [10], 'only #10 went out, #11 never retried');
|
||||||
|
assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
|
||||||
|
assert.strictEqual(ov.weekStatus(WK2).state, 'not planned');
|
||||||
|
assert.strictEqual(tg.filter(t => /needs review/.test(t)).length, 1);
|
||||||
|
const bad = await ov.resolve(WK1, 11, 'paid', '0xnot-a-real-tx'); assert.ok(bad.error, 'an unverifiable tx is refused');
|
||||||
|
payer.opts.throwOn = []; // the node is healthy again
|
||||||
|
await ov.resolve(WK1, 11, 'carry'); assert.strictEqual(ov.weekStatus(WK1).state, 'paid');
|
||||||
|
await ov.payDue(); assert.strictEqual(payer.sends.length, 2); assert.strictEqual(payer.sends[1].id, 11); // week 2 pays #11: carried 6 + 0.006
|
||||||
|
assert.strictEqual(payer.sends[1].wei, toWei('6.006'));
|
||||||
|
});
|
||||||
|
await test('a review row is settled from the chain index when the AwardPaid shows up', async () => {
|
||||||
|
const payer = fakePayer(1000n * E, { throwOn: [11] }), chain = fakeChain(TREE, PUR);
|
||||||
|
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
|
||||||
|
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).rows.find(r => r.memberId === 11).state, 'review');
|
||||||
|
chain.events.push({ type: 'AwardPaid', tx: '0xlanded', from: payer.address, toId: 11, amountWei: toWei('6').toString(), ts: clock.t });
|
||||||
|
await ov.payDue(); const r = ov.weekStatus(WK1).rows.find(x => x.memberId === 11); assert.strictEqual(r.state, 'paid'); assert.strictEqual(r.txHash, '0xlanded');
|
||||||
|
assert.strictEqual(payer.sends.length, 1); assert.ok(ov.txInfo('0xLANDED'));
|
||||||
|
});
|
||||||
|
await test('a plan is frozen: a buyer count that changes after planning does not change the amounts', async () => {
|
||||||
|
const tree = JSON.parse(JSON.stringify(TREE)); const payer = fakePayer(26n * E), chain = fakeChain(tree, PUR);
|
||||||
|
const ov = instance({ dir: tmp(), chain, payer, clock, site: LIVE });
|
||||||
|
await ov.payDue(); assert.strictEqual(ov.weekStatus(WK1).state, 'held'); // planned, short of funds
|
||||||
|
tree[20][1] = 9; // #20 qualifies later
|
||||||
|
payer.bal = 100n * E; await ov.payDue(); assert.deepStrictEqual(payer.sends.map(s => s.id).sort(), [10, 11]);
|
||||||
|
});
|
||||||
|
await test('dry run Monday report: once per week across two copies, says no money moved', async () => {
|
||||||
|
const dir = tmp(), tg = [], chain = fakeChain(TREE, PUR), mon = { t: payableAt(WK1) + 600000 };
|
||||||
|
const A = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) }), B = instance({ dir, chain, clock: mon, site: {}, tg, payer: fakePayer(0) });
|
||||||
|
await Promise.all([A.tick(), B.tick(), A.tick()]);
|
||||||
|
assert.strictEqual(tg.length, 1); assert.match(tg[0], /DRY RUN/); assert.match(tg[0], /No money moved/); assert.match(tg[0], /\$0\.21|\$2\.10/);
|
||||||
|
});
|
||||||
|
await test('payer status never exposes a key', async () => {
|
||||||
|
process.env.OVERRIDE_PAYER_KEY = '0x' + '11'.repeat(32);
|
||||||
|
const ov = create(); ov.init({ dataDir: tmp(), chain: fakeChain(TREE, PUR), siteConfig: () => ({}) });
|
||||||
|
const s = JSON.stringify(ov.liveState()) + JSON.stringify(Object.assign({}, await ov.payerStatus().catch(e => ({ e: e.message }))));
|
||||||
|
assert.ok(!s.includes('1111111111'), 'no key material'); delete process.env.OVERRIDE_PAYER_KEY;
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('override.test: ' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// Refill notice copy + deploy-overlap claim (refill.js) on throwaway data. Run: node qa/refill.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const assert = require('assert');
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } }
|
||||||
|
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
function world(dir, cfg) {
|
||||||
|
const W = { inbox: [], mail: [], cfg: cfg || {} };
|
||||||
|
W.campaigns = [
|
||||||
|
{ id: 1, owner: 'a@x.test', type: 'banner', name: 'Alpha', budget: 1000, spent: 1000, accrued: 0, imps: 5000, clicks: 40, status: 'out', created: now - 30 * 864e5 },
|
||||||
|
{ id: 2, owner: 'b@x.test', type: 'text', name: 'Bravo', budget: 1000, spent: 850, accrued: 0, imps: 8500, clicks: 9, status: 'active', created: now - 30 * 864e5 },
|
||||||
|
];
|
||||||
|
W.deps = {
|
||||||
|
dataDir: dir, siteConfig: () => W.cfg,
|
||||||
|
ads: { adminList: async () => W.campaigns.map(c => Object.assign({}, c)), rates: () => ({ videoTiers: [] }) },
|
||||||
|
accounts: { byEmail: async e => ({ email: e, memberId: 5 }), positions: async () => [] },
|
||||||
|
chain: { recentEvents: () => [] },
|
||||||
|
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
|
||||||
|
drip: { isUnsubscribed: async () => false },
|
||||||
|
creditsFor: async () => 300,
|
||||||
|
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
|
||||||
|
};
|
||||||
|
return W;
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('bonus block names Five Dollar Friday AND Wired Wednesday ($20 floor, +25%)', async () => {
|
||||||
|
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')));
|
||||||
|
const r = fresh('refill.js'); r.init(W.deps);
|
||||||
|
const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
|
||||||
|
assert.ok(/Five Dollar Friday: any package from \$5 up/.test(m.text), 'friday text');
|
||||||
|
assert.ok(/Wired Wednesday: any package from \$20 up, bought on a Wednesday \(Central time\), earns an extra 25%/.test(m.text), 'wednesday text');
|
||||||
|
assert.ok(/<b>Wired Wednesday:<\/b>/.test(m.html), 'wednesday html');
|
||||||
|
assert.ok(!/—/.test(m.text + m.html), 'no em dash');
|
||||||
|
});
|
||||||
|
await t('Wednesday follows its settings (off, other floor and pct)', async () => {
|
||||||
|
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')), { wednesdayPromo: '0' });
|
||||||
|
const r = fresh('refill.js'); r.init(W.deps);
|
||||||
|
let m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
|
||||||
|
assert.ok(!/Wired Wednesday/.test(m.text));
|
||||||
|
W.cfg = { wednesdayBonusPct: '30', wednesdayMinCents: '5000', fridayPromo: '0' };
|
||||||
|
m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
|
||||||
|
assert.ok(/from \$50 up.*extra 30%/.test(m.text) && !/Five Dollar Friday/.test(m.text));
|
||||||
|
});
|
||||||
|
await t('streak hook line (stage 2) lands in text and html; absent hook changes nothing', async () => {
|
||||||
|
const W = world(fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-')));
|
||||||
|
const r = fresh('refill.js'); r.init(Object.assign({}, W.deps, { streakLine: async e => e === 'a@x.test' ? { text: 'Refuel streak: 2 months.', html: '<b>Refuel streak:</b> 2 months.' } : null }));
|
||||||
|
const m = await r.compose('a@x.test', [W.campaigns[0]], 'out', 300);
|
||||||
|
assert.ok(/Refuel streak: 2 months\./.test(m.text) && /<b>Refuel streak:<\/b>/.test(m.html));
|
||||||
|
const m2 = await r.compose('b@x.test', [W.campaigns[1]], 'low', 300);
|
||||||
|
assert.ok(!/Refuel streak/.test(m2.text));
|
||||||
|
});
|
||||||
|
await t('two app copies (shared claims): each owner gets one message', async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refill-'));
|
||||||
|
const W = world(dir);
|
||||||
|
const marks = fresh('marks.js'); marks.init({}); // no DB: one process-wide set stands in for event_marks
|
||||||
|
const A = fresh('refill.js'); A.init(Object.assign({}, W.deps, { marks }));
|
||||||
|
const B = fresh('refill.js'); B.init(Object.assign({}, W.deps, { marks }));
|
||||||
|
await Promise.all([A.tick(), B.tick()]);
|
||||||
|
const per = {}; for (const x of W.inbox) per[x.to] = (per[x.to] || 0) + 1;
|
||||||
|
assert.deepStrictEqual(per, { 'a@x.test': 1, 'b@x.test': 1 }, JSON.stringify(per));
|
||||||
|
assert.strictEqual(W.mail.length, 2);
|
||||||
|
await Promise.all([A.tick(), B.tick()]);
|
||||||
|
assert.strictEqual(W.inbox.length, 2, 'nothing repeats on later passes');
|
||||||
|
});
|
||||||
|
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// Engine Room (engine.js, the same file ships in LinkSpin): build() rules, facts() on stubbed sites, the member goal.
|
||||||
|
// Run: node qa/refuel-engine.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const E = require(path.join(ROOT, 'engine.js'));
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 2).join(' | ')); } }
|
||||||
|
const NOW = Date.UTC(2026, 10, 15, 18); const DAY = 864e5;
|
||||||
|
const rf = o => Object.assign({ on: true, started: true, active: true, streak: 2, best: 2, refuelDayLabel: 'Wed, Dec 2', graceLabel: 'Mon, Dec 7', daysToRefuel: 17, windowOpen: false,
|
||||||
|
cycle: { month: 2, both: true, iap: { refueled: true, credits: 2000, pct: 20, bonus: 400 }, linkspin: { refueled: true, credits: 2500, pct: 20, bonus: 500 } },
|
||||||
|
next: { month: 2, secondEngine: 20 }, pitStop: { pct: 10, iap: true, linkspin: true }, freeMiss: { available: true }, minUsd: { iap: 20, linkspin: 25 } }, o || {});
|
||||||
|
const camp = o => Object.assign({ id: 1, name: 'A', type: 'banner', status: 'active', budget: 1000, delivered: 300, clicks: 30, created: NOW - 10 * DAY }, o);
|
||||||
|
const iap = o => Object.assign({ site: 'iap', ok: true, credits: { available: 1000, inCampaigns: 700 }, campaigns: [camp({})], clicksWeek: 40, loginFree: 0 }, o || {});
|
||||||
|
const green = { state: 'green', note: 'ok' };
|
||||||
|
const ls = o => Object.assign({ site: 'linkspin', ok: true, credits: { available: 2000, inCampaigns: 0 }, campaigns: [], clicksWeek: 10, loginFree: 0, goalsCount: 1, goalsMonth: 6, conv30: 9,
|
||||||
|
parts: { bannerSpin: green, spinLink: green, page: green, testing: green } }, o || {});
|
||||||
|
const B = o => E.build(Object.assign({ now: NOW, refuel: rf(), iap: iap(), ls: ls(), goal: 20 }, o || {}));
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('switch off: nothing', async () => { assert.deepStrictEqual(E.build({ refuel: { on: false } }), { on: false }); });
|
||||||
|
await t('locked until the first counted refuel: greyed, one move "Refuel to start your engine"', async () => {
|
||||||
|
const d = B({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) });
|
||||||
|
assert.ok(d.locked); assert.strictEqual(d.next.key, 'start'); assert.strictEqual(d.next.label, 'Refuel to start your engine');
|
||||||
|
});
|
||||||
|
await t('fuel dial: credits free + in campaigns on both sites vs this cycle\'s refuel (with bonus), days left at the burn', async () => {
|
||||||
|
const d = B();
|
||||||
|
assert.strictEqual(d.fuel.left, 3700); assert.strictEqual(d.fuel.refuelCredits, 5400); assert.strictEqual(d.fuel.pct, 69);
|
||||||
|
assert.strictEqual(d.fuel.burnPerDay, 30); assert.strictEqual(d.fuel.daysLeft, 123);
|
||||||
|
});
|
||||||
|
await t('clicks dial: this week on both sites, and per 1,000 credits on recent campaigns', async () => {
|
||||||
|
const d = B({ iap: iap({ clicksPrevWeek: 30 }), ls: ls({ clicksPrevWeek: 20, campaigns: [camp({ id: 9, delivered: 700, clicks: 5 })] }) });
|
||||||
|
assert.strictEqual(d.clicks.week, 50); assert.strictEqual(d.clicks.per1000, 35); assert.strictEqual(d.clicks.prevWeek, 50); assert.strictEqual(d.clicks.pct, 50, 'same as last week = half way');
|
||||||
|
});
|
||||||
|
await t('goals dial: conversions this month vs the member goal; LinkSpin down = unknown, never zero', async () => {
|
||||||
|
assert.deepStrictEqual([B().goals.month, B().goals.target, B().goals.pct], [6, 20, 30]);
|
||||||
|
const d = B({ ls: null }); assert.strictEqual(d.goals.month, null); assert.strictEqual(d.parts[5].note, 'LinkSpin did not answer'); assert.deepStrictEqual(d.sites, { iap: true, linkspin: false });
|
||||||
|
});
|
||||||
|
await t('warning lights: 80%, out, refuel day coming, login slot open', async () => {
|
||||||
|
const d = B({ refuel: rf({ daysToRefuel: 4 }), iap: iap({ loginFree: 2, campaigns: [camp({ delivered: 850 }), camp({ id: 2, status: 'out', delivered: 1000 })] }) });
|
||||||
|
assert.deepStrictEqual(d.warnings.map(w => [w.key, w.on]), [['low', true], ['out', true], ['refuel', true], ['login', true]]);
|
||||||
|
const q = B(); assert.ok(q.warnings.every(w => !w.on));
|
||||||
|
});
|
||||||
|
await t('six part lights: green / amber / grey with setup links', async () => {
|
||||||
|
const d = B({ ls: ls({ goalsCount: 1, conv30: 0, parts: { bannerSpin: { state: 'grey', note: 'not set up' }, spinLink: green, page: { state: 'amber', note: 'draft only' }, testing: green } }) });
|
||||||
|
assert.deepStrictEqual(d.parts.map(p => p.label), ['Fuel', 'Banner spin', 'Spin link', 'Page', 'Testing', 'Conversion tracking']);
|
||||||
|
assert.deepStrictEqual(d.parts.map(p => p.state), ['green', 'grey', 'green', 'amber', 'green', 'amber']);
|
||||||
|
assert.strictEqual(d.parts[5].note, 'no conversions tracked yet'); assert.ok(/linkspin\.app\/links/.test(d.parts[1].link));
|
||||||
|
assert.strictEqual(B({ iap: iap({ campaigns: [] }), ls: ls({ campaigns: [] }) }).parts[0].state, 'grey');
|
||||||
|
});
|
||||||
|
await t('next move, in order of what matters most', async () => {
|
||||||
|
assert.strictEqual(B({ refuel: rf({ windowOpen: true, next: { month: 3, single: 20, both: 30 } }) }).next.key, 'refuel');
|
||||||
|
assert.strictEqual(B({ iap: iap({ campaigns: [camp({ status: 'out', delivered: 1000 })] }) }).next.key, 'relaunch');
|
||||||
|
assert.strictEqual(B({ iap: iap({ credits: { available: 20, inCampaigns: 0 }, campaigns: [camp({ delivered: 900, created: NOW - 2 * DAY })] }), ls: ls({ credits: { available: 0, inCampaigns: 0 } }) }).next.key, 'pitstop');
|
||||||
|
assert.strictEqual(B({ iap: iap({ campaigns: [camp({ delivered: 850, created: NOW - 29 * DAY })] }) }).next.key, 'topup');
|
||||||
|
assert.strictEqual(B({ ls: ls({ goalsCount: 0 }) }).next.key, 'tracking');
|
||||||
|
assert.strictEqual(B({ ls: ls({ parts: { bannerSpin: { state: 'grey', note: '' }, spinLink: green, page: green, testing: green } }) }).next.key, 'bannerspin');
|
||||||
|
assert.strictEqual(B({ ls: ls({ parts: { bannerSpin: green, spinLink: green, page: green, testing: { state: 'amber', note: '' } } }) }).next.key, 'testing');
|
||||||
|
const cut = B({ iap: iap({ campaigns: [camp({ id: 1, name: 'Good', delivered: 400, clicks: 40 }), camp({ id: 2, name: 'Weak', delivered: 400, clicks: 4 })] }) });
|
||||||
|
assert.strictEqual(cut.next.key, 'cut'); assert.ok(/"Weak"/.test(cut.next.why));
|
||||||
|
assert.strictEqual(B().next.key, 'cruise');
|
||||||
|
for (const d of [B(), cut]) assert.ok(!/—/.test(JSON.stringify(d)));
|
||||||
|
});
|
||||||
|
await t('links follow the site the member is on (2026-10-25): own buy/campaigns/conversion screen, LinkSpin-only tools cross over', async () => {
|
||||||
|
const onIap = B({ ls: ls({ goalsCount: 0 }) }), onLs = B({ site: 'linkspin', ls: ls({ goalsCount: 0 }) });
|
||||||
|
assert.strictEqual(onIap.site, 'iap'); assert.strictEqual(onLs.site, 'linkspin');
|
||||||
|
assert.strictEqual(onIap.next.link, 'https://instantadpay.com/my#conversions'); assert.strictEqual(onIap.next.guide, '/conversion-tracking');
|
||||||
|
assert.strictEqual(onLs.next.link, 'https://linkspin.app/conversions');
|
||||||
|
assert.strictEqual(onIap.parts[5].key, 'conversions'); assert.strictEqual(onIap.parts[1].link, 'https://linkspin.app/links#b'); assert.strictEqual(onIap.parts[1].key, 'bannerspin');
|
||||||
|
const lock = o => B(Object.assign({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) }, o));
|
||||||
|
assert.strictEqual(lock().next.link, 'https://instantadpay.com/my#buy'); assert.strictEqual(lock({ site: 'linkspin' }).next.link, 'https://linkspin.app/credits#buy');
|
||||||
|
assert.ok(/\$25 or more here/.test(lock({ site: 'linkspin' }).next.why)); assert.ok(/\$20 or more here/.test(lock().next.why));
|
||||||
|
assert.strictEqual(B({ site: 'linkspin', iap: iap({ campaigns: [] }), ls: ls({ campaigns: [] }) }).parts[0].link, 'https://linkspin.app/ads');
|
||||||
|
});
|
||||||
|
await t('facts(): LinkSpin parts and the goals dial count from the Central-time 1st', async () => {
|
||||||
|
const own = 'o@x.test'; const ts = Date.UTC(2026, 10, 1, 4, 30); // 11:30 PM CT Oct 31 = Nov 1 in UTC
|
||||||
|
const conv = [{ owner: own, ts, self: false }, { owner: own, ts: Date.UTC(2026, 10, 3), self: false }, { owner: own, ts: Date.UTC(2026, 10, 4), self: true }];
|
||||||
|
const d = { site: 'linkspin', now: NOW,
|
||||||
|
adminMember: { view: async () => ({ credits: { available: 500, inCampaigns: 250 } }) },
|
||||||
|
ads: { listCampaigns: async () => [{ id: 1, name: 'x', type: 'banner', status: 'active', budget: 1000, spent: 500, clicks: 9, created: NOW - DAY }, { id: 2, house: true, status: 'active', spent: 1 }], loginSlots: async () => ({ free: 1 }) },
|
||||||
|
coach: { clicksSince: async (ids, since) => (assert.deepStrictEqual(ids, [1]), since === NOW - 7 * DAY ? 4 : since === NOW - 14 * DAY ? 10 : -1) },
|
||||||
|
convtrack: { goalsOf: () => [{ px: 'p' }], countSince: (o, since) => conv.filter(c => c.owner === o && c.ts >= since && !c.self).length },
|
||||||
|
bannerspin: { list: async () => [{ paused: false, imps30: 120, banners: [{ active: true, imps30: 80 }, { active: true, imps30: 40 }] }] },
|
||||||
|
rotator: { list: async () => [{ paused: false, hits7: 0, destinations: [{ active: true, hits7: 0 }] }] },
|
||||||
|
pages: { list: async () => [{ status: 'draft', views: 0 }] } };
|
||||||
|
const f = await E.facts(d, own);
|
||||||
|
assert.deepStrictEqual(f.credits, { available: 500, inCampaigns: 250 }); assert.strictEqual(f.campaigns.length, 1); assert.strictEqual(f.clicksWeek, 4); assert.strictEqual(f.clicksPrevWeek, 6); assert.strictEqual(f.loginFree, 1);
|
||||||
|
assert.strictEqual(f.goalsMonth, 1, 'Oct 31 11:30 PM CT is October'); assert.strictEqual(f.conv30, 2);
|
||||||
|
assert.deepStrictEqual([f.parts.bannerSpin.state, f.parts.spinLink.state, f.parts.page.state, f.parts.testing.state], ['green', 'amber', 'amber', 'green']);
|
||||||
|
});
|
||||||
|
await t('streak note: both sites refueled says so, one site asks for the OTHER by name, window open quotes the next rates', async () => {
|
||||||
|
assert.strictEqual(B().streak.note, 'Both engines fueled this cycle: +20% on each.');
|
||||||
|
assert.ok(!/Refuel the other|Refuel (LinkSpin|InstantAdPay) this cycle/.test(B().streak.note));
|
||||||
|
const oneIap = rf({ cycle: { month: 2, both: false, iap: { refueled: true, credits: 2000, pct: 15, bonus: 300 }, linkspin: { refueled: false } } });
|
||||||
|
assert.strictEqual(B({ refuel: oneIap }).streak.note, 'Refuel LinkSpin this cycle for +20% on both.');
|
||||||
|
const oneLs = rf({ cycle: { month: 2, both: false, iap: { refueled: false }, linkspin: { refueled: true, credits: 2500, pct: 15, bonus: 375 } } });
|
||||||
|
assert.strictEqual(B({ refuel: oneLs }).streak.note, 'Refuel InstantAdPay this cycle for +20% on both.');
|
||||||
|
assert.strictEqual(B({ refuel: rf({ windowOpen: true, next: { month: 3, single: 20, both: 30 } }) }).streak.note, 'Window open: next refuel +20% (+30% on each with both).');
|
||||||
|
assert.strictEqual(B({ refuel: rf({ started: false, active: false, cycle: null, streak: 0 }) }).streak.note, '');
|
||||||
|
});
|
||||||
|
await t('the member goal lives with the streak (InstantAdPay); switch off refuses', async () => {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-eng-')); const cfg = { refuelStreak: '1' };
|
||||||
|
const marks = require(path.join(ROOT, 'marks.js'));
|
||||||
|
const R = require(path.join(ROOT, 'refuel.js')); R.init({ dataDir: dir, db: require(path.join(ROOT, 'db.js')), marks, siteConfig: () => cfg, accounts: {}, ads: {}, message: async () => {} });
|
||||||
|
assert.deepStrictEqual(await R.setGoal('g@x.test', 25), { ok: true, goal: 25 });
|
||||||
|
assert.strictEqual((await R.view('g@x.test')).goal, 25);
|
||||||
|
cfg.refuelStreak = '0'; assert.ok((await R.setGoal('g@x.test', 5)).error);
|
||||||
|
});
|
||||||
|
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// Refuel Kit (kit.js) with the real refuel.js entitlement, throwaway data, placeholder art from public/banners, real ffmpeg.
|
||||||
|
// Run: node qa/refuel-kit.test.cjs (skips the render checks when ffmpeg or a font is missing)
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const assert = require('assert');
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 2).join(' | ')); } }
|
||||||
|
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
|
||||||
|
const ct = (day, hour) => { const [y, m, d] = day.split('-').map(Number); return Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + 6); };
|
||||||
|
let ffmpegOk = true; try { execSync('ffmpeg -version', { stdio: 'ignore' }); } catch (e) { ffmpegOk = false; }
|
||||||
|
function dims(buf) {
|
||||||
|
if (buf[0] === 0x89) return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
|
||||||
|
if (buf.slice(0, 3).toString() === 'GIF') return [buf.readUInt16LE(6), buf.readUInt16LE(8)];
|
||||||
|
for (let i = 2; i < buf.length - 9;) { if (buf[i] !== 0xff) { i++; continue; } const m = buf[i + 1]; const len = buf.readUInt16BE(i + 2); if (m >= 0xc0 && m <= 0xc3) return [buf.readUInt16BE(i + 7), buf.readUInt16BE(i + 5)]; i += 2 + len; }
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
function world(cfg) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-kit-'));
|
||||||
|
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}) };
|
||||||
|
const marks = fresh('marks.js'); marks.init({});
|
||||||
|
W.R = fresh('refuel.js');
|
||||||
|
W.R.init({ dataDir: dir, db: require(path.join(ROOT, 'db.js')), marks, siteConfig: () => W.cfg, accounts: { byMemberId: async () => null, byEmail: async e => ({ email: e }) },
|
||||||
|
ads: { addEarned: async () => {} }, message: async () => {}, featuredPerDay: () => 40 });
|
||||||
|
W.K = fresh('kit.js');
|
||||||
|
W.K.init({ dataDir: dir, program: 'iap', publicDir: path.join(ROOT, 'public'), siteUrl: 'https://instantadpay.com',
|
||||||
|
entitled: async email => { const v = await W.R.view(email, W.now); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel, today: v.today } : { on: false }; },
|
||||||
|
linkFor: async email => email === 'nouser@x.test' ? null : { username: 'mike', link: 'https://instantadpay.com/join/mike' } });
|
||||||
|
W.buy = (tx, day, cents) => W.R.record({ site: 'iap', email: 'm@x.test', tx, cents: cents || 2000, credits: cents || 2000, ts: ct(day) });
|
||||||
|
return W;
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('admin: month format, sizes, file type; release needs all five sizes; placeholder art fills all five', async () => {
|
||||||
|
const W = world();
|
||||||
|
assert.ok(W.K.saveKit({ month: '2026-13' }).error);
|
||||||
|
assert.ok(W.K.saveKit({ month: '2026-11', theme: 'Harvest' }).ok);
|
||||||
|
assert.ok(W.K.uploadBase('2026-11', '999x1', Buffer.alloc(64), 'image/png').error);
|
||||||
|
assert.ok(W.K.uploadBase('2026-11', '728x90', Buffer.from('not an image at all, honestly, no...........'), 'image/png').error);
|
||||||
|
assert.ok(/all five sizes/.test(W.K.saveKit({ month: '2026-11', released: true }).error));
|
||||||
|
const r = W.K.usePlaceholder('2026-11'); assert.deepStrictEqual(r.sizes, W.K.ORDER);
|
||||||
|
assert.ok(W.K.saveKit({ month: '2026-11', released: true }).ok);
|
||||||
|
const k = W.K.listKits()[0]; assert.ok(k.released && k.complete && k.theme === 'Harvest');
|
||||||
|
});
|
||||||
|
await t('switch off: no kits for anyone', async () => {
|
||||||
|
const W = world({ refuelStreak: '0' }); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true });
|
||||||
|
assert.deepStrictEqual(await W.K.myKits('m@x.test'), { on: false });
|
||||||
|
assert.ok((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error);
|
||||||
|
});
|
||||||
|
await t('locked until the next counted refuel; unlocked by a refuel in that Central month; drafts never shown', async () => {
|
||||||
|
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); W.K.usePlaceholder('2026-12');
|
||||||
|
W.now = ct('2026-11-03');
|
||||||
|
let mk = await W.K.myKits('m@x.test'); assert.strictEqual(mk.kits.length, 1); assert.strictEqual(mk.kits[0].unlocked, false);
|
||||||
|
assert.ok(/next counted refuel/.test((await W.K.renderFor('m@x.test', '2026-11', '728x90')).error));
|
||||||
|
await W.buy('0x1', '2026-11-03');
|
||||||
|
mk = await W.K.myKits('m@x.test'); assert.ok(mk.kits[0].unlocked); assert.strictEqual(mk.kits[0].gif, false); assert.strictEqual(mk.link, 'https://instantadpay.com/join/mike');
|
||||||
|
});
|
||||||
|
await t('a Pit Stop does not unlock a kit; the next counted refuel does; kits stay usable after the month; a missed month stops only new kits', async () => {
|
||||||
|
const W = world();
|
||||||
|
for (const m of ['2026-11', '2026-12', '2027-02']) { W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); }
|
||||||
|
await W.buy('0x1', '2026-11-20'); // unlocks November
|
||||||
|
await W.buy('0x2', '2026-12-05'); // a Pit Stop: not a refuel, December stays locked
|
||||||
|
W.now = ct('2026-12-06'); let mk = await W.K.myKits('m@x.test');
|
||||||
|
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2026-12', false], ['2026-11', true]], // February is released early but waits for its month
|
||||||
|
JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
|
||||||
|
await W.buy('0x3', '2026-12-17'); // counted refuel in December: unlocks December
|
||||||
|
W.now = ct('2027-02-10'); mk = await W.K.myKits('m@x.test'); // January missed (free miss), February not refueled yet
|
||||||
|
assert.deepStrictEqual(mk.kits.map(k => [k.month, k.unlocked]), [['2027-02', false], ['2026-12', true], ['2026-11', true]], JSON.stringify(mk.kits.map(k => [k.month, k.unlocked])));
|
||||||
|
});
|
||||||
|
await t('animated version from a 3-month streak; BannerKitAI custom-banner credit from 6 months (entitlement + note only)', async () => {
|
||||||
|
const W = world(); let day = '2026-06-02';
|
||||||
|
const months = [];
|
||||||
|
for (let k = 1; k <= 6; k++) { const m = day.slice(0, 7); months.push(m); W.K.usePlaceholder(m); W.K.saveKit({ month: m, released: true }); await W.buy('t' + k, day); day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
|
||||||
|
W.now = ct(day); const mk = await W.K.myKits('m@x.test');
|
||||||
|
const by = Object.fromEntries(mk.kits.map(k => [k.month, k]));
|
||||||
|
assert.strictEqual(by[months[1]].gif, false); assert.strictEqual(by[months[2]].gif, true); assert.strictEqual(by[months[5]].custom, true); assert.strictEqual(by[months[4]].custom, false);
|
||||||
|
assert.strictEqual(mk.customCredits.length, 1); assert.ok(/BannerKitAI/.test(mk.customNote));
|
||||||
|
assert.ok(/3-month streak/.test((await W.K.renderFor('m@x.test', months[1], '300x250', 'gif')).error));
|
||||||
|
});
|
||||||
|
if (!ffmpegOk || !require(path.join(ROOT, 'kit.js')).font()) { console.log('skip render checks: ffmpeg or font missing'); }
|
||||||
|
else {
|
||||||
|
await t('personalized renders: every size at its exact dimensions, @name + QR drawn (differs from the base), cached, served by unguessable name', async () => {
|
||||||
|
const W = world(); W.K.usePlaceholder('2026-11'); W.K.saveKit({ month: '2026-11', released: true }); await W.buy('0x1', '2026-11-03'); W.now = ct('2026-11-04');
|
||||||
|
for (const size of W.K.ORDER) {
|
||||||
|
const r = await W.K.renderFor('m@x.test', '2026-11', size);
|
||||||
|
assert.ok(r.ok, size + ' ' + r.error); const buf = fs.readFileSync(r.file);
|
||||||
|
assert.deepStrictEqual(dims(buf), W.K.SIZES[size], size + ' dims');
|
||||||
|
assert.ok(/^\/kitimg\/[a-f0-9]{28}\.(png|jpg)$/.test(r.url)); assert.ok(r.abs.startsWith('https://instantadpay.com/kitimg/'));
|
||||||
|
assert.ok(W.K.servePath(r.url.slice(8)));
|
||||||
|
const again = await W.K.renderFor('m@x.test', '2026-11', size); assert.strictEqual(again.url, r.url, 'cached');
|
||||||
|
}
|
||||||
|
assert.strictEqual(W.K.servePath('0000000000000000000000000000.png'), null);
|
||||||
|
assert.strictEqual(W.K.servePath('../kits.json'), null);
|
||||||
|
});
|
||||||
|
await t('animated GIF at month 3: three-frame loop at the exact size', async () => {
|
||||||
|
const W = world(); let day = '2026-09-02';
|
||||||
|
for (let k = 1; k <= 3; k++) { W.K.usePlaceholder(day.slice(0, 7)); W.K.saveKit({ month: day.slice(0, 7), released: true }); await W.buy('g' + k, day); if (k < 3) day = new Date(ct(day) + 30 * 864e5).toISOString().slice(0, 10); }
|
||||||
|
W.now = ct(day);
|
||||||
|
const r = await W.K.renderFor('m@x.test', day.slice(0, 7), '300x250', 'gif');
|
||||||
|
assert.ok(r.ok, r.error); const buf = fs.readFileSync(r.file); assert.strictEqual(buf.slice(0, 6).toString(), 'GIF89a'); assert.deepStrictEqual(dims(buf), [300, 250]);
|
||||||
|
assert.ok(buf.includes(Buffer.from('NETSCAPE2.0')), 'loops');
|
||||||
|
});
|
||||||
|
await t('admin preview renders without any member', async () => {
|
||||||
|
const W = world(); W.K.usePlaceholder('2026-11');
|
||||||
|
const r = await W.K.preview('2026-11', '160x600', 'yourname'); assert.ok(r.ok, r.error); assert.deepStrictEqual(dims(fs.readFileSync(r.file)), [160, 600]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
// Monthly Refuel streak (refuel.js): every rule on throwaway data. JSON store in a temp dir, stubbed accounts/ads/mail,
|
||||||
|
// the real db.js lock (per-process queue without DATABASE_URL) and marks.js (per-process claims without a DB).
|
||||||
|
// Run: node qa/refuel.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const assert = require('assert');
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 2).join(' | ')); } }
|
||||||
|
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
|
||||||
|
const db = require(path.join(ROOT, 'db.js'));
|
||||||
|
|
||||||
|
// a timestamp at a given Central-time day + hour (handles CST and CDT)
|
||||||
|
function ct(day, hour) {
|
||||||
|
const [y, m, d] = day.split('-').map(Number);
|
||||||
|
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, d, (hour == null ? 12 : hour) + off, 0); const back = new Date(ts).toLocaleString('en-CA', { timeZone: 'America/Chicago', hour12: false }); if (back.startsWith(day) && Number(back.split(', ')[1].slice(0, 2)) % 24 === (hour == null ? 12 : hour)) return ts; }
|
||||||
|
throw new Error('no ts for ' + day);
|
||||||
|
}
|
||||||
|
|
||||||
|
function world(cfg) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-refuel-'));
|
||||||
|
const W = { dir, cfg: Object.assign({ refuelStreak: '1' }, cfg || {}), earned: [], inbox: [], mail: [], badges: [], feed: [] };
|
||||||
|
W.marks = fresh('marks.js'); W.marks.init({});
|
||||||
|
W.deps = {
|
||||||
|
dataDir: dir, db, marks: W.marks, siteConfig: () => W.cfg,
|
||||||
|
accounts: { byMemberId: async id => id === 7 ? { email: 'm@x.test', memberId: 7, username: 'mike' } : null, positionByMember: async id => id === 70 ? { email: 'm@x.test', memberId: 70 } : null, byEmail: async e => ({ email: e, username: e === 'm@x.test' ? 'mike' : null, memberId: 9 }) },
|
||||||
|
ads: { addEarned: async (email, credits, opts) => { W.earned.push({ email, credits, opts }); } },
|
||||||
|
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.mail.push({ to, subject, text }); } },
|
||||||
|
drip: { isUnsubscribed: async () => false, unsubUrl: e => 'https://instantadpay.com/unsubscribe?e=' + e },
|
||||||
|
featuredPerDay: () => 40,
|
||||||
|
message: async (to, subject, html) => { W.inbox.push({ to, subject, html }); },
|
||||||
|
badge: async (email, key) => { W.badges.push(key); },
|
||||||
|
feed: async text => { W.feed.push(text); },
|
||||||
|
};
|
||||||
|
W.R = fresh('refuel.js'); W.R.init(W.deps);
|
||||||
|
W.buy = (site, tx, cents, credits, day, hour, email) => W.R.record({ site, email: email || 'm@x.test', tx, cents, credits, ts: ct(day, hour) });
|
||||||
|
W.out = site => W.R.outbox(site);
|
||||||
|
W.store = () => JSON.parse(fs.readFileSync(path.join(dir, 'refuel.json'), 'utf8'));
|
||||||
|
W.rec = () => W.store().members['m@x.test'];
|
||||||
|
W.grants = () => Object.values(W.store().outbox).filter(r => r.kind === 'grant');
|
||||||
|
return W;
|
||||||
|
}
|
||||||
|
const D = (day, k) => new Date(Date.UTC(...day.split('-').map((v, i) => i === 1 ? v - 1 : Number(v))) + k * 864e5).toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await t('MASTER SWITCH off: nothing recorded, granted, reminded or shown', async () => {
|
||||||
|
const W = world({ refuelStreak: '0' });
|
||||||
|
const r = await W.buy('iap', '0xa', 2000, 2000, '2026-11-02');
|
||||||
|
assert.deepStrictEqual(r, { on: false });
|
||||||
|
assert.ok(!fs.existsSync(path.join(W.dir, 'refuel.json')));
|
||||||
|
assert.deepStrictEqual(await W.R.view('m@x.test'), { on: false });
|
||||||
|
assert.deepStrictEqual(await W.R.tick(), { on: false });
|
||||||
|
assert.strictEqual(await W.R.streakLine('m@x.test'), null);
|
||||||
|
assert.strictEqual(await W.R.onIapPurchase({ type: 'Purchase', buyerId: 7, tx: '0xz', priceCents: 2000, creditAmount: 2000, ts: Date.now() }), null);
|
||||||
|
assert.strictEqual(W.earned.length + W.feed.length + W.badges.length, 0);
|
||||||
|
});
|
||||||
|
await t('first counted refuel: month 1 +10%, purchased-grade, labelled, refuel day +30 (Central), Engine Started badge, feed line', async () => {
|
||||||
|
const W = world();
|
||||||
|
const r = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 1);
|
||||||
|
assert.strictEqual(W.earned.length, 1); const g = W.earned[0];
|
||||||
|
assert.strictEqual(g.credits, 200); assert.ok(g.opts.purchased); assert.strictEqual(g.opts.log.kind, 'bonus'); assert.ok(/^Refuel streak month 1: \+10% on your \$20 package$/.test(g.opts.log.note), g.opts.log.note);
|
||||||
|
const v = await W.R.view('m@x.test', ct('2026-11-03'));
|
||||||
|
assert.strictEqual(v.refuelDay, '2026-12-02'); assert.strictEqual(v.opensDay, '2026-11-27'); assert.strictEqual(v.graceEnd, '2026-12-07');
|
||||||
|
assert.strictEqual(v.streak, 1); assert.ok(v.engineUnlocked); assert.ok(!v.windowOpen);
|
||||||
|
assert.deepStrictEqual(W.badges, ['refuelStart']);
|
||||||
|
assert.strictEqual(W.feed.length, 1); assert.ok(/@mike<\/b> refueled InstantAdPay · streak 1/.test(W.feed[0]), W.feed[0]);
|
||||||
|
});
|
||||||
|
await t('below the floor: $5 on InstantAdPay, $20 on LinkSpin do not count', async () => {
|
||||||
|
const W = world();
|
||||||
|
assert.strictEqual((await W.buy('iap', '0x5', 500, 500, '2026-11-02')).kind, 'below');
|
||||||
|
assert.strictEqual((await W.buy('linkspin', '0x6', 2000, 2000, '2026-11-02')).kind, 'below');
|
||||||
|
assert.strictEqual(W.earned.length, 0); assert.strictEqual((await W.R.view('m@x.test')).started, false);
|
||||||
|
});
|
||||||
|
await t('both engines: second site gets the both-rate, first site topped up by the difference only; outbox per site', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
const r = await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-09');
|
||||||
|
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.both, true);
|
||||||
|
const ls = await W.out('linkspin'); assert.strictEqual(ls.length, 1); assert.strictEqual(ls[0].payload.credits, 375); assert.strictEqual(ls[0].ref, 'rf:linkspin:0xL1');
|
||||||
|
const top = W.earned.find(e => /Twin Engine top-up/.test(e.opts.log.note)); assert.ok(top, 'top-up applied'); assert.strictEqual(top.credits, 100);
|
||||||
|
assert.strictEqual(W.earned.reduce((s, e) => s + e.credits, 0), 300); // 200 + 100 = 15% of 2000
|
||||||
|
assert.ok(/refueled both engines · streak 1/.test(W.feed[1]), W.feed[1]);
|
||||||
|
const v = await W.R.view('m@x.test', ct('2026-11-10'));
|
||||||
|
assert.ok(v.cycle.both); assert.strictEqual(v.cycle.iap.pct, 15); assert.strictEqual(v.cycle.linkspin.bonus, 375);
|
||||||
|
});
|
||||||
|
await t('Pit Stop: half the current rate, once per site per cycle, not a refuel, not posted', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
const p1 = await W.buy('iap', '0xp1', 5000, 5500, '2026-11-12');
|
||||||
|
assert.strictEqual(p1.kind, 'pitstop'); assert.strictEqual(W.earned[1].credits, 275); // 10% / 2 = 5% of 5,500
|
||||||
|
assert.ok(/Pit Stop: \+5% \(half your \+10% streak rate\)/.test(W.earned[1].opts.log.note));
|
||||||
|
const p2 = await W.buy('iap', '0xp2', 2000, 2000, '2026-11-13'); assert.strictEqual(p2.kind, 'none');
|
||||||
|
assert.strictEqual(W.earned.length, 2); assert.strictEqual(W.feed.length, 1);
|
||||||
|
assert.strictEqual((await W.R.view('m@x.test', ct('2026-11-13'))).streak, 1, 'a pit stop is not a counted refuel');
|
||||||
|
// LinkSpin joins (both engines, 15%), then a LinkSpin Pit Stop at half the BOTH rate (7.5%)
|
||||||
|
await W.buy('linkspin', '0xL1', 2500, 2500, '2026-11-14');
|
||||||
|
const p3 = await W.buy('linkspin', '0xL2', 10000, 10000, '2026-11-15'); assert.strictEqual(p3.kind, 'pitstop');
|
||||||
|
const lsg = (await W.out('linkspin')).find(x => x.ref === 'rfpit:linkspin:0xL2'); assert.strictEqual(lsg.payload.credits, 750);
|
||||||
|
});
|
||||||
|
await t('window: day 24 is a Pit Stop/none, day 25 (window open) is month 2 at +15%', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
assert.strictEqual((await W.buy('iap', '0x2', 2000, 2000, D('2026-11-02', 24))).kind, 'pitstop');
|
||||||
|
const r = await W.buy('iap', '0x3', 2000, 2000, D('2026-11-02', 25));
|
||||||
|
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.month, 2); assert.strictEqual(W.earned[2].credits, 300);
|
||||||
|
assert.strictEqual(W.rec().dueDay, D(D('2026-11-02', 25), 30), 'next due 30 days after THIS refuel');
|
||||||
|
});
|
||||||
|
await t('grace: refuel on the last grace day keeps the streak; ladder m3 +20%, m4 +25%, m5 stays +25%', async () => {
|
||||||
|
const W = world();
|
||||||
|
let day = '2026-11-02'; await W.buy('iap', 't1', 2000, 2000, day);
|
||||||
|
const pcts = [];
|
||||||
|
for (let k = 2; k <= 5; k++) { day = D(day, 35); const r = await W.buy('iap', 't' + k, 2000, 2000, day); assert.strictEqual(r.month, k, 'month ' + k); pcts.push(W.earned[W.earned.length - 1].credits / 20); }
|
||||||
|
assert.deepStrictEqual(pcts, [15, 20, 25, 25]);
|
||||||
|
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3']);
|
||||||
|
});
|
||||||
|
await t('missed grace: the free miss keeps the streak once; the next package counts as month k+1; a second miss inside 365 days resets', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', 't1', 2000, 2000, '2026-01-05');
|
||||||
|
await W.buy('iap', 't2', 2000, 2000, '2026-02-04'); // month 2, due 03-06, grace to 03-11
|
||||||
|
const r3 = await W.buy('iap', 't3', 2000, 2000, '2026-03-12'); // one day late: free miss covers it
|
||||||
|
assert.strictEqual(r3.kind, 'refuel'); assert.strictEqual(r3.month, 3);
|
||||||
|
const rec = W.rec(); assert.strictEqual(rec.misses[0].free, true); assert.strictEqual(rec.freeMissDay, '2026-03-11');
|
||||||
|
const r4 = await W.buy('iap', 't4', 2000, 2000, D('2026-03-12', 36)); // late again, inside 365 days: reset
|
||||||
|
assert.strictEqual(r4.month, 1); assert.strictEqual(W.rec().misses[0].free, false);
|
||||||
|
});
|
||||||
|
await t('free miss comes back after 365 days', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', 'a1', 2000, 2000, '2026-01-05');
|
||||||
|
await W.buy('iap', 'a2', 2000, 2000, '2026-02-12'); // late: free miss used (grace ended 02-09)
|
||||||
|
assert.strictEqual(W.rec().freeMissDay, '2026-02-09');
|
||||||
|
let day = '2026-02-12', k = 2;
|
||||||
|
while (day < '2027-02-01') { day = D(day, 30); k++; await W.buy('iap', 'a' + k, 2000, 2000, day); }
|
||||||
|
const before = W.rec().streak; const late = D(W.rec().graceEnd, 1);
|
||||||
|
const r = await W.buy('iap', 'late', 2000, 2000, late);
|
||||||
|
assert.strictEqual(r.month, before + 1, 'kept by a fresh free miss'); assert.strictEqual(W.rec().misses[0].free, true);
|
||||||
|
});
|
||||||
|
await t('m4+ both engines: +40% each and a 100-credit Featured bonus on InstantAdPay, once per cycle', async () => {
|
||||||
|
const W = world();
|
||||||
|
let day = '2026-11-02';
|
||||||
|
for (let k = 1; k <= 4; k++) { await W.buy('iap', 'i' + k, 2000, 2000, day); if (k < 4) day = D(day, 30); }
|
||||||
|
await W.buy('linkspin', 'L4', 2500, 2500, D(day, 2));
|
||||||
|
assert.strictEqual((await W.out('linkspin')).find(x => x.ref === 'rf:linkspin:L4').payload.credits, 1000);
|
||||||
|
const feat = W.earned.filter(e => /Featured bonus/.test(e.opts.log.note)); assert.strictEqual(feat.length, 1); assert.strictEqual(feat[0].credits, 100);
|
||||||
|
const top = W.earned.find(e => e.opts.log.ref === 'rftop:iap:L4'); assert.strictEqual(top.credits, 800 - 500);
|
||||||
|
});
|
||||||
|
await t('stacking: the streak grant is its own labelled grant (Friday and Wednesday add theirs untouched)', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', '0xfri', 2000, 2000, '2026-11-06'); // a Friday
|
||||||
|
assert.strictEqual(W.earned.length, 1); assert.ok(/^rf:iap:0xfri$/.test(W.earned[0].opts.log.ref));
|
||||||
|
assert.ok(!/Friday|Wednesday/.test(W.earned[0].opts.log.note));
|
||||||
|
});
|
||||||
|
await t('idempotent: the same tx twice = one decision, one grant, one feed line', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
const again = await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
assert.ok(again.repeat); assert.strictEqual(W.earned.length, 1); assert.strictEqual(W.feed.length, 1);
|
||||||
|
});
|
||||||
|
await t('two concurrent workers (two module copies, one store): both engines at once, no double grant', async () => {
|
||||||
|
const W = world();
|
||||||
|
const B = fresh('refuel.js'); B.init(W.deps);
|
||||||
|
await W.buy('iap', '0x1', 2000, 2000, '2026-11-02');
|
||||||
|
const tsL = ct('2026-11-05'); const tsI = ct('2026-11-06');
|
||||||
|
await Promise.all([
|
||||||
|
W.R.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
|
||||||
|
B.record({ site: 'linkspin', email: 'm@x.test', tx: '0xL', cents: 2500, credits: 2500, ts: tsL }),
|
||||||
|
B.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
|
||||||
|
W.R.record({ site: 'iap', email: 'm@x.test', tx: '0xP', cents: 2000, credits: 2000, ts: tsI }),
|
||||||
|
]);
|
||||||
|
await Promise.all([W.R.drainLocal(), B.drainLocal()]);
|
||||||
|
const refs = W.earned.map(e => e.opts.log.ref).sort();
|
||||||
|
assert.deepStrictEqual(refs, ['rf:iap:0x1', 'rfpit:iap:0xP', 'rftop:iap:0xL'], JSON.stringify(refs));
|
||||||
|
assert.strictEqual((await W.out('linkspin')).length, 1);
|
||||||
|
assert.strictEqual(W.feed.length, 2);
|
||||||
|
});
|
||||||
|
await t('linked position purchase counts for the owner; Central day: 11:30 PM CT Oct 31 is Oct 31 (UTC says Nov 1)', async () => {
|
||||||
|
const W = world();
|
||||||
|
const ts = ct('2026-10-31', 23) + 30 * 60000;
|
||||||
|
assert.strictEqual(new Date(ts).toISOString().slice(0, 10), '2026-11-01');
|
||||||
|
const r = await W.R.onIapPurchase({ type: 'Purchase', buyerId: 70, tx: '0xpos', priceCents: 2000, creditAmount: 2000, ts });
|
||||||
|
assert.strictEqual(r.kind, 'refuel'); assert.strictEqual(r.day, '2026-10-31');
|
||||||
|
assert.strictEqual(W.rec().dueDay, '2026-11-30', 'across the Nov 1 clock change: exactly 30 calendar days');
|
||||||
|
});
|
||||||
|
await t('Refuel Day promo: off by default; on, the 1st (Central) adds its own grant to a counted refuel only', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', 'd1', 2000, 2000, '2026-12-01'); assert.strictEqual(W.earned.length, 1);
|
||||||
|
const W2 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||||
|
await W2.buy('iap', 'd1', 2000, 2000, '2026-12-01');
|
||||||
|
assert.deepStrictEqual(W2.earned.map(e => e.credits), [200, 200]); assert.ok(/Refuel Day \(the 1st\)/.test(W2.earned[1].opts.log.note));
|
||||||
|
const W3 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||||
|
await W3.buy('iap', 'e1', 2000, 2000, '2026-11-20');
|
||||||
|
const pit = await W3.buy('iap', 'e2', 2000, 2000, '2026-12-01', 1); // 1 AM CT on the 1st, but a Pit Stop: no promo
|
||||||
|
assert.strictEqual(pit.kind, 'pitstop'); assert.ok(!W3.earned.some(e => /Refuel Day/.test(e.opts.log.note)));
|
||||||
|
const W4 = world({ refuelDayPromo: '1', refuelDayPct: '10' });
|
||||||
|
await W4.buy('iap', 'f1', 2000, 2000, '2026-11-30', 23); // 11 PM CT Nov 30 = Dec 1 in UTC: not the 1st
|
||||||
|
assert.strictEqual(W4.earned.length, 1);
|
||||||
|
});
|
||||||
|
await t('badges at 3, 6 and 12 months, once each', async () => {
|
||||||
|
const W = world(); let day = '2026-01-02';
|
||||||
|
for (let k = 1; k <= 13; k++) { await W.buy('iap', 'b' + k, 2000, 2000, day); day = D(day, 30); }
|
||||||
|
assert.deepStrictEqual(W.badges, ['refuelStart', 'refuel3', 'refuel6', 'refuel12']);
|
||||||
|
assert.deepStrictEqual((await W.R.badgesOf('m@x.test')).sort(), ['refuel12', 'refuel3', 'refuel6', 'refuelStart']);
|
||||||
|
});
|
||||||
|
await t('reminders: 5 days before, on the day, last call; from the home site; once; after the reminder hour; none once refueled', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', 'r1', 2000, 2000, '2026-11-02'); // due 12-02
|
||||||
|
await W.R.tick(ct('2026-11-27', 8)); assert.strictEqual(W.inbox.filter(m => /refuel day is/i.test(m.subject)).length, 0, 'not before 9 AM CT');
|
||||||
|
await W.R.tick(ct('2026-11-27', 10)); await W.R.tick(ct('2026-11-27', 15));
|
||||||
|
const soon = W.inbox.filter(m => m.subject === 'Your refuel day is Wed, Dec 2'); assert.strictEqual(soon.length, 1);
|
||||||
|
assert.ok(W.mail.some(m => m.subject === 'Your refuel day is Wed, Dec 2' && /Stop these emails/.test(m.text)));
|
||||||
|
await W.R.tick(ct('2026-12-02', 10)); assert.ok(W.inbox.some(m => m.subject === 'Today is your refuel day'));
|
||||||
|
await W.R.tick(ct('2026-12-07', 10)); const last = W.inbox.find(m => /Last call/.test(m.subject)); assert.ok(last && /free miss/.test(last.html));
|
||||||
|
// LinkSpin home: the reminder goes to LinkSpin's outbox instead
|
||||||
|
const W2 = world(); await W2.buy('linkspin', 'L1', 2500, 2500, '2026-11-02');
|
||||||
|
await W2.R.tick(ct('2026-11-27', 10));
|
||||||
|
assert.ok((await W2.out('linkspin')).some(x => x.kind === 'reminder' && x.payload.remind === 'soon')); assert.strictEqual(W2.inbox.length, 0);
|
||||||
|
// refueled inside the window: no "on the day" reminder
|
||||||
|
const W3 = world(); await W3.buy('iap', 'x1', 2000, 2000, '2026-11-02'); await W3.buy('iap', 'x2', 2000, 2000, '2026-11-28');
|
||||||
|
await W3.R.tick(ct('2026-12-02', 10)); assert.ok(!W3.inbox.some(m => /refuel day/i.test(m.subject) && !/Refuel counted/.test(m.subject)));
|
||||||
|
});
|
||||||
|
await t('weekly roundup: Monday after 9 AM CT, last Mon..Sun, once per week, skipped when nobody refueled', async () => {
|
||||||
|
const W = world();
|
||||||
|
await W.buy('iap', 'w1', 2000, 2000, '2026-11-03'); // Tue
|
||||||
|
await W.buy('iap', 'w2', 2000, 2000, '2026-11-05', 12, 'z@x.test');
|
||||||
|
W.feed.length = 0;
|
||||||
|
await W.R.tick(ct('2026-11-09', 8)); assert.strictEqual(W.feed.length, 0, 'before 9 AM');
|
||||||
|
await W.R.tick(ct('2026-11-09', 10)); await W.R.tick(ct('2026-11-09', 11));
|
||||||
|
assert.strictEqual(W.feed.length, 1); assert.ok(/Refueled this week:<\/b> 2 members, 2 new streaks, longest streak 1/.test(W.feed[0]), W.feed[0]);
|
||||||
|
await W.R.tick(ct('2026-11-16', 10)); assert.strictEqual(W.feed.length, 1, 'nobody refueled 11-09..11-15: skipped');
|
||||||
|
});
|
||||||
|
await t('view + streak line: next bonus, Pit Stop status, free miss', async () => {
|
||||||
|
const W = world();
|
||||||
|
const v0 = await W.R.view('m@x.test'); assert.ok(v0.on && !v0.started && v0.next.single === 10 && v0.next.both === 15);
|
||||||
|
await W.buy('iap', 'v1', 2000, 2000, '2026-11-02');
|
||||||
|
const v = await W.R.view('m@x.test', ct('2026-11-04'));
|
||||||
|
assert.deepStrictEqual(v.next, { month: 1, secondEngine: 15 }); assert.strictEqual(v.pitStop.pct, 5); assert.ok(v.pitStop.iap && !v.pitStop.linkspin);
|
||||||
|
assert.ok(v.freeMiss.available);
|
||||||
|
const sl = await W.R.streakLine('m@x.test'); assert.ok(/month 1, next refuel day Wed, Dec 2/.test(sl.text), sl.text);
|
||||||
|
for (const s of [sl.text, JSON.stringify(v)]) assert.ok(!/—/.test(s));
|
||||||
|
});
|
||||||
|
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -4,10 +4,19 @@
|
|||||||
# bash qa/run.sh member # local copy: member + admin walk
|
# bash qa/run.sh member # local copy: member + admin walk
|
||||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||||
# bash qa/run.sh all # public + member + earn
|
# bash qa/run.sh all # public + member + earn
|
||||||
|
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||||
|
# bash qa/run.sh walletnudge # game wallet push (any linked wallet, activated or not) + no-wallet nudge copy against a mock game (also runs in member)
|
||||||
|
# bash qa/run.sh tankhold # holding-tank activation hold, 24-hour safety net (mocked clock) and LinkSpin alignment: unit + local copy (also runs in member)
|
||||||
|
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
|
||||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||||
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
||||||
# bash qa/run.sh sov-passes # Explorer/Champion tiers: store unit checks + admin buys Explorer with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
|
# bash qa/run.sh sov-passes # pass tiers (Explorer/Champion/Sovereign/Legend): store unit checks + admin buys Explorer + Sovereign with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
|
||||||
|
# bash qa/run.sh nas # Network Ad Space billing: served-count trap, stopped-ad restart (no phantom delivery), the 1/N network rate + PassiveDrip partner visits (stubbed NAS, throwaway data)
|
||||||
|
# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data)
|
||||||
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
|
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
|
||||||
|
# bash qa/run.sh override # level-4 override: week math, hunt, house, dust carry, cap, balance, two concurrent payers (fake chain + signer, throwaway data)
|
||||||
|
# bash qa/run.sh convpixel # conversion pixel: lsclk click ids on /api/ads/click, signed push to a MOCK LinkSpin, own-click self flag, Campaigns > Conversion tracking + cost per goal, LinkSpin down (local copy, throwaway data)
|
||||||
|
# bash qa/run.sh fuel # Fuel Your Offers: refill notices, refuel streak, Refuel Kit, Engine Room (unit + two-copy tests, throwaway data)
|
||||||
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||||
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
|
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
|
||||||
set -u
|
set -u
|
||||||
@@ -34,6 +43,18 @@ if [ "$MODE" = "public" ]; then
|
|||||||
node qa/chatbot-sync.mjs || status=1
|
node qa/chatbot-sync.mjs || status=1
|
||||||
elif [ "$MODE" = "member" ]; then
|
elif [ "$MODE" = "member" ]; then
|
||||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||||
|
node qa/tank-hold.mjs || status=1
|
||||||
|
node qa/walletnudge.test.cjs || status=1
|
||||||
|
elif [ "$MODE" = "walletnudge" ]; then
|
||||||
|
node qa/walletnudge.test.cjs || status=1
|
||||||
|
elif [ "$MODE" = "tankhold" ]; then
|
||||||
|
node qa/tank-hold.mjs || status=1
|
||||||
|
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||||
|
node qa/sponsorfollow.test.cjs || status=1
|
||||||
|
node qa/sponsorfollow-e2e.mjs || status=1
|
||||||
|
elif [ "$MODE" = "kb" ]; then
|
||||||
|
node qa/kb-retrieval.cjs || status=1
|
||||||
|
node qa/kb-chat.mjs || status=1
|
||||||
elif [ "$MODE" = "door" ]; then
|
elif [ "$MODE" = "door" ]; then
|
||||||
node qa/door.mjs || status=1
|
node qa/door.mjs || status=1
|
||||||
elif [ "$MODE" = "gamepass" ]; then
|
elif [ "$MODE" = "gamepass" ]; then
|
||||||
@@ -41,6 +62,19 @@ elif [ "$MODE" = "gamepass" ]; then
|
|||||||
elif [ "$MODE" = "sov-passes" ]; then
|
elif [ "$MODE" = "sov-passes" ]; then
|
||||||
node qa/sov-passes-store.cjs || status=1
|
node qa/sov-passes-store.cjs || status=1
|
||||||
node qa/sov-passes-local.mjs || status=1
|
node qa/sov-passes-local.mjs || status=1
|
||||||
|
elif [ "$MODE" = "nas" ]; then
|
||||||
|
node qa/nas-served.mjs || status=1
|
||||||
|
node qa/nas-restart.mjs || status=1
|
||||||
|
node qa/nas-ratio.mjs || status=1
|
||||||
|
elif [ "$MODE" = "login-queue" ]; then
|
||||||
|
node qa/login-queue.cjs || status=1
|
||||||
|
node qa/login-queue-sql.cjs || status=1
|
||||||
|
elif [ "$MODE" = "convpixel" ]; then
|
||||||
|
node qa/convpixel.test.mjs || status=1
|
||||||
|
elif [ "$MODE" = "fuel" ]; then
|
||||||
|
for f in qa/refill.test.cjs qa/refuel*.test.cjs; do [ -f "$f" ] && { node "$f" || status=1; }; done
|
||||||
|
elif [ "$MODE" = "override" ]; then
|
||||||
|
node qa/override.test.cjs || status=1
|
||||||
elif [ "$MODE" = "gamepass-games" ]; then
|
elif [ "$MODE" = "gamepass-games" ]; then
|
||||||
node qa/gamepass-games.cjs || status=1
|
node qa/gamepass-games.cjs || status=1
|
||||||
elif [ "$MODE" = "earn" ]; then
|
elif [ "$MODE" = "earn" ]; then
|
||||||
|
|||||||
+92
-19
@@ -6,6 +6,13 @@
|
|||||||
// Explorer in the browser through the REAL ads.gamePurchase(purchasedOnly) charge; the 500 left is short for a second Explorer
|
// Explorer in the browser through the REAL ads.gamePurchase(purchasedOnly) charge; the 500 left is short for a second Explorer
|
||||||
// (waiting order, $20 package copy); the Shards of Valor hand-off token and GET /api/partner/player carry tier explorer;
|
// (waiting order, $20 package copy); the Shards of Valor hand-off token and GET /api/partner/player carry tier explorer;
|
||||||
// polgrant answers pass: true with the weekly pass caps; Admin > Game Pass shows the tier table. Exit 1 on any failure.
|
// polgrant answers pass: true with the weekly pass caps; Admin > Game Pass shows the tier table. Exit 1 on any failure.
|
||||||
|
// 2026-10-22 (Marty): no pass is bought with credits any more. The seeded credits must stay untouched: every tier is an order plus a
|
||||||
|
// fresh package purchase (faked locally with /api/dev/gamepass-purchase), and the card sends the member to Buy credits.
|
||||||
|
// 2026-10-22: + Sovereign / Legend: members refused while sovTiers is off, the admin preview lists all five, the admin buys Sovereign
|
||||||
|
// (real charge), a Legend waiting order is settled by a $250 package (a year), the token / partner player carry tier legend + tiers.
|
||||||
|
// 2026-10-25 (Marty): no admin-only tier UI on the member card. The ADMIN_EMAIL account gets the member view on /my (weekly only,
|
||||||
|
// hidden-tier buys refused there too); every tier test runs from Admin > Game Pass > Tier test and preview (/api/admin/gamepass/preview,
|
||||||
|
// test-buy, test-cancel, test-comp), always on the admin's own account. A holder of a tier sees it on the card like any member.
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
@@ -21,7 +28,7 @@ const B = 'http://127.0.0.1:' + PORT;
|
|||||||
const SHOTS = process.env.SHOTS || 'D:/tmp/sov-passes'; fs.mkdirSync(SHOTS, { recursive: true });
|
const SHOTS = process.env.SHOTS || 'D:/tmp/sov-passes'; fs.mkdirSync(SHOTS, { recursive: true });
|
||||||
const SOV = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
|
const SOV = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
|
||||||
const ADMIN_PW = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com', MEMBER = 'qa-sov-member@example.com';
|
const ADMIN_PW = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com', MEMBER = 'qa-sov-member@example.com';
|
||||||
const SEED_ID = 9001, SEED_CREDITS = 2500;
|
const SEED_ID = 9001, SEED_CREDITS = 2000 + 10000 + 500; // Explorer + Sovereign, then 500 left (short for a second Explorer)
|
||||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovpasses-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-sovpasses-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||||
const hide = page => page.evaluate(() => { document.querySelectorAll('.lgate,.iap-welcome,#onboardModal').forEach(m => m.hidden = true); });
|
const hide = page => page.evaluate(() => { document.querySelectorAll('.lgate,.iap-welcome,#onboardModal').forEach(m => m.hidden = true); });
|
||||||
@@ -70,7 +77,8 @@ try {
|
|||||||
ok(up && /qa stub: position #9001/.test(srvLog), 'local copy up with the seeded position', '');
|
ok(up && /qa stub: position #9001/.test(srvLog), 'local copy up with the seeded position', '');
|
||||||
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1' } }, adminH);
|
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1' } }, adminH);
|
||||||
const site = (await api('/api/admin/site', null, adminH)).j; const sc = (site && (site.site || site)) || {};
|
const site = (await api('/api/admin/site', null, adminH)).j; const sc = (site && (site.site || site)) || {};
|
||||||
ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 2000 && Number(sc.gamePassChampionPriceCredits) === 4000 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 2000 / Champion 4000 credits, 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits }));
|
ok(sc.sovTiers === '0' && Number(sc.gamePassExplorerPriceCredits) === 2000 && Number(sc.gamePassChampionPriceCredits) === 5000 && Number(sc.gamePassExplorerDays) === 30 && sc.passTournamentTierSales === '0', 'defaults: sovTiers 0, Explorer 2000 / Champion 5000 cents ($20 / $50, 2026-10-25), 30 days, passTournamentTierSales 0', JSON.stringify({ sovTiers: sc.sovTiers, e: sc.gamePassExplorerPriceCredits, c: sc.gamePassChampionPriceCredits }));
|
||||||
|
ok(Number(sc.gamePassSovereignPriceCredits) === 10000 && Number(sc.gamePassSovereignDays) === 30 && sc.gamePassSovereignEnabled === '1' && Number(sc.gamePassLegendPriceCredits) === 25000 && Number(sc.gamePassLegendDays) === 365 && sc.gamePassLegendEnabled === '1' && Number(sc.gamePassPriceCredits) === 500 && Number(sc.gamePassDays) === 7, 'defaults: Sovereign 10000 / 30 days, Legend 25000 / 365 days (kill switches 1), weekly 500 / 7 unchanged', JSON.stringify({ s: [sc.gamePassSovereignPriceCredits, sc.gamePassSovereignDays], l: [sc.gamePassLegendPriceCredits, sc.gamePassLegendDays] }));
|
||||||
const hA = await signIn(ADMIN_EMAIL, 'qaadmin'), hM = await signIn(MEMBER, 'qasovm');
|
const hA = await signIn(ADMIN_EMAIL, 'qaadmin'), hM = await signIn(MEMBER, 'qasovm');
|
||||||
|
|
||||||
// 1. a member with sovTiers off: weekly only, Explorer refused
|
// 1. a member with sovTiers off: weekly only, Explorer refused
|
||||||
@@ -78,33 +86,70 @@ try {
|
|||||||
ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'member, sovTiers off: only the weekly pass is offered', JSON.stringify((g.passes || []).map(x => x.tier)));
|
ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'member, sovTiers off: only the weekly pass is offered', JSON.stringify((g.passes || []).map(x => x.tier)));
|
||||||
let r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hM);
|
let r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hM);
|
||||||
ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'member, sovTiers off: Explorer buy refused', JSON.stringify(r.j));
|
ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'member, sovTiers off: Explorer buy refused', JSON.stringify(r.j));
|
||||||
|
for (const [tier, name] of [['sovereign', 'Sovereign'], ['legend', 'Legend']]) { r = await api('/api/my/gamepass/buy', { data: { tier } }, hM);
|
||||||
|
ok(r.status === 400 && r.j.error === 'The ' + name + ' pass is not open yet.', 'member, sovTiers off: ' + name + ' buy refused', JSON.stringify(r.j)); }
|
||||||
|
g = (await api('/api/my/gamepass', null, hM)).j; ok(!g.active && !g.waiting && g.passes.length === 1, 'the refused buys left the member with no pass and no waiting order', JSON.stringify({ a: g.active, w: g.waiting }));
|
||||||
browser = await chromium.launch();
|
browser = await chromium.launch();
|
||||||
{ const { page, errs, ctx } = await pageFor(hM); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 });
|
{ const { page, errs, ctx } = await pageFor(hM); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 });
|
||||||
const txt = await page.textContent('#gpCard'); ok(!/Explorer|Champion/.test(txt) && errs.length === 0, 'member page: the weekly card as before, no Explorer/Champion text, no page errors', errs.join(' | '));
|
const txt = await page.textContent('#gpCard'); ok(!/Explorer|Champion|Sovereign|Legend/.test(txt) && errs.length === 0, 'member page: the weekly card as before, no Explorer/Champion/Sovereign/Legend text, no page errors', errs.join(' | '));
|
||||||
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '1-member-weekly-only.png') }); await ctx.close(); }
|
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '1-member-weekly-only.png') }); await ctx.close(); }
|
||||||
|
|
||||||
// 2. the admin: preview of all three, buys Explorer in the browser with the seeded purchased credits (the real charge)
|
// 2. the admin account on /my gets the MEMBER view (2026-10-25): weekly only, no preview note, hidden tiers refused on the member route
|
||||||
g = (await api('/api/my/gamepass', null, hA)).j;
|
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||||
ok(g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion', 'admin, sovTiers off: preview with all three tiers', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open])));
|
ok(g.passes && g.passes.length === 1 && g.passes[0].tier === 'weekly' && !g.tierPreview, 'admin on /my, sovTiers off: the member view, weekly only, no preview', JSON.stringify((g.passes || []).map(x => x.tier)));
|
||||||
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes');
|
r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA);
|
||||||
await page.waitForSelector('#gpCard [data-gp-tier="explorer"]', { timeout: 15000 }); await sleep(600); await hide(page);
|
ok(r.status === 400 && r.j.error === 'The Explorer pass is not open yet.', 'admin on the member route: Explorer refused like any member (tests moved to Admin > Game Pass)', JSON.stringify(r.j));
|
||||||
|
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my#passes'); await page.waitForSelector('#gpCard:not([hidden]) #gpBuy', { timeout: 15000 }); await sleep(600); await hide(page);
|
||||||
const txt = await page.textContent('#gpCard');
|
const txt = await page.textContent('#gpCard');
|
||||||
ok(/never make you stronger than players who earn their gear/.test(txt) && /main story of Shards of Valor is free/.test(txt) && /Admin preview/.test(txt) && !/\u2014/.test(txt), 'tier card copy: never stronger, main story free, admin preview note, no em dashes', '');
|
ok(!/Explorer|Champion|Sovereign|Legend|Admin preview/.test(txt) && errs.length === 0, 'admin /my Games card: the weekly card a member sees, no tier boxes, no admin preview note', errs.join(' | '));
|
||||||
ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url());
|
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-member-card-weekly-only.png') }); await ctx.close(); }
|
||||||
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '2-admin-preview-three-tiers.png') });
|
// the admin portal preview: all five tiers with what each includes, every one open to the admin's own account
|
||||||
await page.click('#gpCard [data-gp-tier="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 });
|
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
|
||||||
await page.screenshot({ path: path.join(SHOTS, '3-admin-confirm-explorer.png') });
|
ok(g.test === true && g.email === ADMIN_EMAIL && g.tierPreview === true && g.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && g.passes.map(x => x.price).join() === '500,2000,5000,10000,25000' && g.passes.map(x => x.package).join() === '5,20,50,100,250' && g.passes.every(x => x.usd === x.package) && g.passes.every(x => x.open) && g.passes.filter(x => x.tier !== 'weekly').every(x => x.sale === false), 'GET /api/admin/gamepass/preview: all five tiers (500 / 2000 / 5000 / 10000 / 25000, each price = its package), open to the admin, none on sale', JSON.stringify(g.passes.map(x => [x.tier, x.price, x.open, x.sale])));
|
||||||
|
ok((await api('/api/admin/gamepass/preview', null, hM)).status === 401 && (await api('/api/admin/gamepass/test-buy', { data: { tier: 'explorer' } }, hM)).status === 401, 'tier test endpoints refuse a member session (401)', '');
|
||||||
|
// test cancel + test comp + end, on the admin's own account
|
||||||
|
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'champion' } }, adminH);
|
||||||
|
ok(r.status === 200 && r.j.needPay && r.j.tier === 'champion' && r.j.email === ADMIN_EMAIL && r.j.package === 50, 'test-buy Champion: a waiting order for a $50 package on the admin account', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/admin/gamepass/test-cancel', { data: { tier: 'champion' } }, adminH);
|
||||||
|
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
|
||||||
|
ok(r.j.ok && r.j.order && !g.passes.find(x => x.tier === 'champion').waiting, 'test-cancel drops the Champion test order', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/admin/gamepass/test-comp', { data: { tier: 'champion' } }, adminH);
|
||||||
|
ok(r.j.ok && r.j.tier === 'champion' && r.j.email === ADMIN_EMAIL && r.j.until > Date.now(), 'test-comp Champion starts one period on the admin account at once', JSON.stringify(r.j));
|
||||||
|
r = await api('/api/admin/gamepass/revoke', { data: { email: ADMIN_EMAIL, tier: 'champion', why: 'admin tier test' } }, adminH);
|
||||||
|
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||||
|
ok(r.j.ok && !g.active && g.passes.length === 1, 'ending the test Champion puts the admin card back to the weekly member view', JSON.stringify({ a: g.active, rows: g.passes.map(x => x.tier) }));
|
||||||
|
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
|
||||||
|
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
|
||||||
|
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
|
||||||
|
const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForSelector('#gpTest [data-gpt-buy="explorer"]', { timeout: 10000 }).catch(() => {}); }
|
||||||
|
let txt = await page.textContent('#gpTest').catch(() => '');
|
||||||
|
ok(/Test \/ preview, admin only/.test(txt) && /hidden from members/.test(txt) && /Sovereign/.test(txt) && /Necromancer/.test(txt) && /Legend/.test(txt) && /\$250 /.test(txt) && /for 1 year/.test(txt) && /Archer/.test(txt) && /Druid/.test(txt) && /level cap 30/.test(txt) && /\$20 /.test(txt) && !/\.99/.test(txt) && /Shards of Valor > Passes/.test(txt) && !/\u2014/.test(txt) && errs.length === 0, 'Admin > Game Pass > Tier test and preview: labelled test/preview, all five tiers with what each includes, no em dashes', errs.join(' | ') || (nav ? '' : 'admin nav not found'));
|
||||||
|
await page.locator('#gpTestCard').scrollIntoViewIfNeeded(); await sleep(300);
|
||||||
|
await page.locator('#gpTestCard').screenshot({ path: path.join(SHOTS, '3-admin-tier-test-panel.png') });
|
||||||
|
await page.click('#gpTest [data-gpt-buy="explorer"]'); await page.waitForSelector('#dlgOk', { timeout: 5000 });
|
||||||
|
await page.screenshot({ path: path.join(SHOTS, '3b-admin-confirm-test-explorer.png') });
|
||||||
await page.click('#dlgOk');
|
await page.click('#dlgOk');
|
||||||
|
await page.waitForFunction(() => /test order waiting for a \$20 package/.test((document.getElementById('gpTest') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {});
|
||||||
|
txt = await page.textContent('#gpTest').catch(() => '');
|
||||||
|
ok(/test order waiting for a \$20 package/.test(txt) && errs.length === 0, 'Test buy Explorer from the admin panel: the card shows the waiting test order', errs.join(' | '));
|
||||||
|
await page.locator('#gpTestCard').screenshot({ path: path.join(SHOTS, '4-admin-test-order-waiting.png') }); await ctx.close(); }
|
||||||
|
let g1 = (await api('/api/admin/gamepass/preview', null, adminH)).j; const ex1 = g1.passes.find(x => x.tier === 'explorer');
|
||||||
|
ok(!g1.active && ex1 && ex1.waiting === true && !ex1.active, 'the click opened a waiting Explorer order; nothing active yet', JSON.stringify(ex1));
|
||||||
|
ok(!/gamepass bought with credits/.test(srvLog), 'no credit charge: the seeded purchased credits were not spent on the pass', '');
|
||||||
|
const dv0 = (await api('/api/dev/gamepass-purchase', { data: { cents: 2000, email: ADMIN_EMAIL } })).j;
|
||||||
|
ok(dv0 && dv0.order && dv0.order.tier === 'explorer', 'a fresh $20 package fulfils the Explorer test order', JSON.stringify(dv0));
|
||||||
|
// a HOLDER sees the tier on the member card the way any member holding it would (no preview note, nothing they cannot buy listed)
|
||||||
|
{ const { page, errs, ctx } = await pageFor(hA); await page.goto(B + '/my?from=shardsofvalor#passes');
|
||||||
await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {});
|
await page.waitForFunction(() => /Explorer active/.test((document.getElementById('gpCard') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {});
|
||||||
|
await sleep(600); await hide(page);
|
||||||
const after = await page.textContent('#gpCard');
|
const after = await page.textContent('#gpCard');
|
||||||
ok(/Explorer active/.test(after) && errs.length === 0, 'after the buy the card shows Explorer active (Central date)', errs.join(' | '));
|
ok(/#games/.test(page.url()), 'the Shards of Valor link (#passes) lands on the pass card, not the Buy pane', page.url());
|
||||||
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '4-admin-explorer-active.png') }); await ctx.close(); }
|
ok(/Explorer active/.test(after) && /never better than gear players can earn/.test(after) && /main story of Shards of Valor is free/.test(after) && !/Admin preview|Champion|Sovereign|Legend/.test(after) && !/\u2014/.test(after) && errs.length === 0, 'holder card: Explorer active, weekly + Explorer only, no admin preview, no em dashes', errs.join(' | '));
|
||||||
|
await page.locator('#gpCard').screenshot({ path: path.join(SHOTS, '5-admin-explorer-active-holder-card.png') }); await ctx.close(); }
|
||||||
g = (await api('/api/my/gamepass', null, hA)).j;
|
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||||
const ex = g.passes.find(x => x.tier === 'explorer');
|
const ex = g.passes.find(x => x.tier === 'explorer');
|
||||||
ok(g.active && g.tier === 'explorer' && ex.active && Math.abs(ex.until - (Date.now() + 30 * 86400000)) < 120000, 'GET /api/my/gamepass: tier explorer, 30 days', JSON.stringify({ tier: g.tier, until: ex && new Date(ex.until).toISOString() }));
|
ok(g.active && g.tier === 'explorer' && ex.active && Math.abs(ex.until - (Date.now() + 30 * 86400000)) < 120000, 'GET /api/my/gamepass: tier explorer, 30 days', JSON.stringify({ tier: g.tier, until: ex && new Date(ex.until).toISOString() }));
|
||||||
ok(/gamepass bought with credits explorer qa-admin@example.com 2000/.test(srvLog), 'paid through the real ads.gamePurchase(purchasedOnly) path, 2000 credits', '');
|
ok(/gamepass fulfilled by package explorer qa-admin@example.com/.test(srvLog), 'Explorer paid by the package rail, not credits', '');
|
||||||
r = await api('/api/my/gamepass/buy', { data: { tier: 'explorer' } }, hA);
|
|
||||||
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'explorer' && r.j.available === 500 && /\$20 package/.test(r.j.message), 'a second Explorer: only 500 purchased credits left -> waiting order, "$20 package"', JSON.stringify({ needPay: r.j.needPay, available: r.j.available, payUrl: r.j.payUrl }));
|
|
||||||
|
|
||||||
// 3. the Shards of Valor hand-off token and the partner player answer carry tier explorer
|
// 3. the Shards of Valor hand-off token and the partner player answer carry tier explorer
|
||||||
const ho = await api('/api/my/shardsofvalor', null, hA);
|
const ho = await api('/api/my/shardsofvalor', null, hA);
|
||||||
@@ -119,15 +164,43 @@ try {
|
|||||||
const gr = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 0.2, ref: 'qa:1' });
|
const gr = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 0.2, ref: 'qa:1' });
|
||||||
ok(gr.pass === true && gr.allowed === 0.2, 'polgrant: pass true (a boolean) for the Explorer holder', JSON.stringify(gr));
|
ok(gr.pass === true && gr.allowed === 0.2, 'polgrant: pass true (a boolean) for the Explorer holder', JSON.stringify(gr));
|
||||||
|
|
||||||
|
// 3b. Sovereign (10000 cents = $100, 30 days) and the yearly Legend (25000 = $250, 365 days), 2026-10-22: the admin buys Sovereign through the
|
||||||
|
// real charge, then is short for Legend (waiting order, $250 package) and for a second Explorer; a $250 package settles Legend.
|
||||||
|
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'sovereign' } }, adminH);
|
||||||
|
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'sovereign' && r.j.package === 100, 'admin Sovereign (sovTiers off, testing): a waiting order for a $100 package, credits untouched', JSON.stringify(r.j));
|
||||||
|
let dvS = (await api('/api/dev/gamepass-purchase', { data: { cents: 10000, email: ADMIN_EMAIL } })).j;
|
||||||
|
ok(dvS && dvS.order && dvS.order.tier === 'sovereign' && Math.abs(dvS.order.until - (Date.now() + 30 * 86400000)) < 120000, 'a fresh $100 package fulfils Sovereign: 30 days', JSON.stringify(dvS));
|
||||||
|
ok(!/gamepass bought with credits/.test(srvLog), 'still no credit charge anywhere', '');
|
||||||
|
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'explorer' } }, adminH);
|
||||||
|
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'explorer' && /package of \$20 or more/.test(r.j.message), 'a second Explorer -> waiting order, "package of $20 or more"', JSON.stringify({ needPay: r.j.needPay, payUrl: r.j.payUrl, msg: r.j.message }));
|
||||||
|
r = await api('/api/admin/gamepass/test-buy', { data: { tier: 'legend' } }, adminH);
|
||||||
|
ok(r.status === 200 && r.j.needPay === true && r.j.tier === 'legend' && r.j.price === 25000 && r.j.payUrl === '/my?from=gamepass&tier=legend#buy' && /package of \$250 or more/.test(r.j.message), 'Legend: waiting order, "package of $250 or more", payUrl with tier', JSON.stringify({ needPay: r.j.needPay, payUrl: r.j.payUrl, msg: r.j.message }));
|
||||||
|
let dv = (await api('/api/dev/gamepass-purchase', { data: { cents: 10000, email: ADMIN_EMAIL } })).j;
|
||||||
|
ok(dv && dv.order && dv.order.tier === 'explorer' && dv.order.until === ex.until + 30 * 86400000, 'a $100 package fulfils the waiting Explorer (extends it from its end), never Legend', JSON.stringify(dv));
|
||||||
|
g = (await api('/api/admin/gamepass/preview', null, adminH)).j;
|
||||||
|
ok(!g.passes.find(x => x.tier === 'legend').active && g.passes.find(x => x.tier === 'legend').waiting, 'Legend still waiting after a $100 package', JSON.stringify(g.passes.find(x => x.tier === 'legend')));
|
||||||
|
dv = (await api('/api/dev/gamepass-purchase', { data: { cents: 25000, email: ADMIN_EMAIL } })).j;
|
||||||
|
ok(dv && dv.order && dv.order.tier === 'legend' && Math.abs(dv.order.until - (Date.now() + 365 * 86400000)) < 120000, 'a $250 package fulfils the Legend order: a year', JSON.stringify(dv));
|
||||||
|
g = (await api('/api/my/gamepass', null, hA)).j;
|
||||||
|
const lg = g.passes.find(x => x.tier === 'legend'), sv = g.passes.find(x => x.tier === 'sovereign');
|
||||||
|
ok(g.active && g.tier === 'legend' && g.until === lg.until && lg.active && sv.active && lg.days === 365, 'GET /api/my/gamepass: tier legend (highest), Sovereign and Explorer still running underneath', JSON.stringify({ tier: g.tier, l: lg.until, s: sv.until }));
|
||||||
|
const ho2 = await api('/api/my/shardsofvalor', null, hA); const t2 = new URL(ho2.headers.get('location') || 'http://x/').searchParams.get('t'); const c2 = t2 ? decode(t2) : null;
|
||||||
|
ok(c2 && c2.gamePass && c2.gamePass.active === true && c2.gamePass.tier === 'legend' && c2.gamePass.until === lg.until, 'hand-off token: gamePass { active, until, tier: legend }', JSON.stringify(c2 && c2.gamePass));
|
||||||
|
const pl2 = await playerOf(ADMIN_EMAIL);
|
||||||
|
ok(pl2.status === 200 && pl2.j.pass.tier === 'legend' && pl2.j.pass.tiers.legend === lg.until && pl2.j.pass.tiers.sovereign === sv.until && pl2.j.pass.tiers.explorer === ex.until + 30 * 86400000 && pl2.j.pass.tiers.champion === null && pl2.j.caps.daily === 1.5 && pl2.j.caps.total === 5, 'GET /api/partner/player: tier legend, tiers carry sovereign + legend, weekly pass caps 1.50 / 5', JSON.stringify(pl2.j.pass));
|
||||||
|
const gr2 = await grant({ memberId: 0, email: ADMIN_EMAIL, game: 'shardsofvalor', kind: 'daily', pol: 5, ref: 'qa:2' });
|
||||||
|
ok(gr2.pass === true && gr2.enforced === false && gr2.allowed === 5, 'polgrant: pass true (a boolean) for the Legend holder (caps not enforced on this copy: no capsStartDate; the cap values are the player answer above)', JSON.stringify(gr2));
|
||||||
|
|
||||||
// 4. Admin > Game Pass: the tier table
|
// 4. Admin > Game Pass: the tier table
|
||||||
const st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
|
const st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
|
||||||
ok(st.tiers && st.tiers.explorer.active === 1 && st.tiers.explorer.soldTotal === 1 && st.tiers.explorer.usdTotal === 20 && st.tiers.explorer.waitingOrders === 1 && st.tierSales === false, 'admin stats: Explorer 1 active, 1 sold ($20), 1 waiting; sale switch off', JSON.stringify(st.tiers.explorer));
|
ok(st.tiers && st.tiers.explorer.active === 0 && st.tiers.explorer.soldTotal === 2 && st.tiers.explorer.usdTotal === 40 && st.tiers.explorer.waitingOrders === 0 && st.tierSales === false, 'admin stats: Explorer 2 sold ($40: credits + the $100 package order), not counted active (the account is at Legend); sale switch off', JSON.stringify(st.tiers.explorer));
|
||||||
|
ok(st.tiers.sovereign && st.tiers.sovereign.active === 0 && st.tiers.sovereign.soldTotal === 1 && st.tiers.sovereign.usdTotal === 100 && st.tiers.legend.active === 1 && st.tiers.legend.soldTotal === 1 && st.tiers.legend.usdTotal === 250 && st.tiers.legend.waitingOrders === 0 && st.settings.tiers.legend.days === 365 && st.settings.tiers.sovereign.sale === false, 'admin stats: Sovereign 1 sold ($100), Legend 1 active + 1 sold ($250), not on sale', JSON.stringify({ s: st.tiers.sovereign, l: st.tiers.legend }));
|
||||||
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
|
{ const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } }); const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(String(e)));
|
||||||
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
|
await page.goto(B + '/admin', { waitUntil: 'networkidle' });
|
||||||
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
|
await page.fill('#adEmail', ADMIN_EMAIL); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await sleep(1200);
|
||||||
const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForFunction(() => /Explorer/.test((document.getElementById('gpTiers') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {}); }
|
const nav = await page.$('.bo-menu [data-pane="gamepass"]'); if (nav) { await nav.click(); await page.waitForFunction(() => /Explorer/.test((document.getElementById('gpTiers') || {}).textContent || ''), null, { timeout: 10000 }).catch(() => {}); }
|
||||||
const txt = await page.textContent('#gpTiers').catch(() => '');
|
const txt = await page.textContent('#gpTiers').catch(() => '');
|
||||||
ok(/Explorer/.test(txt) && /Champion/.test(txt), 'Admin > Game Pass renders the per-tier table', errs.join(' | ') || (nav ? '' : 'admin nav not found (sign-in flow)'));
|
ok(/Explorer/.test(txt) && /Champion/.test(txt) && /Sovereign/.test(txt) && /Legend/.test(txt) && /365 d/.test(txt), 'Admin > Game Pass renders the per-tier table (all five, Legend 365 d)', errs.join(' | ') || (nav ? '' : 'admin nav not found (sign-in flow)'));
|
||||||
await sleep(800); await page.locator('#gpTiers').evaluate(e => e.closest('.card').scrollIntoView()); await sleep(400); await page.locator('#gpTiers').evaluate(e => e.closest('.card').id = 'gpTiersCard'); await page.locator('#gpTiersCard').screenshot({ path: path.join(SHOTS, '5-admin-gamepass-tiers.png') }); await ctx.close(); }
|
await sleep(800); await page.locator('#gpTiers').evaluate(e => e.closest('.card').scrollIntoView()); await sleep(400); await page.locator('#gpTiers').evaluate(e => e.closest('.card').id = 'gpTiersCard'); await page.locator('#gpTiersCard').screenshot({ path: path.join(SHOTS, '5-admin-gamepass-tiers.png') }); await ctx.close(); }
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('FAIL harness error', e && e.stack || e); fails++;
|
console.error('FAIL harness error', e && e.stack || e); fails++;
|
||||||
|
|||||||
+146
-38
@@ -1,9 +1,11 @@
|
|||||||
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md section 8): unit checks of the gamepass.js store, no server.
|
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md section 8): unit checks of the gamepass.js store, no server.
|
||||||
// node qa/sov-passes-store.cjs
|
// node qa/sov-passes-store.cjs
|
||||||
// Loads gamepass.js with in-memory maps and a fake site config. Covers: lazy migration of a weekly-only record, buy per tier,
|
// Loads gamepass.js with in-memory maps and a fake site config. Since 2026-10-22 every "buy" is an order + a fresh package (buyX). Covers: lazy migration of a weekly-only record, buy per tier,
|
||||||
// extend from max(now, until), side-by-side expiry, highest active tier wins, the sovTiers switch (off refuses, admin may buy),
|
// extend from max(now, until), side-by-side expiry, highest active tier wins, the sovTiers switch (off refuses, admin may buy),
|
||||||
// waiting orders per tier fulfilled by a big-enough package (each tx once, highest price first), the same caps for every tier
|
// waiting orders per tier fulfilled by a big-enough package (each tx once, highest price first), the same caps for every tier
|
||||||
// (no extra POL), comp and revoke, admin stats per tier (each account once at its top tier, Central week/month). Exit 1 on failure.
|
// (no extra POL), comp and revoke, admin stats per tier (each account once at its top tier, Central week/month). Exit 1 on failure.
|
||||||
|
// 2026-10-22: section 10 adds Sovereign (10000 / 30 days) and the yearly Legend (25000 / 365 days; prices = packages since 2026-10-25): rank, off-switch refusal,
|
||||||
|
// buy, short -> waiting order ($100 / $250 package), extend from max(now, until), kill switches, comp/revoke, flag payload, stats.
|
||||||
'use strict';
|
'use strict';
|
||||||
const fs = require('fs'); const os = require('os'); const path = require('path');
|
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||||
const gp = require('../gamepass');
|
const gp = require('../gamepass');
|
||||||
@@ -16,8 +18,20 @@ gp.init({ dataDir, siteConfig: () => Object.assign({}, SC), persistedMap: k => (
|
|||||||
accounts: { byMemberId: async () => null, byEmail: async () => null }, marks: { claim: async () => true }, polUsd: async () => 0.1, telegram: async () => {}, notify: async () => {} });
|
accounts: { byMemberId: async () => null, byEmail: async () => null }, marks: { claim: async () => true }, polUsd: async () => 0.1, telegram: async () => {}, notify: async () => {} });
|
||||||
const passes = maps.gamepass, orders = maps.gporders;
|
const passes = maps.gamepass, orders = maps.gporders;
|
||||||
const T0 = Date.parse('2026-10-20T17:00:00Z'); // Tue Oct 20, noon Central
|
const T0 = Date.parse('2026-10-20T17:00:00Z'); // Tue Oct 20, noon Central
|
||||||
const paid = async () => ({ ok: true, campaignId: 1 });
|
// 2026-10-22: no pass is bought with credits any more. buy() only opens a waiting order; a fresh package Purchase fulfils it.
|
||||||
const short = async () => ({ error: 'short', available: 0, need: 1 });
|
// buyX keeps the old test shape: `short` = the member opens the order and pays nothing yet; any other payer (paid / a spy) = the member
|
||||||
|
// opens the order and then buys a package of exactly the pass price, mined at `now` (the spy sees the price and the pass label).
|
||||||
|
const paid = async () => ({ ok: true });
|
||||||
|
const short = async () => ({ error: 'short' });
|
||||||
|
let txN = 0;
|
||||||
|
async function buyX(email, payer, now, tier, opts) {
|
||||||
|
const r = gp.buy(email, now, tier, opts); if (r.error || payer === short) return r;
|
||||||
|
const t = r.tier; const days = gp.cfg().tiers[t].days;
|
||||||
|
await payer(r.price, (t === 'weekly' ? 'Game Pass' : gp.TIER_NAMES[t] + ' pass') + ' (' + days + ' days)');
|
||||||
|
const ev = await gp.onEvent({ type: 'Purchase', priceCents: r.price, tx: '0xpkg' + (++txN), ts: now, devEmail: email, devMinedAt: now, devNow: now });
|
||||||
|
if (!ev) return { error: 'package did not fulfil the order', r };
|
||||||
|
return { ok: true, tier: ev.tier, until: ev.until, days, paid: 'package' };
|
||||||
|
}
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
// 1. migration: a record from before tiers (until only) reads as the weekly tier; flag answers as before plus tier
|
// 1. migration: a record from before tiers (until only) reads as the weekly tier; flag answers as before plus tier
|
||||||
@@ -27,47 +41,48 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
f = gp.flag('old@x.com', T0 + 5 * DAY);
|
f = gp.flag('old@x.com', T0 + 5 * DAY);
|
||||||
ok(f.active === false && f.tier === null && f.until === T0 + 3 * DAY, 'expired weekly-only record: inactive, until kept as before tiers, tier null', JSON.stringify(f));
|
ok(f.active === false && f.tier === null && f.until === T0 + 3 * DAY, 'expired weekly-only record: inactive, until kept as before tiers, tier null', JSON.stringify(f));
|
||||||
f = gp.flag('never@x.com', T0); ok(f.active === false && f.until === null && f.tier === null, 'never bought: { active false, until null, tier null }', JSON.stringify(f));
|
f = gp.flag('never@x.com', T0); ok(f.active === false && f.until === null && f.tier === null, 'never bought: { active false, until null, tier null }', JSON.stringify(f));
|
||||||
await gp.buy('old@x.com', paid, T0, 'weekly');
|
await buyX('old@x.com', paid, T0, 'weekly');
|
||||||
const oldRec = passes.get('old@x.com');
|
const oldRec = passes.get('old@x.com');
|
||||||
ok(oldRec.tiers && oldRec.tiers.weekly.until === T0 + 10 * DAY && oldRec.until === T0 + 10 * DAY, 'buying weekly on a migrated record extends from its until and writes tiers + legacy until', JSON.stringify({ until: oldRec.until, tiers: oldRec.tiers }));
|
ok(oldRec.tiers && oldRec.tiers.weekly.until === T0 + 10 * DAY && oldRec.until === T0 + 10 * DAY, 'buying weekly on a migrated record extends from its until and writes tiers + legacy until', JSON.stringify({ until: oldRec.until, tiers: oldRec.tiers }));
|
||||||
|
|
||||||
// 2. the switch: off refuses Explorer/Champion for members, the weekly pass is unchanged; the admin may buy
|
// 2. the switch: off refuses Explorer/Champion for members, the weekly pass is unchanged; the admin may buy
|
||||||
let r = await gp.buy('a@x.com', paid, T0, 'explorer');
|
let r = await buyX('a@x.com', paid, T0, 'explorer');
|
||||||
ok(r.error === 'The Explorer pass is not open yet.', 'sovTiers off: Explorer refused', JSON.stringify(r));
|
ok(r.error === 'The Explorer pass is not open yet.', 'sovTiers off: Explorer refused', JSON.stringify(r));
|
||||||
r = await gp.buy('a@x.com', paid, T0, 'champion');
|
r = await buyX('a@x.com', paid, T0, 'champion');
|
||||||
ok(r.error === 'The Champion pass is not open yet.', 'sovTiers off: Champion refused', JSON.stringify(r));
|
ok(r.error === 'The Champion pass is not open yet.', 'sovTiers off: Champion refused', JSON.stringify(r));
|
||||||
ok(!passes.get('a@x.com'), 'a refused buy writes nothing', '');
|
ok(!passes.get('a@x.com'), 'a refused buy writes nothing', '');
|
||||||
let v = gp.view('a@x.com', T0);
|
let v = gp.view('a@x.com', T0);
|
||||||
ok(v.passes.length === 1 && v.passes[0].tier === 'weekly' && v.show === true && v.tierPreview === false, 'sovTiers off: a member sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier)));
|
ok(v.passes.length === 1 && v.passes[0].tier === 'weekly' && v.show === true && v.tierPreview === false, 'sovTiers off: a member sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier)));
|
||||||
v = gp.view('admin@x.com', T0, { admin: true });
|
v = gp.view('admin@x.com', T0); ok(v.passes.length === 1 && !v.tierPreview, 'the member view (GET /api/my/gamepass) is the same for the admin account: weekly only (2026-10-25)', JSON.stringify(v.passes.map(x => x.tier)));
|
||||||
ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion' && v.tierPreview === true && v.passes[1].open === true && v.passes[1].price === 2000 && v.passes[2].price === 4000 && v.passes[1].days === 30, 'sovTiers off: the admin sees all three (preview), prices 2000 / 4000, 30 days', JSON.stringify(v.passes));
|
v = gp.view('admin@x.com', T0, { preview: true }); // Admin > Game Pass > Tier test and preview
|
||||||
r = await gp.buy('admin@x.com', paid, T0, 'explorer', { admin: true });
|
ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign,legend' && v.tierPreview === true && v.passes.slice(1).every(x => x.open === true) && v.passes.map(x => x.price).join() === '500,2000,5000,10000,25000' && v.passes.map(x => x.days).join() === '7,30,30,30,365' && v.passes.map(x => x.package).join() === '5,20,50,100,250', 'sovTiers off: the admin sees all five (preview), prices 500 / 2000 / 5000 / 10000 / 25000, days 7 / 30 / 30 / 30 / 365, packages $5 / $20 / $50 / $100 / $250', JSON.stringify(v.passes));
|
||||||
|
r = await buyX('admin@x.com', paid, T0, 'explorer', { preview: true });
|
||||||
ok(r.ok && r.tier === 'explorer' && r.until === T0 + 30 * DAY && r.days === 30, 'sovTiers off: the admin can buy Explorer (testing)', JSON.stringify(r));
|
ok(r.ok && r.tier === 'explorer' && r.until === T0 + 30 * DAY && r.days === 30, 'sovTiers off: the admin can buy Explorer (testing)', JSON.stringify(r));
|
||||||
r = await gp.buy('a@x.com', paid, T0); // tier missing = weekly
|
r = await buyX('a@x.com', paid, T0); // tier missing = weekly
|
||||||
ok(r.ok && r.tier === 'weekly' && r.until === T0 + 7 * DAY && r.days === 7, 'tier missing = weekly: 500 credits, 7 days, as before', JSON.stringify(r));
|
ok(r.ok && r.tier === 'weekly' && r.until === T0 + 7 * DAY && r.days === 7, 'tier missing = weekly: 500 credits, 7 days, as before', JSON.stringify(r));
|
||||||
let charged = null; await gp.buy('z@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0);
|
let charged = null; await buyX('z@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0);
|
||||||
ok(charged && charged.price === 500 && charged.label === 'Game Pass (7 days)', 'weekly charge unchanged: 500 credits, label "Game Pass (7 days)"', JSON.stringify(charged));
|
ok(charged && charged.price === 500 && charged.label === 'Game Pass (7 days)', 'weekly charge unchanged: 500 credits, label "Game Pass (7 days)"', JSON.stringify(charged));
|
||||||
r = await gp.buy('a@x.com', paid, T0, 'platinum'); ok(r.error === 'There is no such pass.', 'unknown tier refused', JSON.stringify(r));
|
r = await buyX('a@x.com', paid, T0, 'platinum'); ok(r.error === 'There is no such pass.', 'unknown tier refused', JSON.stringify(r));
|
||||||
SC.gamePassEnabled = '0'; SC.sovTiers = '1';
|
SC.gamePassEnabled = '0'; SC.sovTiers = '1';
|
||||||
r = await gp.buy('a@x.com', paid, T0, 'explorer'); ok(!!r.error, 'sovTiers on but the weekly Game Pass off: Explorer refused for members', JSON.stringify(r));
|
r = await buyX('a@x.com', paid, T0, 'explorer'); ok(!!r.error, 'sovTiers on but the weekly Game Pass off: Explorer refused for members', JSON.stringify(r));
|
||||||
SC.gamePassEnabled = '1';
|
SC.gamePassEnabled = '1';
|
||||||
|
|
||||||
// 3. on: each tier extends only itself; buying again extends from max(now, until)
|
// 3. on: each tier extends only itself; buying again extends from max(now, until)
|
||||||
charged = null; r = await gp.buy('b@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0, 'explorer');
|
charged = null; r = await buyX('b@x.com', async (price, label) => { charged = { price, label }; return { ok: true }; }, T0, 'explorer');
|
||||||
ok(r.ok && r.until === T0 + 30 * DAY && charged.price === 2000 && charged.label === 'Explorer pass (30 days)', 'sovTiers on: Explorer charges 2000 credits, 30 days', JSON.stringify(charged));
|
ok(r.ok && r.until === T0 + 30 * DAY && charged.price === 2000 && charged.label === 'Explorer pass (30 days)', 'sovTiers on: Explorer charges 2000 credits, 30 days', JSON.stringify(charged));
|
||||||
let rec = passes.get('b@x.com');
|
let rec = passes.get('b@x.com');
|
||||||
ok(rec.tiers.explorer.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.champion && rec.until === 0 && rec.bought[0].tier === 'explorer' && rec.bought[0].usd === 20, 'only the Explorer tier moved; legacy until (weekly) stays 0; bought row has tier + $20', JSON.stringify(rec));
|
ok(rec.tiers.explorer.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.champion && rec.until === 0 && rec.bought[0].tier === 'explorer' && rec.bought[0].usd === 20, 'only the Explorer tier moved; legacy until (weekly) stays 0; bought row has tier + $20', JSON.stringify(rec));
|
||||||
r = await gp.buy('b@x.com', paid, T0 + 10 * DAY, 'explorer');
|
r = await buyX('b@x.com', paid, T0 + 10 * DAY, 'explorer');
|
||||||
ok(r.until === T0 + 60 * DAY, 'Explorer again while active: extends from its until (+30 days, nothing lost)', new Date(r.until).toISOString());
|
ok(r.until === T0 + 60 * DAY, 'Explorer again while active: extends from its until (+30 days, nothing lost)', new Date(r.until).toISOString());
|
||||||
r = await gp.buy('c@x.com', paid, T0, 'champion'); ok(r.ok && r.until === T0 + 30 * DAY, 'Champion: 30 days', '');
|
r = await buyX('c@x.com', paid, T0, 'champion'); ok(r.ok && r.until === T0 + 30 * DAY, 'Champion: 30 days', '');
|
||||||
r = await gp.buy('c@x.com', paid, T0 + 45 * DAY, 'champion');
|
r = await buyX('c@x.com', paid, T0 + 45 * DAY, 'champion');
|
||||||
ok(r.until === T0 + 75 * DAY, 'Champion again after it ended: extends from now', new Date(r.until).toISOString());
|
ok(r.until === T0 + 75 * DAY, 'Champion again after it ended: extends from now', new Date(r.until).toISOString());
|
||||||
charged = null; await gp.buy('c2@x.com', async (price) => { charged = price; return { ok: true }; }, T0, 'champion'); ok(charged === 4000, 'Champion charges 4000 credits', String(charged));
|
charged = null; await buyX('c2@x.com', async (price) => { charged = price; return { ok: true }; }, T0, 'champion'); ok(charged === 5000, 'Champion charges 5000 credits', String(charged));
|
||||||
|
|
||||||
// 4. side by side: Champion over Explorer, then Explorer shows through; weekly underneath
|
// 4. side by side: Champion over Explorer, then Explorer shows through; weekly underneath
|
||||||
await gp.buy('d@x.com', paid, T0, 'weekly'); // weekly to T0+7
|
await buyX('d@x.com', paid, T0, 'weekly'); // weekly to T0+7
|
||||||
await gp.buy('d@x.com', paid, T0, 'explorer'); // explorer to T0+30
|
await buyX('d@x.com', paid, T0, 'explorer'); // explorer to T0+30
|
||||||
await gp.buy('d@x.com', paid, T0 - 20 * DAY, 'champion'); // champion bought earlier, to T0+10
|
await buyX('d@x.com', paid, T0 - 20 * DAY, 'champion'); // champion bought earlier, to T0+10
|
||||||
f = gp.flag('d@x.com', T0 + DAY);
|
f = gp.flag('d@x.com', T0 + DAY);
|
||||||
ok(f.tier === 'champion' && f.until === T0 + 10 * DAY && f.active && f.tiers.weekly === T0 + 7 * DAY && f.tiers.explorer === T0 + 30 * DAY && f.tiers.champion === T0 + 10 * DAY, 'all three on: tier champion, until = Champion end, tiers side by side', JSON.stringify(f));
|
ok(f.tier === 'champion' && f.until === T0 + 10 * DAY && f.active && f.tiers.weekly === T0 + 7 * DAY && f.tiers.explorer === T0 + 30 * DAY && f.tiers.champion === T0 + 10 * DAY, 'all three on: tier champion, until = Champion end, tiers side by side', JSON.stringify(f));
|
||||||
f = gp.flag('d@x.com', T0 + 12 * DAY);
|
f = gp.flag('d@x.com', T0 + 12 * DAY);
|
||||||
@@ -76,7 +91,7 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
|
|
||||||
// 5. no extra POL: the caps are identical for weekly, explorer and champion holders (and higher than free)
|
// 5. no extra POL: the caps are identical for weekly, explorer and champion holders (and higher than free)
|
||||||
const day = '2026-10-21'; const at = Date.parse(day + 'T17:00:00Z');
|
const day = '2026-10-21'; const at = Date.parse(day + 'T17:00:00Z');
|
||||||
await gp.buy('w@x.com', paid, at, 'weekly'); await gp.buy('e@x.com', paid, at, 'explorer'); await gp.buy('ch@x.com', paid, at, 'champion');
|
await buyX('w@x.com', paid, at, 'weekly'); await buyX('e@x.com', paid, at, 'explorer'); await buyX('ch@x.com', paid, at, 'champion');
|
||||||
const capsOf = e => { const c = gp.capsFor(e, at); return [c.pass, c.daily, c.total].join('/'); };
|
const capsOf = e => { const c = gp.capsFor(e, at); return [c.pass, c.daily, c.total].join('/'); };
|
||||||
ok(capsOf('w@x.com') === capsOf('e@x.com') && capsOf('e@x.com') === capsOf('ch@x.com') && capsOf('w@x.com') === 'true/1.5/5' && capsOf('free@x.com') === 'false/0.3/2', 'capsFor: weekly = explorer = champion = pass caps 1.50 / 5', [capsOf('w@x.com'), capsOf('e@x.com'), capsOf('ch@x.com'), capsOf('free@x.com')].join(' '));
|
ok(capsOf('w@x.com') === capsOf('e@x.com') && capsOf('e@x.com') === capsOf('ch@x.com') && capsOf('w@x.com') === 'true/1.5/5' && capsOf('free@x.com') === 'false/0.3/2', 'capsFor: weekly = explorer = champion = pass caps 1.50 / 5', [capsOf('w@x.com'), capsOf('e@x.com'), capsOf('ch@x.com'), capsOf('free@x.com')].join(' '));
|
||||||
const g = e => gp.grant({ email: e, game: 'polhunter', kind: 'daily', pol: 3, ref: 'cap:' + e, now: at });
|
const g = e => gp.grant({ email: e, game: 'polhunter', kind: 'daily', pol: 3, ref: 'cap:' + e, now: at });
|
||||||
@@ -84,14 +99,14 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
ok(gw.allowed === 1.5 && ge.allowed === 1.5 && gc.allowed === 1.5 && gw.pass && ge.pass && gc.pass, 'polgrant: a 3 POL daily grant allows 1.50 for every tier, pass: true (a boolean)', [gw.allowed, ge.allowed, gc.allowed, typeof gc.pass].join(' '));
|
ok(gw.allowed === 1.5 && ge.allowed === 1.5 && gc.allowed === 1.5 && gw.pass && ge.pass && gc.pass, 'polgrant: a 3 POL daily grant allows 1.50 for every tier, pass: true (a boolean)', [gw.allowed, ge.allowed, gc.allowed, typeof gc.pass].join(' '));
|
||||||
|
|
||||||
// 6. waiting orders per tier; a package of at least the tier price fulfils it; each tx once; highest-priced first
|
// 6. waiting orders per tier; a package of at least the tier price fulfils it; each tx once; highest-priced first
|
||||||
r = await gp.buy('p@x.com', short, T0, 'explorer');
|
r = await buyX('p@x.com', short, T0, 'explorer');
|
||||||
ok(r.needPay && r.tier === 'explorer' && r.payUrl === '/my?from=gamepass&tier=explorer#buy' && r.package === 20 && /\$20 package/.test(r.message), 'Explorer short: waiting order, payUrl with tier, "$20 package"', JSON.stringify({ payUrl: r.payUrl, msg: r.message }));
|
ok(r.needPay && r.tier === 'explorer' && r.payUrl === '/my?from=gamepass&tier=explorer#buy' && r.package === 20 && /package of \$20 or more/.test(r.message), 'Explorer short: waiting order, payUrl with tier, "$20 package"', JSON.stringify({ payUrl: r.payUrl, msg: r.message }));
|
||||||
const ordE = r.order;
|
const ordE = r.order;
|
||||||
r = await gp.buy('p@x.com', short, T0, 'explorer'); ok(r.order === ordE, 'same tier again reuses its waiting order', '');
|
r = await buyX('p@x.com', short, T0, 'explorer'); ok(r.order === ordE, 'same tier again reuses its waiting order', '');
|
||||||
r = await gp.buy('p@x.com', short, T0, 'champion'); const ordC = r.order;
|
r = await buyX('p@x.com', short, T0, 'champion'); const ordC = r.order;
|
||||||
ok(r.needPay && r.order !== ordE && r.package === 50 && /\$50 package/.test(r.message), 'Champion short: its own waiting order; copy names the $50 package (there is no $40 one)', r.message);
|
ok(r.needPay && r.order !== ordE && r.package === 50 && /package of \$50 or more/.test(r.message), 'Champion short: its own waiting order; copy names the $50 package (exactly the price since 2026-10-25)', r.message);
|
||||||
r = await gp.buy('p@x.com', short, T0, 'weekly');
|
r = await buyX('p@x.com', short, T0, 'weekly');
|
||||||
ok(r.payUrl === '/my?from=gamepass#buy' && /Buy a \$5 package/.test(r.message), 'weekly short: payUrl and copy exactly as before', r.payUrl);
|
ok(r.payUrl === '/my?from=gamepass#buy' && /package of \$5 or more/.test(r.message), 'weekly short: payUrl and copy exactly as before', r.payUrl);
|
||||||
let ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xa1', ts: T0 + 60000, devEmail: 'p@x.com' });
|
let ev = await gp.onEvent({ type: 'Purchase', priceCents: 500, tx: '0xa1', ts: T0 + 60000, devEmail: 'p@x.com' });
|
||||||
ok(ev && ev.tier === 'weekly', 'a $5 package fulfils the weekly order, not Explorer or Champion', JSON.stringify(ev));
|
ok(ev && ev.tier === 'weekly', 'a $5 package fulfils the weekly order, not Explorer or Champion', JSON.stringify(ev));
|
||||||
ev = await gp.onEvent({ type: 'Purchase', priceCents: 1000, tx: '0xa2', ts: T0 + 60000, devEmail: 'p@x.com' });
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 1000, tx: '0xa2', ts: T0 + 60000, devEmail: 'p@x.com' });
|
||||||
@@ -102,7 +117,7 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
ok(ev === null, 'the same tx again counts once', JSON.stringify(ev));
|
ok(ev === null, 'the same tx again counts once', JSON.stringify(ev));
|
||||||
ev = await gp.onEvent({ type: 'Purchase', priceCents: 5000, tx: '0xa4', ts: T0 + 60000, devEmail: 'p@x.com' });
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 5000, tx: '0xa4', ts: T0 + 60000, devEmail: 'p@x.com' });
|
||||||
ok(ev && ev.tier === 'champion' && ev.order === ordC, 'a $50 package fulfils the Champion order', JSON.stringify(ev));
|
ok(ev && ev.tier === 'champion' && ev.order === ordC, 'a $50 package fulfils the Champion order', JSON.stringify(ev));
|
||||||
await gp.buy('q@x.com', short, T0, 'weekly'); await gp.buy('q@x.com', short, T0, 'explorer'); await gp.buy('q@x.com', short, T0, 'champion');
|
await buyX('q@x.com', short, T0, 'weekly'); await buyX('q@x.com', short, T0, 'explorer'); await buyX('q@x.com', short, T0, 'champion');
|
||||||
ev = await gp.onEvent({ type: 'Purchase', priceCents: 2000, tx: '0xb1', ts: T0, devEmail: 'q@x.com' });
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 2000, tx: '0xb1', ts: T0, devEmail: 'q@x.com' });
|
||||||
ok(ev && ev.tier === 'explorer', 'three orders waiting, a $20 package: the highest-priced one it covers (Explorer) is fulfilled first', JSON.stringify(ev));
|
ok(ev && ev.tier === 'explorer', 'three orders waiting, a $20 package: the highest-priced one it covers (Explorer) is fulfilled first', JSON.stringify(ev));
|
||||||
ev = await gp.onEvent({ type: 'Purchase', priceCents: 50000, tx: '0xb2', ts: T0, devEmail: 'q@x.com' });
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 50000, tx: '0xb2', ts: T0, devEmail: 'q@x.com' });
|
||||||
@@ -124,16 +139,16 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
// 8. admin stats: each account once at its top tier, Central week and month
|
// 8. admin stats: each account once at its top tier, Central week and month
|
||||||
for (const k of [...passes.keys()]) passes.delete(k); for (const k of [...orders.keys()]) orders.delete(k);
|
for (const k of [...passes.keys()]) passes.delete(k); for (const k of [...orders.keys()]) orders.delete(k);
|
||||||
const NOW = Date.parse('2026-11-04T18:00:00Z'); // Wed Nov 4, noon Central (CST); week from Mon Nov 2, month from Nov 1
|
const NOW = Date.parse('2026-11-04T18:00:00Z'); // Wed Nov 4, noon Central (CST); week from Mon Nov 2, month from Nov 1
|
||||||
await gp.buy('s1@x.com', paid, Date.parse('2026-11-02T06:30:00Z'), 'weekly'); // Mon Nov 2 00:30 Central: this week
|
await buyX('s1@x.com', paid, Date.parse('2026-11-02T06:30:00Z'), 'weekly'); // Mon Nov 2 00:30 Central: this week
|
||||||
await gp.buy('s1@x.com', paid, Date.parse('2026-11-02T05:30:00Z'), 'explorer'); // Sun Nov 1 23:30 Central: last week, this month
|
await buyX('s1@x.com', paid, Date.parse('2026-11-02T05:30:00Z'), 'explorer'); // Sun Nov 1 23:30 Central: last week, this month
|
||||||
await gp.buy('s2@x.com', paid, Date.parse('2026-11-01T04:30:00Z'), 'champion'); // Oct 31 23:30 Central: last month
|
await buyX('s2@x.com', paid, Date.parse('2026-11-01T04:30:00Z'), 'champion'); // Oct 31 23:30 Central: last month
|
||||||
await gp.buy('s2@x.com', paid, Date.parse('2026-11-03T18:00:00Z'), 'champion'); // a renewal this week
|
await buyX('s2@x.com', paid, Date.parse('2026-11-03T18:00:00Z'), 'champion'); // a renewal this week
|
||||||
await gp.buy('s3@x.com', paid, NOW - 2 * DAY, 'weekly'); // ends within 7 Central days
|
await buyX('s3@x.com', paid, NOW - 2 * DAY, 'weekly'); // ends within 7 Central days
|
||||||
gp.comp('s4@x.com', 'qa', 'explorer', NOW - DAY);
|
gp.comp('s4@x.com', 'qa', 'explorer', NOW - DAY);
|
||||||
await gp.buy('s5@x.com', short, NOW, 'champion');
|
await buyX('s5@x.com', short, NOW, 'champion');
|
||||||
const st = gp.adminStats(NOW); const S = st.tiers;
|
const st = gp.adminStats(NOW); const S = st.tiers;
|
||||||
ok(S.weekly.active === 1 && S.explorer.active === 2 && S.champion.active === 1, 'active counts each account once at its top tier (s1 = explorer, not weekly)', JSON.stringify({ w: S.weekly.active, e: S.explorer.active, c: S.champion.active }));
|
ok(S.weekly.active === 1 && S.explorer.active === 2 && S.champion.active === 1, 'active counts each account once at its top tier (s1 = explorer, not weekly)', JSON.stringify({ w: S.weekly.active, e: S.explorer.active, c: S.champion.active }));
|
||||||
ok(S.weekly.soldWeek === 2 && S.explorer.soldWeek === 0 && S.explorer.soldMonth === 1 && S.champion.soldWeek === 1 && S.champion.soldMonth === 1 && S.champion.soldTotal === 2 && S.champion.usdTotal === 80, 'Central week (from Mon 00:00) and month (from the 1st 00:00) boundaries', JSON.stringify({ w: [S.weekly.soldWeek, S.weekly.soldMonth], e: [S.explorer.soldWeek, S.explorer.soldMonth], c: [S.champion.soldWeek, S.champion.soldMonth, S.champion.soldTotal, S.champion.usdTotal] }));
|
ok(S.weekly.soldWeek === 2 && S.explorer.soldWeek === 0 && S.explorer.soldMonth === 1 && S.champion.soldWeek === 1 && S.champion.soldMonth === 1 && S.champion.soldTotal === 2 && S.champion.usdTotal === 100, 'Central week (from Mon 00:00) and month (from the 1st 00:00) boundaries', JSON.stringify({ w: [S.weekly.soldWeek, S.weekly.soldMonth], e: [S.explorer.soldWeek, S.explorer.soldMonth], c: [S.champion.soldWeek, S.champion.soldMonth, S.champion.soldTotal, S.champion.usdTotal] }));
|
||||||
ok(S.champion.renewals30d === 1 && S.weekly.renewals30d === 0, 'renewals30d: a second Champion purchase by a Champion holder', String(S.champion.renewals30d));
|
ok(S.champion.renewals30d === 1 && S.weekly.renewals30d === 0, 'renewals30d: a second Champion purchase by a Champion holder', String(S.champion.renewals30d));
|
||||||
ok(S.weekly.expiring7d === 2 && S.explorer.comped === 1 && S.champion.waitingOrders === 1, 'expiring7d (weekly passes ending in 7 Central days), comped, waiting orders per tier', JSON.stringify({ exp: S.weekly.expiring7d, comped: S.explorer.comped, wait: S.champion.waitingOrders }));
|
ok(S.weekly.expiring7d === 2 && S.explorer.comped === 1 && S.champion.waitingOrders === 1, 'expiring7d (weekly passes ending in 7 Central days), comped, waiting orders per tier', JSON.stringify({ exp: S.weekly.expiring7d, comped: S.explorer.comped, wait: S.champion.waitingOrders }));
|
||||||
ok(st.passes.active === 4 && st.passes.soldTotal === 5 && st.passes.comped === 1 && st.passes.waitingOrders === 1, 'the existing all-tier passes block still adds up', JSON.stringify(st.passes));
|
ok(st.passes.active === 4 && st.passes.soldTotal === 5 && st.passes.comped === 1 && st.passes.waitingOrders === 1, 'the existing all-tier passes block still adds up', JSON.stringify(st.passes));
|
||||||
@@ -143,7 +158,100 @@ const short = async () => ({ error: 'short', available: 0, need: 1 });
|
|||||||
ok(rows.sales === 2 && rows.salesUsd === 10, 'passTournamentTierSales off: only the 2 weekly sales ($10) feed the pool', JSON.stringify({ sales: rows.sales, usd: rows.salesUsd }));
|
ok(rows.sales === 2 && rows.salesUsd === 10, 'passTournamentTierSales off: only the 2 weekly sales ($10) feed the pool', JSON.stringify({ sales: rows.sales, usd: rows.salesUsd }));
|
||||||
SC.passTournamentTierSales = '1';
|
SC.passTournamentTierSales = '1';
|
||||||
const rows2 = await gp.runTournament(Date.parse('2026-11-03T18:00:00Z'), { force: true });
|
const rows2 = await gp.runTournament(Date.parse('2026-11-03T18:00:00Z'), { force: true });
|
||||||
ok(rows2.sales === 3 && rows2.salesUsd === 50, 'passTournamentTierSales on: the Champion renewal ($40) is added', JSON.stringify({ sales: rows2.sales, usd: rows2.salesUsd }));
|
ok(rows2.sales === 3 && rows2.salesUsd === 60, 'passTournamentTierSales on: the Champion renewal ($50) is added', JSON.stringify({ sales: rows2.sales, usd: rows2.salesUsd }));
|
||||||
|
// 10. Sovereign ($100 / 30 days) and Legend ($250 / 365 days), 2026-10-22 (Dallas's structure); prices = packages since 2026-10-25
|
||||||
|
for (const k of [...passes.keys()]) passes.delete(k); for (const k of [...orders.keys()]) orders.delete(k);
|
||||||
|
delete SC.passTournamentTierSales; SC.sovTiers = '0';
|
||||||
|
ok(gp.TIERS.join() === 'weekly,explorer,champion,sovereign,legend' && gp.TIER_NAMES.sovereign === 'Sovereign' && gp.TIER_NAMES.legend === 'Legend', 'rank: weekly < explorer < champion < sovereign < legend; names from the one table', gp.TIERS.join());
|
||||||
|
const C0 = gp.cfg().tiers;
|
||||||
|
ok(C0.weekly.price === 500 && C0.weekly.days === 7 && C0.explorer.price === 2000 && C0.champion.price === 5000 && C0.sovereign.price === 10000 && C0.sovereign.days === 30 && C0.legend.price === 25000 && C0.legend.days === 365 && !C0.sovereign.sale && !C0.legend.sale && C0.weekly.sale, 'defaults: weekly 500/7 (unchanged), Sovereign 10000/30, Legend 25000/365; sovTiers off = not on sale, weekly on sale', JSON.stringify(C0));
|
||||||
|
// off switch: members refused, nothing written, nothing charged; the weekly pass still sells
|
||||||
|
charged = null; const spy = async (price, label) => { charged = { price, label }; return { ok: true }; };
|
||||||
|
r = await buyX('m@x.com', spy, T0, 'sovereign'); ok(r.error === 'The Sovereign pass is not open yet.' && !charged, 'sovTiers off: Sovereign refused for a member, nothing charged', JSON.stringify(r));
|
||||||
|
r = await buyX('m@x.com', spy, T0, 'legend'); ok(r.error === 'The Legend pass is not open yet.' && !charged, 'sovTiers off: Legend refused for a member, nothing charged', JSON.stringify(r));
|
||||||
|
r = await buyX('m@x.com', short, T0, 'legend'); ok(r.error && ![...orders.values()].some(o => o.email === 'm@x.com' && o.status === 'waiting'), 'sovTiers off: a short member gets no waiting Legend order either', JSON.stringify(r));
|
||||||
|
ok(!passes.get('m@x.com'), 'refused Sovereign/Legend buys write nothing', '');
|
||||||
|
v = gp.view('m@x.com', T0); ok(v.passes.map(x => x.tier).join() === 'weekly' && !v.tierPreview, 'sovTiers off: the member still sees only the weekly pass', JSON.stringify(v.passes.map(x => x.tier)));
|
||||||
|
charged = null; r = await buyX('m@x.com', spy, T0); ok(r.ok && r.tier === 'weekly' && charged.price === 500 && charged.label === 'Game Pass (7 days)' && r.until === T0 + 7 * DAY, 'sovTiers off: the weekly Game Pass sells exactly as before', JSON.stringify(charged));
|
||||||
|
charged = null; r = await buyX('adm@x.com', spy, T0, 'legend', { preview: true });
|
||||||
|
ok(r.ok && r.tier === 'legend' && r.days === 365 && r.until === T0 + 365 * DAY && charged.price === 25000 && charged.label === 'Legend pass (365 days)', 'sovTiers off: the admin can buy Legend (testing): 25000 credits, 365 days', JSON.stringify({ r, charged }));
|
||||||
|
SC.sovTiers = '1';
|
||||||
|
// buy with enough purchased credits
|
||||||
|
charged = null; r = await buyX('sv@x.com', spy, T0, 'sovereign');
|
||||||
|
ok(r.ok && r.tier === 'sovereign' && r.days === 30 && r.until === T0 + 30 * DAY && charged.price === 10000 && charged.label === 'Sovereign pass (30 days)', 'sovTiers on: Sovereign charges 10000 credits, 30 days', JSON.stringify(charged));
|
||||||
|
rec = passes.get('sv@x.com');
|
||||||
|
ok(rec.tiers.sovereign.until === T0 + 30 * DAY && !rec.tiers.weekly && !rec.tiers.legend && rec.until === 0 && rec.bought[0].tier === 'sovereign' && rec.bought[0].usd === 100 && rec.bought[0].cents === 10000 && rec.bought[0].via === 'package', 'only the Sovereign tier moved; bought row has tier, $100, a 10000-cent package', JSON.stringify(rec));
|
||||||
|
charged = null; r = await buyX('lg@x.com', spy, T0, 'legend');
|
||||||
|
ok(r.ok && r.until === T0 + 365 * DAY && charged.price === 25000 && passes.get('lg@x.com').bought[0].usd === 250, 'sovTiers on: Legend charges 25000 credits, a YEAR (365 days), $250 row', JSON.stringify(charged));
|
||||||
|
// extend: from max(now, until)
|
||||||
|
r = await buyX('lg@x.com', paid, T0 + 100 * DAY, 'legend'); ok(r.until === T0 + 730 * DAY, 'Legend again while active: +365 days from its end (nothing lost)', new Date(r.until).toISOString());
|
||||||
|
r = await buyX('sv@x.com', paid, T0 + 10 * DAY, 'sovereign'); ok(r.until === T0 + 60 * DAY, 'Sovereign again while active: +30 days from its end', new Date(r.until).toISOString());
|
||||||
|
r = await buyX('sv@x.com', paid, T0 + 90 * DAY, 'sovereign'); ok(r.until === T0 + 120 * DAY, 'Sovereign again after it ended: +30 days from now', new Date(r.until).toISOString());
|
||||||
|
r = await buyX('lg2@x.com', paid, T0, 'legend'); r = await buyX('lg2@x.com', paid, T0 + 400 * DAY, 'legend'); ok(r.until === T0 + 765 * DAY, 'Legend again after it ended: +365 days from now', new Date(r.until).toISOString());
|
||||||
|
// ordering: all five side by side
|
||||||
|
await buyX('all@x.com', paid, T0, 'weekly'); await buyX('all@x.com', paid, T0, 'explorer'); await buyX('all@x.com', paid, T0, 'champion');
|
||||||
|
await buyX('all@x.com', paid, T0, 'sovereign'); await buyX('all@x.com', paid, T0 - 360 * DAY, 'legend'); // legend to T0+5
|
||||||
|
f = gp.flag('all@x.com', T0 + DAY);
|
||||||
|
ok(f.active && f.tier === 'legend' && f.until === T0 + 5 * DAY && f.tiers.sovereign === T0 + 30 * DAY && f.tiers.legend === T0 + 5 * DAY && f.tiers.champion === T0 + 30 * DAY && f.tiers.weekly === T0 + 7 * DAY && Object.keys(f.tiers).join() === 'weekly,explorer,champion,sovereign,legend', 'all five on: tier legend, until = Legend end, every tier side by side in the payload', JSON.stringify(f));
|
||||||
|
f = gp.flag('all@x.com', T0 + 6 * DAY); ok(f.tier === 'sovereign' && f.until === T0 + 30 * DAY && f.tiers.legend === null, 'Legend ended: Sovereign shows through (above Champion and Explorer, same end)', JSON.stringify(f));
|
||||||
|
await buyX('ce@x.com', paid, T0, 'champion'); await buyX('ce@x.com', paid, T0, 'sovereign'); await buyX('ce@x.com', paid, T0, 'explorer');
|
||||||
|
ok(gp.flag('ce@x.com', T0 + 1).tier === 'sovereign', 'Sovereign outranks Champion and Explorer whatever the buy order', gp.flag('ce@x.com', T0 + 1).tier);
|
||||||
|
// the same caps (no extra POL) and pass: true
|
||||||
|
const at2 = Date.parse('2026-10-22T17:00:00Z');
|
||||||
|
ok([gp.capsFor('sv@x.com', at2), gp.capsFor('lg@x.com', at2)].every(c => c.pass === true && c.daily === 1.5 && c.total === 5), 'capsFor: Sovereign and Legend holders get exactly the weekly pass caps 1.50 / 5', '');
|
||||||
|
const gs = gp.grant({ email: 'lg@x.com', game: 'shardsofvalor', kind: 'daily', pol: 3, ref: 'cap:lg', now: at2 });
|
||||||
|
ok(gs.allowed === 1.5 && gs.pass === true, 'polgrant: a Legend holder is capped at 1.50 on daily play, pass: true (a boolean)', JSON.stringify(gs));
|
||||||
|
// waiting orders: a $50 package does not cover Sovereign, $100 does; $100 does not cover Legend, $250 does
|
||||||
|
r = await buyX('wo@x.com', short, T0, 'sovereign');
|
||||||
|
ok(r.needPay && r.tier === 'sovereign' && r.payUrl === '/my?from=gamepass&tier=sovereign#buy' && r.package === 100 && /package of \$100 or more/.test(r.message) && r.price === 10000, 'Sovereign short: waiting order, payUrl with tier, "$100 package"', r.message);
|
||||||
|
const ordS = r.order;
|
||||||
|
r = await buyX('wo@x.com', short, T0, 'legend'); const ordL = r.order;
|
||||||
|
ok(r.needPay && r.order !== ordS && r.package === 250 && /package of \$250 or more/.test(r.message) && r.payUrl === '/my?from=gamepass&tier=legend#buy', 'Legend short: its own waiting order, "$250 package"', r.message);
|
||||||
|
r = await buyX('wo@x.com', short, T0, 'legend'); ok(r.order === ordL, 'Legend again: reuses its waiting order', '');
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 5000, tx: '0xd1', ts: T0, devEmail: 'wo@x.com' }); ok(ev === null, 'a $50 package fulfils neither Sovereign nor Legend', JSON.stringify(ev));
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 10000, tx: '0xd2', ts: T0, devEmail: 'wo@x.com' });
|
||||||
|
ok(ev && ev.tier === 'sovereign' && ev.order === ordS && ev.until === T0 + 30 * DAY, 'a $100 package fulfils the Sovereign order (not Legend)', JSON.stringify(ev));
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 10000, tx: '0xd2', ts: T0, devEmail: 'wo@x.com' }); ok(ev === null, 'the same tx again counts once', JSON.stringify(ev));
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 25000, tx: '0xd3', ts: T0, devEmail: 'wo@x.com' });
|
||||||
|
ok(ev && ev.tier === 'legend' && ev.order === ordL && ev.until === T0 + 365 * DAY, 'a $250 package fulfils the Legend order: a year', JSON.stringify(ev));
|
||||||
|
await buyX('wo2@x.com', short, T0, 'champion'); await buyX('wo2@x.com', short, T0, 'sovereign'); await buyX('wo2@x.com', short, T0, 'legend');
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 50000, tx: '0xd4', ts: T0, devEmail: 'wo2@x.com' }); ok(ev && ev.tier === 'legend', 'three orders waiting, a $500 package: Legend (the highest-priced it covers) first', JSON.stringify(ev));
|
||||||
|
ev = await gp.onEvent({ type: 'Purchase', priceCents: 10000, tx: '0xd5', ts: T0, devEmail: 'wo2@x.com' }); ok(ev && ev.tier === 'sovereign', 'then a $100 package: Sovereign', JSON.stringify(ev));
|
||||||
|
// kill switches: one tier stops alone, the rest keep selling
|
||||||
|
SC.gamePassLegendEnabled = '0';
|
||||||
|
r = await buyX('ks@x.com', paid, T0, 'legend'); const r2 = await buyX('ks@x.com', paid, T0, 'sovereign');
|
||||||
|
ok(r.error === 'The Legend pass is not open yet.' && r2.ok, 'gamePassLegendEnabled 0: Legend refused, Sovereign still sells', JSON.stringify(r));
|
||||||
|
v = gp.view('ks2@x.com', T0); ok(v.passes.map(x => x.tier).join() === 'weekly,explorer,champion,sovereign', 'a stopped tier drops off the member card', v.passes.map(x => x.tier).join());
|
||||||
|
v = gp.view('lg@x.com', T0); const lrow = v.passes.find(x => x.tier === 'legend');
|
||||||
|
ok(lrow && lrow.active && !lrow.open, 'a Legend holder still sees their pass (not on sale) after the switch stops it', JSON.stringify(lrow));
|
||||||
|
delete SC.gamePassLegendEnabled; SC.gamePassSovereignEnabled = '0';
|
||||||
|
r = await buyX('ks@x.com', paid, T0, 'sovereign'); ok(r.error === 'The Sovereign pass is not open yet.', 'gamePassSovereignEnabled 0: Sovereign refused', JSON.stringify(r));
|
||||||
|
delete SC.gamePassSovereignEnabled;
|
||||||
|
SC.gamePassLegendPriceCredits = '20000'; SC.gamePassLegendDays = '180';
|
||||||
|
charged = null; r = await buyX('pr@x.com', spy, T0, 'legend'); ok(charged.price === 20000 && r.until === T0 + 180 * DAY, 'gamePassLegendPriceCredits / gamePassLegendDays settings override the defaults', JSON.stringify(charged));
|
||||||
|
delete SC.gamePassLegendPriceCredits; delete SC.gamePassLegendDays;
|
||||||
|
// comp and revoke
|
||||||
|
cp = gp.comp('cv@x.com', 'qa', 'legend', T0); f = gp.flag('cv@x.com', T0 + 1);
|
||||||
|
ok(cp.tier === 'legend' && cp.days === 365 && cp.until === T0 + 365 * DAY && f.tier === 'legend' && passes.get('cv@x.com').bought[0].via === 'admin' && passes.get('cv@x.com').bought[0].usd === 0, 'comp Legend: a year, an admin row worth $0', JSON.stringify(cp));
|
||||||
|
gp.comp('cv@x.com', 'qa', 'sovereign', T0);
|
||||||
|
rv = gp.revoke('cv@x.com', 'legend', 'refund qa', T0 + DAY); f = gp.flag('cv@x.com', T0 + DAY + 1);
|
||||||
|
ok(rv.ok && rv.tier === 'legend' && f.tier === 'sovereign' && f.tiers.legend === null, 'revoke Legend: ends now, Sovereign shows through', JSON.stringify(f));
|
||||||
|
rv = gp.revoke('cv@x.com', 'sovereign', 'refund qa', T0 + DAY); ok(rv.ok && gp.flag('cv@x.com', T0 + DAY + 1).active === false, 'revoke Sovereign: no pass left', JSON.stringify(rv));
|
||||||
|
rv = gp.revoke('cv@x.com', 'legend', 'again', T0 + 2 * DAY); ok(rv.error === 'No active Legend pass on this account.', 'revoking an inactive Legend is refused', rv.error);
|
||||||
|
// admin stats: per tier, each account once at its top tier; comps are not sales
|
||||||
|
const st2 = gp.adminStats(T0 + DAY); const S2 = st2.tiers;
|
||||||
|
ok(Object.keys(S2).join() === 'weekly,explorer,champion,sovereign,legend' && S2.sovereign.name === 'Sovereign' && S2.legend.name === 'Legend', 'admin stats carry all five tiers by name', Object.keys(S2).join());
|
||||||
|
ok(S2.legend.active >= 3 && S2.legend.comped === 1 && S2.sovereign.comped === 1 && S2.legend.soldTotal >= 4 && S2.sovereign.soldTotal >= 4, 'admin stats: Legend/Sovereign active, sold and comped counted', JSON.stringify({ l: S2.legend, s: S2.sovereign }));
|
||||||
|
ok(st2.settings.tiers.legend.days === 365 && st2.settings.tiers.sovereign.price === 10000, 'admin settings block shows Legend 365 days, Sovereign 10000', '');
|
||||||
|
// tournament: Legend/Sovereign sales stay out of the pool unless passTournamentTierSales
|
||||||
|
for (const k of [...passes.keys()]) passes.delete(k);
|
||||||
|
const wkT = Date.parse('2026-11-10T18:00:00Z');
|
||||||
|
await buyX('t1@x.com', paid, wkT, 'weekly'); await buyX('t2@x.com', paid, wkT, 'legend'); await buyX('t3@x.com', paid, wkT, 'sovereign');
|
||||||
|
let tr = await gp.runTournament(wkT, { force: true }); ok(tr.sales === 1 && tr.salesUsd === 5, 'passTournamentTierSales default off: Sovereign/Legend sales do not feed the pool', JSON.stringify({ s: tr.sales, u: tr.salesUsd }));
|
||||||
|
SC.passTournamentTierSales = '1';
|
||||||
|
tr = await gp.runTournament(wkT, { force: true }); ok(tr.sales === 3 && tr.salesUsd === 355, 'passTournamentTierSales on: Legend ($250) and Sovereign ($100) are added', JSON.stringify({ s: tr.sales, u: tr.salesUsd }));
|
||||||
|
delete SC.passTournamentTierSales;
|
||||||
|
|
||||||
try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch (e) {}
|
try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch (e) {}
|
||||||
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
|
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
|
||||||
process.exit(fails ? 1 : 0);
|
process.exit(fails ? 1 : 0);
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
// End-to-end check of the sponsor follow through the REAL sync code (lssync.js -> LinkSpin /api/partner/registry and
|
||||||
|
// iapsync.js -> InstantAdPay /api/partner/registry, the hash and registry loop guards, the Sponsor check endpoints).
|
||||||
|
// Boots a local InstantAdPay AND a local LinkSpin, each on a throwaway data dir seeded with the same few accounts (JSON
|
||||||
|
// stores, no DATABASE_URL, no mail key, no engine key), pointed ONLY at each other with a throwaway LS_SYNC_SECRET.
|
||||||
|
// Nothing touches production. Needs the LinkSpin repo beside this one (LS_SITE to override).
|
||||||
|
// node qa/sponsorfollow-e2e.mjs
|
||||||
|
import { spawn, execSync } from 'node:child_process';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const IAP_SITE = path.join(HERE, '..');
|
||||||
|
const LS_SITE = process.env.LS_SITE || path.join(IAP_SITE, '..', '..', 'linkspin', 'site');
|
||||||
|
const SECRET = 'qa-sponsorfollow-' + 'x'.repeat(40);
|
||||||
|
process.env.LS_SYNC_SECRET = SECRET;
|
||||||
|
const SF = require(path.join(IAP_SITE, 'sponsorfollow.js'));
|
||||||
|
const IAP_PORT = 8811, LS_PORT = 8812, IAP = 'http://127.0.0.1:' + IAP_PORT, LS = 'http://127.0.0.1:' + LS_PORT;
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
let pass = 0, fail = 0; const lines = [];
|
||||||
|
const ok = (cond, name, extra) => { if (cond) { pass++; lines.push('ok ' + name); } else { fail++; lines.push('FAIL ' + name + (extra ? '\n ' + extra : '')); } };
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const acct = (email, username, o) => Object.assign({ email, pass: null, sponsorRef: '', code: ('c' + username).slice(0, 7), username, address: null, created: now - 20 * 86400000, lastSeen: now - 3600000, memberId: 0 }, o || {});
|
||||||
|
function seed(dir, list) {
|
||||||
|
fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true });
|
||||||
|
const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
|
||||||
|
for (const a of list) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
|
||||||
|
fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(db));
|
||||||
|
}
|
||||||
|
const base = () => [acct('adopter@qa.test', 'adopter', { memberId: 0 }), acct('old@qa.test', 'oldsponsor'), acct('lead1@qa.test', 'leadone'), acct('lead2@qa.test', 'leadtwo', { sponsorRef: 'oldsponsor' }), acct('lead4@qa.test', 'leadfour', { sponsorRef: 'oldsponsor' })];
|
||||||
|
const iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-iap-')), lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-ls-'));
|
||||||
|
// lead3 is bound on InstantAdPay (memberId), lead4 joined LinkSpin under someone else (ordinary, already different)
|
||||||
|
seed(iapDir, base().concat([acct('lead3@qa.test', 'leadthree', { memberId: 42, sponsorRef: 'oldsponsor' })]));
|
||||||
|
seed(lsDir, base().map(a => a.email === 'lead4@qa.test' ? Object.assign(a, { sponsorRef: 'adopter' }) : a).concat([acct('lead3@qa.test', 'leadthree', { sponsorRef: 'oldsponsor' })]));
|
||||||
|
|
||||||
|
const env = (port, dir, extra) => Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', LS_SYNC_SECRET: SECRET, DATABASE_URL: '', SENDGRID_API_KEY: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' }, extra);
|
||||||
|
for (const k of ['DATABASE_URL', 'NETWORK_DB_URL']) delete process.env[k];
|
||||||
|
const procs = [];
|
||||||
|
function boot(site, port, dir, extra, log) {
|
||||||
|
const p = spawn(process.execPath, ['server.js'], { cwd: site, env: env(port, dir, extra), stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] });
|
||||||
|
procs.push(p); return p;
|
||||||
|
}
|
||||||
|
async function up(url) { for (let i = 0; i < 40; i++) { try { const r = await fetch(url + '/api/config', { signal: AbortSignal.timeout(2000) }); if (r.status < 500) return true; } catch (e) {} await sleep(1000); } return false; }
|
||||||
|
const admin = async (url, pth, body, method) => { const r = await fetch(url + pth, { method: method || (body ? 'POST' : 'GET'), headers: { Authorization: 'Bearer localtest', 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); return r.json(); };
|
||||||
|
const facts = async (url, email) => ((await SF.peerPost(url, '/api/partner/sponsor-facts', { emails: [email] })).rows || [])[0] || null;
|
||||||
|
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 20000)) { try { if (await fn()) return true; } catch (e) {} await sleep(700); } return false; }
|
||||||
|
|
||||||
|
const OUT = path.join(IAP_SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
||||||
|
try {
|
||||||
|
boot(IAP_SITE, IAP_PORT, iapDir, { LS_URL: LS }, path.join(OUT, 'sf-e2e-iap.log'));
|
||||||
|
boot(LS_SITE, LS_PORT, lsDir, { IAP_URL: IAP, SITE_HOST: '127.0.0.1:' + LS_PORT, TANK_RESCUE: '' }, path.join(OUT, 'sf-e2e-ls.log'));
|
||||||
|
ok(await up(IAP), 'local InstantAdPay up'); ok(await up(LS), 'local LinkSpin up');
|
||||||
|
|
||||||
|
// 1. a deliberate change on InstantAdPay (admin edit from the tank) follows to LinkSpin
|
||||||
|
let r = await admin(IAP, '/api/admin/member', { email: 'lead1@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||||
|
ok(!r.error, 'IAP admin sets lead1 -> @adopter', JSON.stringify(r));
|
||||||
|
ok(await waitFor(async () => (await facts(LS, 'lead1@qa.test')).sponsorEmail === 'adopter@qa.test'), 'LinkSpin follows: lead1 under adopter');
|
||||||
|
const l1 = await facts(LS, 'lead1@qa.test'); ok(l1 && l1.prov && l1.prov.by === 'admin' && l1.prov.origin === 'instantadpay', 'LinkSpin keeps the same record (by admin, origin instantadpay)', JSON.stringify(l1 && l1.prov));
|
||||||
|
|
||||||
|
// 2. a deliberate change on LinkSpin (both had @oldsponsor) follows to InstantAdPay, a clear back to the tank
|
||||||
|
r = await admin(LS, '/api/admin/member', { email: 'lead2@qa.test', sponsorRef: '' }, 'PATCH');
|
||||||
|
ok(!r.error, 'LinkSpin admin clears lead2 to the tank', JSON.stringify(r));
|
||||||
|
ok(await waitFor(async () => (await facts(IAP, 'lead2@qa.test')).sponsorEmail === null), 'InstantAdPay follows the clear: lead2 in the tank');
|
||||||
|
|
||||||
|
// 3. bound on InstantAdPay: a LinkSpin change does not move it there; reported; resolve refuses on the bound side
|
||||||
|
r = await admin(LS, '/api/admin/member', { email: 'lead3@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||||
|
await sleep(6000);
|
||||||
|
ok((await facts(IAP, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'bound on InstantAdPay: sponsor there unchanged');
|
||||||
|
|
||||||
|
// 4. ping-pong: let both ticks run; nothing keeps bouncing
|
||||||
|
const s1 = await admin(IAP, '/api/admin/lssync'), t1 = await admin(LS, '/api/admin/iapsync');
|
||||||
|
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||||
|
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||||
|
const s2 = await admin(IAP, '/api/admin/lssync/run', {}), t2 = await admin(LS, '/api/admin/iapsync/run', {});
|
||||||
|
ok(s2.sent === 0 && t2.sent === 0, 'no ping-pong: a third reconcile on each side sends 0 rows', JSON.stringify({ s1: s1.pushed, s2, t1: t1.pushed, t2 }));
|
||||||
|
|
||||||
|
// 5. the Sponsor check on both apps lists lead3 (bound on IAP) and lead4 (ordinary, different) and nothing else
|
||||||
|
const rep = await admin(IAP, '/api/admin/sponsor-check'); const rep2 = await admin(LS, '/api/admin/sponsor-check');
|
||||||
|
const emails = x => (x.rows || []).map(y => y.email).sort().join(',');
|
||||||
|
ok(!rep.peerError && emails(rep) === 'lead3@qa.test,lead4@qa.test', 'IAP Sponsor check rows = lead3, lead4', JSON.stringify({ e: emails(rep), err: rep.peerError }));
|
||||||
|
ok(emails(rep2) === emails(rep), 'LinkSpin Sponsor check shows the same rows');
|
||||||
|
const r3 = (rep.rows || []).find(x => x.email === 'lead3@qa.test');
|
||||||
|
ok(r3 && r3.iap.bound && !r3.ls.bound, 'lead3: bound on InstantAdPay, not on LinkSpin');
|
||||||
|
ok(r3 && (r3.iap.log || []).some(l => l.action === 'bound'), 'lead3: the refused follow is in the InstantAdPay log');
|
||||||
|
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'linkspin' });
|
||||||
|
ok(r.error && /bound/.test(r.error), "resolve 'Use LinkSpin's sponsor' on the bound side is refused", JSON.stringify(r));
|
||||||
|
r = await admin(LS, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'instantadpay' });
|
||||||
|
ok(r.ok, "resolve from LinkSpin admin: 'Use InstantAdPay's sponsor' applies on LinkSpin", JSON.stringify(r));
|
||||||
|
ok((await facts(LS, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'lead3 now @oldsponsor on both');
|
||||||
|
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead4@qa.test', use: 'instantadpay' });
|
||||||
|
ok(r.ok, "resolve from InstantAdPay admin: lead4 'Use InstantAdPay's sponsor' applied on LinkSpin through the partner call", JSON.stringify(r));
|
||||||
|
await sleep(5000);
|
||||||
|
const rep3 = await admin(IAP, '/api/admin/sponsor-check');
|
||||||
|
ok((rep3.rows || []).length === 0, 'after both picks the Sponsor check is empty', emails(rep3));
|
||||||
|
ok((await facts(IAP, 'lead4@qa.test')).sponsorEmail === 'old@qa.test', 'lead4 on InstantAdPay untouched by its own pick');
|
||||||
|
|
||||||
|
// 6. an old peer (no proto 2): rows carrying the new facts are sent again later (checked through the stored hashes)
|
||||||
|
const st = JSON.parse(fs.readFileSync(path.join(iapDir, 'sponsorfollow.json'), 'utf8'));
|
||||||
|
ok(st.peer && st.peer.proto === 2, 'IAP saw LinkSpin answer proto 2');
|
||||||
|
} catch (e) { fail++; lines.push('FAIL exception ' + (e && e.stack || e)); }
|
||||||
|
finally {
|
||||||
|
for (const p of procs) { try { p.kill(); } catch (e) {} }
|
||||||
|
if (process.platform === 'win32') for (const port of [IAP_PORT, LS_PORT]) { try { const o = execSync('netstat -ano | findstr :' + port, { encoding: 'utf8' }); for (const pid of new Set(o.split(/\r?\n/).map(l => l.trim().split(/\s+/).pop()).filter(x => /^\d+$/.test(x) && x !== '0'))) { try { execSync('taskkill /F /PID ' + pid, { stdio: 'ignore' }); } catch (e) {} } } catch (e) {} }
|
||||||
|
await sleep(500);
|
||||||
|
for (const d of [iapDir, lsDir]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} }
|
||||||
|
}
|
||||||
|
console.log(lines.join('\n')); console.log('\nsponsorfollow e2e: ' + pass + ' passed, ' + fail + ' failed');
|
||||||
|
process.exit(fail ? 1 : 0);
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
// Unit tests for the sponsor follow rule + the one network holding tank (sponsorfollow.js, tank.js). The SAME file ships in
|
||||||
|
// InstantAdPay and LinkSpin. No server, no network, no chain: two in-process "platforms" (two instances of this repo's
|
||||||
|
// tank.js, each with its own in-memory accounts, follow store and throwaway data dir) and a mini sync that builds rows the
|
||||||
|
// way lssync.js / iapsync.js do (rowFields + tank summary) and delivers them the way the inbound handlers do.
|
||||||
|
// node qa/sponsorfollow.test.cjs
|
||||||
|
'use strict';
|
||||||
|
const assert = require('assert');
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const SITE = path.join(__dirname, '..');
|
||||||
|
const SF = require(path.join(SITE, 'sponsorfollow.js'));
|
||||||
|
delete process.env.DATABASE_URL; // JSON stores only
|
||||||
|
|
||||||
|
let passed = 0, failed = 0; const results = [];
|
||||||
|
async function t(name, fn) { try { await fn(); passed++; results.push('ok ' + name); } catch (e) { failed++; results.push('FAIL ' + name + '\n ' + (e && e.stack || e).split('\n').slice(0, 3).join('\n ')); } }
|
||||||
|
|
||||||
|
// ---------- pure rule ----------
|
||||||
|
const H = 3600000, T0 = Date.UTC(2026, 9, 22, 15, 0, 0);
|
||||||
|
const inc = (o) => Object.assign({ sponsorEmail: 'a@x.co', at: T0, by: 'adopt', prevEmail: null, origin: 'instantadpay' }, o);
|
||||||
|
const loc = (o) => Object.assign({ sponsorEmail: null, prov: null, bound: false }, o);
|
||||||
|
|
||||||
|
async function pure() {
|
||||||
|
await t('ordinary incoming row (no sponsorSetBy) is left to the first-platform rule', () => {
|
||||||
|
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), { sponsorEmail: 'a@x.co' }).action, 'ordinary');
|
||||||
|
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'join' })).action, 'ordinary');
|
||||||
|
assert.strictEqual(SF.incomingOf({ sponsorEmail: 'a@x.co', sponsorSetBy: 'join', sponsorSetAt: T0 }), null);
|
||||||
|
});
|
||||||
|
await t('deliberate adoption fills an empty sponsor (one network tank)', () => {
|
||||||
|
const d = SF.decide(loc(), inc()); assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
|
||||||
|
});
|
||||||
|
await t('bound member never changes, even for a newer deliberate change', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', bound: true }), inc({ prevEmail: 'b@x.co' })); assert.strictEqual(d.action, 'bound'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||||
|
assert.strictEqual(SF.decide(loc({ bound: true }), inc()).action, 'bound');
|
||||||
|
});
|
||||||
|
await t('newer deliberate change wins when both sides agreed before it', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'rescue', sponsorEmail: null, prevEmail: 'b@x.co' }));
|
||||||
|
assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
|
||||||
|
});
|
||||||
|
await t('clear back to the tank applies (sponsorEmail null)', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0 - 9 * 86400000, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ by: 'expire', sponsorEmail: null, prevEmail: 'a@x.co', at: T0 }));
|
||||||
|
assert.strictEqual(d.action, 'apply');
|
||||||
|
});
|
||||||
|
await t('ordinary sponsor that already differed from the sender is NOT moved (diverged, reported)', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'c@x.co' }), inc({ prevEmail: null }));
|
||||||
|
assert.strictEqual(d.action, 'diverged'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||||
|
});
|
||||||
|
await t('older incoming deliberate change loses to a newer local one (stale)', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 2 * H, by: 'admin', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||||
|
assert.strictEqual(d.action, 'stale'); assert.ok(!d.apply);
|
||||||
|
});
|
||||||
|
await t('newer incoming deliberate change beats an older local deliberate one', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 2 * H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||||
|
assert.strictEqual(d.action, 'apply');
|
||||||
|
});
|
||||||
|
await t('conflict window: earlier incoming wins over a later local change, flagged', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||||
|
assert.strictEqual(d.action, 'conflict-apply'); assert.ok(d.apply); assert.ok(d.conflict);
|
||||||
|
});
|
||||||
|
await t('conflict window: later incoming loses to an earlier local change, flagged, not applied', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
|
||||||
|
assert.strictEqual(d.action, 'conflict-keep'); assert.ok(!d.apply); assert.ok(d.conflict);
|
||||||
|
});
|
||||||
|
await t('two changes from the same platform minutes apart are sequential, not a race', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ at: T0 + 60000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'a@x.co' }));
|
||||||
|
assert.strictEqual(d.action, 'apply');
|
||||||
|
});
|
||||||
|
await t('a sender that built on our current sponsor is sequential, not a race', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 + 120000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'b@x.co', origin: 'instantadpay' }));
|
||||||
|
assert.strictEqual(d.action, 'apply');
|
||||||
|
});
|
||||||
|
await t('same sponsor already: no-op (the ping-pong stopper)', () => {
|
||||||
|
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'A@x.co ' }), inc()).action, 'same');
|
||||||
|
});
|
||||||
|
await t('a local record that no longer describes the current sponsor is ignored (later ordinary change)', () => {
|
||||||
|
const d = SF.decide(loc({ sponsorEmail: 'w@x.co', prov: { at: T0 + H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0, prevEmail: null }));
|
||||||
|
assert.strictEqual(d.action, 'diverged');
|
||||||
|
assert.strictEqual(SF.rowFields({ at: T0, by: 'adopt', sponsorEmail: 'b@x.co' }, 'w@x.co'), null);
|
||||||
|
});
|
||||||
|
await t('back-compat: rows without the new facts hash exactly as before (no resend on deploy)', () => {
|
||||||
|
assert.strictEqual(SF.hashExtra({ email: 'm@x.co', sponsorEmail: 'a@x.co', tank: null }), '');
|
||||||
|
assert.notStrictEqual(SF.hashExtra({ sponsorSetBy: 'adopt', sponsorSetAt: T0 }), '');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- two platforms in one process ----------
|
||||||
|
function fakeAccounts() {
|
||||||
|
const by = new Map(); let nextId = 100;
|
||||||
|
const pub = a => a ? Object.assign({}, a) : null;
|
||||||
|
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||||
|
return {
|
||||||
|
_by: by,
|
||||||
|
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: T0 - 30 * 86400000, lastSeen: T0 - H }, o || {}); by.set(email, a); return pub(a); },
|
||||||
|
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
|
||||||
|
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
|
||||||
|
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
|
||||||
|
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
|
||||||
|
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true, account: pub(a) }; },
|
||||||
|
async listAll() { return [...by.values()].map(pub); },
|
||||||
|
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); },
|
||||||
|
async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = id; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function platform(name, peerName) {
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-' + name + '-'));
|
||||||
|
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
|
||||||
|
const tank = require(path.join(SITE, 'tank.js'));
|
||||||
|
const accounts = fakeAccounts();
|
||||||
|
const purchases = [];
|
||||||
|
const chain = { recentEvents: () => purchases, getConfig: () => ({}) };
|
||||||
|
const chats = [];
|
||||||
|
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 };
|
||||||
|
const store = SF.create({ dataDir: dir, platform: name });
|
||||||
|
const bound = new Set();
|
||||||
|
const glue = SF.glue({ store, accounts, tank: () => tank, peer: peerName,
|
||||||
|
isBound: async a => Number(a.memberId) > 0 || bound.has(a.email) ? { bound: true, why: name + ' member #' + a.memberId } : { bound: false },
|
||||||
|
sponsorAccount: em => accounts.byEmail(em),
|
||||||
|
wouldCycle: async (email, sp) => { let cur = sp; for (let i = 0; cur && i < 60; i++) { if (cur.email === email) return true; cur = await accounts.sponsorOf(cur.email); } return false; } });
|
||||||
|
tank.init({ dataDir: dir, chain, accounts, messages, mailer: null, site: 'https://' + name + '.test', follow: glue, store });
|
||||||
|
const P = { name, dir, tank, accounts, store, glue, chats, purchases, bound, hashes: {} };
|
||||||
|
// what the sync module would send for one account (lssync/iapsync rowFor)
|
||||||
|
P.rowFor = async email => {
|
||||||
|
const a = await accounts.byEmail(email); const sp = await accounts.sponsorOf(email);
|
||||||
|
const row = { email, username: a.username, sponsorEmail: sp && sp.email !== email ? sp.email : null };
|
||||||
|
Object.assign(row, SF.rowFields(store.get(email), row.sponsorEmail) || {});
|
||||||
|
row.tank = (await tank.summaryFor(email)) || null;
|
||||||
|
return row;
|
||||||
|
};
|
||||||
|
return P;
|
||||||
|
}
|
||||||
|
// deliver one row from P to Q the way the inbound handlers do (tank state first, then the follow rule)
|
||||||
|
async function deliver(P, Q, email) {
|
||||||
|
const row = await P.rowFor(email);
|
||||||
|
if (Object.prototype.hasOwnProperty.call(row, 'tank')) Q.store.setRemote(email, row.tank);
|
||||||
|
const d = await Q.glue.applyIncoming(email, row);
|
||||||
|
return { row, d };
|
||||||
|
}
|
||||||
|
// a mini "both sides synced" loop: push changed rows both ways until nothing changes (with a guard against ping-pong)
|
||||||
|
async function settle(P, Q, emails) {
|
||||||
|
let rounds = 0, moves = 0;
|
||||||
|
for (; rounds < 6; rounds++) {
|
||||||
|
let changed = 0;
|
||||||
|
for (const [X, Y] of [[P, Q], [Q, P]]) for (const e of emails) {
|
||||||
|
const row = await X.rowFor(e); const h = JSON.stringify(row);
|
||||||
|
if (X.hashes[e] === h) continue; X.hashes[e] = h; changed++;
|
||||||
|
Y.store.setRemote(e, row.tank); const d = await Y.glue.applyIncoming(e, row); if (d.apply) moves++;
|
||||||
|
}
|
||||||
|
if (!changed) break;
|
||||||
|
}
|
||||||
|
return { rounds, moves };
|
||||||
|
}
|
||||||
|
const spOf = async (P, e) => { const s = await P.accounts.sponsorOf(e); return s ? s.email : null; };
|
||||||
|
function people(P, Q) {
|
||||||
|
for (const X of [P, Q]) {
|
||||||
|
X.accounts.add('adopter@x.co', { memberId: 7, username: 'adopter' });
|
||||||
|
X.accounts.add('other@x.co', { memberId: 8, username: 'otheradopter' });
|
||||||
|
X.accounts.add('lead@x.co', { username: 'lead' });
|
||||||
|
X.accounts.add('old@x.co', { username: 'oldsponsor', memberId: 9 });
|
||||||
|
X.purchases.push({ type: 'Purchase', buyerId: 7, priceCents: 2500 }, { type: 'Purchase', buyerId: 8, priceCents: 2500 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function network() {
|
||||||
|
await t('network tank: adopting on one platform makes the person adopted on both (same adopter), notices only once', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||||
|
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||||
|
const r = await P.tank.adopt('adopter@x.co', 'lead', 'hi'); assert.ok(r.ok, JSON.stringify(r));
|
||||||
|
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||||
|
assert.strictEqual(d.action, 'apply');
|
||||||
|
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
|
||||||
|
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'), 'hidden on the other side');
|
||||||
|
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
|
||||||
|
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
|
||||||
|
});
|
||||||
|
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead');
|
||||||
|
const s = await settle(P, Q, ['lead@x.co']);
|
||||||
|
assert.strictEqual(s.moves, 1); assert.ok(s.rounds <= 3, 'rounds ' + s.rounds);
|
||||||
|
const back = await Q.rowFor('lead@x.co'); const fromP = await P.rowFor('lead@x.co');
|
||||||
|
assert.strictEqual(back.sponsorSetAt, fromP.sponsorSetAt); assert.strictEqual(back.sponsorSetOrigin, 'instantadpay');
|
||||||
|
assert.strictEqual((await P.glue.applyIncoming('lead@x.co', back)).action, 'same');
|
||||||
|
});
|
||||||
|
await t('waiting list hides someone with an open adoption elsewhere even if the follow could not apply', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
Q.bound.add('lead@x.co'); // say LinkSpin cannot take the change
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead');
|
||||||
|
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||||
|
assert.strictEqual(d.action, 'bound');
|
||||||
|
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||||
|
assert.ok(Q.store.recent(5).some(x => x.action === 'bound' && x.conflict), 'logged for the report');
|
||||||
|
});
|
||||||
|
await t('release mirrors: releasing on the quiet side clears both and closes the open adoption as dropped', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||||
|
// the 3-day commitment counts on the quiet side too
|
||||||
|
const early = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(early.error && /commitment/.test(early.error), JSON.stringify(early));
|
||||||
|
// four days later
|
||||||
|
const realNow = Date.now; Date.now = () => realNow() + 4 * 86400000;
|
||||||
|
try {
|
||||||
|
const r = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(r.ok, JSON.stringify(r));
|
||||||
|
await settle(P, Q, ['lead@x.co']);
|
||||||
|
assert.strictEqual(await spOf(P, 'lead@x.co'), null); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||||
|
const pad = (await P.tank.adminView()).adoptions.find(a => a.adoptee === 'lead@x.co');
|
||||||
|
assert.strictEqual(pad.status, 'dropped');
|
||||||
|
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'), 'back in the tank on both');
|
||||||
|
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
|
||||||
|
} finally { Date.now = realNow; }
|
||||||
|
});
|
||||||
|
await t('expiry mirrors: the adopting side ends the window and the other side follows the clear', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||||
|
const realNow = Date.now; Date.now = () => realNow() + 8 * 86400000;
|
||||||
|
try {
|
||||||
|
const sw = await P.tank.sweep(); assert.strictEqual(sw.back, 1);
|
||||||
|
await settle(P, Q, ['lead@x.co']);
|
||||||
|
assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||||
|
assert.strictEqual(Q.store.get('lead@x.co').by, 'expire');
|
||||||
|
} finally { Date.now = realNow; }
|
||||||
|
});
|
||||||
|
await t('two adoptions per person count across both platforms', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
|
||||||
|
try {
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
|
||||||
|
off = 8 * 86400000; await P.tank.sweep(); await settle(P, Q, ['lead@x.co']);
|
||||||
|
const r2 = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(r2.ok, JSON.stringify(r2)); await settle(P, Q, ['lead@x.co']);
|
||||||
|
assert.strictEqual(await spOf(P, 'lead@x.co'), 'other@x.co');
|
||||||
|
off = 16 * 86400000; await Q.tank.sweep(); await settle(P, Q, ['lead@x.co']);
|
||||||
|
// adopted once on each side now: a third adoption anywhere is refused
|
||||||
|
if (!(await P.tank.waiting()).some(w => w.email === 'lead@x.co')) { /* kept where they are after two */ }
|
||||||
|
const r3 = await P.tank.adopt('adopter@x.co', 'lead'); assert.ok(r3.error, JSON.stringify(r3));
|
||||||
|
} finally { Date.now = realNow; }
|
||||||
|
});
|
||||||
|
await t('race: both sides adopt within minutes -> the earlier adoption wins on both, the later one is a conflict', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
|
||||||
|
try {
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead');
|
||||||
|
off = 90000; await Q.tank.adopt('other@x.co', 'lead'); // 90 s later on LinkSpin, before the sync arrived
|
||||||
|
off = 100000;
|
||||||
|
const a = await deliver(Q, P, 'lead@x.co'); // the later change reaches the earlier side: kept, flagged
|
||||||
|
assert.strictEqual(a.d.action, 'conflict-keep');
|
||||||
|
const b = await deliver(P, Q, 'lead@x.co'); // the earlier change reaches the later side: applied, flagged
|
||||||
|
assert.strictEqual(b.d.action, 'conflict-apply');
|
||||||
|
await settle(P, Q, ['lead@x.co']);
|
||||||
|
assert.strictEqual(await spOf(P, 'lead@x.co'), 'adopter@x.co'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
|
||||||
|
const qad = (await Q.tank.adminView()).adoptions.find(x => x.adopter === 'other@x.co');
|
||||||
|
assert.strictEqual(qad.status, 'conflict');
|
||||||
|
assert.ok(P.store.recent(10).some(x => x.action === 'conflict-keep'));
|
||||||
|
} finally { Date.now = realNow; }
|
||||||
|
});
|
||||||
|
await t('ordinary join on the other side is never overwritten by an adoption here (diverged, reported)', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
await Q.accounts.setSponsorRef('lead@x.co', 'oldsponsor'); // joined LinkSpin through @oldsponsor's link
|
||||||
|
await P.tank.adopt('adopter@x.co', 'lead');
|
||||||
|
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||||
|
assert.strictEqual(d.action, 'diverged'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'old@x.co');
|
||||||
|
});
|
||||||
|
await t('rescue clears the other side when both had the same sponsor', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
|
||||||
|
for (const X of [P, Q]) await X.accounts.setSponsorRef('lead@x.co', 'oldsponsor');
|
||||||
|
await P.glue.setDeliberate('lead@x.co', '', 'rescue', 'test');
|
||||||
|
const { d } = await deliver(P, Q, 'lead@x.co');
|
||||||
|
assert.strictEqual(d.action, 'apply'); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
|
||||||
|
});
|
||||||
|
await t('admin pick from the mismatch report applies on the unbound side and refuses on a bound one', async () => {
|
||||||
|
const P = platform('instantadpay', 'linkspin'); P.accounts.add('m@x.co'); P.accounts.add('s@x.co', { username: 'sss' });
|
||||||
|
const ok = await P.glue.adminApply('m@x.co', 's@x.co'); assert.ok(ok.ok, JSON.stringify(ok)); assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
|
||||||
|
assert.strictEqual(P.store.get('m@x.co').by, 'admin');
|
||||||
|
P.bound.add('m@x.co'); const no = await P.glue.adminApply('m@x.co', null); assert.ok(no.error && /bound/.test(no.error));
|
||||||
|
assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
|
||||||
|
});
|
||||||
|
await t('mismatch report: differ / one-sided rows, matches counted', async () => {
|
||||||
|
const r = SF.mismatches([{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's1' }, { email: 'c@x', sponsorEmail: null }, { email: 'd@x', sponsorEmail: 's2' }],
|
||||||
|
[{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's2' }, { email: 'c@x', sponsorEmail: 's3' }, { email: 'e@x', sponsorEmail: 's4' }]);
|
||||||
|
assert.strictEqual(r.shared, 3); assert.strictEqual(r.same, 1); assert.deepStrictEqual(r.rows.map(x => x.email + ':' + x.kind), ['b@x:differ', 'c@x:ls-only']);
|
||||||
|
});
|
||||||
|
await t('pending follow: retried later and settled (sponsor account arrives)', async () => {
|
||||||
|
const Q = platform('linkspin', 'instantadpay'); Q.accounts.add('lead@x.co');
|
||||||
|
const row = { email: 'lead@x.co', sponsorEmail: 'late@x.co', sponsorSetAt: T0, sponsorSetBy: 'adopt', sponsorPrevEmail: null, sponsorSetOrigin: 'instantadpay' };
|
||||||
|
assert.strictEqual((await Q.glue.applyIncoming('lead@x.co', row)).action, 'pending');
|
||||||
|
Q.accounts.add('late@x.co', { username: 'late' });
|
||||||
|
const rr = await Q.glue.retryPending(); assert.strictEqual(rr.settled, 1);
|
||||||
|
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'late@x.co'); assert.strictEqual(Q.store.pendingFor('lead@x.co'), null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
await pure(); await network();
|
||||||
|
console.log(results.join('\n'));
|
||||||
|
console.log('\nsponsorfollow: ' + passed + ' passed, ' + failed + ' failed');
|
||||||
|
process.exit(failed ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
// Holding-tank activation hold + 24-hour safety net + network alignment (2026-10-27).
|
||||||
|
// node qa/tank-hold.mjs (or: bash qa/run.sh tankhold; also part of `bash qa/run.sh member`)
|
||||||
|
// Part A, no server: tank.js with in-memory accounts, a fake chain and a MOCKED CLOCK (tank.setClock):
|
||||||
|
// ready clock starts at first sight of a linked wallet, the hold, alignment to a LinkSpin sponsor (and the refusals:
|
||||||
|
// released-from sponsor, unclaimed shell, loop), the safety net at 24 h (rotation order, cap, 7-day sign-in, company
|
||||||
|
// excluded, no-payout chain skipped, own-downline skipped), nobody eligible = keep holding + one admin alert.
|
||||||
|
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, LS_URL pointed at a dead local port so nothing
|
||||||
|
// reaches LinkSpin): a tank account links a wallet -> /api/me + /api/sponsor answer tankHold with no fallback sponsor,
|
||||||
|
// the Wallet tab hides Activate payouts and shows the hold text, the Getting started card has no activate button,
|
||||||
|
// Admin tank shows the ready badge; a member who joined through a link is never held; a LinkSpin row naming a sponsor
|
||||||
|
// aligns a tank member instead of holding them; the one-tap /my?activate=1#wallet link (stubbed wallet) starts the Activate
|
||||||
|
// flow only with a wallet, a real sponsor and no hold, and carries on after an on-page sign-in. Never production. Exit code 1 on any failure.
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import os from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { pathToFileURL } from 'node:url';
|
||||||
|
|
||||||
|
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||||
|
const require = createRequire(path.join(SITE, 'package.json'));
|
||||||
|
delete process.env.DATABASE_URL; // JSON stores only
|
||||||
|
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; };
|
||||||
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||||
|
const H = 3600000;
|
||||||
|
|
||||||
|
// ---------------- Part A ----------------
|
||||||
|
function fakeAccounts() {
|
||||||
|
const by = new Map(); let nextId = 100;
|
||||||
|
const pub = a => a ? Object.assign({}, a) : null;
|
||||||
|
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||||
|
return {
|
||||||
|
_by: by,
|
||||||
|
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
|
||||||
|
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
|
||||||
|
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
|
||||||
|
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
|
||||||
|
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
|
||||||
|
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
|
||||||
|
async listAll() { return [...by.values()].filter(a => !(a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId)).map(pub); },
|
||||||
|
isUnclaimedShell: a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId,
|
||||||
|
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function bench(o) {
|
||||||
|
o = o || {};
|
||||||
|
const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)];
|
||||||
|
const tank = require(tankPath);
|
||||||
|
const dir = o.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-'));
|
||||||
|
const accounts = o.accounts || fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {};
|
||||||
|
const notices = []; const claims = o.claims || new Set(); const onChain = o.onChain || new Set();
|
||||||
|
const blocked = new Set();
|
||||||
|
const env = o.env || { now: Date.now() };
|
||||||
|
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) },
|
||||||
|
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
|
||||||
|
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
|
||||||
|
hooks: { network: e => net[e] || null, isSuspended: () => false, excluded: () => false, payoutBlocked: async id => blocked.has(id), companyId: () => 1,
|
||||||
|
assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); },
|
||||||
|
claim: k => { if (claims.has(k)) return false; claims.add(k); return true; }, activated: a => onChain.has(a.address), notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
|
||||||
|
tank.setClock(() => env.now);
|
||||||
|
let block = 1000;
|
||||||
|
const buyer = (email, memberId, o) => { const a = accounts.add(email, Object.assign({ memberId, address: '0x' + crypto.randomBytes(20).toString('hex'), lastSeen: env.now - H }, o || {})); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2000, block: block++ }); return a; };
|
||||||
|
return { tank, accounts, events, chats, mails, alerts, assigned, net, blocked, env, buyer, dir, notices, claims, onChain };
|
||||||
|
}
|
||||||
|
async function partA() {
|
||||||
|
console.log('-- Part A: tank.js with a mocked clock');
|
||||||
|
{ // hold + ready clock + safety net rotation
|
||||||
|
const B = bench(); const { tank, accounts, env } = B;
|
||||||
|
const t0 = env.now;
|
||||||
|
accounts.add('free@x.co'); // in the tank, no wallet
|
||||||
|
const h0 = await tank.holdFor(await accounts.byEmail('free@x.co'));
|
||||||
|
ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: held, no clock yet');
|
||||||
|
accounts._by.get('free@x.co').address = '0x' + 'a'.repeat(40);
|
||||||
|
const h1 = await tank.holdFor(await accounts.byEmail('free@x.co'));
|
||||||
|
ok(h1 && h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'wallet linked: clock starts now, until = +24 h');
|
||||||
|
env.now = t0 + 5 * H;
|
||||||
|
const h2 = await tank.holdFor(await accounts.byEmail('free@x.co'));
|
||||||
|
ok(h2.hold.since === t0, 'the clock does not restart on later visits');
|
||||||
|
const sponsored = accounts.add('kid@x.co', { sponsorRef: 'someone', address: '0x' + 'b'.repeat(40) });
|
||||||
|
ok((await tank.holdFor(sponsored)) === null, 'a member with a sponsor is never held');
|
||||||
|
const w = await tank.waiting();
|
||||||
|
ok(w[0] && w[0].email === 'free@x.co' && w[0].ready && w[0].holdUntil === t0 + 24 * H, 'waiting(): ready member first with holdUntil');
|
||||||
|
// adopters: A qualified first, B second, C third; D stale (8 days), E company #1, F blocked chain, G full (2 open)
|
||||||
|
B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13);
|
||||||
|
B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16);
|
||||||
|
const tk = await tank.readyTick(); // 5 h in: nothing due
|
||||||
|
ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh.map(x => x.email)));
|
||||||
|
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
|
||||||
|
ok(tk.assigned.length === 0, 'not assigned before 24 h');
|
||||||
|
env.now = t0 + 24 * H - 10 * 60000; // 23 h 50 min: inside the last tick, so the hold never runs past 24 h
|
||||||
|
const r1 = await tank.readyTick();
|
||||||
|
ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', 'safety net: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned));
|
||||||
|
const fa = await accounts.byEmail('free@x.co');
|
||||||
|
ok(fa.sponsorRef === 'a', 'adoptee now sponsored by A', fa.sponsorRef);
|
||||||
|
ok((await tank.holdFor(fa)) === null, 'hold lifted once sponsored');
|
||||||
|
const recs = (await tank.adminView()).adoptions;
|
||||||
|
ok(recs[0] && recs[0].note === 'auto-assigned after 24 hours in the tank' && recs[0].status === 'open', 'adoption record note', recs[0] && recs[0].note);
|
||||||
|
ok(B.chats.some(c => c.from === 'a@x.co' && c.to === 'free@x.co'), 'sponsor chat opened');
|
||||||
|
ok(B.mails.some(m => m.to === 'free@x.co') && B.mails.some(m => m.to === 'a@x.co' && /holding tank is now in your line/.test(m.subject)), 'both sides emailed');
|
||||||
|
const LINK = 'https://iap.test/my?activate=1#wallet';
|
||||||
|
ok(B.chats.some(c => c.to === 'free@x.co' && c.text.includes('Switch on payouts in one tap') && c.text.includes(LINK)), 'auto-assign chat carries the one-tap link');
|
||||||
|
ok(B.mails.some(m => m.to === 'free@x.co' && m.body.includes('Switch on payouts: ' + LINK) && m.body.includes('locks @a in as your sponsor')), 'auto-assign member email carries the one-tap link');
|
||||||
|
ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup line with "(auto-assigned)")');
|
||||||
|
// second ready member: rotation moves to B (A was just auto-assigned)
|
||||||
|
accounts.add('free2@x.co', { address: '0x' + 'c'.repeat(40) });
|
||||||
|
await tank.readyTick(); env.now += 24 * H;
|
||||||
|
const r2 = await tank.readyTick();
|
||||||
|
ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: least recently auto-assigned next (B)', JSON.stringify(r2.assigned));
|
||||||
|
// third: C; D stale, E company, F blocked chain never picked
|
||||||
|
accounts.add('free3@x.co', { address: '0x' + 'd'.repeat(40) });
|
||||||
|
await tank.readyTick(); env.now += 24 * H;
|
||||||
|
const r3 = await tank.readyTick();
|
||||||
|
ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned));
|
||||||
|
// fourth: everyone in rotation has been used once: back to A (oldest auto-assign)
|
||||||
|
accounts.add('free4@x.co', { address: '0x' + 'e'.repeat(40) });
|
||||||
|
await tank.readyTick(); env.now += 24 * H;
|
||||||
|
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
|
||||||
|
const r4 = await tank.readyTick();
|
||||||
|
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned));
|
||||||
|
// A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible
|
||||||
|
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
|
||||||
|
accounts.add('free5@x.co', { address: '0x' + 'f'.repeat(40) });
|
||||||
|
await tank.readyTick(); env.now += 24 * H;
|
||||||
|
const r5 = await tank.readyTick();
|
||||||
|
const f5 = await accounts.byEmail('free5@x.co');
|
||||||
|
ok(r5.assigned.length === 0 && r5.held === 1 && !f5.sponsorRef, 'nobody eligible: keeps holding, never the company');
|
||||||
|
ok(B.alerts.length === 1 && /free5@x.co/.test(B.alerts[0]), 'admin alerted once');
|
||||||
|
await tank.readyTick(); await tank.sweep();
|
||||||
|
ok(B.alerts.length === 1, 'no second alert on later ticks / the hourly sweep');
|
||||||
|
const h5 = await tank.holdFor(f5);
|
||||||
|
ok(h5 && h5.hold && h5.hold.until <= env.now, 'still held past the clock (client shows "Any minute now")');
|
||||||
|
}
|
||||||
|
{ // one-tap link + switch-on-payouts reminders (24 h member + sponsor, 72 h member only), mocked clock
|
||||||
|
const B = bench(); const { tank, accounts, env } = B; const LINK = 'https://iap.test/my?activate=1#wallet';
|
||||||
|
B.buyer('sp@x.co', 41);
|
||||||
|
accounts.add('m1@x.co', { address: '0x' + '7'.repeat(40) }); accounts.add('m2@x.co'); accounts.add('m3@x.co', { address: '0x' + '8'.repeat(40) }); accounts.add('m4@x.co', { address: '0x' + '9'.repeat(40) });
|
||||||
|
const r = await tank.adopt('sp@x.co', 'm1', 'Hey, I am your new sponsor.');
|
||||||
|
ok(r && r.ok && !r.auto, 'manual adoption (setup)', JSON.stringify(r && r.error));
|
||||||
|
const chat = B.chats.find(c => c.to === 'm1@x.co');
|
||||||
|
ok(chat && chat.text === 'Hey, I am your new sponsor.\n\nSwitch on payouts in one tap (one free transaction, it locks me in as your sponsor): ' + LINK, 'manual adoption chat: own note + the one-tap line', chat && chat.text);
|
||||||
|
const mail = B.mails.find(m => m.to === 'm1@x.co');
|
||||||
|
ok(mail && mail.body.includes('Switch on payouts: ' + LINK) && !mail.body.includes('No wallet linked yet'), 'manual adoption email: link, no wallet sentence when linked');
|
||||||
|
await tank.adopt('sp@x.co', 'm2'); // no wallet yet
|
||||||
|
ok(B.mails.some(m => m.to === 'm2@x.co' && m.body.includes('No wallet linked yet? The same link shows you how')), 'no wallet: the email says the link walks them through linking');
|
||||||
|
const t0 = env.now;
|
||||||
|
env.now = t0 + 23 * H; let p = await tank.payTick();
|
||||||
|
ok(p.sent.length === 0, 'no reminder before 24 h');
|
||||||
|
accounts._by.get('m2@x.co').memberId = 51; // m2 switched on payouts: no reminder ever
|
||||||
|
env.now = t0 + 24 * H + 60000; const mailsBefore = B.mails.length;
|
||||||
|
p = await tank.payTick();
|
||||||
|
const r1 = B.mails.slice(mailsBefore);
|
||||||
|
ok(p.sent.length === 1 && p.sent[0].email === 'm1@x.co' && p.sent[0].stage === 1, '24 h: one reminder, only for the member still off', JSON.stringify(p.sent));
|
||||||
|
ok(r1.length === 1 && r1[0].to === 'm1@x.co' && r1[0].subject === 'Reminder: switch on payouts with @sp on InstantAdPay' && r1[0].body.includes(LINK), '24 h member email: subject + one-tap link', r1[0] && r1[0].subject);
|
||||||
|
ok(B.notices.length === 1 && B.notices[0].to === 'sp@x.co' && B.notices[0].subject === "@m1 hasn't switched on payouts yet" && B.notices[0].text.startsWith("@m1 hasn't switched on payouts yet; a nudge from you helps.") && B.notices[0].text.includes(LINK), '24 h sponsor notice', B.notices[0] && B.notices[0].text.slice(0, 80));
|
||||||
|
ok(!r1.some(m => m.to === 'sp@x.co'), 'the sponsor gets a notice, not an email');
|
||||||
|
await tank.payTick(); env.now += 15 * 60000; p = await tank.payTick();
|
||||||
|
ok(p.sent.length === 0 && B.notices.length === 1, 'idempotent: later ticks send nothing more before 72 h');
|
||||||
|
ok(tank.payView().find(x => x.email === 'm2@x.co').done === 'activated', 'activated member: record closed (activated)');
|
||||||
|
env.now = t0 + 72 * H + 60000; const m72 = B.mails.length;
|
||||||
|
p = await tank.payTick();
|
||||||
|
ok(p.sent.length === 1 && p.sent[0].stage === 2 && B.mails.length === m72 + 1 && B.mails[m72].subject === 'Last reminder: switch on payouts with @sp on InstantAdPay' && B.mails[m72].body.includes(LINK), '72 h: the last reminder, member only', JSON.stringify(p.sent));
|
||||||
|
ok(B.notices.length === 1, '72 h: no second sponsor notice');
|
||||||
|
env.now += 24 * H; p = await tank.payTick();
|
||||||
|
ok(p.sent.length === 0 && tank.payView().find(x => x.email === 'm1@x.co').done === 'reminded', 'after 72 h: done, nothing more');
|
||||||
|
ok(!/—/.test(B.chats.map(c => c.text).join(' ') + B.mails.map(m => m.subject + m.body).join(' ') + B.notices.map(n => n.subject + n.text).join(' ')), 'no em dashes in member texts');
|
||||||
|
// m3 activated on chain (MemberActivated) before the account has a memberId; m4 moved away before 24 h: both stop
|
||||||
|
B.buyer('sp2@x.co', 42);
|
||||||
|
const r3 = await tank.adopt('sp2@x.co', 'm3'); ok(r3 && r3.ok, 'second sponsor adopts m3 (setup)', JSON.stringify(r3 && r3.error));
|
||||||
|
const r4 = await tank.adopt('sp2@x.co', 'm4'); ok(r4 && r4.ok, 'second sponsor adopts m4 (setup)', JSON.stringify(r4 && r4.error));
|
||||||
|
const t3 = env.now; B.onChain.add(accounts._by.get('m3@x.co').address);
|
||||||
|
accounts._by.get('m4@x.co').sponsorRef = '';
|
||||||
|
env.now = t3 + 25 * H; p = await tank.payTick();
|
||||||
|
ok(p.sent.length === 0, 'activated on chain / sponsor changed: no reminder', JSON.stringify(p.sent));
|
||||||
|
const pv = tank.payView();
|
||||||
|
ok(pv.find(x => x.email === 'm3@x.co').done === 'activated' && pv.find(x => x.email === 'm4@x.co').done === 'moved', 'records closed as activated / moved');
|
||||||
|
ok((await tank.adminView()).payReminders.length >= 4, 'adminView lists the reminder records');
|
||||||
|
}
|
||||||
|
{ // deploy overlap: a second app copy with a stale tank-ready.json and the shared claim table sends nothing twice
|
||||||
|
const accounts = fakeAccounts(); const claims = new Set(); const env = { now: Date.now() };
|
||||||
|
const A = bench({ accounts, claims, env });
|
||||||
|
A.buyer('ov@x.co', 61); accounts.add('ovm@x.co', { address: '0x' + '6'.repeat(40) });
|
||||||
|
await A.tank.adopt('ov@x.co', 'ovm');
|
||||||
|
const stale = fs.readFileSync(path.join(A.dir, 'tank-ready.json'), 'utf8');
|
||||||
|
env.now += 25 * H;
|
||||||
|
const pa = await A.tank.payTick();
|
||||||
|
const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-ov-')); fs.writeFileSync(path.join(dir2, 'tank-ready.json'), stale);
|
||||||
|
const Bc = bench({ accounts, claims, env, dir: dir2 }); // copy B: same accounts + claims, stale state
|
||||||
|
const pb = await Bc.tank.payTick();
|
||||||
|
ok(pa.sent.length === 1 && pb.sent.length === 0 && Bc.mails.length === 0 && Bc.notices.length === 0, 'overlap: copy A sends the 24 h reminder, stale copy B sends nothing', JSON.stringify({ a: pa.sent.length, b: pb.sent.length }));
|
||||||
|
}
|
||||||
|
{ // own-downline adopter skipped
|
||||||
|
const B = bench(); const { tank, accounts, env } = B;
|
||||||
|
accounts.add('top@x.co', { address: '0x' + '1'.repeat(40) });
|
||||||
|
B.buyer('under@x.co', 21, { sponsorRef: 'top' }); B.buyer('other@x.co', 22);
|
||||||
|
await tank.readyTick(); env.now += 24 * H;
|
||||||
|
const r = await tank.readyTick();
|
||||||
|
ok(r.assigned.length === 1 && r.assigned[0].adopter === 'other@x.co', 'an adopter in the member\'s own downline is skipped', JSON.stringify(r.assigned));
|
||||||
|
}
|
||||||
|
{ // network alignment
|
||||||
|
const B = bench(); const { tank, accounts, net } = B;
|
||||||
|
accounts.add('lsboss@x.co', { memberId: 31 });
|
||||||
|
accounts.add('t1@x.co', { address: '0x' + '2'.repeat(40) }); net['t1@x.co'] = { sponsorEmail: 'lsboss@x.co', via: 'same email' };
|
||||||
|
const h = await tank.holdFor(await accounts.byEmail('t1@x.co'));
|
||||||
|
ok(h && h.aligned && (await accounts.byEmail('t1@x.co')).sponsorRef === 'lsboss', 'LinkSpin sponsor with an account here: aligned, not held', JSON.stringify(h));
|
||||||
|
ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @lsboss from LinkSpin'), 'alignment recorded with the reason');
|
||||||
|
accounts.add('shell@x.co', { joinedVia: 'linkspin', lastSeen: 0 });
|
||||||
|
accounts.add('t2@x.co'); net['t2@x.co'] = { sponsorEmail: 'shell@x.co' };
|
||||||
|
ok((await tank.holdFor(await accounts.byEmail('t2@x.co'))).hold, 'sponsor only an unclaimed LinkSpin shell here: held, not aligned');
|
||||||
|
accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' };
|
||||||
|
ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'sponsor with no account here: held');
|
||||||
|
// released from lsboss on purpose: never back to them
|
||||||
|
accounts.add('t4@x.co', { sponsorRef: 'lsboss' });
|
||||||
|
const rel = await tank.release('lsboss@x.co', 't4@x.co');
|
||||||
|
ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel));
|
||||||
|
net['t4@x.co'] = { sponsorEmail: 'lsboss@x.co' };
|
||||||
|
ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them');
|
||||||
|
// loop: the LinkSpin sponsor sits under the tank member
|
||||||
|
accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' };
|
||||||
|
ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------- Part B ----------------
|
||||||
|
async function partB() {
|
||||||
|
console.log('-- Part B: local copy');
|
||||||
|
const PORT = Number(process.env.TANKHOLD_PORT || 8799);
|
||||||
|
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'localtest';
|
||||||
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||||
|
const LSSECRET = crypto.randomBytes(24).toString('hex'); // throwaway
|
||||||
|
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, LS_SYNC_SECRET: LSSECRET, LS_URL: 'http://127.0.0.1:1' }) });
|
||||||
|
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
|
||||||
|
let browser = null;
|
||||||
|
try {
|
||||||
|
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config')).ok; } catch (e) { await sleep(500); } }
|
||||||
|
if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500));
|
||||||
|
const api = async (p, body, hdr) => { const r = await fetch(BASE + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
|
||||||
|
const adminH = { Authorization: 'Bearer ' + ADMIN };
|
||||||
|
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 20 } }, adminH);
|
||||||
|
async function signIn(email, username, extraCookie, ip) { // ip: X-Forwarded-For of its own (the code guard allows 5 sends per IP per 10 min)
|
||||||
|
const xf = ip ? { 'X-Forwarded-For': ip } : {};
|
||||||
|
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, Object.assign({}, xf, extraCookie ? { Cookie: extraCookie } : {}));
|
||||||
|
const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, xf, extraCookie ? { Cookie: extraCookie } : {}), body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
|
||||||
|
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).filter(c => /^iap\./.test(c) || c.includes('=')).join('; ');
|
||||||
|
if (username) await api('/api/my/profile', { username }, { Cookie: cookie });
|
||||||
|
return cookie;
|
||||||
|
}
|
||||||
|
const { ethers } = require('ethers');
|
||||||
|
async function linkWallet(cookie) {
|
||||||
|
const w = ethers.Wallet.createRandom();
|
||||||
|
const c = await api('/api/auth/challenge', { address: w.address }, { Cookie: cookie });
|
||||||
|
const signature = await w.signMessage(c.j.message);
|
||||||
|
const v = await api('/api/auth/verify', { address: w.address, signature }, { Cookie: cookie });
|
||||||
|
return { w, v };
|
||||||
|
}
|
||||||
|
// 1. tank member with a wallet
|
||||||
|
const tc = await signIn('qa-tank@example.com', 'qatankone');
|
||||||
|
const lw = await linkWallet(tc);
|
||||||
|
ok(lw.v.j && lw.v.j.linked, 'tank member links a wallet', JSON.stringify(lw.v.j));
|
||||||
|
const me = (await api('/api/me', null, { Cookie: tc })).j;
|
||||||
|
ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold));
|
||||||
|
ok(me && !me.sponsorId && me.sponsorBlocked === 'tankHold', '/api/me: no fallback sponsor (sponsorId ' + (me && me.sponsorId) + ')');
|
||||||
|
const sp = (await api('/api/sponsor?intent=buy', null, { Cookie: tc })).j;
|
||||||
|
ok(sp && sp.sponsorId === 1 && !sp.sponsorBlocked && !sp.tankHold, '/api/sponsor (buy) is NEVER held: falls back to the catch position #1 (Marty 2026-10-27)', JSON.stringify({ id: sp && sp.sponsorId, b: sp && sp.sponsorBlocked }));
|
||||||
|
const spa = (await api('/api/sponsor', null, { Cookie: tc })).j;
|
||||||
|
ok(spa && !spa.sponsorId && spa.sponsorBlocked === 'tankHold', '/api/sponsor without buy intent still holds (activation only)', JSON.stringify({ id: spa && spa.sponsorId, b: spa && spa.sponsorBlocked }));
|
||||||
|
const adm = (await api('/api/admin/tank', null, adminH)).j;
|
||||||
|
const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com');
|
||||||
|
ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: ready with holdUntil');
|
||||||
|
// 2. joined through a link: never held, today's behaviour
|
||||||
|
const jc = await signIn('qa-kid@example.com', 'qakidone', 'iap.sponsor=qatankone');
|
||||||
|
await linkWallet(jc);
|
||||||
|
const me2 = (await api('/api/me', null, { Cookie: jc })).j;
|
||||||
|
ok(me2 && !me2.tankHold && me2.sponsorBlocked !== 'tankHold' && me2.sponsorId > 0, 'member with a sponsor link: no hold, sponsor resolves as before', JSON.stringify({ id: me2 && me2.sponsorId, b: me2 && me2.sponsorBlocked, routed: me2 && me2.sponsorRouted }));
|
||||||
|
// 3. LinkSpin knows a sponsor for this email: aligned instead of held
|
||||||
|
await signIn('qa-lsboss@example.com', 'qalsboss');
|
||||||
|
const tc3 = await signIn('qa-tank3@example.com', 'qatankthree');
|
||||||
|
const raw = JSON.stringify({ rows: [{ email: 'qa-tank3@example.com', username: 'qatankthree', sponsorEmail: 'qa-lsboss@example.com', joinedAt: Date.now() - 86400000 }] });
|
||||||
|
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', LSSECRET).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const pr = await fetch(BASE + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw });
|
||||||
|
ok(pr.ok, 'LinkSpin row accepted (first-platform rule leaves the sponsor empty)');
|
||||||
|
const me3 = (await api('/api/me', null, { Cookie: tc3 })).j;
|
||||||
|
ok(me3 && !me3.tankHold && me3.sponsorBlocked !== 'tankHold', 'tank member LinkSpin knows: aligned, not held', JSON.stringify({ b: me3 && me3.sponsorBlocked, h: me3 && me3.tankHold }));
|
||||||
|
const adm3 = (await api('/api/admin/tank', null, adminH)).j;
|
||||||
|
ok(adm3 && adm3.aligned && adm3.aligned.some(x => x.email === 'qa-tank3@example.com' && x.to === 'qa-lsboss@example.com'), 'admin tank lists the alignment');
|
||||||
|
// 4. the page: Wallet tab + Getting started card
|
||||||
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||||
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||||
|
browser = await chromium.launch();
|
||||||
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
||||||
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); localStorage.removeItem('iap.gs.collapsed'); } catch (e) {} });
|
||||||
|
await ctx.addCookies(tc.split('; ').filter(Boolean).map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), url: BASE }; }));
|
||||||
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
||||||
|
await page.goto(BASE + '/my#wallet', { waitUntil: 'load' }); await page.waitForTimeout(4000);
|
||||||
|
const st = await page.evaluate(() => { const b = document.getElementById('activateBtn'); const n = document.getElementById('tankHoldNote'); const g = document.getElementById('gsNow');
|
||||||
|
return { card: !document.getElementById('activateCard').hidden, btnHidden: !!(b && b.hidden), note: n && !n.hidden ? n.textContent : null, gs: g ? g.textContent : '', gsBtn: !!document.getElementById('gsGo') }; });
|
||||||
|
ok(st.card && st.btnHidden, 'Wallet tab: Activate payouts button hidden', JSON.stringify(st));
|
||||||
|
ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'hold text with time left', st.note);
|
||||||
|
ok(/Matching you with a sponsor/.test(st.gs) && !st.gsBtn, 'Getting started: hold text, no activate button', st.gs.slice(0, 120));
|
||||||
|
await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-wallet.png') }).catch(() => {});
|
||||||
|
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
|
||||||
|
// 5. one-tap link /my?activate=1#wallet (2026-10-27): IAPWallet.activate is stubbed in the page (records the sponsor id,
|
||||||
|
// never reaches a wallet); it must start only for a signed-in member with a wallet, a real sponsor and no hold
|
||||||
|
const STUB = () => { window.__act = []; let real; Object.defineProperty(window, 'IAPWallet', { configurable: true, get() { return real; },
|
||||||
|
set(v) { if (v && v.activate) v.activate = async id => { window.__act.push(id); throw new Error('qa: activation stub'); }; real = v; } });
|
||||||
|
try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} };
|
||||||
|
async function actCtx(cookie, ip) { // ip: its own address for the on-page sign-in (the code guard allows 5 sends per IP per 10 min)
|
||||||
|
const c = await browser.newContext(Object.assign({ viewport: { width: 390, height: 844 } }, ip ? { extraHTTPHeaders: { 'X-Forwarded-For': ip } } : {})); await c.addInitScript(STUB);
|
||||||
|
if (cookie) await c.addCookies(cookie.split('; ').filter(Boolean).map(x => { const i = x.indexOf('='); return { name: x.slice(0, i), value: x.slice(i + 1), url: BASE }; }));
|
||||||
|
const pg = await c.newPage(); pg.on('pageerror', e => errs.push(e.message)); return { c, pg };
|
||||||
|
}
|
||||||
|
const actState = pg => pg.evaluate(() => { const n = document.getElementById('actIntentNote'); return { act: window.__act, note: n && !n.hidden ? n.textContent : null, url: location.pathname + location.search + location.hash, hold: (document.getElementById('tankHoldNote') || {}).hidden === false }; });
|
||||||
|
{ // held tank member: never triggers, the param is dropped, the hold text shows
|
||||||
|
const { c, pg } = await actCtx(tc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
|
||||||
|
const s1 = await actState(pg);
|
||||||
|
ok(s1.act.length === 0 && !s1.note && s1.hold && !/activate=1/.test(s1.url), '?activate=1 on a held tank member: no activation, hold text, param dropped', JSON.stringify(s1));
|
||||||
|
await c.close();
|
||||||
|
}
|
||||||
|
{ // sponsor link to a member who never switched on payouts (walk-up / routed): no real sponsor, never triggers
|
||||||
|
ok(me2 && me2.sponsorRouted, 'setup: the link-joined member routes past an unactivated sponsor', JSON.stringify(me2 && me2.sponsorRouted));
|
||||||
|
const { c, pg } = await actCtx(jc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
|
||||||
|
const s2 = await actState(pg);
|
||||||
|
ok(s2.act.length === 0 && !s2.note, '?activate=1 when no real sponsor resolves: no activation', JSON.stringify(s2));
|
||||||
|
await c.close();
|
||||||
|
}
|
||||||
|
// a member with a real sponsor (#21) and a wallet: the Activate flow starts at once with #21
|
||||||
|
const pc = await signIn('qa-pay@example.com', 'qapayone', 'iap.sponsor=21', '10.78.0.1'); await linkWallet(pc);
|
||||||
|
const mp = (await api('/api/me', null, { Cookie: pc })).j;
|
||||||
|
ok(mp && mp.sponsorId === 21 && !mp.sponsorFallback && !mp.tankHold && !mp.memberId, 'setup: sponsored member, sponsor #21 resolves', JSON.stringify({ id: mp && mp.sponsorId, f: mp && mp.sponsorFallback }));
|
||||||
|
{ const { c, pg } = await actCtx(pc); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4500);
|
||||||
|
const s3 = await actState(pg);
|
||||||
|
ok(s3.act.length === 1 && s3.act[0] === 21, '?activate=1: the Activate flow starts once with the sponsor prefilled (#21)', JSON.stringify(s3));
|
||||||
|
ok(s3.note === 'One free transaction switches on your payouts and locks member #21 in as your sponsor. Confirm it in your wallet.', 'explainer line above the Activate button', s3.note);
|
||||||
|
ok(/#wallet$/.test(s3.url) && !/activate=1/.test(s3.url), 'Wallet tab open, param consumed', s3.url);
|
||||||
|
await pg.reload({ waitUntil: 'load' }); await pg.waitForTimeout(3500);
|
||||||
|
ok((await actState(pg)).act.length === 0, 'a reload does not start it again');
|
||||||
|
await pg.screenshot({ path: path.join(SITE, 'qa/out/tank-activate-link.png') }).catch(() => {});
|
||||||
|
await c.close(); }
|
||||||
|
{ // signed out: sign in on the page, then the same flow carries on
|
||||||
|
const c2 = await signIn('qa-pay2@example.com', 'qapaytwo', 'iap.sponsor=21', '10.78.0.2'); await linkWallet(c2);
|
||||||
|
const { c, pg } = await actCtx(null, '10.77.' + (1 + Math.floor(Math.random() * 250)) + '.9'); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
|
||||||
|
ok((await actState(pg)).act.length === 0, 'signed out: nothing starts before sign-in');
|
||||||
|
await pg.fill('#mcEmail', 'qa-pay2@example.com'); await pg.click('#mcSendBtn');
|
||||||
|
await pg.waitForFunction(() => (document.getElementById('mcCode') || {}).value, null, { timeout: 15000 }).catch(() => {});
|
||||||
|
await pg.click('#mcVerifyBtn'); await pg.waitForTimeout(5000);
|
||||||
|
const s4 = await actState(pg);
|
||||||
|
ok(s4.act.length === 1 && s4.act[0] === 21, 'signed out -> sign in -> the Activate flow continues with #21', JSON.stringify(s4));
|
||||||
|
await c.close(); }
|
||||||
|
{ // sponsored, no wallet yet: link first (note), nothing starts; the intent waits for the link
|
||||||
|
const c3 = await signIn('qa-pay3@example.com', 'qapaythree', 'iap.sponsor=21', '10.78.0.3');
|
||||||
|
const { c, pg } = await actCtx(c3); await pg.goto(BASE + '/my?activate=1#wallet', { waitUntil: 'load' }); await pg.waitForTimeout(4000);
|
||||||
|
const s5 = await actState(pg);
|
||||||
|
ok(s5.act.length === 0 && s5.note === 'Step 1: link your wallet (one free signature). Then switching on payouts with member #21 starts by itself.', 'no wallet yet: asks to link first, nothing starts', JSON.stringify(s5));
|
||||||
|
await c.close(); }
|
||||||
|
ok(!errs.length, 'no page errors (one-tap link pages)', errs.join(' | ').slice(0, 200));
|
||||||
|
} finally {
|
||||||
|
if (browser) await browser.close().catch(() => {});
|
||||||
|
try { srv.kill(); } catch (e) {}
|
||||||
|
await sleep(500);
|
||||||
|
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await partA();
|
||||||
|
if (process.argv[2] !== 'unit') await partB();
|
||||||
|
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
|
||||||
|
process.exit(fails ? 1 : 0);
|
||||||
+22
-4
@@ -177,7 +177,7 @@ if (MODE === 'member' || MODE === 'all') {
|
|||||||
// admin
|
// admin
|
||||||
await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' });
|
await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' });
|
||||||
await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200);
|
await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200);
|
||||||
for (const pn of ['overview', 'house', 'campaigns', 'members', 'support', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'settings']) {
|
for (const pn of ['overview', 'house', 'campaigns', 'members', 'support', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'kb', 'settings']) {
|
||||||
const label = L + 'admin#' + pn;
|
const label = L + 'admin#' + pn;
|
||||||
await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200);
|
await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200);
|
||||||
const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn);
|
const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn);
|
||||||
@@ -206,6 +206,20 @@ if (MODE === 'member' || MODE === 'all') {
|
|||||||
if (!/internal note/.test(txt) || !/Waiting on member/.test(await page.$eval('#spSt', e => e.selectedOptions[0].textContent).catch(() => ''))) note('bug', L + 'admin#support', 'note/reply/status not reflected');
|
if (!/internal note/.test(txt) || !/Waiting on member/.test(await page.$eval('#spSt', e => e.selectedOptions[0].textContent).catch(() => ''))) note('bug', L + 'admin#support', 'note/reply/status not reflected');
|
||||||
await page.selectOption('#spPr', 'high'); await page.waitForTimeout(800);
|
await page.selectOption('#spPr', 'high'); await page.waitForTimeout(800);
|
||||||
await domChecks(page, L + 'admin#support (ticket)'); console.log('ok admin Support ticket', helpRef);
|
await domChecks(page, L + 'admin#support (ticket)'); console.log('ok admin Support ticket', helpRef);
|
||||||
|
// "Save as KB entry" under the reply: a prefilled knowledge-base draft (question from the member, answer from the reply) that saves
|
||||||
|
flush(bag, L + 'admin#support (ticket)');
|
||||||
|
const save = await page.$('#spView [data-kbsave]');
|
||||||
|
if (!save) note('bug', L + 'admin#support', 'no "Save as KB entry" button under the sent reply');
|
||||||
|
else {
|
||||||
|
await save.click(); await page.waitForTimeout(1200);
|
||||||
|
const draft = await page.evaluate(() => ({ q: (document.getElementById('kbQs') || {}).value || '', a: (document.getElementById('kbAns') || {}).value || '', vis: !document.getElementById('kbEdit').hidden }));
|
||||||
|
if (!draft.vis || !draft.q.trim() || !draft.a.trim()) note('bug', L + 'admin#kb', 'Save as KB entry did not open a prefilled draft ' + JSON.stringify(draft).slice(0, 160));
|
||||||
|
await domChecks(page, L + 'admin#kb (draft from ticket)');
|
||||||
|
await page.click('#kbSave'); await page.waitForTimeout(1200);
|
||||||
|
const listed = await page.$eval('#kbTable', e => e.textContent).catch(() => '');
|
||||||
|
if (!/from a ticket/.test(listed)) note('bug', L + 'admin#kb', 'entry saved from the ticket is not in the list');
|
||||||
|
flush(bag, L + 'admin#kb (saved from ticket)'); console.log('ok admin Save as KB entry');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
flush(bag, L + 'admin#support (ticket)');
|
flush(bag, L + 'admin#support (ticket)');
|
||||||
await page.screenshot({ path: OUT + '/admin-support-ticket.png' }).catch(() => {});
|
await page.screenshot({ path: OUT + '/admin-support-ticket.png' }).catch(() => {});
|
||||||
@@ -232,7 +246,8 @@ if (MODE === 'member' || MODE === 'all') {
|
|||||||
if (/QA internal note/.test(th)) note('bug', L + 'my#help', 'INTERNAL NOTE LEAKED to the member');
|
if (/QA internal note/.test(th)) note('bug', L + 'my#help', 'INTERNAL NOTE LEAKED to the member');
|
||||||
flush(bag, L + 'my#help (reply seen)'); console.log('ok member sees reply, no internal note');
|
flush(bag, L + 'my#help (reply seen)'); console.log('ok member sees reply, no internal note');
|
||||||
}
|
}
|
||||||
// public /support (signed out): the form, the guard, the private ticket link
|
// public /support (signed out): the form, the guard, the private ticket link. Members only since 2026-10-24 (962cdf0):
|
||||||
|
// a signed-out ticket needs an email that has an account (qa-walk@example.com signed up above); others get a 403
|
||||||
{
|
{
|
||||||
const pctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true });
|
const pctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true });
|
||||||
await pctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
await pctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
||||||
@@ -241,7 +256,7 @@ if (MODE === 'member' || MODE === 'all') {
|
|||||||
await domChecks(pp, L + '/support');
|
await domChecks(pp, L + '/support');
|
||||||
if (!(await pp.$('#supForm'))) note('bug', L + '/support', 'form did not render');
|
if (!(await pp.$('#supForm'))) note('bug', L + '/support', 'form did not render');
|
||||||
else {
|
else {
|
||||||
await pp.fill('#supName', 'QA Visitor'); await pp.fill('#supEmail', 'qa-visitor@example.com');
|
await pp.fill('#supName', 'QA Visitor'); await pp.fill('#supEmail', 'qa-walk@example.com');
|
||||||
await pp.fill('#supSubject', 'QA: cannot sign in'); await pp.fill('#supBody', 'The sign-in code never arrives. QA walk.');
|
await pp.fill('#supSubject', 'QA: cannot sign in'); await pp.fill('#supBody', 'The sign-in code never arrives. QA walk.');
|
||||||
await pp.click('#supSend'); await pp.waitForTimeout(3500);
|
await pp.click('#supSend'); await pp.waitForTimeout(3500);
|
||||||
const tl = await pp.$eval('#supMain a.btn[href^="/support/t/"]', e => e.getAttribute('href')).catch(() => '');
|
const tl = await pp.$eval('#supMain a.btn[href^="/support/t/"]', e => e.getAttribute('href')).catch(() => '');
|
||||||
@@ -254,7 +269,10 @@ if (MODE === 'member' || MODE === 'all') {
|
|||||||
const bad = await pp.request.get(LOCAL + '/api/support/t/' + tl.split('/').pop().slice(0, -4) + 'AAAA');
|
const bad = await pp.request.get(LOCAL + '/api/support/t/' + tl.split('/').pop().slice(0, -4) + 'AAAA');
|
||||||
if (bad.status() !== 404) note('bug', L + '/support/t', 'a tampered token was accepted: ' + bad.status());
|
if (bad.status() !== 404) note('bug', L + '/support/t', 'a tampered token was accepted: ' + bad.status());
|
||||||
}
|
}
|
||||||
const bot = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-bot@example.com', subject: 'x bot', body: 'bot body here', fts: Date.now(), fage: 10 } });
|
const nm = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-visitor@example.com', name: 'QA', subject: 'QA: not a member', category: 'Other', body: 'Not a member, should be refused.', fage: 9000 } });
|
||||||
|
const nmj = await nm.json().catch(() => ({}));
|
||||||
|
if (nm.status() !== 403 || !nmj.membersOnly) note('bug', L + '/api/support', 'a non-member email was not refused (members-only): ' + nm.status());
|
||||||
|
const bot = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-walk@example.com', subject: 'x bot', body: 'bot body here', fts: Date.now(), fage: 10 } });
|
||||||
if (bot.status() !== 400) note('bug', L + '/api/support', 'instant (form-age 10ms) post was not refused: ' + bot.status());
|
if (bot.status() !== 400) note('bug', L + '/api/support', 'instant (form-age 10ms) post was not refused: ' + bot.status());
|
||||||
}
|
}
|
||||||
await pp.screenshot({ path: OUT + '/support-public.png' }).catch(() => {});
|
await pp.screenshot({ path: OUT + '/support-public.png' }).catch(() => {});
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// Wallet push + nudge (walletnudge.js) against a MOCK game on localhost, throwaway data. Run: node qa/walletnudge.test.cjs
|
||||||
|
// 2026-10-27 (Marty, "build all three"): a signature-linked wallet is pushed to the game whether or not it is an on-chain
|
||||||
|
// member (memberId 0 when it is not); only players with NO linked wallet are nudged, and the nudge asks for the link step only.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
const http = require('http');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const assert = require('assert');
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
let fails = 0, n = 0;
|
||||||
|
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.message); } }
|
||||||
|
function fresh(mod) { const p = require.resolve(path.join(ROOT, mod)); delete require.cache[p]; return require(p); }
|
||||||
|
const SECRET = 'x'.repeat(40);
|
||||||
|
const W1 = '0x' + '1'.repeat(40), W2 = '0x' + '2'.repeat(40), W3 = '0x' + '3'.repeat(40);
|
||||||
|
|
||||||
|
// a game with the same contract as the real ones: signed GET /api/iap/unpaid, signed POST /api/iap/wallet (fill empty only)
|
||||||
|
function mockGame(players) {
|
||||||
|
const pushes = [];
|
||||||
|
const srv = http.createServer((req, res) => {
|
||||||
|
const u = new URL(req.url, 'http://x'), send = (c, j) => { res.writeHead(c, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(j)); };
|
||||||
|
if (u.pathname === '/api/iap/unpaid') {
|
||||||
|
const ts = u.searchParams.get('ts'), want = crypto.createHmac('sha256', SECRET).update('unpaid\n' + ts).digest('hex');
|
||||||
|
if (u.searchParams.get('sig') !== want) return send(401, { error: 'bad signature' });
|
||||||
|
return send(200, { ok: true, rows: Object.entries(players).filter(([, p]) => p.unpaid > 0 && !p.wallet).map(([email, p]) => ({ email, memberId: 0, username: null, unpaid: p.unpaid })) });
|
||||||
|
}
|
||||||
|
if (u.pathname === '/api/iap/wallet' && req.method === 'POST') {
|
||||||
|
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
||||||
|
const ts = String(req.headers['x-iap-ts'] || '');
|
||||||
|
const want = crypto.createHmac('sha256', SECRET).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex');
|
||||||
|
if (req.headers['x-iap-sig'] !== want) return send(401, { error: 'bad signature' });
|
||||||
|
const b = JSON.parse(raw), p = players[b.email]; pushes.push(b);
|
||||||
|
if (!p) return send(404, { error: 'unknown player' });
|
||||||
|
if (p.wallet && p.wallet.toLowerCase() !== b.wallet.toLowerCase()) return send(409, { error: 'a different wallet is already set' });
|
||||||
|
const changed = !p.wallet; if (!p.wallet) p.wallet = b.wallet;
|
||||||
|
send(200, { ok: true, changed, wallet: b.wallet, unpaid: p.unpaid });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
send(404, {});
|
||||||
|
});
|
||||||
|
return new Promise(ok => srv.listen(0, '127.0.0.1', () => ok({ srv, pushes, url: 'http://127.0.0.1:' + srv.address().port })));
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
for (const k of ['SD', 'GK', 'SEEK', 'DR', 'RA', 'PB', 'SW', 'PW']) { delete process.env[k + '_URL']; delete process.env[k + '_SSO_SECRET']; }
|
||||||
|
const players = {
|
||||||
|
'tank@x.test': { unpaid: 1.5 }, // linked wallet, NOT activated (holding tank): must be pushed, memberId 0
|
||||||
|
'member@x.test': { unpaid: 0.4 }, // linked + activated: pushed with its member id, as before
|
||||||
|
'nowallet@x.test': { unpaid: 0.75 }, // no linked wallet: nudged
|
||||||
|
'other@x.test': { unpaid: 0.2, wallet: null }, // game already holds a different wallet -> refused below
|
||||||
|
'rpc@x.test': { unpaid: 0.3 } // chain read fails: still pushed (stored member id, here 0)
|
||||||
|
};
|
||||||
|
const G = await mockGame(players);
|
||||||
|
process.env.GK_URL = G.url; process.env.GK_SSO_SECRET = SECRET;
|
||||||
|
const accts = {
|
||||||
|
'tank@x.test': { email: 'tank@x.test', username: 'tanky', address: W1, memberId: 0 },
|
||||||
|
'member@x.test': { email: 'member@x.test', username: 'mem', address: W2, memberId: 0 },
|
||||||
|
'nowallet@x.test': { email: 'nowallet@x.test', username: 'nw', address: null, memberId: 0 },
|
||||||
|
'other@x.test': { email: 'other@x.test', username: 'ot', address: W3, memberId: 0 },
|
||||||
|
'rpc@x.test': { email: 'rpc@x.test', username: 'rp', address: '0x' + '4'.repeat(40), memberId: 0 }
|
||||||
|
};
|
||||||
|
const chainIds = { [W2.toLowerCase()]: 77 };
|
||||||
|
const inbox = [], mail = [];
|
||||||
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-wn-'));
|
||||||
|
const wn = fresh('walletnudge.js');
|
||||||
|
// the 'other' player's game copy got a different wallet in between (fill-empty-only must refuse a replacement)
|
||||||
|
players['other@x.test'].wallet = '0x' + '5'.repeat(40);
|
||||||
|
players['other@x.test'].unpaid = 0.2;
|
||||||
|
// ...but then the game would not list it as unpaid-without-wallet; force it into the list once to exercise the 409 path
|
||||||
|
const origOther = players['other@x.test'];
|
||||||
|
wn.init({ dataDir: dir, site: 'https://instantadpay.com',
|
||||||
|
accounts: { byEmail: async e => accts[e] || null, byMemberId: async () => null },
|
||||||
|
chain: { memberIdByAccount: async a => { if (a === accts['rpc@x.test'].address) throw new Error('rpc down'); return chainIds[a.toLowerCase()] || 0; } },
|
||||||
|
mailer: { hasKey: () => true, send: async (to, subject, text, html) => { mail.push({ to, subject, text, html }); } },
|
||||||
|
optedIn: async () => true,
|
||||||
|
message: async (to, subject, html) => { inbox.push({ to, subject, html }); } });
|
||||||
|
|
||||||
|
let r;
|
||||||
|
await t('tick runs against the mock game', async () => { r = await wn.tick(); assert.ok(r.ok); assert.strictEqual(r.games.gemkingdom, 4); });
|
||||||
|
await t('non-activated linked wallet is pushed with memberId 0 and filled', async () => {
|
||||||
|
const p = G.pushes.find(x => x.email === 'tank@x.test'); assert.ok(p, 'no push');
|
||||||
|
assert.strictEqual(p.wallet, W1); assert.strictEqual(p.memberId, 0); assert.strictEqual(players['tank@x.test'].wallet, W1);
|
||||||
|
});
|
||||||
|
await t('activated wallet still pushed with its member id', async () => {
|
||||||
|
const p = G.pushes.find(x => x.email === 'member@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 77); assert.strictEqual(players['member@x.test'].wallet, W2);
|
||||||
|
});
|
||||||
|
await t('a failed chain read still pushes the linked wallet (stored member id)', async () => {
|
||||||
|
const p = G.pushes.find(x => x.email === 'rpc@x.test'); assert.ok(p); assert.strictEqual(p.memberId, 0);
|
||||||
|
});
|
||||||
|
await t('linked players are never nudged; the no-wallet player is', async () => {
|
||||||
|
assert.deepStrictEqual(inbox.map(x => x.to), ['nowallet@x.test']); assert.deepStrictEqual(mail.map(x => x.to), ['nowallet@x.test']);
|
||||||
|
assert.strictEqual(r.pushed, 3); assert.strictEqual(r.sent, 1);
|
||||||
|
});
|
||||||
|
await t('nudge copy: link step only, the exact approved wording, /my#wallet', async () => {
|
||||||
|
const m = mail[0];
|
||||||
|
assert.strictEqual(m.subject, '0.75 POL is waiting for your wallet');
|
||||||
|
assert.ok(m.text.includes("You've earned 0.75 POL in Gem Kingdom. Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far."), m.text);
|
||||||
|
assert.ok(m.text.includes('https://instantadpay.com/my#wallet')); assert.ok(inbox[0].html.includes('https://instantadpay.com/my#wallet'));
|
||||||
|
assert.ok(!/switch on|activate/i.test(m.text + inbox[0].html), 'mentions switching on payouts');
|
||||||
|
assert.ok(!/—/.test(m.text + inbox[0].html), 'em dash');
|
||||||
|
});
|
||||||
|
await t('second tick: nothing re-pushed as a change, no second nudge before 3 days', async () => {
|
||||||
|
const before = G.pushes.length; const r2 = await wn.tick();
|
||||||
|
assert.strictEqual(r2.pushed, 0); assert.strictEqual(r2.sent, 0); assert.strictEqual(G.pushes.length, before, 'filled players are no longer listed');
|
||||||
|
});
|
||||||
|
await t('a different wallet in the game is refused (409), never replaced, and not retried within the day', async () => {
|
||||||
|
// list the "other" player as unpaid with no wallet in the listing, but the game copy holds a different wallet
|
||||||
|
const realWallet = origOther.wallet;
|
||||||
|
const saved = G.srv.listeners('request')[0];
|
||||||
|
G.srv.removeAllListeners('request');
|
||||||
|
G.srv.on('request', (req, res) => {
|
||||||
|
if (req.url.startsWith('/api/iap/unpaid')) { res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ ok: true, rows: [{ email: 'other@x.test', memberId: 0, unpaid: 0.2 }] })); }
|
||||||
|
return saved(req, res);
|
||||||
|
});
|
||||||
|
const before = G.pushes.length;
|
||||||
|
await wn.tick(); assert.strictEqual(G.pushes.length, before + 1); assert.strictEqual(players['other@x.test'].wallet, realWallet);
|
||||||
|
const v = wn.adminView(); assert.ok(v.pushRefused.some(x => x.email === 'other@x.test' && x.status === 'conflict'));
|
||||||
|
await wn.tick(); assert.strictEqual(G.pushes.length, before + 1, 'retried within 24 h');
|
||||||
|
});
|
||||||
|
G.srv.close(); fs.rmSync(dir, { recursive: true, force: true });
|
||||||
|
console.log((n - fails) + '/' + n + ' passed'); process.exit(fails ? 1 : 0);
|
||||||
|
})();
|
||||||
@@ -10,6 +10,10 @@
|
|||||||
//
|
//
|
||||||
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget
|
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget
|
||||||
// delivered that counts as "running low".
|
// delivered that counts as "running low".
|
||||||
|
//
|
||||||
|
// 2026-10-24 (Fuel Your Offers): the bonus block names Wired Wednesday next to Five Dollar Friday, and takes
|
||||||
|
// the member's refuel-streak line from X.streakLine(owner) -> { text, html } | null when the streak is on.
|
||||||
|
// Every send is claimed first (marks.js), so the two app copies of a deploy never both write to a person.
|
||||||
'use strict';
|
'use strict';
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
@@ -32,6 +36,9 @@ function cfg() {
|
|||||||
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
|
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
|
||||||
fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
||||||
fridayPct: Number(c.fridayBonusPct) || 20,
|
fridayPct: Number(c.fridayBonusPct) || 20,
|
||||||
|
wedOn: String(c.wednesdayPromo == null ? '1' : c.wednesdayPromo) === '1',
|
||||||
|
wedPct: Math.max(0, Number(c.wednesdayBonusPct) || 25),
|
||||||
|
wedMinUsd: Math.max(0, Number(c.wednesdayMinCents) || 2000) / 100,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,21 +68,34 @@ const PACKS = [
|
|||||||
{ price: 500, credits: 70000, bonus: 40 },
|
{ price: 500, credits: 70000, bonus: 40 },
|
||||||
];
|
];
|
||||||
|
|
||||||
function ladderText() {
|
// the day bonuses, one line each; Friday and Wednesday never fall on the same day
|
||||||
|
function dayBonusLines() {
|
||||||
|
const c = cfg(); const out = [];
|
||||||
|
if (c.fridayOn) out.push({ title: 'Five Dollar Friday', body: 'any package from $5 up, bought on a Friday (Central time), earns an extra ' + c.fridayPct + '% in credits on top of the above.' });
|
||||||
|
if (c.wedOn) out.push({ title: 'Wired Wednesday', body: 'any package from $' + c.wedMinUsd + ' up, bought on a Wednesday (Central time), earns an extra ' + c.wedPct + '% in credits, wired in the moment it settles.' });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
async function streakLine(owner) {
|
||||||
|
if (typeof X.streakLine !== 'function' || !owner) return null;
|
||||||
|
try { return await X.streakLine(owner); } catch (e) { return null; }
|
||||||
|
}
|
||||||
|
function ladderText(sl) {
|
||||||
const c = cfg();
|
const c = cfg();
|
||||||
const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : ''));
|
const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : ''));
|
||||||
let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n')
|
let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n')
|
||||||
+ '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.';
|
+ '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.';
|
||||||
if (c.fridayOn) s += '\n\nFive Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.';
|
for (const d of dayBonusLines()) s += '\n\n' + d.title + ': ' + d.body;
|
||||||
|
if (sl && sl.text) s += '\n\n' + sl.text;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
function ladderHtml() {
|
function ladderHtml(sl) {
|
||||||
const c = cfg();
|
const c = cfg();
|
||||||
const rows = PACKS.map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + p.price + '</b></td><td style="padding:6px 14px 6px 0">' + money(p.credits)
|
const rows = PACKS.map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + p.price + '</b></td><td style="padding:6px 14px 6px 0">' + money(p.credits)
|
||||||
+ ' credits</td><td style="padding:6px 0;color:#0E8F72">' + (p.bonus ? p.bonus + '% more per dollar' : '') + '</td></tr>').join('');
|
+ ' credits</td><td style="padding:6px 0;color:#0E8F72">' + (p.bonus ? p.bonus + '% more per dollar' : '') + '</td></tr>').join('');
|
||||||
return '<p><b>Ad packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
|
return '<p><b>Ad packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
|
||||||
+ '<p style="color:#556">A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.</p>'
|
+ '<p style="color:#556">A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.</p>'
|
||||||
+ (c.fridayOn ? '<p><b>Five Dollar Friday:</b> any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.</p>' : '');
|
+ dayBonusLines().map(d => '<p><b>' + d.title + ':</b> ' + esc(d.body) + '</p>').join('')
|
||||||
|
+ (sl && sl.html ? '<p>' + sl.html + '</p>' : '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// what one owner's batch of campaigns says in the body
|
// what one owner's batch of campaigns says in the body
|
||||||
@@ -112,7 +132,8 @@ async function compose(owner, list, state, credits) {
|
|||||||
: canRelaunch
|
: canRelaunch
|
||||||
? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns'
|
? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns'
|
||||||
: 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy';
|
: 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy';
|
||||||
const lines = [opener, totals, next, ladderText(),
|
const sl = await streakLine(owner);
|
||||||
|
const lines = [opener, totals, next, ladderText(sl),
|
||||||
'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.'];
|
'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.'];
|
||||||
const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay';
|
const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay';
|
||||||
const html = '<p>' + opener + '</p>' + (totals ? '<p>' + totals + '</p>' : '')
|
const html = '<p>' + opener + '</p>' + (totals ? '<p>' + totals + '</p>' : '')
|
||||||
@@ -120,7 +141,7 @@ async function compose(owner, list, state, credits) {
|
|||||||
+ '<p><b>What each one did:</b></p><ul>' + list.map(c => '<li>' + esc(c.name || ('campaign #' + c.id)) + ' (' + esc(c.type || 'ad') + '): '
|
+ '<p><b>What each one did:</b></p><ul>' + list.map(c => '<li>' + esc(c.name || ('campaign #' + c.id)) + ' (' + esc(c.type || 'ad') + '): '
|
||||||
+ money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'
|
+ money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'
|
||||||
+ (n0(c.imps) ? ', ' + money(n0(c.imps)) + ' ' + unit(c) : '') + (n0(c.clicks) ? ', ' + money(n0(c.clicks)) + ' clicks' : '') + esc(videoNote(c)) + '</li>').join('') + '</ul>'
|
+ (n0(c.imps) ? ', ' + money(n0(c.imps)) + ' ' + unit(c) : '') + (n0(c.clicks) ? ', ' + money(n0(c.clicks)) + ' clicks' : '') + esc(videoNote(c)) + '</li>').join('') + '</ul>'
|
||||||
+ ladderHtml()
|
+ ladderHtml(sl)
|
||||||
+ '<p style="color:#556">Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.</p>';
|
+ '<p style="color:#556">Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.</p>';
|
||||||
return { subject, text, html };
|
return { subject, text, html };
|
||||||
}
|
}
|
||||||
@@ -178,7 +199,7 @@ async function followUps(all, alreadySent) {
|
|||||||
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
|
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
|
||||||
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
|
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
|
||||||
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; });
|
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; });
|
||||||
r.followUp = ok ? S.seq : 'failed';
|
r.followUp = ok ? S.seq : 'claimed';
|
||||||
if (ok) sent++;
|
if (ok) sent++;
|
||||||
}
|
}
|
||||||
if (due.length) save();
|
if (due.length) save();
|
||||||
@@ -186,6 +207,9 @@ async function followUps(all, alreadySent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function notify(owner, list, state, parentId) {
|
async function notify(owner, list, state, parentId) {
|
||||||
|
// claim before anything goes out: one copy of the app per message, ever (deploy overlap)
|
||||||
|
const claimKey = 'refill:' + (state === 'idle' ? 'idle:' + parentId : list.map(c => c.id).sort((a, b) => a - b).join(',') + ':' + state);
|
||||||
|
if (X.marks && !(await X.marks.claim(claimKey))) { if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = S.sent[key(cm.id, state)] || -1; return false; }
|
||||||
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
|
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
|
||||||
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
|
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
|
||||||
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
|
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
|
||||||
@@ -281,4 +305,4 @@ function resetConversions(kinds) {
|
|||||||
return { cleared: n };
|
return { cleared: n };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { init, tick, stats, resetConversions, PACKS };
|
module.exports = { init, tick, stats, resetConversions, PACKS, compose };
|
||||||
|
|||||||
@@ -0,0 +1,414 @@
|
|||||||
|
// The Monthly Refuel streak (Fuel Your Offers, Marty approved the build 2026-10-24; rules decided 2026-10-23).
|
||||||
|
// ONE streak per member across InstantAdPay and LinkSpin, kept HERE (InstantAdPay is the source of truth). LinkSpin
|
||||||
|
// reports its purchases through a signed partner call and collects its own grants and reminders from the outbox.
|
||||||
|
//
|
||||||
|
// THE RULES
|
||||||
|
// counted refuel a NEW on-chain package of $20+ on InstantAdPay (refuelMinIapCents) or $25+ on LinkSpin
|
||||||
|
// (refuelMinLsCents), bought by one of the member's own positions
|
||||||
|
// refuel day the first counted refuel starts the streak; the next is due 30 days after the last counted
|
||||||
|
// refuel (Central-time calendar days). The window opens 5 days before the due day and closes at
|
||||||
|
// the end of a 5-day grace after it. A purchase before the window is a Pit Stop, not a refuel.
|
||||||
|
// missing the grace passes with no refuel: the streak resets, unless the member's one free miss per
|
||||||
|
// 365 days covers it (the streak is kept, the month does not count, and the very next qualifying
|
||||||
|
// package counts as the next refuel)
|
||||||
|
// streak bonus purchased-grade credits on the site where bought, credit log labelled "Refuel streak":
|
||||||
|
// one engine m1 +10% m2 +15% m3 +20% m4+ +25%
|
||||||
|
// both m1 +15% m2 +20% m3 +30% m4+ +40% (+ a 100-credit Featured bonus on InstantAdPay at m4+, Marty 2026-10-24)
|
||||||
|
// both engines the other site's first qualifying package in the same cycle (any time before the next window)
|
||||||
|
// gets the both-rate, and the first site's bonus is topped up to the both-rate (difference only)
|
||||||
|
// stacking separate grants: Five Dollar Friday and Wired Wednesday still add their own on the same package
|
||||||
|
// Pit Stop a qualifying package between refuel days gets half the current streak rate, once per site per
|
||||||
|
// cycle; it is not a counted refuel
|
||||||
|
// badges 3, 6 and 12 months in a row: the InstantAdPay badge posts (one time each, like every badge)
|
||||||
|
// reminders 5 days before the refuel day, on the day, and a last call at the end of the grace: email +
|
||||||
|
// on-site notice from the site of the member's last counted refuel, from refuelReminderHour (CT)
|
||||||
|
// Refuel Day optional network bonus on the 1st of the month (refuelDayPromo, default OFF): +refuelDayPct
|
||||||
|
// on a counted refuel bought that day
|
||||||
|
// MASTER SWITCH: site setting refuelStreak (default '0'). Off: nothing is counted or granted, no reminders, the
|
||||||
|
// cards report { on:false } and stay hidden. Purchases made while it is off are never counted later.
|
||||||
|
//
|
||||||
|
// ONCE, EVERYWHERE: every purchase is decided inside a lock on the member (MySQL GET_LOCK across app copies) and
|
||||||
|
// stored by tx, so a repeat call returns the same decision. Every grant is an outbox row keyed by a unique ref
|
||||||
|
// (rf:<site>:<tx>, rftop:<site>:<tx>, rfpit:<site>:<tx>, rfday:<site>:<tx>, rffeat:<email>:<cycle>); the site
|
||||||
|
// that applies it claims 'rfg:<ref>' first (marks.js), so two copies of either app never double-grant.
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
let X = {}, FILE = null;
|
||||||
|
const TZ = 'America/Chicago';
|
||||||
|
const SITE = 'https://instantadpay.com';
|
||||||
|
const LS_SITE = 'https://linkspin.app';
|
||||||
|
const SINGLE = [10, 15, 20, 25];
|
||||||
|
const BOTH = [15, 20, 30, 40];
|
||||||
|
const CYCLE_DAYS = 30, EARLY_DAYS = 5, GRACE_DAYS = 5, FREE_MISS_DAYS = 365;
|
||||||
|
const BADGE_AT = [3, 6, 12];
|
||||||
|
const NAME = { iap: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||||
|
|
||||||
|
// ---- Central-time calendar days -----------------------------------------------------------------
|
||||||
|
const ctDay = ts => new Date(ts === undefined ? Date.now() : ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||||
|
const ctHour = ts => Number(new Date(ts === undefined ? Date.now() : ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false })) % 24;
|
||||||
|
const utcOf = day => { const [y, m, d] = String(day).split('-').map(Number); return Date.UTC(y, m - 1, d); };
|
||||||
|
const addDays = (day, n) => new Date(utcOf(day) + n * 86400000).toISOString().slice(0, 10);
|
||||||
|
const diffDays = (a, b) => Math.round((utcOf(b) - utcOf(a)) / 86400000); // b - a
|
||||||
|
const label = day => day ? new Date(utcOf(day) + 12 * 3600000).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' }) : null;
|
||||||
|
const rateSingle = k => SINGLE[Math.min(Math.max(k, 1), 4) - 1];
|
||||||
|
const rateBoth = k => BOTH[Math.min(Math.max(k, 1), 4) - 1];
|
||||||
|
const usd = c => ('$' + (Number(c || 0) / 100).toFixed(2)).replace(/\.00$/, '');
|
||||||
|
const money = n => Number(n || 0).toLocaleString('en-US');
|
||||||
|
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
|
|
||||||
|
function init(opts) { X = opts || {}; FILE = path.join(X.dataDir, 'refuel.json'); }
|
||||||
|
function cfg() {
|
||||||
|
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||||
|
return {
|
||||||
|
on: String(c.refuelStreak == null ? '0' : c.refuelStreak) === '1',
|
||||||
|
reminders: String(c.refuelReminders == null ? '1' : c.refuelReminders) === '1',
|
||||||
|
reminderHour: Math.min(23, Math.max(0, Number(c.refuelReminderHour == null ? 9 : c.refuelReminderHour) || 0)),
|
||||||
|
dayPromo: String(c.refuelDayPromo == null ? '0' : c.refuelDayPromo) === '1',
|
||||||
|
dayPct: Math.max(0, Math.min(100, Number(c.refuelDayPct == null ? 10 : c.refuelDayPct) || 0)),
|
||||||
|
minIap: Math.max(0, Number(c.refuelMinIapCents) || 2000),
|
||||||
|
minLs: Math.max(0, Number(c.refuelMinLsCents) || 2500),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const minFor = (site, c) => site === 'linkspin' ? c.minLs : c.minIap;
|
||||||
|
const dbOn = () => !!(X.db && X.db.enabled && X.db.enabled());
|
||||||
|
|
||||||
|
// ---- storage: MySQL when there is one, else one JSON file (read and written synchronously, no await in between) ----
|
||||||
|
let tablesReady = null;
|
||||||
|
async function ensureTables() {
|
||||||
|
if (!dbOn()) return;
|
||||||
|
if (!tablesReady) tablesReady = (async () => {
|
||||||
|
await X.db.q('CREATE TABLE IF NOT EXISTS refuel_members (email VARCHAR(190) PRIMARY KEY, data MEDIUMTEXT NOT NULL, updated BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||||
|
await X.db.q("CREATE TABLE IF NOT EXISTS refuel_outbox (ref VARCHAR(160) PRIMARY KEY, site VARCHAR(12) NOT NULL, email VARCHAR(190) NOT NULL, kind VARCHAR(16) NOT NULL, payload TEXT NOT NULL, status VARCHAR(8) NOT NULL DEFAULT 'pending', created BIGINT NOT NULL, done BIGINT NULL, INDEX (site, status), INDEX (email)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
|
||||||
|
})().catch(e => { tablesReady = null; throw e; });
|
||||||
|
return tablesReady;
|
||||||
|
}
|
||||||
|
function readFile() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.members = s.members || {}; s.outbox = s.outbox || {}; return s; } catch (e) { return { members: {}, outbox: {} }; } }
|
||||||
|
function writeFile(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s)); fs.renameSync(tmp, FILE); }
|
||||||
|
async function getRec(email) {
|
||||||
|
if (dbOn()) { await ensureTables(); const r = await X.db.q('SELECT data FROM refuel_members WHERE email=?', [email]); return r.length ? JSON.parse(r[0].data) : null; }
|
||||||
|
return readFile().members[email] || null;
|
||||||
|
}
|
||||||
|
async function putRec(rec) {
|
||||||
|
if (dbOn()) { await ensureTables(); await X.db.q('INSERT INTO refuel_members (email, data, updated) VALUES (?,?,?) ON DUPLICATE KEY UPDATE data=VALUES(data), updated=VALUES(updated)', [rec.email, JSON.stringify(rec), Date.now()]); return; }
|
||||||
|
const s = readFile(); s.members[rec.email] = rec; writeFile(s);
|
||||||
|
}
|
||||||
|
async function allRecs() {
|
||||||
|
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT data FROM refuel_members')).map(r => JSON.parse(r.data)); }
|
||||||
|
return Object.values(readFile().members);
|
||||||
|
}
|
||||||
|
// an outbox row is added once per ref, whatever happens after
|
||||||
|
async function addOut(item) {
|
||||||
|
const row = { ref: item.ref, site: item.site, email: item.email, kind: item.kind, payload: item.payload, status: 'pending', created: Date.now(), done: null };
|
||||||
|
if (dbOn()) { await ensureTables(); await X.db.q('INSERT IGNORE INTO refuel_outbox (ref, site, email, kind, payload, status, created) VALUES (?,?,?,?,?,?,?)', [row.ref, row.site, row.email, row.kind, JSON.stringify(row.payload), 'pending', row.created]); return; }
|
||||||
|
const s = readFile(); if (!s.outbox[row.ref]) { s.outbox[row.ref] = row; writeFile(s); }
|
||||||
|
}
|
||||||
|
async function pendingOut(site, email, limit) {
|
||||||
|
if (dbOn()) {
|
||||||
|
await ensureTables();
|
||||||
|
const rows = email ? await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' AND email=? ORDER BY created LIMIT ?", [site, email, limit || 200])
|
||||||
|
: await X.db.q("SELECT * FROM refuel_outbox WHERE site=? AND status='pending' ORDER BY created LIMIT ?", [site, limit || 200]);
|
||||||
|
return rows.map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind, payload: JSON.parse(r.payload), created: Number(r.created) }));
|
||||||
|
}
|
||||||
|
return Object.values(readFile().outbox).filter(r => r.site === site && r.status === 'pending' && (!email || r.email === email)).sort((a, b) => a.created - b.created).slice(0, limit || 200);
|
||||||
|
}
|
||||||
|
async function markDone(site, refs) {
|
||||||
|
refs = (refs || []).map(String).filter(Boolean).slice(0, 500); if (!refs.length) return 0;
|
||||||
|
if (dbOn()) { await ensureTables(); const r = await X.db.q("UPDATE refuel_outbox SET status='done', done=? WHERE site=? AND ref IN (?) AND status='pending'", [Date.now(), site, refs]); return r.affectedRows || 0; }
|
||||||
|
const s = readFile(); let n = 0; for (const ref of refs) { const r = s.outbox[ref]; if (r && r.site === site && r.status === 'pending') { r.status = 'done'; r.done = Date.now(); n++; } } writeFile(s); return n;
|
||||||
|
}
|
||||||
|
async function outRows(filter) {
|
||||||
|
if (dbOn()) { await ensureTables(); return (await X.db.q('SELECT ref, site, email, kind, payload, status, created, done FROM refuel_outbox ORDER BY created DESC LIMIT 2000')).map(r => Object.assign(r, { payload: JSON.parse(r.payload), created: Number(r.created) })).filter(filter || (() => true)); }
|
||||||
|
return Object.values(readFile().outbox).sort((a, b) => b.created - a.created).filter(filter || (() => true));
|
||||||
|
}
|
||||||
|
const lock = (email, fn) => X.db && X.db.withLock ? X.db.withLock('rf:' + email, fn, 15) : fn();
|
||||||
|
|
||||||
|
// ---- the record ---------------------------------------------------------------------------------
|
||||||
|
function blank(email) { return { v: 1, email, active: false, streak: 0, best: 0, firstDay: null, lastDay: null, dueDay: null, opensDay: null, graceEnd: null, home: null, cycle: null, history: [], misses: [], freeMissDay: null, txs: {}, badges: {} }; }
|
||||||
|
function archive(rec) { if (rec.cycle) { rec.history.unshift(rec.cycle); rec.history = rec.history.slice(0, 24); } rec.cycle = null; }
|
||||||
|
// walk the calendar forward to `today`: every grace that passed with no refuel is a miss
|
||||||
|
function settle(rec, today) {
|
||||||
|
let changed = false;
|
||||||
|
for (let guard = 0; rec.active && rec.graceEnd && today > rec.graceEnd && guard < 40; guard++) {
|
||||||
|
changed = true;
|
||||||
|
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
|
||||||
|
if (freeOk) {
|
||||||
|
rec.misses.unshift({ day: rec.dueDay, free: true }); rec.freeMissDay = rec.graceEnd;
|
||||||
|
archive(rec);
|
||||||
|
rec.opensDay = addDays(rec.graceEnd, 1); // the very next qualifying package counts
|
||||||
|
rec.dueDay = addDays(rec.dueDay, CYCLE_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
|
||||||
|
} else {
|
||||||
|
rec.misses.unshift({ day: rec.dueDay, free: false, streak: rec.streak });
|
||||||
|
archive(rec); rec.active = false; rec.streak = 0; rec.dueDay = rec.opensDay = rec.graceEnd = null;
|
||||||
|
}
|
||||||
|
rec.misses = rec.misses.slice(0, 24);
|
||||||
|
}
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
function startCycle(rec, site, day, k) {
|
||||||
|
archive(rec);
|
||||||
|
rec.active = true; rec.streak = k; rec.best = Math.max(rec.best || 0, k);
|
||||||
|
rec.firstDay = rec.firstDay || day; rec.lastDay = day; rec.home = site;
|
||||||
|
rec.dueDay = addDays(day, CYCLE_DAYS); rec.opensDay = addDays(rec.dueDay, -EARLY_DAYS); rec.graceEnd = addDays(rec.dueDay, GRACE_DAYS);
|
||||||
|
rec.cycle = { n: k, startDay: day, sites: {}, pit: {}, both: false, featured: false };
|
||||||
|
}
|
||||||
|
const pctOf = (credits, pct) => Math.round((Number(credits) || 0) * pct / 100);
|
||||||
|
|
||||||
|
// classify one purchase and build its grants. Pure on (rec, purchase, config): the tests drive it directly.
|
||||||
|
function decide(rec, p, c) {
|
||||||
|
const day = ctDay(p.ts); const site = p.site; const other = site === 'iap' ? 'linkspin' : 'iap';
|
||||||
|
settle(rec, day);
|
||||||
|
const grants = [];
|
||||||
|
const g = (gs, kind, credits, note, extra) => { if (credits > 0) grants.push(Object.assign({ site: gs, kind, credits, note, ref: null }, extra || {})); };
|
||||||
|
let kind = 'none'; const firstEver = !rec.firstDay;
|
||||||
|
if (!rec.active || !rec.cycle || day >= rec.opensDay) {
|
||||||
|
// a counted refuel that opens a new cycle (first ever, after a reset, after a free miss, or in the window)
|
||||||
|
const k = rec.active ? rec.streak + 1 : 1;
|
||||||
|
startCycle(rec, site, day, k);
|
||||||
|
const pct = rateSingle(k), bonus = pctOf(p.credits, pct);
|
||||||
|
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
|
||||||
|
kind = 'refuel';
|
||||||
|
g(site, 'streak', bonus, 'Refuel streak month ' + k + ': +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k });
|
||||||
|
} else if (!rec.cycle.sites[site]) {
|
||||||
|
// the second engine in the same cycle: both-rate here, and the first site topped up to it
|
||||||
|
const k = rec.cycle.n, pct = rateBoth(k), bonus = pctOf(p.credits, pct);
|
||||||
|
rec.cycle.sites[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus, day };
|
||||||
|
rec.cycle.both = true; kind = 'refuel';
|
||||||
|
g(site, 'streak', bonus, 'Refuel streak month ' + k + ', both engines: +' + pct + '% on your ' + usd(p.cents) + ' package', { ref: 'rf:' + site + ':' + p.tx, pct, month: k, both: true });
|
||||||
|
const o = rec.cycle.sites[other];
|
||||||
|
if (o) {
|
||||||
|
const owed = pctOf(o.credits, pct) - (o.bonus || 0);
|
||||||
|
if (owed > 0) { g(other, 'topup', owed, 'Twin Engine top-up: your month ' + k + ' refuel raised to +' + pct + '%', { ref: 'rftop:' + other + ':' + p.tx, pct, month: k }); o.bonus += owed; o.pct = pct; }
|
||||||
|
}
|
||||||
|
if (k >= 4 && !rec.cycle.featured) {
|
||||||
|
rec.cycle.featured = true;
|
||||||
|
const per = Math.max(0, Number(X.featuredBonus ? X.featuredBonus() : 100) || 100); // Marty 2026-10-24: 100 credits (was one day's Featured price, 40)
|
||||||
|
g('iap', 'featured', per, 'Twin Engine month ' + k + ': Featured bonus (' + per + ' credits)', { ref: 'rffeat:' + rec.email + ':' + rec.cycle.startDay, month: k });
|
||||||
|
}
|
||||||
|
} else if (!rec.cycle.pit[site]) {
|
||||||
|
const k = rec.cycle.n, cur = rec.cycle.both ? rateBoth(k) : rateSingle(k), pct = cur / 2;
|
||||||
|
rec.cycle.pit[site] = { tx: p.tx, cents: p.cents, credits: p.credits, pct, bonus: pctOf(p.credits, pct), day };
|
||||||
|
kind = 'pitstop';
|
||||||
|
g(site, 'pitstop', pctOf(p.credits, pct), 'Pit Stop: +' + pct + '% (half your +' + cur + '% streak rate) on your ' + usd(p.cents) + ' package', { ref: 'rfpit:' + site + ':' + p.tx, pct, month: k });
|
||||||
|
}
|
||||||
|
// the Refuel Kit: a counted refuel unlocks the kit of its Central-time month, remembered with the streak month it came at
|
||||||
|
if (kind === 'refuel') { rec.kits = rec.kits || {}; const m = day.slice(0, 7); if (!rec.kits[m]) rec.kits[m] = rec.cycle ? rec.cycle.n : 1; }
|
||||||
|
if (kind === 'refuel' && c.dayPromo && c.dayPct > 0 && day.slice(8) === '01') g(site, 'refuelday', pctOf(p.credits, c.dayPct), 'Refuel Day (the 1st): +' + c.dayPct + '% on your ' + usd(p.cents) + ' package', { ref: 'rfday:' + site + ':' + p.tx, pct: c.dayPct });
|
||||||
|
// badges: Engine Started at the first counted refuel ever (Marty 2026-10-24), then 3, 6 and 12 months in a row
|
||||||
|
const badges = [];
|
||||||
|
const opened = kind === 'refuel' && rec.cycle && rec.cycle.startDay === day && Object.keys(rec.cycle.sites).length === 1;
|
||||||
|
if (kind === 'refuel' && firstEver && !rec.badges.refuelStart) badges.push('refuelStart');
|
||||||
|
if (opened && BADGE_AT.includes(rec.streak) && !rec.badges['refuel' + rec.streak]) badges.push('refuel' + rec.streak);
|
||||||
|
for (const b of badges) rec.badges[b] = Date.now();
|
||||||
|
return { kind, day, month: rec.cycle ? rec.cycle.n : 0, grants, badges, both: !!(rec.cycle && rec.cycle.both) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- recording a purchase (both sites come through here) ------------------------------------------
|
||||||
|
async function record(p) {
|
||||||
|
const c = cfg(); if (!c.on) return { on: false };
|
||||||
|
const email = String(p.email || '').toLowerCase(); const site = p.site === 'linkspin' ? 'linkspin' : 'iap';
|
||||||
|
const tx = String(p.tx || ''); const cents = Number(p.cents) || 0; const credits = Number(p.credits) || 0;
|
||||||
|
if (!email || !tx) return { on: true, error: 'email and tx required' };
|
||||||
|
if (cents < minFor(site, c)) return { on: true, kind: 'below', minCents: minFor(site, c) };
|
||||||
|
const out = await lock(email, async () => {
|
||||||
|
const rec = (await getRec(email)) || blank(email);
|
||||||
|
if (rec.txs[tx]) return Object.assign({ repeat: true }, rec.txs[tx]);
|
||||||
|
const d = decide(rec, { site, tx, cents, credits, ts: Number(p.ts) || Date.now() }, c);
|
||||||
|
for (const gr of d.grants) {
|
||||||
|
const payload = { credits: gr.credits, note: gr.note, kind: gr.kind, pct: gr.pct || null, month: gr.month || null, cents, tx };
|
||||||
|
await addOut({ ref: gr.ref, site: gr.site, email, kind: 'grant', payload });
|
||||||
|
}
|
||||||
|
rec.txs[tx] = { kind: d.kind, site, day: d.day, month: d.month, both: d.both, refs: d.grants.map(x => x.ref), at: Date.now() };
|
||||||
|
const keys = Object.keys(rec.txs); if (keys.length > 400) for (const k of keys.slice(0, keys.length - 400)) delete rec.txs[k];
|
||||||
|
await putRec(rec);
|
||||||
|
return Object.assign({ badges: d.badges }, rec.txs[tx]);
|
||||||
|
});
|
||||||
|
if (!out.repeat && out.badges && X.badge) for (const b of out.badges) { try { await X.badge(email, b); } catch (e) { console.error('refuel badge', e.message); } }
|
||||||
|
// one short line in the payments feed for every counted refuel (never a Pit Stop), once per tx across app copies
|
||||||
|
if (!out.repeat && out.kind === 'refuel' && X.feed && (!X.marks || await X.marks.claim('rffeed:' + tx))) {
|
||||||
|
try { await X.feed(await feedLine(email, out)); } catch (e) { console.error('refuel feed', e.message); }
|
||||||
|
}
|
||||||
|
await drainLocal().catch(e => console.error('refuel drain', e.message));
|
||||||
|
if (out.kind && out.kind !== 'none') console.log('refuel:', site, out.kind, 'month', out.month, email.replace(/^(.).*(@.*)$/, '$1***$2'), String(tx).slice(0, 12));
|
||||||
|
return Object.assign({ on: true }, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function whoOf(email) {
|
||||||
|
let a = null; try { a = await X.accounts.byEmail(email); } catch (e) {}
|
||||||
|
return a && a.username ? '@' + a.username : a && a.memberId ? 'member #' + a.memberId : 'a member';
|
||||||
|
}
|
||||||
|
async function feedLine(email, out) {
|
||||||
|
const who = (await whoOf(email)).replace(/[<>&]/g, '');
|
||||||
|
const what = out.both ? 'refueled both engines' : 'refueled ' + NAME[out.site];
|
||||||
|
return '⛽ <b>' + who + '</b> ' + what + ' · streak ' + out.month;
|
||||||
|
}
|
||||||
|
// Monday roundup of the week that just ended (Mon..Sun, Central), one per week across app copies
|
||||||
|
function weekOf(today) { const dow = new Date(utcOf(today)).getUTCDay(); const mon = addDays(today, -((dow + 6) % 7)); return { thisMon: mon, from: addDays(mon, -7), to: addDays(mon, -1) }; }
|
||||||
|
async function roundup(today) {
|
||||||
|
const w = weekOf(today); let members = 0, fresh = 0, longest = 0;
|
||||||
|
for (const r of await allRecs()) {
|
||||||
|
const hits = Object.values(r.txs || {}).filter(x => x.kind === 'refuel' && x.day >= w.from && x.day <= w.to);
|
||||||
|
if (hits.length) { members++; if (hits.some(x => x.month === 1)) fresh++; }
|
||||||
|
if (r.active) longest = Math.max(longest, r.streak || 0);
|
||||||
|
}
|
||||||
|
return { week: w, members, fresh, longest };
|
||||||
|
}
|
||||||
|
// an InstantAdPay chain Purchase: resolve the owner (main member or a linked position) and record it
|
||||||
|
async function onIapPurchase(ev) {
|
||||||
|
if (!ev || ev.type !== 'Purchase' || !cfg().on) return null;
|
||||||
|
let a = await X.accounts.byMemberId(ev.buyerId).catch(() => null);
|
||||||
|
if (!a && X.accounts.positionByMember) { const pos = await X.accounts.positionByMember(ev.buyerId).catch(() => null); if (pos && pos.email) a = await X.accounts.byEmail(pos.email).catch(() => null); }
|
||||||
|
if (!a || !a.email) return null;
|
||||||
|
return record({ site: 'iap', email: a.email, tx: ev.tx, cents: ev.priceCents, credits: ev.creditAmount, ts: ev.ts });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- applying InstantAdPay's own outbox rows ---------------------------------------------------------
|
||||||
|
let draining = false;
|
||||||
|
async function drainLocal() {
|
||||||
|
if (draining) return 0; draining = true; let n = 0;
|
||||||
|
try {
|
||||||
|
for (const it of await pendingOut('iap', null, 200)) {
|
||||||
|
const mine = X.marks ? await X.marks.claim('rfg:' + it.ref) : true;
|
||||||
|
if (mine) {
|
||||||
|
if (it.kind === 'grant') {
|
||||||
|
await X.ads.addEarned(it.email, it.payload.credits, { purchased: true, log: { kind: 'bonus', note: it.payload.note, ref: it.ref.slice(0, 60) } });
|
||||||
|
try { await X.message(it.email, grantSubject(it.payload), grantHtml(it.payload, 'iap')); } catch (e) { console.error('refuel notice', e.message); }
|
||||||
|
} else if (it.kind === 'reminder') await sendReminder(it.email, it.payload, 'iap');
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
await markDone('iap', [it.ref]);
|
||||||
|
}
|
||||||
|
} finally { draining = false; }
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
function grantSubject(p) {
|
||||||
|
if (p.kind === 'topup') return 'Twin Engine top-up: +' + money(p.credits) + ' bonus credits';
|
||||||
|
if (p.kind === 'pitstop') return 'Pit Stop bonus: +' + money(p.credits) + ' credits';
|
||||||
|
if (p.kind === 'featured') return 'Twin Engine: +' + money(p.credits) + ' Featured bonus credits';
|
||||||
|
if (p.kind === 'refuelday') return 'Refuel Day bonus: +' + money(p.credits) + ' credits';
|
||||||
|
return 'Refuel counted: +' + money(p.credits) + ' bonus credits (month ' + (p.month || 1) + ')';
|
||||||
|
}
|
||||||
|
function grantHtml(p, site) {
|
||||||
|
const where = site === 'linkspin' ? 'Credits' : 'Campaigns';
|
||||||
|
return '<p>' + esc(p.note) + '. <b>' + money(p.credits) + ' bonus ad credits</b> were added to your ' + NAME[site] + ' balance, purchased-grade, so they run on any format, login ads included, and the credit log names them.</p>'
|
||||||
|
+ (p.kind === 'featured' ? '<p>Enough for two Featured days and more: book Featured links under Campaigns whenever you like, or spend them on any format.</p>' : '')
|
||||||
|
+ (p.kind === 'pitstop' ? '<p>A Pit Stop keeps an ad running between refuel days. It does not count as your monthly refuel: that is still due on your refuel day.</p>' : '')
|
||||||
|
+ '<p>See your refuel day and streak on the Refuel card (' + where + '). Bonus credits buy ad delivery only; they are never cash.</p>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the LinkSpin side of the outbox --------------------------------------------------------------
|
||||||
|
async function outbox(site, email) { return pendingOut(site === 'linkspin' ? 'linkspin' : 'iap', email ? String(email).toLowerCase() : null, 200); }
|
||||||
|
async function ack(site, refs) { return markDone(site === 'linkspin' ? 'linkspin' : 'iap', refs); }
|
||||||
|
|
||||||
|
// ---- reminders ---------------------------------------------------------------------------------------
|
||||||
|
function reminderCopy(rec, kind) {
|
||||||
|
const k = rec.streak, next = k + 1, sOne = rateSingle(next), sBoth = rateBoth(next);
|
||||||
|
const due = label(rec.dueDay), grace = label(rec.graceEnd);
|
||||||
|
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, rec.graceEnd) >= FREE_MISS_DAYS;
|
||||||
|
const offer = 'A $20+ package on InstantAdPay or $25+ on LinkSpin counts. Your next refuel earns +' + sOne + '% bonus ad credits, or +' + sBoth + '% on each site when you refuel both in the same cycle.';
|
||||||
|
if (kind === 'soon') return { subject: 'Your refuel day is ' + due, text: 'Your refuel day is ' + due + ' (Central time), and your window is open from today. ' + offer + ' Keep your ' + k + '-month streak by ' + grace + ', the end of your 5-day grace.' };
|
||||||
|
if (kind === 'day') return { subject: 'Today is your refuel day', text: 'Today is your refuel day. ' + offer + ' You have until ' + grace + ' (Central time) to keep your ' + k + '-month streak.' };
|
||||||
|
return { subject: 'Last call: your refuel grace ends tonight', text: 'Today is the last day of your 5-day grace. Refuel before midnight Central to keep your ' + k + '-month streak. ' + offer
|
||||||
|
+ (freeOk ? ' If you skip it, your one free miss this year keeps the streak, and your next package counts as the refuel.' : ' Your free miss for this year is already used, so after tonight the streak starts again from month 1.') };
|
||||||
|
}
|
||||||
|
async function sendReminder(email, payload, site) {
|
||||||
|
const host = site === 'linkspin' ? LS_SITE + '/credits' : SITE + '/my#buy';
|
||||||
|
const text = payload.text + '\n\nBuy a package: ' + host;
|
||||||
|
const html = '<p>' + esc(payload.text) + '</p><p><a href="' + host + '">Buy a package</a></p><p style="color:#556">Bonus credits buy ad delivery only; they are never cash.</p>';
|
||||||
|
try { await X.message(email, payload.subject, html); } catch (e) { console.error('refuel reminder inbox', e.message); }
|
||||||
|
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(email).catch(() => false) : false;
|
||||||
|
if (!stopped && X.mailer && X.mailer.hasKey()) {
|
||||||
|
const foot = X.drip && X.drip.unsubUrl ? '\n\nStop these emails: ' + X.drip.unsubUrl(email) : '';
|
||||||
|
try { await X.mailer.send(email, payload.subject, text + foot + '\n\nInstantAdPay'); } catch (e) { console.error('refuel reminder mail', e.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// the daily pass: settle misses, queue the reminders that came due today, apply our outbox
|
||||||
|
let ticking = false;
|
||||||
|
async function tick(now) {
|
||||||
|
const c = cfg(); if (!c.on || ticking) return { on: c.on };
|
||||||
|
ticking = true; let reminders = 0, settled = 0;
|
||||||
|
try {
|
||||||
|
const t = now || Date.now(); const today = ctDay(t); const hourOk = ctHour(t) >= c.reminderHour;
|
||||||
|
for (const r0 of await allRecs()) {
|
||||||
|
if (!r0.active) continue;
|
||||||
|
const res = await lock(r0.email, async () => {
|
||||||
|
const rec = await getRec(r0.email); if (!rec) return null;
|
||||||
|
if (settle(rec, today)) { await putRec(rec); settled++; }
|
||||||
|
if (!rec.active || !c.reminders || !hourOk) return null;
|
||||||
|
const kind = today === addDays(rec.dueDay, -EARLY_DAYS) ? 'soon' : today === rec.dueDay ? 'day' : today === rec.graceEnd ? 'last' : null;
|
||||||
|
if (!kind) return null;
|
||||||
|
if (rec.cycle && rec.cycle.startDay >= rec.opensDay) return null; // already refueled in this window
|
||||||
|
const ref = 'rfrem:' + rec.email + ':' + rec.dueDay + ':' + kind;
|
||||||
|
await addOut({ ref, site: rec.home === 'linkspin' ? 'linkspin' : 'iap', email: rec.email, kind: 'reminder', payload: Object.assign({ remind: kind, dueDay: rec.dueDay, graceEnd: rec.graceEnd, streak: rec.streak }, reminderCopy(rec, kind)) });
|
||||||
|
return kind;
|
||||||
|
});
|
||||||
|
if (res) reminders++;
|
||||||
|
}
|
||||||
|
await drainLocal();
|
||||||
|
// Monday after the reminder hour: last week's roundup to the payments feed (skipped when nobody refueled)
|
||||||
|
if (X.feed && new Date(utcOf(today)).getUTCDay() === 1 && ctHour(t) >= Math.max(9, c.reminderHour)) {
|
||||||
|
const ru = await roundup(today);
|
||||||
|
if (ru.members > 0 && (!X.marks || await X.marks.claim('rfweek:' + ru.week.thisMon))) {
|
||||||
|
try { await X.feed('⛽ <b>Refueled this week:</b> ' + ru.members + ' member' + (ru.members === 1 ? '' : 's') + ', ' + ru.fresh + ' new streak' + (ru.fresh === 1 ? '' : 's') + ', longest streak ' + ru.longest); } catch (e) { console.error('refuel roundup', e.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally { ticking = false; }
|
||||||
|
return { on: true, settled, reminders };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- what the member sees ----------------------------------------------------------------------------
|
||||||
|
async function view(email, now) {
|
||||||
|
const c = cfg(); if (!c.on) return { on: false };
|
||||||
|
email = String(email || '').toLowerCase();
|
||||||
|
const rec0 = await getRec(email); const today = ctDay(now || Date.now());
|
||||||
|
const rec = rec0 ? JSON.parse(JSON.stringify(rec0)) : blank(email);
|
||||||
|
settle(rec, today); // read-only copy: a passed grace shows as it will be stored on the next tick
|
||||||
|
const k = rec.active ? rec.streak : 0, next = k + 1;
|
||||||
|
const cy = rec.cycle;
|
||||||
|
const curRate = cy ? (cy.both ? rateBoth(cy.n) : rateSingle(cy.n)) : 0;
|
||||||
|
const windowOpen = !rec.active || !cy || today >= rec.opensDay;
|
||||||
|
const freeOk = !rec.freeMissDay || diffDays(rec.freeMissDay, today) >= FREE_MISS_DAYS;
|
||||||
|
const siteState = s => cy && cy.sites[s] ? { refueled: true, credits: cy.sites[s].credits, pct: cy.sites[s].pct, bonus: cy.sites[s].bonus, day: cy.sites[s].day, dayLabel: label(cy.sites[s].day) } : { refueled: false };
|
||||||
|
return {
|
||||||
|
on: true, started: !!rec.firstDay, engineUnlocked: !!rec.firstDay, active: rec.active, streak: k, best: rec.best || 0,
|
||||||
|
firstDay: rec.firstDay, lastDay: rec.lastDay, refuelDay: rec.dueDay, refuelDayLabel: label(rec.dueDay), opensDay: rec.opensDay, opensLabel: label(rec.opensDay),
|
||||||
|
graceEnd: rec.graceEnd, graceLabel: label(rec.graceEnd), today, daysToRefuel: rec.dueDay ? diffDays(today, rec.dueDay) : null, windowOpen,
|
||||||
|
cycle: cy ? { month: cy.n, startDay: cy.startDay, both: !!cy.both, iap: siteState('iap'), linkspin: siteState('linkspin'), rate: curRate } : null,
|
||||||
|
next: windowOpen ? { month: next, single: rateSingle(next), both: rateBoth(next) } : { month: cy.n, secondEngine: rateBoth(cy.n) },
|
||||||
|
pitStop: cy && !windowOpen ? { pct: curRate / 2, iap: !cy.pit.iap && !!cy.sites.iap, linkspin: !cy.pit.linkspin && !!cy.sites.linkspin, usedIap: !!cy.pit.iap, usedLinkspin: !!cy.pit.linkspin } : null,
|
||||||
|
freeMiss: { available: freeOk, usedDay: rec.freeMissDay }, misses: rec.misses.slice(0, 6), badges: Object.keys(rec.badges || {}),
|
||||||
|
kits: rec.kits || {}, goal: rec.engineGoal || null,
|
||||||
|
minUsd: { iap: c.minIap / 100, linkspin: c.minLs / 100 }, ladder: { single: SINGLE, both: BOTH }, refuelDay1: c.dayPromo ? c.dayPct : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// the line the refill notices add to their bonus block
|
||||||
|
async function streakLine(email) {
|
||||||
|
const v = await view(email).catch(() => null);
|
||||||
|
if (!v || !v.on) return null;
|
||||||
|
let t;
|
||||||
|
if (!v.active) t = 'Refuel streak: a $20+ package on InstantAdPay (or $25+ on LinkSpin) starts your monthly refuel streak with +10% bonus ad credits, +15% on each site when you refuel both.';
|
||||||
|
else if (v.windowOpen) t = 'Refuel streak: you are on ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') + ', and your refuel window is open now (refuel day ' + v.refuelDayLabel + ', grace to ' + v.graceLabel + ', Central time). Refuel now for +' + v.next.single + '%, or +' + v.next.both + '% on each site with both.';
|
||||||
|
else t = 'Refuel streak: month ' + v.streak + ', next refuel day ' + v.refuelDayLabel + ' (Central time).' + (v.pitStop && (v.pitStop.iap || v.pitStop.linkspin) ? ' A top-up before then earns a Pit Stop bonus of +' + v.pitStop.pct + '% (once per site this cycle).' : '');
|
||||||
|
return { text: t, html: '<b>Refuel streak:</b> ' + esc(t.replace(/^Refuel streak: /, '')) };
|
||||||
|
}
|
||||||
|
// the member's own monthly goal for the Engine Room's goals dial (conversions from the pixel); 0 clears it
|
||||||
|
async function setGoal(email, goal) {
|
||||||
|
if (!cfg().on) return { error: 'The Engine Room is not switched on.' };
|
||||||
|
email = String(email || '').toLowerCase(); const g = Math.max(0, Math.min(100000, Math.round(Number(goal) || 0)));
|
||||||
|
return lock(email, async () => { const rec = (await getRec(email)) || blank(email); rec.engineGoal = g || null; await putRec(rec); return { ok: true, goal: rec.engineGoal }; });
|
||||||
|
}
|
||||||
|
function badgesOf(email) { return getRec(String(email || '').toLowerCase()).then(r => (r && cfg().on) ? Object.keys(r.badges || {}) : []).catch(() => []); }
|
||||||
|
|
||||||
|
// ---- admin ------------------------------------------------------------------------------------------
|
||||||
|
async function stats() {
|
||||||
|
const c = cfg(); const recs = await allRecs(); const rows = await outRows();
|
||||||
|
const by = {}; for (const r of rows) { const k = r.kind === 'grant' ? r.payload.kind : 'reminder'; const b = by[k] || (by[k] = { n: 0, credits: 0, pending: 0 }); b.n++; b.credits += Number(r.payload.credits) || 0; if (r.status === 'pending') b.pending++; }
|
||||||
|
return { settings: c, members: recs.length, active: recs.filter(r => r.active).length, both: recs.filter(r => r.cycle && r.cycle.both).length,
|
||||||
|
byMonth: recs.filter(r => r.active).reduce((m, r) => { const k = Math.min(r.streak, 12); m[k] = (m[k] || 0) + 1; return m; }, {}),
|
||||||
|
grants: by, pending: rows.filter(r => r.status === 'pending').length,
|
||||||
|
recent: rows.slice(0, 40).map(r => ({ ref: r.ref, site: r.site, email: r.email, kind: r.kind === 'grant' ? r.payload.kind : 'reminder:' + r.payload.remind, credits: r.payload.credits || 0, status: r.status, at: r.created })) };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { setGoal, init, cfg, record, roundup, weekOf, feedLine, onIapPurchase, decide, settle, blank, view, streakLine, badgesOf, outbox, ack, drainLocal, tick, stats, reminderCopy,
|
||||||
|
_days: { ctDay, addDays, diffDays, label, ctHour }, SINGLE, BOTH };
|
||||||
+1
-1
@@ -64,7 +64,7 @@ function renderPage() {
|
|||||||
h += '<h2 style="font-size:24px;margin:10px 0 16px">Release notes</h2>';
|
h += '<h2 style="font-size:24px;margin:10px 0 16px">Release notes</h2>';
|
||||||
h += v.notes.length ? v.notes.map(n => '<article class="note" id="' + esc(n.id) + '"><h2>' + esc(n.title) + n.tags.map(tagChip).join('') + '</h2><p class="when">' + fmt(n.date) + '</p>' + bodyHtml(n.body) + '</article>').join('') : '<p class="muted">No notes yet.</p>';
|
h += v.notes.length ? v.notes.map(n => '<article class="note" id="' + esc(n.id) + '"><h2>' + esc(n.title) + n.tags.map(tagChip).join('') + '</h2><p class="when">' + fmt(n.date) + '</p>' + bodyHtml(n.body) + '</article>').join('') : '<p class="muted">No notes yet.</p>';
|
||||||
h += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.</p>';
|
h += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.</p>';
|
||||||
h += '</div><script src="/assets/common.js?v=20261016n"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
h += '</div><script src="/assets/common.js?v=20261023ov"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||||
return h;
|
return h;
|
||||||
}
|
}
|
||||||
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
|
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
|
||||||
|
|||||||
@@ -0,0 +1,286 @@
|
|||||||
|
// Sponsor follow + one network holding tank (Marty, 2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
|
||||||
|
//
|
||||||
|
// Background: the registry sync between the two sites (IAP lssync.js / lsinbound.js, LinkSpin iapsync.js + its
|
||||||
|
// /api/partner/registry) never overwrites a sponsor (first-platform rule). That is right for ordinary bindings (join link,
|
||||||
|
// cookie, last touch, carry-over), but a DELIBERATE change on one side (tank adoption, dormant-lead rescue, release to the
|
||||||
|
// tank, an adoption falling back at the end of its window, an admin edit) stayed on that side only.
|
||||||
|
//
|
||||||
|
// The follow rule (decide() below, unit-tested in qa/sponsorfollow.test.cjs / tests/sponsorfollow.test.cjs):
|
||||||
|
// - A deliberate change is recorded here with when, how and the sponsor before it (record()). Sync rows carry it as
|
||||||
|
// sponsorSetAt / sponsorSetBy / sponsorPrevEmail / sponsorSetOrigin, and only while it still describes the current
|
||||||
|
// sponsor (rowFields()), so a later ordinary change never travels as if it were deliberate.
|
||||||
|
// - The receiver applies the incoming sponsor (a clear back to the tank included) only when ALL hold:
|
||||||
|
// the change is deliberate; the member is NOT bound (or binding) on the receiver's contract; it is newer than the
|
||||||
|
// receiver's own deliberate change; and the receiver either agreed with the sender before the change
|
||||||
|
// (receiver's sponsor == sponsorPrevEmail), has no sponsor, or has an older deliberate change of its own.
|
||||||
|
// Otherwise nothing moves: 'bound' and 'diverged' are logged for the admin mismatch report (conservative: when the
|
||||||
|
// two sides already disagreed before the change, a person decides).
|
||||||
|
// - Race: both sides changed independently within WINDOW_MS -> the EARLIER change wins on both sides and the case is
|
||||||
|
// logged as a conflict (the later one is undone on the side that made it, and reported, never silently kept).
|
||||||
|
// - Ping-pong: the receiver stores the incoming record unchanged (same at/by/origin), so its own row carries the same
|
||||||
|
// facts back and the sender sees 'same' (plus the hash / registry loop guards of the sync modules).
|
||||||
|
// - Accounts with no record (everything before this shipped) are "old, non-deliberate": nothing is rewritten on deploy.
|
||||||
|
//
|
||||||
|
// Network tank: each platform keeps its own adoptions; rows carry a small tank summary (own adoption count and the open
|
||||||
|
// adoption, if any) which the other side stores as remote state: its waiting list hides a member with an open adoption
|
||||||
|
// elsewhere, and the two-adoptions-per-person lifetime limit counts both platforms. The adoption itself reaches the other
|
||||||
|
// side as an ordinary deliberate follow (by 'adopt'), applied quietly (no chat, mail or feed post there).
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin'];
|
||||||
|
const WINDOW_MS = 15 * 60 * 1000;
|
||||||
|
const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 }
|
||||||
|
const n = v => String(v == null ? '' : v).trim().toLowerCase();
|
||||||
|
const isDeliberate = by => DELIBERATE.includes(String(by || ''));
|
||||||
|
|
||||||
|
// ---- the rule (pure) ----
|
||||||
|
// local { sponsorEmail, prov: {at, by, sponsorEmail, prevEmail, origin} | null, bound: bool }
|
||||||
|
// incoming { sponsorEmail, at, by, prevEmail, origin }
|
||||||
|
// -> { action, apply: bool, conflict: bool, reason }
|
||||||
|
// actions: ordinary (caller keeps today's fill-empty rule) | same | bound | stale | conflict-keep | conflict-apply |
|
||||||
|
// diverged | apply
|
||||||
|
function decide(local, incoming, opts) {
|
||||||
|
const win = (opts && opts.windowMs) || WINDOW_MS;
|
||||||
|
const inc = incoming || {}; const loc = local || {};
|
||||||
|
if (!isDeliberate(inc.by) || !(Number(inc.at) > 0)) return { action: 'ordinary', apply: false, reason: 'not a deliberate change' };
|
||||||
|
if (n(inc.sponsorEmail) === n(loc.sponsorEmail)) return { action: 'same', apply: false, reason: 'already the same sponsor' };
|
||||||
|
if (loc.bound) return { action: 'bound', apply: false, conflict: true, reason: 'member is bound on this contract; the sponsor here cannot move' };
|
||||||
|
const lp = loc.prov && isDeliberate(loc.prov.by) && Number(loc.prov.at) > 0 && n(loc.prov.sponsorEmail) === n(loc.sponsorEmail) ? loc.prov : null;
|
||||||
|
const at = Number(inc.at);
|
||||||
|
if (lp) {
|
||||||
|
const lat = Number(lp.at);
|
||||||
|
// sequential, not a race: the earlier record came from the same platform, or the sender built on our current sponsor
|
||||||
|
const sequential = (lp.origin && inc.origin && n(lp.origin) === n(inc.origin)) || n(inc.prevEmail) === n(loc.sponsorEmail);
|
||||||
|
if (at === lat && !sequential) return { action: 'conflict-keep', apply: false, conflict: true, reason: 'two different changes with the same time; nothing moved' };
|
||||||
|
if (!sequential && Math.abs(at - lat) <= win) {
|
||||||
|
if (at < lat) return { action: 'conflict-apply', apply: true, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (incoming) wins on both' };
|
||||||
|
return { action: 'conflict-keep', apply: false, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (this side) wins on both' };
|
||||||
|
}
|
||||||
|
if (at <= lat) return { action: 'stale', apply: false, reason: 'this side has a newer deliberate change' };
|
||||||
|
return { action: 'apply', apply: true, reason: 'newer deliberate change' };
|
||||||
|
}
|
||||||
|
if (!n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'no sponsor here' };
|
||||||
|
if (n(inc.prevEmail) === n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'both sides had the same sponsor before the change' };
|
||||||
|
return { action: 'diverged', apply: false, conflict: true, reason: 'the two sides already had different sponsors before this change; left for the admin' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// the follow fields a sync row carries for an account (only while the record still describes the current sponsor)
|
||||||
|
function rowFields(prov, currentSponsorEmail) {
|
||||||
|
if (!prov || !isDeliberate(prov.by) || !(Number(prov.at) > 0)) return null;
|
||||||
|
if (n(prov.sponsorEmail) !== n(currentSponsorEmail)) return null;
|
||||||
|
return { sponsorSetAt: Number(prov.at), sponsorSetBy: prov.by, sponsorPrevEmail: prov.prevEmail ? n(prov.prevEmail) : null, sponsorSetOrigin: prov.origin || null };
|
||||||
|
}
|
||||||
|
// what a received row says about a deliberate change (null when it says nothing)
|
||||||
|
function incomingOf(row) {
|
||||||
|
if (!row || !isDeliberate(row.sponsorSetBy) || !(Number(row.sponsorSetAt) > 0)) return null;
|
||||||
|
return { sponsorEmail: row.sponsorEmail ? n(row.sponsorEmail) : null, at: Number(row.sponsorSetAt), by: String(row.sponsorSetBy), prevEmail: row.sponsorPrevEmail ? n(row.sponsorPrevEmail) : null, origin: row.sponsorSetOrigin ? n(row.sponsorSetOrigin) : null };
|
||||||
|
}
|
||||||
|
// hash suffix: empty when the row has none of the new fields, so every existing row hashes exactly as before (no resend)
|
||||||
|
function hashExtra(r) {
|
||||||
|
const parts = [];
|
||||||
|
if (r && r.sponsorSetBy) parts.push('f:' + [r.sponsorSetAt, r.sponsorSetBy, r.sponsorPrevEmail || '', r.sponsorSetOrigin || ''].join(','));
|
||||||
|
if (r && r.tank) parts.push('t:' + [r.tank.count || 0, r.tank.open ? 1 : 0, r.tank.adopterEmail || '', r.tank.ts || '', r.tank.expires || ''].join(','));
|
||||||
|
return parts.length ? '|' + parts.join('|') : '';
|
||||||
|
}
|
||||||
|
function cleanTank(t) {
|
||||||
|
if (!t || typeof t !== 'object') return null;
|
||||||
|
const count = Math.max(0, Math.min(99, Number(t.count) || 0)); const open = !!t.open;
|
||||||
|
if (!count && !open) return null;
|
||||||
|
return { count, open, adopterEmail: open && t.adopterEmail ? n(t.adopterEmail) : null, ts: open ? Number(t.ts) || null : null, expires: open ? Number(t.expires) || null : null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- store: records, remote tank state, pending follows, the conflict log ----
|
||||||
|
function create(opts) {
|
||||||
|
const platform = n(opts.platform); const dataDir = opts.dataDir;
|
||||||
|
const FILE = () => path.join(dataDir, 'sponsorfollow.json');
|
||||||
|
let st = null;
|
||||||
|
function load() {
|
||||||
|
if (st) return st;
|
||||||
|
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||||
|
if (!st || typeof st !== 'object') st = {};
|
||||||
|
st.prov = st.prov || {}; st.remote = st.remote || {}; st.pending = st.pending || {}; st.log = st.log || []; st.peer = st.peer || {};
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('sponsorfollow save', e.message); } }
|
||||||
|
const api = {
|
||||||
|
platform, PROTO, WINDOW_MS, DELIBERATE, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate,
|
||||||
|
get(email) { return load().prov[n(email)] || null; },
|
||||||
|
// a deliberate change made on this platform (origin = this platform), or one received and applied (origin kept)
|
||||||
|
record(email, rec) {
|
||||||
|
const e = n(email); if (!e || !isDeliberate(rec.by)) return null;
|
||||||
|
const r = { at: Number(rec.at) || Date.now(), by: rec.by, sponsorEmail: rec.sponsorEmail ? n(rec.sponsorEmail) : null, prevEmail: rec.prevEmail ? n(rec.prevEmail) : null, origin: n(rec.origin || platform) };
|
||||||
|
if (rec.note) r.note = String(rec.note).slice(0, 160);
|
||||||
|
load().prov[e] = r; save(); return r;
|
||||||
|
},
|
||||||
|
remote(email) { return load().remote[n(email)] || null; },
|
||||||
|
setRemote(email, tank) {
|
||||||
|
const e = n(email); const t = cleanTank(tank); const s = load();
|
||||||
|
const cur = s.remote[e] ? JSON.stringify(s.remote[e]) : null;
|
||||||
|
if (!t) { if (cur) { delete s.remote[e]; save(); } return; }
|
||||||
|
if (cur !== JSON.stringify(t)) { s.remote[e] = t; save(); }
|
||||||
|
},
|
||||||
|
remoteOpen(email, now) { const t = api.remote(email); return !!(t && t.open && (!t.expires || t.expires > (now || Date.now()))); },
|
||||||
|
remoteCount(email) { const t = api.remote(email); return t ? Number(t.count) || 0 : 0; },
|
||||||
|
pending() { return Object.assign({}, load().pending); },
|
||||||
|
pendingFor(email) { return load().pending[n(email)] || null; },
|
||||||
|
setPending(email, incoming, why) { const s = load(); s.pending[n(email)] = Object.assign({}, incoming, { why: String(why || '').slice(0, 120), since: (s.pending[n(email)] && s.pending[n(email)].since) || Date.now() }); save(); },
|
||||||
|
clearPending(email) { const s = load(); if (s.pending[n(email)]) { delete s.pending[n(email)]; save(); } },
|
||||||
|
note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 500) s.log = s.log.slice(-500); save(); },
|
||||||
|
recent(k) { return load().log.slice(-(k || 100)).reverse(); },
|
||||||
|
conflictsFor(email) { const e = n(email); return load().log.filter(x => x.email === e && x.conflict); },
|
||||||
|
setPeer(proto) { const s = load(); if (s.peer.proto !== proto) { s.peer.proto = proto; s.peer.at = Date.now(); save(); } },
|
||||||
|
peerProto() { return Number(load().peer.proto) || 1; },
|
||||||
|
view() { const s = load(); return { records: Object.keys(s.prov).length, remoteTank: Object.keys(s.remote).length, pending: Object.keys(s.pending).length, peerProto: Number(s.peer.proto) || 1, recent: s.log.slice(-40).reverse() }; },
|
||||||
|
_state: load, _reset() { st = null; }
|
||||||
|
};
|
||||||
|
return api;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- signed partner calls (the same HMAC the registry sync uses: hex HMAC-SHA256(ts + "\n" + raw), LS_SYNC_SECRET) ----
|
||||||
|
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||||
|
function verify(raw, headers) {
|
||||||
|
const secret = SECRET(); if (secret.length < 32) return { status: 503, error: 'sync not configured' };
|
||||||
|
const ts = String(headers['x-ls-ts'] || ''), sig = String(headers['x-ls-sig'] || '');
|
||||||
|
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' };
|
||||||
|
const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||||
|
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
async function peerPost(baseUrl, pth, body, timeoutMs) {
|
||||||
|
const secret = SECRET(); if (secret.length < 32) throw new Error('sync not configured (LS_SYNC_SECRET)');
|
||||||
|
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||||
|
const sig = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||||
|
const r = await fetch(String(baseUrl).replace(/\/+$/, '') + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 30000) });
|
||||||
|
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
||||||
|
if (!r.ok) throw new Error((j && j.error) || ('peer ' + r.status + ' ' + txt.slice(0, 120)));
|
||||||
|
return j || {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the admin mismatch report (pure): both sides' facts -> rows that differ ----
|
||||||
|
// facts row: { email, username, sponsorEmail, sponsorRef, prov, bound, boundWhy, memberId, created, joinedVia, adoptions, activation }
|
||||||
|
function mismatches(iapRows, lsRows) {
|
||||||
|
const L = new Map((lsRows || []).map(r => [n(r.email), r]));
|
||||||
|
const out = []; let shared = 0, same = 0;
|
||||||
|
for (const a of iapRows || []) {
|
||||||
|
const b = L.get(n(a.email)); if (!b) continue; shared++;
|
||||||
|
const sa = n(a.sponsorEmail), sb = n(b.sponsorEmail);
|
||||||
|
if (sa === sb) { same++; continue; }
|
||||||
|
out.push({ email: n(a.email), username: a.username || b.username || null, kind: sa && sb ? 'differ' : sa ? 'iap-only' : 'ls-only', iap: a, ls: b });
|
||||||
|
}
|
||||||
|
out.sort((x, y) => (x.kind === 'differ' ? 0 : 1) - (y.kind === 'differ' ? 0 : 1) || x.email.localeCompare(y.email));
|
||||||
|
return { shared, same, rows: out };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the platform glue: one implementation, per-platform hooks ----
|
||||||
|
// deps: { store, accounts, tank: () => tankModule|null, peer: 'linkspin'|'instantadpay',
|
||||||
|
// isBound: async acct => { bound, why, retry }, // retry = cannot tell right now (chain read failed, activation in flight)
|
||||||
|
// sponsorAccount: async email => acct|null, // the sponsor's account here (may build a waiting shell)
|
||||||
|
// wouldCycle: async (email, spAcct) => bool, // optional
|
||||||
|
// activationOf: acct => { id, sponsorId, block, tx } | null,
|
||||||
|
// afterResolve: async email => {} } // optional, after a pending follow is settled
|
||||||
|
function glue(deps) {
|
||||||
|
const S = deps.store, A = deps.accounts;
|
||||||
|
const tokenOf = a => a.username || a.code || (a.memberId ? String(a.memberId) : '');
|
||||||
|
async function accountOfRef(ref) {
|
||||||
|
const t = n(ref); if (!t) return null;
|
||||||
|
return (await A.byUsername(t).catch(() => null)) || (await A.byCode(t).catch(() => null)) || (/^\d+$/.test(t) && A.byMemberId ? await A.byMemberId(Number(t)).catch(() => null) : null) || null;
|
||||||
|
}
|
||||||
|
async function emailOfRef(ref) { const a = await accountOfRef(ref); return a ? n(a.email) : null; }
|
||||||
|
// a deliberate change made on THIS platform: record first (so the ~3 s sync touch already carries it), then write
|
||||||
|
async function setDeliberate(email, token, by, note) {
|
||||||
|
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No such account.' };
|
||||||
|
const prev = await emailOfRef(a.sponsorRef); const tok = n(token);
|
||||||
|
const next = tok ? await emailOfRef(tok) : null;
|
||||||
|
if (isDeliberate(by)) S.record(e, { by, sponsorEmail: next, prevEmail: prev, note });
|
||||||
|
return A.setSponsorRef(e, tok);
|
||||||
|
}
|
||||||
|
async function closeLocalAdoptions(email, inc, d) {
|
||||||
|
const T = deps.tank && deps.tank(); if (!T || !T.onFollow) return;
|
||||||
|
try { await T.onFollow(email, inc, d); } catch (e) { console.error('tank onFollow', e.message); }
|
||||||
|
}
|
||||||
|
// a row from the other platform that carries a deliberate change
|
||||||
|
async function applyIncoming(email, row, opts) {
|
||||||
|
const inc = incomingOf(row); if (!inc) return { action: 'ordinary' };
|
||||||
|
const e = n(email); const a = await A.byEmail(e); if (!a) return { action: 'no-account' };
|
||||||
|
const cur = await emailOfRef(a.sponsorRef);
|
||||||
|
if (n(cur) === n(inc.sponsorEmail)) { S.clearPending(e); return { action: 'same', apply: false }; } // nothing to move (no chain read needed)
|
||||||
|
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: 'bound check failed: ' + err.message }))) || {};
|
||||||
|
if (b.retry && !b.bound) { S.setPending(e, inc, b.why); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: b.why }); return { action: 'pending', reason: b.why }; }
|
||||||
|
const d = decide({ sponsorEmail: cur, prov: S.get(e), bound: !!b.bound }, inc, opts);
|
||||||
|
if (!d.apply) {
|
||||||
|
S.clearPending(e);
|
||||||
|
if (d.action !== 'same') S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, prev: inc.prevEmail, reason: d.reason + (b.bound && b.why ? ' (' + b.why + ')' : ''), conflict: !!d.conflict });
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
let tok = '';
|
||||||
|
if (inc.sponsorEmail) {
|
||||||
|
const sp = await ((opts && opts.sponsorAccount) || deps.sponsorAccount)(inc.sponsorEmail);
|
||||||
|
if (!sp) { S.setPending(e, inc, 'the new sponsor has no account here yet'); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'sponsor account missing' }); return { action: 'pending', reason: 'sponsor account missing' }; }
|
||||||
|
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) { S.clearPending(e); S.note({ email: e, action: 'refused', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'would sponsor themselves or close a loop', conflict: true }); return { action: 'refused', reason: 'loop' }; }
|
||||||
|
tok = tokenOf(sp);
|
||||||
|
if (!tok) { S.setPending(e, inc, 'the new sponsor has no username or code here yet'); return { action: 'pending', reason: 'sponsor token missing' }; }
|
||||||
|
}
|
||||||
|
S.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || deps.peer });
|
||||||
|
const r = await A.setSponsorRef(e, tok);
|
||||||
|
if (r && r.error) { S.note({ email: e, action: 'error', reason: r.error, conflict: true }); return { action: 'error', reason: r.error }; }
|
||||||
|
await closeLocalAdoptions(e, inc, d);
|
||||||
|
S.clearPending(e);
|
||||||
|
S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, reason: d.reason, conflict: !!d.conflict });
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
// follows that could not be settled yet (chain unreadable, activation in flight, sponsor not here yet): retried on the sync tick
|
||||||
|
async function retryPending(maxAgeMs) {
|
||||||
|
const out = { tried: 0, settled: 0, dropped: 0 }; const now = Date.now();
|
||||||
|
for (const [e, p] of Object.entries(S.pending())) {
|
||||||
|
if (now - (p.since || now) > (maxAgeMs || 7 * 86400000)) { S.clearPending(e); S.note({ email: e, action: 'gave-up', by: p.by, to: p.sponsorEmail, reason: 'pending for 7 days: ' + (p.why || ''), conflict: true }); out.dropped++; continue; }
|
||||||
|
out.tried++;
|
||||||
|
const r = await applyIncoming(e, { sponsorEmail: p.sponsorEmail, sponsorSetAt: p.at, sponsorSetBy: p.by, sponsorPrevEmail: p.prevEmail, sponsorSetOrigin: p.origin }).catch(err => ({ action: 'error', reason: err.message }));
|
||||||
|
if (r.action !== 'pending') { out.settled++; if (deps.afterResolve) { try { await deps.afterResolve(e); } catch (err) {} } }
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// the admin's pick in the mismatch report: apply `sponsorEmail` (null = back to the tank) here unless bound here
|
||||||
|
async function adminApply(email, sponsorEmail, opts) {
|
||||||
|
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No account for ' + e + ' here.' };
|
||||||
|
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: err.message }))) || {};
|
||||||
|
if (b.bound) return { error: 'Refused: ' + e + ' is already bound on this platform\'s contract (' + (b.why || 'on chain') + '). Its sponsor here cannot change.' };
|
||||||
|
if (b.retry) return { error: 'Could not confirm that ' + e + ' is not on the contract yet (' + (b.why || 'chain read failed') + '). Nothing changed. Try again in a minute.' };
|
||||||
|
let tok = '';
|
||||||
|
if (sponsorEmail) {
|
||||||
|
const sp = await deps.sponsorAccount(n(sponsorEmail));
|
||||||
|
if (!sp) return { error: 'The sponsor ' + n(sponsorEmail) + ' has no account here. Nothing changed.' };
|
||||||
|
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) return { error: 'That would make the member their own upline. Nothing changed.' };
|
||||||
|
tok = tokenOf(sp); if (!tok) return { error: 'The sponsor has no username or code here yet. Nothing changed.' };
|
||||||
|
}
|
||||||
|
const prev = await emailOfRef(a.sponsorRef);
|
||||||
|
S.record(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null, prevEmail: prev, origin: (opts && opts.origin) || S.platform, note: (opts && opts.note) || 'mismatch report' });
|
||||||
|
const r = await A.setSponsorRef(e, tok); if (r && r.error) return r;
|
||||||
|
await closeLocalAdoptions(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null }, { action: 'admin' });
|
||||||
|
S.clearPending(e);
|
||||||
|
S.note({ email: e, action: 'admin-fix', by: 'admin', from: prev, to: sponsorEmail ? n(sponsorEmail) : null, reason: (opts && opts.note) || 'mismatch report' });
|
||||||
|
return { ok: true, email: e, from: prev, to: sponsorEmail ? n(sponsorEmail) : null };
|
||||||
|
}
|
||||||
|
// this platform's facts for the mismatch report (no chain reads: memberId + the indexed activation event)
|
||||||
|
async function facts(onlyEmails) {
|
||||||
|
const all = await A.listAll(50000, { shells: true });
|
||||||
|
const only = onlyEmails && onlyEmails.length ? new Set(onlyEmails.map(n)) : null;
|
||||||
|
const byTok = new Map(); for (const a of all) { if (a.username) byTok.set(n(a.username), a); if (a.code) byTok.set(n(a.code), a); if (a.memberId) byTok.set(String(a.memberId), a); }
|
||||||
|
const T = deps.tank && deps.tank();
|
||||||
|
const hist = T && T.historyMap ? await T.historyMap().catch(() => new Map()) : new Map();
|
||||||
|
const logBy = new Map(); for (const x of S.recent(500)) { if (!x.email) continue; if (!logBy.has(x.email)) logBy.set(x.email, []); if (logBy.get(x.email).length < 6) logBy.get(x.email).push(x); }
|
||||||
|
return all.filter(a => a.email && (!only || only.has(n(a.email)))).map(a => {
|
||||||
|
const e = n(a.email); const sp = a.sponsorRef ? byTok.get(n(a.sponsorRef)) : null;
|
||||||
|
const act = deps.activationOf ? deps.activationOf(a) : null;
|
||||||
|
return { email: e, username: a.username || null, sponsorRef: a.sponsorRef || '', sponsorEmail: sp && n(sp.email) !== e ? n(sp.email) : null, sponsorName: sp ? (sp.username ? '@' + sp.username : n(sp.email)) : null,
|
||||||
|
deadLink: !!(a.sponsorRef && !sp), prov: S.get(e), memberId: Number(a.memberId) || 0, bound: Number(a.memberId) > 0 || !!act, activation: act || null,
|
||||||
|
created: Number(a.created) || null, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null, lastSeen: Number(a.lastSeen) || 0, wallet: !!a.address,
|
||||||
|
adoptions: hist.get(e) || [], remoteTank: S.remote(e), pending: S.pendingFor(e), log: logBy.get(e) || [] };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { setDeliberate, applyIncoming, retryPending, adminApply, facts, emailOfRef, accountOfRef, tokenOf };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { create, glue, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate, verify, peerPost, mismatches, DELIBERATE, WINDOW_MS, PROTO };
|
||||||
@@ -15,6 +15,9 @@ const CAP_OPEN = 2; // open adoptions per adopter
|
|||||||
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
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 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)
|
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)
|
||||||
|
const NOT_COUNTED = ['released', 'conflict'];
|
||||||
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
|
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 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 RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
||||||
@@ -28,10 +31,11 @@ const J = {
|
|||||||
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } 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 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 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 && x.status !== 'released').length; },
|
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 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 recent(n) { return this.db.adoptions.slice(-(n || 100)).reverse(); },
|
||||||
async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && x.status !== 'released'); },
|
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 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(); }
|
async setMark(lead, f) { this.db.marks[lead] = Object.assign(this.db.marks[lead] || {}, f); this.save(); }
|
||||||
};
|
};
|
||||||
@@ -44,10 +48,11 @@ const D = {
|
|||||||
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
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);
|
return rows.map(rowA);
|
||||||
},
|
},
|
||||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status<>'released'", [adoptee]); return Number(r[0].n); },
|
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [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 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 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<>'released'", [adoptee]); return Number(r[0].n) > 0; },
|
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [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 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) {
|
async setMark(lead, f) {
|
||||||
const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f);
|
const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f);
|
||||||
@@ -58,7 +63,16 @@ const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Numbe
|
|||||||
const impl = () => db.enabled() ? D : J;
|
const impl = () => db.enabled() ? D : J;
|
||||||
|
|
||||||
let ads = null;
|
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; J.load(); }
|
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 mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||||
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
||||||
@@ -67,13 +81,16 @@ const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or
|
|||||||
// waiting list: newest sign-in first so a live one is easy to spot
|
// waiting list: newest sign-in first so a live one is easy to spot
|
||||||
async function waiting() {
|
async function waiting() {
|
||||||
const all = await accounts.listAll(5000);
|
const all = await accounts.listAll(5000);
|
||||||
const rows = all.filter(inTank);
|
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
|
// 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)) : {};
|
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,
|
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
|
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 }))
|
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0,
|
||||||
.sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
|
||||||
|
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
|
||||||
|
// ready members first (least time left first), then newest sign-in
|
||||||
|
.sort((a, b) => (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)
|
// has this member bought a $20+ package themselves? (the qualifying-for-yourself buy)
|
||||||
@@ -100,10 +117,11 @@ async function view(email) {
|
|||||||
const a = await accounts.byEmail(ad.adoptee);
|
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) });
|
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, waiting: await waiting(), mine };
|
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, waiting: await waiting(), mine };
|
||||||
}
|
}
|
||||||
|
|
||||||
async function adopt(adopterEmail, who, note) {
|
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 e = String(adopterEmail || '').toLowerCase();
|
||||||
const el = await eligibility(e);
|
const el = await eligibility(e);
|
||||||
if (!el.ok) return { error: el.reason };
|
if (!el.ok) return { error: el.reason };
|
||||||
@@ -113,21 +131,31 @@ async function adopt(adopterEmail, who, note) {
|
|||||||
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
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) return { error: 'That member is no longer in the tank.' };
|
||||||
if (target.email === e) return { error: 'That is you.' };
|
if (target.email === e) return { error: 'That is you.' };
|
||||||
if (await impl().countFor(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' };
|
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 token = me.username || me.code || String(me.memberId);
|
||||||
const r = await accounts.setSponsorRef(target.email, token);
|
const r = await setSponsor(target.email, token, 'adopt');
|
||||||
if (r.error) return r;
|
if (r.error) return r;
|
||||||
const now = Date.now();
|
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 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: text });
|
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
||||||
try { await messages.sendChat(me.memberId || 0, e, target.email, text); } catch (err) {}
|
{ 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()) {
|
if (mailer && mailer.hasKey()) {
|
||||||
try {
|
try {
|
||||||
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay',
|
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\nReply in your member area: ' + siteUrl + '/my#messages\n\nInstantAdPay');
|
'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) {}
|
} catch (err) {}
|
||||||
}
|
}
|
||||||
return { ok: true, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
}
|
||||||
|
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
|
// pay it forward: give one of your own free referrals to the tank
|
||||||
@@ -140,12 +168,15 @@ async function release(ownerEmail, directEmail) {
|
|||||||
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
|
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)
|
// 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);
|
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
|
||||||
const young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
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) {
|
if (young) {
|
||||||
const hrs = Math.ceil((HOLD_MS - (Date.now() - young.ts)) / 3600000);
|
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).' };
|
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 accounts.setSponsorRef(d, '');
|
const r = await setSponsor(d, '', 'release');
|
||||||
if (r.error) return r;
|
if (r.error) return r;
|
||||||
// an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two
|
// an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two
|
||||||
let closed = 0;
|
let closed = 0;
|
||||||
@@ -165,11 +196,12 @@ async function sweep() {
|
|||||||
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
||||||
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; 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; }
|
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||||
await accounts.setSponsorRef(ad.adoptee, '');
|
await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
|
||||||
await impl().setStatus(ad.id, 'expired'); back++;
|
await impl().setStatus(ad.id, 'expired'); back++;
|
||||||
}
|
}
|
||||||
const r = await rescueSweep();
|
const r = await rescueSweep();
|
||||||
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead };
|
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
|
// pay-it-forward gift record: the sponsor already sent POL wallet-to-wallet; we
|
||||||
@@ -231,10 +263,12 @@ async function rescueSweep() {
|
|||||||
for (const a of await accounts.listAll(5000)) {
|
for (const a of await accounts.listAll(5000)) {
|
||||||
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
|
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
|
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);
|
const sp = await sponsorOf(a);
|
||||||
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
||||||
if (now - (a.created || 0) < 86400000) continue;
|
if (now - (a.created || 0) < 86400000) continue;
|
||||||
await accounts.setSponsorRef(a.email, '');
|
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' });
|
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;
|
dead++; continue;
|
||||||
}
|
}
|
||||||
@@ -250,7 +284,7 @@ async function rescueSweep() {
|
|||||||
warned++; continue;
|
warned++; continue;
|
||||||
}
|
}
|
||||||
if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) {
|
if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) {
|
||||||
await accounts.setSponsorRef(a.email, '');
|
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' });
|
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',
|
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) {} }
|
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) {} }
|
||||||
@@ -260,11 +294,262 @@ async function rescueSweep() {
|
|||||||
return { warned, rescued, dead };
|
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);
|
||||||
|
if (rec && !rec.notified) { rec.notified = clock(); fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS }); }
|
||||||
|
}
|
||||||
|
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(); }
|
||||||
|
|
||||||
async function adminView() {
|
async function adminView() {
|
||||||
const recent = await impl().recent(200);
|
const recent = await impl().recent(200);
|
||||||
const names = {};
|
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; }
|
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 };
|
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, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS };
|
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, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||||
|
|||||||
@@ -362,6 +362,7 @@ async function ingestEmail(e) {
|
|||||||
if (!ticketId) { const r = parseRef(e.subject); if (r) { const t = await byRef(r.ref); if (t && t.email === from) ticketId = t.id; } }
|
if (!ticketId) { const r = parseRef(e.subject); if (r) { const t = await byRef(r.ref); if (t && t.email === from) ticketId = t.id; } }
|
||||||
const body = clean(e.text, 5000);
|
const body = clean(e.text, 5000);
|
||||||
if (ticketId) { const r = await addMessage(ticketId, { author: 'member', body, emailMessageId: mid, via: 'email' }); return Object.assign(r, { created: false }); }
|
if (ticketId) { const r = await addMessage(ticketId, { author: 'member', body, emailMessageId: mid, via: 'email' }); return Object.assign(r, { created: false }); }
|
||||||
|
if (e.canOpen && !(await e.canOpen(from))) return { error: 'not a member (new tickets need a platform account)', created: false }; // replies above still land
|
||||||
const r = await create({ platform: e.platform || 'iap', source: 'email', email: from, name: e.name, subject: oneLine(e.subject, 140) || '(no subject)', category: 'Other', body, emailMessageId: mid, via: 'email', confirm: !!e.confirm });
|
const r = await create({ platform: e.platform || 'iap', source: 'email', email: from, name: e.name, subject: oneLine(e.subject, 140) || '(no subject)', category: 'Other', body, emailMessageId: mid, via: 'email', confirm: !!e.confirm });
|
||||||
return Object.assign(r, { created: true });
|
return Object.assign(r, { created: true });
|
||||||
}
|
}
|
||||||
|
|||||||
+68
-10
@@ -4,6 +4,16 @@
|
|||||||
// three touches per person: at once, at 3 days, at 10 days. In-app notice always (kind 'notice', never a pop-up
|
// three touches per person: at once, at 3 days, at 10 days. In-app notice always (kind 'notice', never a pop-up
|
||||||
// broadcast); email only when the member opted in and outbound mail is on. Stops the moment a wallet is linked.
|
// broadcast); email only when the member opted in and outbound mail is on. Stops the moment a wallet is linked.
|
||||||
// State: DATA_DIR/wallet-nudge.json. The coach card reads waitingFor() to badge a direct.
|
// State: DATA_DIR/wallet-nudge.json. The coach card reads waitingFor() to badge a direct.
|
||||||
|
// Wallet push (Marty, 2026-10-25): a game only learns the wallet on the IAP -> game hand-off, so a member who linked a wallet
|
||||||
|
// after that and keeps a remembered game session never got paid (solanaclick, 1.5 POL in Gem Kingdom). Now a row whose IAP
|
||||||
|
// account has a wallet that is an on-chain member (the same a.address the hand-off token carries) is PUSHED to that game's
|
||||||
|
// signed POST /api/iap/wallet instead of nudged; the game's own payout sweep then pays it. Idempotent on the game side (the same
|
||||||
|
// wallet twice is a no-op, a different one is refused), so the deploy overlap's two copies cannot do harm.
|
||||||
|
// Any linked wallet (Marty, 2026-10-27, "build all three"): the push no longer waits for the wallet to be an on-chain member. A
|
||||||
|
// holding-tank member can wait a day or more before switching on payouts, and their game POL sat unpaid with the nudges stopped.
|
||||||
|
// accounts.address is only ever set after a verified wallet signature (auth.verifyChallenge -> accounts.linkWallet), so that is
|
||||||
|
// the wallet every game pays. memberId goes along when the chain knows one, else 0.
|
||||||
|
// nudge: false = push only. PolyBreak, SpellWheel and PolyWarriors joined 2026-10-25 push-only; Marty turned their nudges on the same day.
|
||||||
const fs = require('fs'), path = require('path'), crypto = require('crypto'), https = require('https'), http = require('http');
|
const fs = require('fs'), path = require('path'), crypto = require('crypto'), https = require('https'), http = require('http');
|
||||||
let R = {}, DATA_DIR = '.';
|
let R = {}, DATA_DIR = '.';
|
||||||
const FILE = () => path.join(DATA_DIR, 'wallet-nudge.json');
|
const FILE = () => path.join(DATA_DIR, 'wallet-nudge.json');
|
||||||
@@ -11,6 +21,7 @@ const blank = () => ({ v: 1, people: {}, stats: { sent: 0, converted: 0, runs: 0
|
|||||||
const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } };
|
const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } };
|
||||||
const save = s => { try { fs.writeFileSync(FILE(), JSON.stringify(s)); } catch (e) {} };
|
const save = s => { try { fs.writeFileSync(FILE(), JSON.stringify(s)); } catch (e) {} };
|
||||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||||
|
const now0 = () => Date.now();
|
||||||
const STAGES = [0, 3 * 86400000, 10 * 86400000]; // first touch now, reminder at 3 days, last word at 10 days
|
const STAGES = [0, 3 * 86400000, 10 * 86400000]; // first touch now, reminder at 3 days, last word at 10 days
|
||||||
|
|
||||||
function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; }
|
function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; }
|
||||||
@@ -21,9 +32,35 @@ function games() {
|
|||||||
{ key: 'gemkingdom', name: 'Gem Kingdom', url: process.env.GK_URL, secret: process.env.GK_SSO_SECRET },
|
{ key: 'gemkingdom', name: 'Gem Kingdom', url: process.env.GK_URL, secret: process.env.GK_SSO_SECRET },
|
||||||
{ key: 'clutterhunt', name: 'ClutterHunt', url: process.env.SEEK_URL, secret: process.env.SEEK_SSO_SECRET },
|
{ key: 'clutterhunt', name: 'ClutterHunt', url: process.env.SEEK_URL, secret: process.env.SEEK_SSO_SECRET },
|
||||||
{ key: 'driprunner', name: 'Drip Runner', url: process.env.DR_URL, secret: process.env.DR_SSO_SECRET },
|
{ key: 'driprunner', name: 'Drip Runner', url: process.env.DR_URL, secret: process.env.DR_SSO_SECRET },
|
||||||
{ key: 'roadagent', name: 'Road Agent', url: process.env.RA_URL, secret: process.env.RA_SSO_SECRET }
|
{ key: 'roadagent', name: 'Road Agent', url: process.env.RA_URL, secret: process.env.RA_SSO_SECRET },
|
||||||
|
{ key: 'polybreak', name: 'PolyBreak', url: process.env.PB_URL || 'https://polybreak.app', secret: process.env.PB_SSO_SECRET },
|
||||||
|
{ key: 'polminer', name: 'POL Miner', url: process.env.POLMINER_URL || 'https://polminer.com', secret: process.env.POLMINER_SSO_SECRET }, // 2026-10-28: idle until POLMINER_SSO_SECRET is set
|
||||||
|
{ key: 'spellwheel', name: 'SpellWheel', url: process.env.SW_URL || 'https://spellwheel.com', secret: process.env.SW_SSO_SECRET },
|
||||||
|
{ key: 'polywarriors', name: 'PolyWarriors', url: process.env.PW_URL || 'https://polywarriors.com', secret: process.env.PW_SSO_SECRET }
|
||||||
].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32);
|
].filter(g => g.url && g.secret && String(g.secret).trim().length >= 32);
|
||||||
}
|
}
|
||||||
|
// POST the wallet to the game: X-IAP-Sig = hex HMAC-SHA256(secret, 'wallet\n' + ts + '\n' + hex sha256(body)) -> { status, j }
|
||||||
|
function pushWallet(g, body) {
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const raw = JSON.stringify(body), ts = String(Date.now());
|
||||||
|
const sig = crypto.createHmac('sha256', String(g.secret).trim()).update('wallet\n' + ts + '\n' + crypto.createHash('sha256').update(raw).digest('hex')).digest('hex');
|
||||||
|
let url; try { url = new URL(String(g.url).replace(/\/+$/, '') + '/api/iap/wallet'); } catch (e) { return resolve({ status: 0, j: null }); }
|
||||||
|
const mod = url.protocol === 'https:' ? https : http;
|
||||||
|
const rq = mod.request(url, { method: 'POST', timeout: 8000, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-IAP-Ts': ts, 'X-IAP-Sig': sig, 'User-Agent': 'InstantAdPay wallet-push/1.0' } }, r => {
|
||||||
|
let d = ''; r.on('data', c => { if (d.length < 1e5) d += c; }); r.on('end', () => { let j = null; try { j = JSON.parse(d); } catch (e) {} resolve({ status: r.statusCode, j }); });
|
||||||
|
});
|
||||||
|
rq.on('timeout', () => { rq.destroy(); resolve({ status: 0, j: null }); }); rq.on('error', () => resolve({ status: 0, j: null }));
|
||||||
|
rq.end(raw);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// the wallet to push for an account: its signature-linked address, activated or not -> { wallet, memberId } | null
|
||||||
|
// memberId is the on-chain member id when there is one, else 0; a failed chain read falls back to the account's stored id.
|
||||||
|
async function linkedWallet(a) {
|
||||||
|
if (!a || !a.address || !/^0x[a-f0-9]{40}$/i.test(a.address)) return null;
|
||||||
|
let id = Number(a.memberId) || 0;
|
||||||
|
if (R.chain && R.chain.memberIdByAccount) { try { id = Number(await R.chain.memberIdByAccount(a.address)) || 0; } catch (e) { console.warn('walletnudge chain read', e.message); } }
|
||||||
|
return { wallet: a.address, memberId: id > 0 ? id : 0 };
|
||||||
|
}
|
||||||
function fetchRows(g) {
|
function fetchRows(g) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
const ts = String(Date.now());
|
const ts = String(Date.now());
|
||||||
@@ -36,12 +73,14 @@ function fetchRows(g) {
|
|||||||
rq.on('timeout', () => { rq.destroy(); resolve(null); }); rq.on('error', () => resolve(null));
|
rq.on('timeout', () => { rq.destroy(); resolve(null); }); rq.on('error', () => resolve(null));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
// copy (Marty, 2026-10-27): the ask is the LINK step only (one free signature), never "switch on payouts": a linked wallet is paid
|
||||||
function copy(games, stage, link) {
|
function copy(games, stage, link) {
|
||||||
const total = games.reduce((n, g) => n + g.unpaid, 0);
|
const total = games.reduce((n, g) => n + g.unpaid, 0);
|
||||||
const list = games.map(g => g.unpaid.toFixed(2) + ' POL from ' + g.name).join(', ');
|
const parts = games.map(g => g.unpaid.toFixed(2) + ' POL in ' + g.name);
|
||||||
|
const list = parts.length > 1 ? parts.slice(0, -1).join(', ') + ' and ' + parts[parts.length - 1] : parts[0];
|
||||||
const subject = total.toFixed(2) + ' POL is waiting for your wallet';
|
const subject = total.toFixed(2) + ' POL is waiting for your wallet';
|
||||||
const p1 = 'You have ' + list + ' sitting in your game balance' + (games.length > 1 ? 's' : '') + '. It cannot be paid out yet because no wallet is linked to your InstantAdPay account.';
|
const p1 = "You've earned " + list + ". Link your wallet (one free signature) and it's sent automatically, including everything you've earned so far.";
|
||||||
const p2 = 'Link a wallet on your Wallet tab. It is one free signature, no transaction, and it cannot move funds. Your POL pays out on the next sweep, and every game pays that same wallet from then on.';
|
const p2 = 'It is not a transaction and it cannot move funds. Every game pays that same wallet from then on.';
|
||||||
const p3 = stage >= 2 ? 'This is the last reminder about this balance. It stays yours; it just waits for a wallet.' : 'Not sure which wallet to use? SafePal is the one we recommend; MetaMask and Phantom work too. The Wallet tab has a short guide.';
|
const p3 = stage >= 2 ? 'This is the last reminder about this balance. It stays yours; it just waits for a wallet.' : 'Not sure which wallet to use? SafePal is the one we recommend; MetaMask and Phantom work too. The Wallet tab has a short guide.';
|
||||||
const text = [p1, '', p2, '', 'Link your wallet: ' + link, '', p3].join('\n');
|
const text = [p1, '', p2, '', 'Link your wallet: ' + link, '', p3].join('\n');
|
||||||
const html = '<p>' + esc(p1).replace(esc(list), '<b>' + esc(list) + '</b>') + '</p><p>' + esc(p2) + '</p><p><a href="' + esc(link) + '"><b>Link your wallet</b></a></p><p>' + esc(p3) + '</p>';
|
const html = '<p>' + esc(p1).replace(esc(list), '<b>' + esc(list) + '</b>') + '</p><p>' + esc(p2) + '</p><p><a href="' + esc(link) + '"><b>Link your wallet</b></a></p><p>' + esc(p3) + '</p>';
|
||||||
@@ -49,14 +88,32 @@ function copy(games, stage, link) {
|
|||||||
}
|
}
|
||||||
async function tick() {
|
async function tick() {
|
||||||
const S = load(); S.stats.runs++; S.lastRun = Date.now();
|
const S = load(); S.stats.runs++; S.lastRun = Date.now();
|
||||||
const byEmail = new Map(), snapshot = {};
|
const byEmail = new Map(), snapshot = {}; let pushed = 0;
|
||||||
|
S.pushes = S.pushes || {}; S.pushLog = S.pushLog || []; S.stats.pushed = S.stats.pushed || 0;
|
||||||
for (const g of games()) {
|
for (const g of games()) {
|
||||||
const rows = await fetchRows(g); snapshot[g.key] = rows ? rows.length : null; if (!rows) continue;
|
const rows = await fetchRows(g); snapshot[g.key] = rows ? rows.length : null; if (!rows) continue;
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
let email = String(r.email || '').trim().toLowerCase();
|
let email = String(r.email || '').trim().toLowerCase(), acct = null;
|
||||||
if (!email && r.memberId && R.accounts.byMemberId) { const a = await R.accounts.byMemberId(Number(r.memberId)); email = a ? a.email : ''; }
|
if (!email && Number(r.memberId) > 0 && R.accounts.byMemberId) { acct = await R.accounts.byMemberId(Number(r.memberId)); email = acct ? acct.email : ''; }
|
||||||
if (!email) continue;
|
if (!email) continue;
|
||||||
const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid: Math.max(0, Number(r.unpaid) || 0) }); byEmail.set(email, cur);
|
const unpaid = Math.max(0, Number(r.unpaid) || 0);
|
||||||
|
// the IAP account already has a linked wallet (activated or not): hand it to the game instead of asking the member for it
|
||||||
|
if (!acct) acct = await R.accounts.byEmail(email);
|
||||||
|
const act = await linkedWallet(acct);
|
||||||
|
if (act) {
|
||||||
|
const pk = g.key + ':' + email, prev = S.pushes[pk];
|
||||||
|
// a refusal (different wallet already in the game, unknown player) is retried once a day, never every hour
|
||||||
|
if (prev && prev.wallet === act.wallet && prev.status !== 'ok' && prev.status !== 'error' && now0() - prev.at < 86400000) continue;
|
||||||
|
const out = await pushWallet(g, { email, wallet: act.wallet, username: (acct && acct.username) || r.username || null, memberId: act.memberId });
|
||||||
|
const status = out.status === 200 && out.j && out.j.ok ? 'ok' : out.status === 409 ? 'conflict' : out.status === 404 ? 'unknown' : 'error';
|
||||||
|
const changed = status === 'ok' && !!out.j.changed;
|
||||||
|
S.pushes[pk] = { at: now0(), game: g.key, email, wallet: act.wallet, memberId: act.memberId, unpaid, status, code: out.status, changed };
|
||||||
|
if (changed) { S.stats.pushed++; pushed++; S.pushLog.unshift({ at: now0(), game: g.key, name: g.name, email, username: (acct && acct.username) || r.username || null, memberId: act.memberId, wallet: act.wallet, unpaid }); S.pushLog = S.pushLog.slice(0, 300); }
|
||||||
|
console.log('walletnudge push', g.key, email.replace(/^(..).*(@.*)$/, '$1***$2'), act.wallet, unpaid, status, out.status, changed ? 'FILLED' : '');
|
||||||
|
continue; // pushed (or a refusal that a nudge cannot fix: the member already has a wallet)
|
||||||
|
}
|
||||||
|
if (g.nudge === false) continue;
|
||||||
|
const cur = byEmail.get(email) || []; cur.push({ key: g.key, name: g.name, unpaid }); byEmail.set(email, cur);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
S.lastRows = snapshot;
|
S.lastRows = snapshot;
|
||||||
@@ -82,7 +139,7 @@ async function tick() {
|
|||||||
if (ok) { p.sent.push({ ts: now, stage, total: Number(c.total.toFixed(4)) }); S.stats.sent++; sent++; }
|
if (ok) { p.sent.push({ ts: now, stage, total: Number(c.total.toFixed(4)) }); S.stats.sent++; sent++; }
|
||||||
}
|
}
|
||||||
save(S);
|
save(S);
|
||||||
return { ok: true, sent, people: byEmail.size, games: snapshot };
|
return { ok: true, sent, pushed, people: byEmail.size, games: snapshot };
|
||||||
}
|
}
|
||||||
// POL a specific member has waiting across the games (0 when none, or once they linked a wallet)
|
// POL a specific member has waiting across the games (0 when none, or once they linked a wallet)
|
||||||
function waitingFor(email) {
|
function waitingFor(email) {
|
||||||
@@ -94,6 +151,7 @@ function adminView() {
|
|||||||
const S = load();
|
const S = load();
|
||||||
const people = Object.entries(S.people).map(([email, p]) => ({ email, first: p.first, last: p.last || p.first, sent: p.sent.length, lastSent: p.sent.length ? p.sent[p.sent.length - 1].ts : 0, done: p.done || null, games: p.games, total: Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)) }));
|
const people = Object.entries(S.people).map(([email, p]) => ({ email, first: p.first, last: p.last || p.first, sent: p.sent.length, lastSent: p.sent.length ? p.sent[p.sent.length - 1].ts : 0, done: p.done || null, games: p.games, total: Number(Object.values(p.games || {}).reduce((n, v) => n + Number(v || 0), 0).toFixed(4)) }));
|
||||||
people.sort((a, b) => b.total - a.total);
|
people.sort((a, b) => b.total - a.total);
|
||||||
return { stats: S.stats, lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url })), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) };
|
return { stats: Object.assign({ pushed: 0 }, S.stats), lastRun: S.lastRun, lastRows: S.lastRows, games: games().map(g => ({ key: g.key, name: g.name, url: g.url, nudge: g.nudge !== false })),
|
||||||
|
pushed: (S.pushLog || []).slice(0, 100), pushRefused: Object.values(S.pushes || {}).filter(x => x.status !== 'ok').sort((a, b) => b.at - a.at).slice(0, 100), waiting: people.filter(p => !p.done), done: people.filter(p => p.done).slice(0, 100) };
|
||||||
}
|
}
|
||||||
module.exports = { init, tick, waitingFor, adminView, games, STAGES };
|
module.exports = { init, tick, waitingFor, adminView, games, STAGES };
|
||||||
|
|||||||
Reference in New Issue
Block a user