From 15f5374fac4fc7f8b450df8f146ebbb193ab241d Mon Sep 17 00:00:00 2001 From: martbost Date: Sat, 24 Oct 2026 05:55:02 -0500 Subject: [PATCH] Engine Room (Fuel Your Offers stage 4, Marty approved 2026-10-24): a new Members tab (engineNav, pane-engine) on InstantAdPay, shown only while refuelStreak is on, unlocked by the first counted refuel and greyed with one move "Refuel to start your engine" before. engine.js (the same file ships in LinkSpin): facts() gathers one site's member facts (credits free + in campaigns, recent campaigns, clicks this week and last week from click_sources via coach.clicksSince, free login slots; on LinkSpin also goals this month from the conversion pixel counted from the Central-time 1st, and the Banner Spin / spin link / page / testing parts), build() turns both sites' facts + the streak into three plain dials (fuel left vs this cycle's refuel credits incl. bonus with days left at the recent burn; clicks this week against last week with clicks per 1,000 credits; goals this month vs a member-set goal stored with the streak, refuel.setGoal), the 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 / amber / grey with setup links) and one next move from simple ordered rules (refuel window, relaunch, Pit Stop top-up, top up the winner, tracking, Banner Spin, test A/B, cut the loser, keep running). LinkSpin facts arrive through signed /api/partner/engine (cached a minute; LinkSpin down = unknown, never zero); InstantAdPay answers the same call for LinkSpin's panel with its facts + the streak. Member /api/my/engine, /api/my/engine/goal; partner op refuel/goal. engine-room.js (same file both sites): plain SVG dials with aria labels, works at 390 px, colour only for warnings. Chatbot CANNED + FACTS cover the Engine Room. my.js?v=20261024er (PANES + engine), engine-room.js?v=20261024er. qa/refuel-engine.test.cjs 10 checks (switch, locked, each dial, lights, parts, next-move order, facts on stubbed LinkSpin incl. Central month start, goal storage). Co-Authored-By: Claude Opus 5.5 --- chatbot.js | 4 +- coach.js | 4 +- engine.js | 137 +++++++++++++++++++++++++++++++++++ public/assets/engine-room.js | 65 +++++++++++++++++ public/assets/my.js | 4 +- public/my.html | 7 +- qa/refuel-engine.test.cjs | 93 ++++++++++++++++++++++++ refuel.js | 12 ++- server.js | 30 +++++++- 9 files changed, 346 insertions(+), 10 deletions(-) create mode 100644 engine.js create mode 100644 public/assets/engine-room.js create mode 100644 qa/refuel-engine.test.cjs diff --git a/chatbot.js b/chatbot.js index 04ec92c..aa406b9 100644 --- a/chatbot.js +++ b/chatbot.js @@ -76,7 +76,7 @@ const CANNED = [ 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.' }, { 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 one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days 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 refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview. Buy here: https://instantadpay.com/my#buy. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' }, + 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 one free Featured day on InstantAdPay from month 4. The bonus stacks on Five Dollar Friday and Wired Wednesday. A $20+/$25+ top-up between refuel days 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. Buy here: https://instantadpay.com/my#buy. 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.' }, @@ -214,7 +214,7 @@ function passTiersFact() { } // 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; -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 one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. 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. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\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'; } +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 one free Featured day on InstantAdPay at m4+ (credited as one day's Featured price). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: a $20+/$25+ package between refuel days = 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. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package.\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. diff --git a/coach.js b/coach.js index 3477ac7..a6490fe 100644 --- a/coach.js +++ b/coach.js @@ -180,6 +180,8 @@ function clickSource(referer) { } catch (e) { return 'unknown'; } } 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) { const rows = await impl().clicksFor(campaignIds.map(Number)); const out = {}; @@ -358,4 +360,4 @@ function init(opts) { X = arguments[0] || {}; J.load(); } 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 }; diff --git a/engine.js b/engine.js new file mode 100644 index 0000000..e2f5f92 --- /dev/null +++ b/engine.js @@ -0,0 +1,137 @@ +// 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#campaigns', + lsBuy: 'https://linkspin.app/credits', lsAds: 'https://linkspin.app/ads', lsLinks: 'https://linkspin.app/links', lsPages: 'https://linkspin.app/pages', lsConv: 'https://linkspin.app/conversions', +}; +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) { return { state, label, note, link }; } + +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; + // ---- 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', LINKS.iapCampaigns) + : out.length && !running.length ? part('amber', 'Fuel', 'nothing running', LINKS.iapCampaigns) + : 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', LINKS.iapBuy) + : running.length ? part('green', 'Fuel', running.length + ' ad' + (running.length === 1 ? '' : 's') + ' running', LINKS.iapCampaigns) : part('amber', 'Fuel', 'nothing running', LINKS.iapCampaigns); + const pick = (k, label, link) => { const x = P[k]; return x ? part(x.state, label, x.note, link) : part('grey', label, lsF ? 'not set up' : 'LinkSpin did not answer', link); }; + const parts = [pFuel, pick('bannerSpin', 'Banner spin', LINKS.lsLinks), pick('spinLink', 'Spin link', LINKS.lsLinks), pick('page', 'Page', LINKS.lsPages), pick('testing', 'Testing', LINKS.lsLinks), + lsF ? (n0(lsF.goalsCount) === 0 ? part('grey', 'Conversion tracking', 'no goal set', LINKS.lsConv) : n0(lsF.conv30) === 0 ? part('amber', 'Conversion tracking', 'no conversions tracked yet', LINKS.lsConv) : part('green', 'Conversion tracking', n0(lsF.conv30) + ' in 30 days', LINKS.lsConv)) + : part('grey', 'Conversion tracking', 'LinkSpin did not answer', LINKS.iapTracking)]; + // ---- 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; + if (locked) next = { key: 'start', label: 'Refuel to start your engine', why: 'Your first counted refuel ($' + (rf.minUsd ? rf.minUsd.iap : 20) + '+ here or $' + (rf.minUsd ? rf.minUsd.linkspin : 25) + '+ on LinkSpin) starts the streak and lights this room.', link: LINKS.iapBuy }; + 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.', link: LINKS.iapBuy }; + 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: LINKS.iapBuy }; + 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: 'Count signups and sales back to the ad that sent them.', link: parts[5].link }; + 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.', link: LINKS.lsLinks }; + 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.', 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: LINKS.iapCampaigns }; + 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) }, + warnings, parts, next, 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; +} + +module.exports = { build, facts, burnPerDay, monthStartCT, LINKS }; diff --git a/public/assets/engine-room.js b/public/assets/engine-room.js new file mode 100644 index 0000000..47b74f2 --- /dev/null +++ b/public/assets/engine-room.js @@ -0,0 +1,65 @@ +// 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'); + const sameSite = url => { try { return new URL(url).host === location.host ? new URL(url).pathname + new URL(url).hash : url; } catch (e) { return url; } }; + 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;gap: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 ''; + } + 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 ? '
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)
' : '') + (c.per1000 != null ? n(c.per1000) + ' clicks per 1,000 credits' : 'clicks per 1,000 credits: not enough delivery yet') + '
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') + ''; + const dials = '
' + + dial(f.pct, f.pct != null ? f.pct + '%' : n(f.left), 'Fuel left
' + fuelCap, fuelAria, f.daysLeft != null && f.daysLeft < 5) + + dial(c.pct, n(c.week), 'Clicks this week
' + 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
' + goalCap, 'Goals this month: ' + (g.month == null ? 'unknown' : g.month) + (g.target ? ' of ' + g.target : ''), false) + '
'; + const streak = '

Streak

' + (s.active ? '' + s.months + ' month' + (s.months === 1 ? '' : 's') + '' + (s.both ? ', both engines this cycle' : '') + '. Refuel day ' + esc(s.refuelDay) + ', grace to ' + esc(s.graceEnd) + ' (Central).' + + (s.next ? (s.windowOpen ? ' Window open: next refuel +' + s.next.single + '% (+' + s.next.both + '% on each with both).' : s.next.secondEngine ? ' Refuel the other site this cycle for +' + s.next.secondEngine + '% on both.' : '') : '') + + (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.') + '
'; + const warns = '

Warning lights

' + d.warnings.map(w => '' + esc(w.label) + ': ' + (w.on ? 'on' : 'off') + ' (' + esc(w.note) + ')').join('') + '
'; + const parts = '

The six parts

' + d.parts.map(p => '
' + esc(p.label) + ' (' + (p.state === 'green' ? 'working' : p.state === 'amber' ? 'needs attention' : 'not started') + ')' + esc(p.note) + '' + + (p.state !== 'green' && p.link ? '' + (p.state === 'grey' ? 'Set it up' : 'Fix it') + '' : '') + '
').join('') + '
'; + const next = '

Next move

' + esc(d.next.label) + '
' + esc(d.next.why) + '
' + esc(d.next.label) + '
'; + if (d.locked) return '
' + next + '
'; + return '
' + next + dials + streak + warns + parts + '

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.

'; + } + 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 = '

' + esc(d.error) + '

'; return; } + 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); +})(); diff --git a/public/assets/my.js b/public/assets/my.js index 0e5d2b1..15d214d 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -796,8 +796,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str } // ── back-office menu: hash-routed panes ─────────────── - const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; - const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', + 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 = { 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', wallet: 'Wallet & account', profile: 'Profile' }; function setPane(name) { diff --git a/public/my.html b/public/my.html index 2e6b81c..e361392 100644 --- a/public/my.html +++ b/public/my.html @@ -139,6 +139,7 @@ + @@ -797,6 +798,9 @@ +