Monthly Refuel streak, LinkSpin side (Fuel Your Offers stage 2, Marty approved 2026-10-24). The streak lives on InstantAdPay (one per member across both sites); refuel.js here reports each $25+ LinkSpin package (refuelMinLsCents) once per tx (claim rfev:<tx>, then a pending file in DATA_DIR/refuel-pending retried every minute until InstantAdPay answers), applies LinkSpin's grants and reminders from InstantAdPay's outbox (claim rfg:<ref> before applying, so two app copies or a lost ack never double-grant; grants are purchased-grade addEarned + a credit-log line + a notice), and relays the member's status for the Monthly Refuel panel on Credits and Ads (fuel.js) and the refill notice streak line. Linked positions count for their owner. Chatbot CANNED + FACTS follow the switch, KNOWLEDGE_DATE 2026-10-24. Admin /api/admin/refuel (+ /tick), member /api/my/refuel. MASTER SWITCH refuelStreak default '0': nothing reported, pulled or shown. qa/refuel.test.cjs 10 checks against InstantAdPay's real refuel.js in-process (both switches, cross-site both-engine top-up in both orders, two LinkSpin copies, InstantAdPay down, lost ack, reminders, status).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+13
-4
@@ -26,9 +26,10 @@ let chain = null;
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
|
||||
// TODO(level-4 override, 2026-10-23): at go-live add the CANNED entry + FACTS line drafted in D:/tmp/override-copy/linkspin-override-copy.md (section 2), and bump KNOWLEDGE_DATE only in that deploy.
|
||||
const KNOWLEDGE_DATE = '2026-10-23'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
const KNOWLEDGE_DATE = '2026-10-24'; // the day the CANNED answers and FACTS below were last checked against the site
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
function init(opts) {
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
function key() {
|
||||
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 ''; }
|
||||
@@ -39,6 +40,9 @@ function enabled() { return !!key(); }
|
||||
// handoff: true makes the widget offer "Send this to support" under the answer (help desk, 2026-10-16)
|
||||
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 linkspin|someone|a (human|person|real person))|support (email|address|ticket|team|desk|page)|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 = [
|
||||
{ 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. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Credits screen. Buy here: https://linkspin.app/credits. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||
{ 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 ticket?'], tags: ['support', 'help', 'ticket', 'contact'],
|
||||
re: SUPPORT_RE, handoff: true,
|
||||
a: 'Open Help in your Control Room (' + SITE_URL + '/help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use ' + SITE_URL + '/support. You can also tap "Send this to support" below and I will pass this chat along.' },
|
||||
@@ -145,11 +149,15 @@ function seeds() {
|
||||
}
|
||||
|
||||
// ---- facts for the AI fallback ----
|
||||
// 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. 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 LinkSpin (${SITE_URL}), a link rotator, page builder and advertising network for marketers, a Crypto Team Build Network property.
|
||||
|
||||
FACTS:
|
||||
- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/<code>, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list, CSV or webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. Knowledge checked on ${KNOWLEDGE_DATE}.
|
||||
${refuelFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/<code>, rotates between destinations by weight; pause any destination; a fallback for when all are off; one-hop redirect; every click recorded with day, country, source, device and a daily-salted visitor hash; bots filtered on the server; click ids and sub ids such as clickid, subid, s1 to s4 pass through to the destination; split tests by tagging the same link with different sub ids; a demo spin on the home page needs no account; DAYPARTING is live: a 7x24 hours grid per spin and per destination, time zone by name or the local time of the visitor, presets, and 'my best hours' from the clicks of the member after 200 clicks; automatic HEALTH CHECKS are live: every destination is checked every 30 minutes, a dead or parked one is paused after three failing checks and resumed when it passes twice, the owner is told once, and Check now runs it on demand). PAGES (page builder: scan any offer URL, get a bridge, review or squeeze page; designs, palettes, layouts and niche presets with hero images; leads to the member's own list, CSV or webhook; published on the pages domain lookfirst.page; sales, advertorial and press-release layouts are coming). ZONES (an ad slot on the member's own site: one async script tag, nine sizes 728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50; waterfall = LinkSpin member campaign, then a network ad for 728x90 and 468x60, then the LinkSpin house banner; pays ad credits per VIEWABLE impression, half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day; rates 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, 1 per 8 on a Verified zone; warm-up: a zone earns after its first 100 on-site views with at least 40 percent viewable and goes on hold below that; origin lock: paid ads serve only on the declared site and its subdomains, elsewhere the house banner shows and nothing is earned; up to 50 zones per account; PUBLISHER PROGRAM at /publishers for site owners, tiers Standard (default) and Verified (admin-reviewed site, better network rate)). AUDIENCES (first-party retargeting: "My visitors" collects everyone who viewed the member's pages and zones for 30 days; a pixel tag /p.js for other sites; campaigns can "show only to" or "never show to" an audience; nothing personal stored). PROMO TOOLS at /tools#promo (social posts, text-a-friend, email swipes, banners, objection bank, hook videos; five hook angles with videos: links, pages, zones, audiences, stack; angle links are the invite link plus ?v=). REPORTS (every link in one view, plus Pages, Zones, and since 2026-10-12 Traffic sources and Placements). BLOG at /blog with RSS at /blog/feed.xml. TRAFFIC SOURCES at /sources (2026-10-12): a source is a record of a network the member buys traffic on, created from a catalog of networks (PropellerAds, Zeropark, Adsterra, ExoClick, HilltopAds, TrafficStars, PopAds and more, with each network's macro tokens and conversion postback URL; account-specific slots such as a goal id are filled in at creation) or defined by hand; a spin link is pointed at one source (Share kit on the Links screen, or the Sources screen), and then the Share kit's first row is the exact campaign URL for that network with its macros already in place; when a click that came through that source converts (join, lead, wallet, purchase, or a partner-reported conversion; the member picks which) LinkSpin fires that network's own postback with the network's click id and the payout, server to server, and only the network that sent the click is told; Reports show clicks, uniques and conversions by source and by placement (the value the network's zone, placement, site, campaign, creative, banner or keyword macro carried); up to 30 sources per account, 20 params each; a source with no postback still builds the campaign URL and shows in Reports; the account-level Postbacks list on the Links screen (for the member's own tracker) still works alongside. Knowledge checked on ${KNOWLEDGE_DATE}.
|
||||
- CONVERSION PIXEL (LIVE 2026-10-23, Control Room > Conversions at ${SITE_URL}/conversions; InstantAdPay members see the same goals under Campaigns > Conversion tracking, held on their LinkSpin account): a member names GOALS (subscriber, sale, any word, optional default value, up to 20); each goal has a PUBLIC pixel id (px + 10 characters) that can only count clicks the member owns. EVERY CLICK GETS AN ID: LinkSpin ad clicks (banner, text, zones) and InstantAdPay ad clicks add lsclk=<click id> to the target address (other params kept); a spin link reached through an ad passes its own id on and inherits the ad as its source; spin links of a member with a goal add lsclk to the destination too. SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line <script async src="https://${SITE_HOST}/t.js?px=PIXEL_ID"></script>, keeps the id on the member's own site 30 days (localStorage + a first-party cookie), fills hidden form fields named lsclk, lsid or clickid and adds the id to links that stay on the same site; 2) the GOAL PIXEL on the thank-you page, an image cv.gif?px=PIXEL_ID&goal=NAME (optional &value=19.95) or the script version cv.js that reads what the tag kept; 3) Send a test conversion (recorded apart, never counted). MATCHING ORDER: the click id in the address, then the id the tag kept, then LinkSpin's own cookie, then a 24-hour match on network + browser (a hash, no IP stored); the method is shown per goal so members see how solid each count is. RULES: each goal counts once per click (an ad click and the spin-link click it led to are one click), only within 30 days of a real click, only for the pixel owner's own clicks, rate limited per pixel and per visitor; the advertiser's own clicks are kept as tests. REPORTS per goal: conversions and cost per goal (the campaign's credits spent / its conversions, in that site's ad credits) by ad campaign (LinkSpin and InstantAdPay), spin link, destination page and traffic source, plus CSV export. POSTBACKS: a postback or traffic source set to the event 'goal' fires for every goal with {event} = the goal name. AUTORESPONDERS: when Aweber, GetResponse or another provider hosts the thank-you page, set its thank-you (success) redirect to the member's own page that carries the pixel; otherwise the pixel still counts through the cookie or the 24-hour match, less surely. The tag and pixel never break the page if LinkSpin cannot be reached and work inside traffic-exchange frames.
|
||||
- TOOL LIMITS BY TIER (2026-10-21): spin links and pages each: Free (no package) 3, Starter (any package of your own) 10, Builder (level 2 open, 2 qualifying buyers) 50, Leader (level 3 open, 5 qualifying buyers) unlimited (fair use). Each spin link rotates up to 25 destinations at every tier; clicks are unlimited. Nothing already made is ever removed when a cap applies; new ones wait for the upgrade. Banner Spin has its own ladder (Starter 2 x 5, Builder 5 x 15, Leader 10 x 25). Other limits, same for everyone: 50 zones, 20 audiences, 20 postbacks, 5 linked positions.
|
||||
- BANNER SPIN (LIVE 2026-10-18, reports and health checks 2026-10-20): one image address (/i/<code>.gif on a link domain) and one click address (/c/<code>) that rotate up to 25 banners, each with its own target (any https page or one of the member's spin links), weights 1 to 100, random by weight on every view or one banner per visitor per day, the dayparting grid per Banner Spin and per banner, pause, a fallback page and an optional fallback banner image, and a traffic source so its conversions fire that network's postback. Built on the Links screen (${SITE_URL}/links#b). WHO GETS IT: a free add-on for members with their own package of $25 or more; tiers: Starter 2 Banner Spins x 5 banners, Builder (level 2 open, 2 qualifying buyers) 5 x 15, Leader (level 3 open, 5 qualifying buyers) 10 x 25; dropping below a tier keeps everything serving, it only stops new ones. One size per Banner Spin (468x60, 728x90, 300x250, 125x125, 160x600, 120x600, 336x280, 250x250, 320x50); JPG, PNG or GIF (animated is fine), 150 KB at most, uploads count toward the 10 files a day. EMBEDS: the image + click pair (traffic exchanges, safelists, downline builders), an HTML snippet (own sites, blogs, HTML email), a script tag (writes the banner and its own link, so every click matches exactly) and forum BBCode; every link domain answers every code. MATCHING: with the pair, the server remembers which banner a visitor saw on which page for 15 minutes and sends the click there; an unmatched click goes to the fallback. LIMITS: paid ad networks (Froggy, PropellerAds and the like) copy the image at upload, so it freezes on one banner there; Gmail and some mail apps fetch images through a caching proxy, so email readers mostly see one banner and clicks fall back: use a single-banner Banner Spin for email. REPORTS: per banner and per placement views, unique viewers (daily sample), clicks, CTR, match rate and conversions, by Central day, country and device, bots and server loads shown separately and never counted; a WINNER badge once two or more live banners have 1,000 views each and one leads on click rate (LinkSpin never changes weights by itself); a CACHED flag on a placement that copies banners to its own server; totals also on the Reports screen. HEALTH: every 30 minutes each live banner's image must load as an image of the right size and its target must pass the spin-link checks (dead, parked, slow); three failures in a row pause that banner, two clean passes resume it, the last live banner is never auto-paused, and the status shows on each banner row.
|
||||
@@ -220,8 +228,9 @@ async function answerRaw(message, historyText) {
|
||||
// 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) 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 Object.assign({ reply: c.a, canned: true }, c.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 } : 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 {
|
||||
|
||||
@@ -64,6 +64,7 @@
|
||||
<div class="two">
|
||||
<div class="tbl cl"><div class="hd"><span>Campaign</span><span>Creative</span><span>Budget</span><span class="r">Views</span><span class="r">Clicks</span><span>Status</span><span></span></div><div id="rows"></div><div class="ft" id="foot"></div></div>
|
||||
<div class="side">
|
||||
<div class="panel" id="rfPanel" hidden style="padding:0" aria-live="polite"><div class="ph"><h3>Monthly Refuel</h3><span class="meta" id="rfMeta"></span></div><div style="padding:12px 16px 14px;font-size:13px" class="ink2" id="rfBody"></div></div>
|
||||
<div class="panel"><h2>Earn credits</h2><div class="gauge" id="earnGauge"><i></i><i></i><i></i><i></i><i></i></div><div class="muted" id="earnLine" style="margin-top:8px">loading</div><div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px"><button class="btn blue" type="button" id="earnNext">View an ad</button><button class="btn" type="button" id="earnClaim" hidden>Claim</button></div><div class="muted" id="earnNote" style="margin-top:8px"></div></div>
|
||||
<div class="panel"><h2>Where your ads run</h2><div class="where ink2"><div><b>Banner</b><span>the ad viewer here, every member zone on outside sites, and the partner network</span></div><div><b>Text</b><span>the ad viewer and the partner network</span></div><div><b>Login</b><span id="loginWhere">full screen to every member right after they sign in, for a flat 30-day slot of purchased credits</span></div></div><div class="muted" id="rateLine" style="margin-top:10px"></div></div>
|
||||
<div class="panel" hidden><h2>Credit activity</h2><div id="creditLog" class="ink2" style="font-size:13px"></div></div>
|
||||
@@ -73,5 +74,6 @@
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261023c"></script>
|
||||
<script src="/assets/ads-screen.js?v=20261023q"></script>
|
||||
<script src="/assets/fuel.js?v=20261024rf"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Fuel Your Offers (2026-10-24), LinkSpin: the Monthly Refuel panel on Credits and Ads. The streak lives on InstantAdPay
|
||||
// and is shared by both sites; /api/my/refuel relays InstantAdPay's view. Hidden while the refuelStreak switch is off.
|
||||
(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');
|
||||
window.FUEL = window.FUEL || {};
|
||||
function site(name, s, minUsd) {
|
||||
return s && s.refueled ? '<div class="row"><span>' + name + '</span><b>+' + s.pct + '% · ' + n(s.bonus) + ' credits</b></div>'
|
||||
: '<div class="row"><span>' + name + '</span><span class="muted">not yet ($' + minUsd + '+ counts)</span></div>';
|
||||
}
|
||||
function body(v) {
|
||||
if (v.error) return '<p class="muted">' + esc(v.error) + '</p>';
|
||||
if (!v.active) {
|
||||
return '<p style="margin:0 0 8px">' + (v.started ? 'Your last streak ended. ' : '') + 'A package of <b>$' + v.minUsd.linkspin + ' or more</b> here, or $' + v.minUsd.iap + '+ on InstantAdPay, ' + (v.started ? 'starts it again' : 'starts your monthly refuel streak and sets your own refuel day') + '.</p>'
|
||||
+ '<p class="muted" style="margin:0 0 10px">Bonus ad credits: month 1 +' + v.ladder.single[0] + '%, then +' + v.ladder.single.slice(1).join('%, +') + '%. Refuel both sites in the same cycle and each gets +' + v.ladder.both.join('%, +') + '%.</p>'
|
||||
+ '<a class="btn pri" href="/credits">Start my streak</a>';
|
||||
}
|
||||
const c = v.cycle || {};
|
||||
let h = v.windowOpen
|
||||
? '<p style="margin:0 0 8px"><b>Your refuel window is open.</b> Refuel day <b>' + esc(v.refuelDayLabel) + '</b>, grace to ' + esc(v.graceLabel) + ' (Central). Next refuel: +' + v.next.single + '%, or +' + v.next.both + '% on each site with both.</p>'
|
||||
: '<p style="margin:0 0 8px">Next refuel day <b>' + esc(v.refuelDayLabel) + '</b> (Central). Window opens ' + esc(v.opensLabel) + ', grace to ' + esc(v.graceLabel) + '.</p>';
|
||||
if (c.month) h += '<div style="margin:0 0 8px">' + site('InstantAdPay', c.iap, v.minUsd.iap) + site('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</div>';
|
||||
if (!v.windowOpen && c.month && !c.both) h += '<p class="muted" style="margin:0 0 8px">Refuel ' + (c.linkspin && c.linkspin.refueled ? 'InstantAdPay ($' + v.minUsd.iap + '+)' : 'LinkSpin ($' + v.minUsd.linkspin + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to +' + v.next.secondEngine + '%.</p>';
|
||||
if (v.pitStop && (v.pitStop.linkspin || v.pitStop.usedLinkspin)) h += '<p class="muted" style="margin:0 0 8px"><b>Pit Stop</b> ' + (v.pitStop.linkspin ? 'available here: +' + v.pitStop.pct + '% on a $' + v.minUsd.linkspin + '+ top-up, once this cycle. It does not count as your refuel.' : 'used here this cycle.') + '</p>';
|
||||
h += '<p class="muted" style="margin:0 0 10px">' + (v.freeMiss.available ? 'One free miss left this year.' : 'Free miss for this year used.') + '</p>';
|
||||
return h + '<a class="btn' + (v.windowOpen ? ' pri' : '') + '" href="/credits">' + (v.windowOpen ? 'Refuel now' : 'Buy a package') + '</a>';
|
||||
}
|
||||
async function load() {
|
||||
const panel = $('rfPanel'); if (!panel) return;
|
||||
try {
|
||||
const v = await (await fetch('/api/my/refuel', { cache: 'no-store' })).json();
|
||||
window.FUEL.refuel = v;
|
||||
if (!v || !v.on) { panel.hidden = true; return; }
|
||||
$('rfMeta').textContent = v.active ? 'streak: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') : 'shared with InstantAdPay';
|
||||
$('rfBody').innerHTML = body(v); panel.hidden = false;
|
||||
} catch (e) { panel.hidden = true; }
|
||||
}
|
||||
window.FUEL.loadRefuel = load;
|
||||
load(); setInterval(load, 300000);
|
||||
})();
|
||||
@@ -60,6 +60,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:grid;gap:16px;align-content:start">
|
||||
<div class="panel" id="rfPanel" hidden style="padding:0" aria-live="polite"><div class="ph"><h3>Monthly Refuel</h3><span class="meta" id="rfMeta"></span></div><div style="padding:12px 16px 14px;font-size:13px" class="ink2" id="rfBody"></div></div>
|
||||
<div class="panel" style="padding:0">
|
||||
<div class="ph"><h3 id="goesTitle">Where it goes</h3><span class="meta">same transaction</span></div>
|
||||
<div style="padding:10px 16px 14px" id="goesRows"></div>
|
||||
@@ -84,5 +85,6 @@
|
||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||
<script src="/assets/cr-shell.js?v=20261023c"></script>
|
||||
<script src="/assets/credits-screen.js?v=20261019pos"></script>
|
||||
<script src="/assets/fuel.js?v=20261024rf"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Monthly Refuel, LinkSpin side (refuel.js) against InstantAdPay's REAL refuel.js (sibling repo) wired in-process in
|
||||
// place of the signed HTTP calls. Throwaway data dirs; no network. 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, '..');
|
||||
const IAP_ROOT = path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site');
|
||||
if (!fs.existsSync(path.join(IAP_ROOT, 'refuel.js'))) { console.log('skip: InstantAdPay repo not beside this one'); process.exit(0); }
|
||||
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(file) { const p = require.resolve(file); 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); };
|
||||
process.env.LS_SYNC_SECRET = 'x'.repeat(40);
|
||||
|
||||
function world(opts) {
|
||||
opts = opts || {};
|
||||
const W = { lsEarned: [], lsLog: [], lsInbox: [], lsMail: [], iapEarned: [], down: false, posts: 0, dropAck: false };
|
||||
// InstantAdPay side
|
||||
W.iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-rf-'));
|
||||
const iapMarks = fresh(path.join(IAP_ROOT, 'marks.js')); iapMarks.init({});
|
||||
W.IAP = fresh(path.join(IAP_ROOT, 'refuel.js'));
|
||||
W.iapCfg = { refuelStreak: '1' };
|
||||
W.IAP.init({ dataDir: W.iapDir, db: require(path.join(IAP_ROOT, 'db.js')), marks: iapMarks, siteConfig: () => W.iapCfg,
|
||||
accounts: { byMemberId: async () => null, byEmail: async e => ({ email: e, username: 'sam' }) },
|
||||
ads: { addEarned: async (email, credits, o) => { W.iapEarned.push({ email, credits, ref: o.log.ref }); } },
|
||||
message: async () => {}, featuredPerDay: () => 40 });
|
||||
// the signed partner endpoints, in-process (same routing as InstantAdPay server.js)
|
||||
const post = async (pth, b) => {
|
||||
W.posts++;
|
||||
if (W.down) throw new Error('InstantAdPay 502');
|
||||
const op = pth.replace('/api/partner/refuel/', '');
|
||||
if (op === 'purchase') { const r = await W.IAP.record({ site: 'linkspin', email: b.email, tx: b.tx, cents: b.cents, credits: b.credits, ts: b.ts }); return Object.assign({ ok: true }, r, { items: r.on ? await W.IAP.outbox('linkspin', b.email) : [] }); }
|
||||
if (op === 'outbox') return { ok: true, on: W.IAP.cfg().on, items: W.IAP.cfg().on ? await W.IAP.outbox('linkspin') : [] };
|
||||
if (op === 'ack') { if (W.dropAck) throw new Error('ack lost'); return { ok: true, acked: await W.IAP.ack('linkspin', b.refs) }; }
|
||||
if (op === 'status') return Object.assign({ ok: true }, await W.IAP.view(b.email));
|
||||
throw new Error('404');
|
||||
};
|
||||
// LinkSpin side: one volume, any number of app copies
|
||||
W.lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-rf-'));
|
||||
W.lsCfg = { refuelStreak: opts.lsOff ? '0' : '1' };
|
||||
W.copy = () => {
|
||||
const marks = fresh(path.join(ROOT, 'marks.js')); marks.init({ dataDir: W.lsDir });
|
||||
const R = fresh(path.join(ROOT, 'refuel.js'));
|
||||
R.init({ dataDir: W.lsDir, siteConfig: () => W.lsCfg, marks, siteUrl: 'https://linkspin.app', post,
|
||||
accounts: { byMemberId: async id => id === 4 ? { email: 's@x.test', memberId: 4 } : null, positionByMember: async () => null, byEmail: async e => ({ email: e }) },
|
||||
ads: { addEarned: async (email, credits, o) => { W.lsEarned.push({ email, credits, purchased: !!(o && o.purchased) }); }, logCredit: async (email, delta, reason) => { W.lsLog.push({ email, delta, reason }); } },
|
||||
message: async (to, subject, html) => { W.lsInbox.push({ to, subject, html }); },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, text) => { W.lsMail.push({ to, subject, text }); } },
|
||||
drip: { isUnsubscribed: async () => false, unsubUrl: () => 'https://linkspin.app/unsubscribe' } });
|
||||
return R;
|
||||
};
|
||||
W.ev = (tx, cents, day) => ({ type: 'Purchase', buyerId: 4, tx, priceCents: cents, creditAmount: cents, ts: ct(day) });
|
||||
return W;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
await t('LinkSpin switch off: nothing reported, nothing pulled, card hidden', async () => {
|
||||
const W = world({ lsOff: true }); const R = W.copy();
|
||||
assert.strictEqual(await R.onPurchase(W.ev('0x1', 2500, '2026-11-02')), null);
|
||||
assert.deepStrictEqual(await R.tick(), { on: false }); assert.deepStrictEqual(await R.status('s@x.test'), { on: false });
|
||||
assert.strictEqual(W.posts, 0);
|
||||
});
|
||||
await t('InstantAdPay switch off: the report comes back on:false, nothing granted', async () => {
|
||||
const W = world(); W.iapCfg.refuelStreak = '0'; const R = W.copy();
|
||||
const r = await R.onPurchase(W.ev('0x1', 2500, '2026-11-02')); assert.strictEqual(r.on, false); assert.strictEqual(W.lsEarned.length, 0);
|
||||
assert.strictEqual(fs.readdirSync(path.join(W.lsDir, 'refuel-pending')).length, 0);
|
||||
});
|
||||
await t('a $25 LinkSpin package: month 1 +10% applied on LinkSpin, purchased-grade, logged, notice; $10 ignored', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
assert.strictEqual(await R.onPurchase(W.ev('0x0', 1000, '2026-11-02')), null);
|
||||
const r = await R.onPurchase(W.ev('0x1', 2500, '2026-11-02'));
|
||||
assert.strictEqual(r.kind, 'refuel');
|
||||
assert.deepStrictEqual(W.lsEarned, [{ email: 's@x.test', credits: 250, purchased: true }]);
|
||||
assert.ok(/^Refuel streak month 1: \+10% on your \$25 package$/.test(W.lsLog[0].reason));
|
||||
assert.ok(/Refuel counted/.test(W.lsInbox[0].subject));
|
||||
assert.strictEqual((await W.IAP.outbox('linkspin')).length, 0, 'acked');
|
||||
});
|
||||
await t('cross-site both engines: InstantAdPay first, LinkSpin second -> LinkSpin +15%, InstantAdPay topped up by the difference', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
await W.IAP.record({ site: 'iap', email: 's@x.test', tx: '0xI', cents: 2000, credits: 2000, ts: ct('2026-11-02') });
|
||||
await R.onPurchase(W.ev('0xL', 2500, '2026-11-08'));
|
||||
assert.strictEqual(W.lsEarned[0].credits, 375);
|
||||
assert.deepStrictEqual(W.iapEarned.map(x => [x.ref, x.credits]), [['rf:iap:0xI', 200], ['rftop:iap:0xL', 100]]);
|
||||
});
|
||||
await t('cross-site both engines the other way: LinkSpin first, InstantAdPay second -> LinkSpin top-up arrives through the outbox pull', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
await R.onPurchase(W.ev('0xL', 2500, '2026-11-02'));
|
||||
await W.IAP.record({ site: 'iap', email: 's@x.test', tx: '0xI', cents: 2000, credits: 2000, ts: ct('2026-11-04') });
|
||||
assert.strictEqual(W.iapEarned[0].credits, 300);
|
||||
await R.tick();
|
||||
assert.deepStrictEqual(W.lsEarned.map(x => x.credits), [250, 125]); // 10% then topped up to 15% of 2,500
|
||||
assert.ok(/Twin Engine top-up/.test(W.lsLog[1].reason));
|
||||
await R.tick(); assert.strictEqual(W.lsEarned.length, 2, 'nothing twice');
|
||||
});
|
||||
await t('two LinkSpin app copies see the same purchase: one report, one grant', async () => {
|
||||
const W = world(); const A = W.copy(), B = W.copy();
|
||||
await Promise.all([A.onPurchase(W.ev('0x1', 5000, '2026-11-02')), B.onPurchase(W.ev('0x1', 5000, '2026-11-02'))]);
|
||||
assert.strictEqual(W.lsEarned.length, 1); assert.strictEqual(W.lsEarned[0].credits, 500);
|
||||
await Promise.all([A.tick(), B.tick()]); assert.strictEqual(W.lsEarned.length, 1);
|
||||
});
|
||||
await t('InstantAdPay down: the report waits in a pending file and goes through on the next tick', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
W.down = true; const r = await R.onPurchase(W.ev('0x1', 2500, '2026-11-02')); assert.ok(r.queued);
|
||||
assert.strictEqual(fs.readdirSync(path.join(W.lsDir, 'refuel-pending')).length, 1); assert.strictEqual(R.adminView().pending[0].tries, 1);
|
||||
W.down = false; await R.tick();
|
||||
assert.strictEqual(W.lsEarned.length, 1); assert.strictEqual(fs.readdirSync(path.join(W.lsDir, 'refuel-pending')).length, 0);
|
||||
});
|
||||
await t('a lost ack: the row comes back on the next pull and is acked without being applied twice', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
W.dropAck = true; await R.onPurchase(W.ev('0x1', 2500, '2026-11-02'));
|
||||
assert.strictEqual(W.lsEarned.length, 1); assert.strictEqual((await W.IAP.outbox('linkspin')).length, 1);
|
||||
W.dropAck = false; await R.tick();
|
||||
assert.strictEqual(W.lsEarned.length, 1); assert.strictEqual((await W.IAP.outbox('linkspin')).length, 0);
|
||||
});
|
||||
await t('reminders for a LinkSpin-home member go out from LinkSpin (notice + email with unsubscribe), once', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
await R.onPurchase(W.ev('0x1', 2500, '2026-11-02'));
|
||||
await W.IAP.tick(ct('2026-11-27', 10));
|
||||
await R.tick(); await R.tick();
|
||||
const rem = W.lsInbox.filter(m => /refuel day is/i.test(m.subject)); assert.strictEqual(rem.length, 1);
|
||||
assert.ok(W.lsMail.some(m => /refuel day is/i.test(m.subject) && /unsubscribe/.test(m.text)));
|
||||
});
|
||||
await t('status + streak line for the Credits card and the refill notice', async () => {
|
||||
const W = world(); const R = W.copy();
|
||||
await R.onPurchase(W.ev('0x1', 2500, '2026-11-02'));
|
||||
const v = await R.status('s@x.test'); assert.ok(v.on && v.active && v.streak === 1 && v.cycle.linkspin.refueled);
|
||||
const sl = await R.streakLine('s@x.test'); assert.ok(/^Refuel streak: (month 1|1 month)/.test(sl.text), sl.text);
|
||||
});
|
||||
console.log('\n' + (n - fails) + '/' + n + ' passed');
|
||||
process.exit(fails ? 1 : 0);
|
||||
})();
|
||||
@@ -0,0 +1,162 @@
|
||||
// The Monthly Refuel streak, LinkSpin side (Fuel Your Offers, 2026-10-24). The streak itself lives on InstantAdPay
|
||||
// (its refuel.js is the source of truth: ONE streak per member across both sites). LinkSpin only:
|
||||
// 1. reports each LinkSpin package of $25+ (signed POST <IAP>/api/partner/refuel/purchase), once per tx: the copy
|
||||
// of the app that wins the claim 'rfev:<tx>' writes a pending file (DATA_DIR/refuel-pending/<tx>.json) and
|
||||
// retries it every minute until InstantAdPay answers, so an outage never loses a refuel
|
||||
// 2. applies LinkSpin's grants and reminders from InstantAdPay's outbox (signed /outbox, then /ack). Each grant is
|
||||
// claimed 'rfg:<ref>' first (marks.js), so two copies of the app never double-grant, and a lost ack only means
|
||||
// the row comes back and is acked without being applied twice
|
||||
// 3. shows the member's Refuel card from InstantAdPay's view of them (signed /status, cached 60 s)
|
||||
// MASTER SWITCH: site setting refuelStreak (default '0'): off = nothing reported, pulled or shown. InstantAdPay has
|
||||
// its own switch; a purchase it is not counting comes back { on:false } and is dropped.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
let X = {}, PENDING = null;
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
const IAP = () => String(X.iapBase ? X.iapBase() : (process.env.IAP_URL || 'https://instantadpay.com')).replace(/\/+$/, '');
|
||||
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const money = n => Number(n || 0).toLocaleString('en-US');
|
||||
|
||||
function init(opts) {
|
||||
X = opts || {};
|
||||
PENDING = path.join(X.dataDir, 'refuel-pending');
|
||||
try { fs.mkdirSync(PENDING, { recursive: true }); } catch (e) {}
|
||||
}
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
return { on: String(c.refuelStreak == null ? '0' : c.refuelStreak) === '1', minCents: Math.max(0, Number(c.refuelMinLsCents) || 2500) };
|
||||
}
|
||||
const linked = () => SECRET().length >= 32;
|
||||
|
||||
async function post(pth, body, timeoutMs) {
|
||||
if (X.post) return X.post(pth, body); // tests
|
||||
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(IAP() + 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) throw new Error((j && j.error) || ('InstantAdPay ' + r.status));
|
||||
return j || {};
|
||||
}
|
||||
|
||||
// ---- 1. a LinkSpin package ---------------------------------------------------------------------------
|
||||
async function ownerOf(buyerId) {
|
||||
let a = await X.accounts.byMemberId(Number(buyerId)).catch(() => null);
|
||||
if (!a && X.accounts.positionByMember) { const p = await X.accounts.positionByMember(Number(buyerId)).catch(() => null); if (p && p.email) a = await X.accounts.byEmail(p.email).catch(() => null); }
|
||||
return a && a.email ? String(a.email).toLowerCase() : null;
|
||||
}
|
||||
const fileOf = tx => path.join(PENDING, crypto.createHash('sha1').update(String(tx)).digest('hex') + '.json');
|
||||
async function onPurchase(ev) {
|
||||
const c = cfg();
|
||||
if (!ev || ev.type !== 'Purchase' || !c.on || (Number(ev.priceCents) || 0) < c.minCents) return null;
|
||||
if (X.marks && !(await X.marks.claim('rfev:' + ev.tx))) return null; // the other copy of the app has it
|
||||
const email = await ownerOf(ev.buyerId); if (!email) return null;
|
||||
const item = { email, tx: ev.tx, cents: Number(ev.priceCents) || 0, credits: Number(ev.creditAmount) || 0, ts: Number(ev.ts) || Date.now(), tries: 0 };
|
||||
try { fs.writeFileSync(fileOf(ev.tx), JSON.stringify(item)); } catch (e) { console.error('refuel pending write', e.message); }
|
||||
return pushOne(item);
|
||||
}
|
||||
async function pushOne(item) {
|
||||
if (!linked()) return { queued: true };
|
||||
try {
|
||||
const r = await post('/api/partner/refuel/purchase', { email: item.email, tx: item.tx, cents: item.cents, credits: item.credits, ts: item.ts });
|
||||
try { fs.unlinkSync(fileOf(item.tx)); } catch (e) {}
|
||||
if (r && r.on && Array.isArray(r.items)) await applyAll(r.items);
|
||||
return r;
|
||||
} catch (e) {
|
||||
item.tries = (item.tries || 0) + 1; item.lastError = e.message;
|
||||
try { if (fs.existsSync(fileOf(item.tx))) fs.writeFileSync(fileOf(item.tx), JSON.stringify(item)); } catch (er) {}
|
||||
console.error('refuel report failed (will retry)', String(item.tx).slice(0, 12), e.message);
|
||||
return { queued: true, error: e.message };
|
||||
}
|
||||
}
|
||||
async function retryPending() {
|
||||
let n = 0;
|
||||
for (const f of (() => { try { return fs.readdirSync(PENDING); } catch (e) { return []; } })()) {
|
||||
if (!f.endsWith('.json')) continue;
|
||||
let item; try { item = JSON.parse(fs.readFileSync(path.join(PENDING, f), 'utf8')); } catch (e) { continue; }
|
||||
const r = await pushOne(item); if (r && !r.queued) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- 2. grants and reminders from InstantAdPay's outbox -----------------------------------------------
|
||||
async function applyAll(items) {
|
||||
const done = [];
|
||||
for (const it of items || []) {
|
||||
try { await applyOne(it); done.push(it.ref); } catch (e) { console.error('refuel apply', it.ref, e.message); }
|
||||
}
|
||||
if (done.length) { try { await post('/api/partner/refuel/ack', { refs: done }); } catch (e) { console.error('refuel ack', e.message); } }
|
||||
return done.length;
|
||||
}
|
||||
async function applyOne(it) {
|
||||
const mine = X.marks ? await X.marks.claim('rfg:' + it.ref) : true;
|
||||
if (!mine) return false; // applied before (or by the other copy): ack only
|
||||
const p = it.payload || {};
|
||||
if (it.kind === 'grant') {
|
||||
const credits = Math.max(0, Math.round(Number(p.credits) || 0)); if (!credits) return false;
|
||||
await X.ads.addEarned(it.email, credits, { purchased: true });
|
||||
if (X.ads.logCredit) await X.ads.logCredit(it.email, credits, String(p.note || 'Refuel streak bonus').slice(0, 160));
|
||||
try { await X.message(it.email, subjectOf(p), htmlOf(p)); } catch (e) { console.error('refuel notice', e.message); }
|
||||
console.log('refuel grant applied', it.ref.slice(0, 40), credits);
|
||||
} else if (it.kind === 'reminder') {
|
||||
const html = '<p>' + esc(p.text) + '</p><p><a href="' + X.siteUrl + '/credits">Buy a package</a></p><p style="color:#556">Bonus credits buy ad delivery only; they are never cash.</p>';
|
||||
try { await X.message(it.email, p.subject, html); } catch (e) { console.error('refuel reminder inbox', e.message); }
|
||||
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(it.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(it.email) : '';
|
||||
try { await X.mailer.send(it.email, p.subject, p.text + '\n\nBuy a package: ' + X.siteUrl + '/credits' + foot + '\n\nLinkSpin'); } catch (e) { console.error('refuel reminder mail', e.message); }
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function subjectOf(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 === 'refuelday') return 'Refuel Day bonus: +' + money(p.credits) + ' credits';
|
||||
return 'Refuel counted: +' + money(p.credits) + ' bonus credits (month ' + (p.month || 1) + ')';
|
||||
}
|
||||
function htmlOf(p) {
|
||||
return '<p>' + esc(p.note) + '. <b>' + money(p.credits) + ' bonus ad credits</b> were added to your LinkSpin balance, purchased-grade, so they run on any format, login ads included.</p>'
|
||||
+ (p.kind === 'pitstop' ? '<p>A Pit Stop keeps an ad running between refuel days. It does not count as your monthly refuel.</p>' : '')
|
||||
+ '<p>Your refuel day and streak are on the Refuel card under Credits. Bonus credits buy ad delivery only; they are never cash.</p>';
|
||||
}
|
||||
let pulling = false;
|
||||
async function pull() {
|
||||
if (!cfg().on || !linked() || pulling) return 0;
|
||||
pulling = true;
|
||||
try { const r = await post('/api/partner/refuel/outbox', {}); return r && r.on ? await applyAll(r.items || []) : 0; }
|
||||
catch (e) { console.error('refuel pull', e.message); return 0; }
|
||||
finally { pulling = false; }
|
||||
}
|
||||
async function tick() { if (!cfg().on) return { on: false }; const retried = await retryPending(); const applied = await pull(); return { on: true, retried, applied }; }
|
||||
|
||||
// ---- 3. the member's card ---------------------------------------------------------------------------------
|
||||
const cache = new Map();
|
||||
async function status(email) {
|
||||
if (!cfg().on) return { on: false };
|
||||
email = String(email || '').toLowerCase(); if (!email) return { on: false };
|
||||
const hit = cache.get(email); if (hit && Date.now() - hit.at < 60000) return hit.v;
|
||||
if (!linked()) return { on: false, reason: 'not linked' };
|
||||
let v;
|
||||
try { v = await post('/api/partner/refuel/status', { email }, 6000); } catch (e) { return { on: true, error: 'InstantAdPay did not answer just now.' }; }
|
||||
cache.set(email, { at: Date.now(), v }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
||||
return v;
|
||||
}
|
||||
// the refill notice's streak line, from the same view
|
||||
async function streakLine(email) {
|
||||
const v = await status(email).catch(() => null);
|
||||
if (!v || !v.on || v.error) return null;
|
||||
let t;
|
||||
if (!v.active) t = 'Refuel streak: a $' + v.minUsd.linkspin + '+ package here (or $' + v.minUsd.iap + '+ on InstantAdPay) 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: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') + ', and your refuel window is open (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.linkspin ? ' A $' + v.minUsd.linkspin + '+ top-up before then earns a Pit Stop bonus of +' + v.pitStop.pct + '%.' : '');
|
||||
return { text: t, html: '<b>Refuel streak:</b> ' + esc(t.replace(/^Refuel streak: /, '')) };
|
||||
}
|
||||
function adminView() {
|
||||
let pending = []; try { pending = fs.readdirSync(PENDING).filter(f => f.endsWith('.json')).map(f => { try { return JSON.parse(fs.readFileSync(path.join(PENDING, f), 'utf8')); } catch (e) { return null; } }).filter(Boolean); } catch (e) {}
|
||||
return { on: cfg().on, linked: linked(), iap: IAP(), pending: pending.map(p => ({ email: p.email, tx: p.tx, cents: p.cents, tries: p.tries || 0, lastError: p.lastError || null })) };
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, onPurchase, retryPending, pull, tick, status, streakLine, applyAll, adminView };
|
||||
@@ -65,7 +65,8 @@ const health = require('./health'); // destination health checks + auto-pause (2
|
||||
const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29)
|
||||
const convtrack = require('./convtrack'); // conversion pixel: goals, ad click ids, landing tag + goal pixel, per-goal reports (2026-10-23)
|
||||
const marks = require('./marks'); // one-time claims shared by both app copies during a deploy (event_marks or exclusive files), 2026-10-24
|
||||
const refill = require('./refill'); // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
|
||||
const refill = require('./refill');
|
||||
const refuel = require('./refuel'); // Monthly Refuel streak, LinkSpin side: reports $25+ packages to InstantAdPay (the source of truth), applies its grants (2026-10-24) // refill notices: low / out / idle, one message per owner, conversions tracked (2026-10-24)
|
||||
const bannerspin = require('./bannerspin'); // Banner Spin: one image URL + one click URL rotating up to 25 banners (2026-10-18)
|
||||
const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12)
|
||||
const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/<slug> (2026-09-29)
|
||||
@@ -605,7 +606,8 @@ async function boot() {
|
||||
marks.ensureTable().catch(e => console.error('marks table', e.message));
|
||||
setInterval(() => marks.prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {});
|
||||
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {}); } });
|
||||
if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {});
|
||||
if (ev && ev.type === 'Purchase') refuel.onPurchase(ev).catch(e => console.error('refuel report', e.message)); } }); // no-op while refuelStreak is off
|
||||
auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST });
|
||||
accounts.init({ dataDir: DATA_DIR });
|
||||
ads.init({ dataDir: DATA_DIR, chain });
|
||||
@@ -614,7 +616,7 @@ async function boot() {
|
||||
messages.reclassifyCarryNotices(ADMIN_EMAIL || 'house@linkspin.co').then(n => { if (n) console.log('messages: ' + n + ' carry notices made quiet (notice kind)'); }).catch(() => {});
|
||||
reports.init({ dataDir: DATA_DIR });
|
||||
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: SITE_URL });
|
||||
chatbot.init({ dataDir: DATA_DIR, chain });
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, refuelOn: () => refuel.cfg().on });
|
||||
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
||||
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
||||
@@ -631,7 +633,11 @@ async function boot() {
|
||||
});
|
||||
// campaign refill notices (2026-10-24, copied from InstantAdPay): told when an ad is nearly out, when it stops, and once more
|
||||
// a week later if credits sit idle; one email + one on-site notice per owner, every send watched for what they did next
|
||||
refill.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, siteUrl: SITE_URL, houseOwner: ads.HOUSE_OWNER,
|
||||
refuel.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, marks, mailer, drip, siteUrl: SITE_URL, iapBase: IAP_BASE,
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
|
||||
setTimeout(() => refuel.tick().catch(e => console.error('refuel', e.message)), 75000);
|
||||
setInterval(() => refuel.tick().catch(e => console.error('refuel', e.message)), 60 * 1000);
|
||||
refill.init({ dataDir: DATA_DIR, siteConfig, ads, accounts, chain, mailer, drip, marks, siteUrl: SITE_URL, houseOwner: ads.HOUSE_OWNER, streakLine: email => refuel.streakLine(email),
|
||||
creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; },
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [to], subject, html, 'notice'); } });
|
||||
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
|
||||
@@ -766,7 +772,8 @@ function siteConfig() {
|
||||
geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE)
|
||||
geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else
|
||||
pnlFixedMonthlyUsd: 0,
|
||||
refillNotices: '1', refillLowPct: 80, // refill notices (2026-10-24): '0' turns them off; the share of a budget delivered that counts as running low
|
||||
refillNotices: '1', refillLowPct: 80,
|
||||
refuelStreak: '0', refuelMinLsCents: 2500, // Monthly Refuel streak (2026-10-24): '0' = nothing reported or shown; the streak itself lives on InstantAdPay // refill notices (2026-10-24): '0' turns them off; the share of a budget delivered that counts as running low
|
||||
campaignEditFee: 100 // credits per ad edit after each campaign's first, free one (Orlando's ask, 2026-10-18); 0 = edits always free
|
||||
}, saved);
|
||||
}
|
||||
@@ -3816,6 +3823,19 @@ const server = http.createServer(async (req, res) => {
|
||||
passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length },
|
||||
wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() });
|
||||
}
|
||||
if (p === '/api/admin/refuel' && req.method === 'GET') { // Monthly Refuel, LinkSpin side: switch, link to InstantAdPay, reports waiting to go
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, refuel.adminView());
|
||||
}
|
||||
if (p === '/api/admin/refuel/tick' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await refuel.tick());
|
||||
}
|
||||
if (p === '/api/my/refuel' && req.method === 'GET') { // the member's Refuel card, from InstantAdPay's record ({ on:false } while switched off)
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
|
||||
return json(res, 200, await refuel.status(s.email));
|
||||
}
|
||||
if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran low or out, and what they did next
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, refill.stats());
|
||||
|
||||
Reference in New Issue
Block a user