diff --git a/bannerspin.js b/bannerspin.js index a1d59dc..0968378 100644 --- a/bannerspin.js +++ b/bannerspin.js @@ -331,7 +331,7 @@ async function click(code, req, reqHost) { url = url.replace(/\{([a-z0-9_]{1,24})\}/gi, (mm, k) => encodeURIComponent(vals[k.toLowerCase()] == null ? '' : vals[k.toLowerCase()])); try { const t = new URL(url); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid') && !/^\/r\//.test(t.pathname)) { t.searchParams.set('lsid', id); url = t.toString(); } } catch (e) {} // straight to a page: the click id rides along for the landing tag (a spin-link target adds its own on the /r/ hop) - if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner)) url = WITH_CLICK_ID(url, id); } catch (e) {} } } + if (!bot) { let spinHop = false; try { spinHop = /^\/r\/[a-z0-9]{4,12}$/i.test(new URL(url).pathname); } catch (e) {} if (!spinHop) { try { if (WANTS_CLICK_ID(s.owner, url)) url = WITH_CLICK_ID(url, id); } catch (e) {} } } } return { url, lsid: id, banner: b, matched: m, owner: s.owner }; } @@ -348,10 +348,13 @@ function clickById(id) { async function convert(lsid, ev, facts) { const c = J.db.clicks.find(x => x.id === String(lsid)); if (!c) return null; const s = J.db.spins.find(x => x.id === c.s); if (!s) return null; - if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); } + if (!J.db.conv.some(x => x.lsid === c.id && x.ev === ev)) { J.db.conv.push({ lsid: c.id, s: s.id, b: c.b, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: c.sr || undefined, key: facts && facts.key ? String(facts.key) : undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); } return { owner: s.owner, code: s.code, rotationId: 0, bannerSpinId: s.id, bannerId: c.b, q: c.q || {}, s: c.h || 'direct', c: c.c || '', dv: c.dv, sourceId: c.sr || '' }; } +// a member's Banner Spin conversions as rows (netconv.unified); rows with a key are the ledger's and are skipped there +function convRows(owner, since) { const ids = new Set(J.db.spins.filter(x => x.owner === String(owner || '').trim().toLowerCase()).map(x => x.id)); return J.db.conv.filter(c => ids.has(c.s) && c.ts >= since); } + // ── stats (phase 3, 2026-10-20): one aggregation for the builder's Stats tab and the Reports screen ── // Views are the counted impressions (bots, prefetches and servers left out); bots and server loads are reported beside // them. Clicks are rows (bots flagged), so day / country / device come from human clicks, the same way spin links report. diff --git a/chatbot.js b/chatbot.js index 98734bb..865c5f2 100644 --- a/chatbot.js +++ b/chatbot.js @@ -87,7 +87,7 @@ const CANNED = [ a: 'A zone is an ad slot on your own site: one script tag, nine standard sizes (728x90, 468x60, 300x250, 336x280, 250x250, 125x125, 160x600, 120x600, 320x50). Each load shows a LinkSpin member campaign first, then a network ad, then our house banner if nothing paid fits. You earn ad credits per viewable impression (half the banner on screen for one second, bots never, 50 credited views per visitor per zone per day): 1 credit per 5 viewable member-ad views and 1 per 10 network-ad views, or 1 per 8 on a Verified zone the admin has reviewed. A new zone earns after its first 100 on-site views with at least 40 percent viewable, and paid ads serve only on the site you declared, so copying the tag elsewhere earns nothing. Everything is explained at ' + SITE_URL + '/publishers and you add zones under Zones in your Control Room.' }, { id: 'conversions', title: 'Conversion tracking (the conversion pixel)', q: ['How do I track sign-ups or sales from my ads?', 'What is the conversion pixel?', 'How do I see cost per lead?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion pixel', 'goal', 'cost per goal', 'landing tag', 'thank-you page', 'tracking', 'wordpress', 'setup guide'], re: /(conversion (pixel|tracking)|goal pixel|landing tag|\bt\.js|cv\.(gif|js)|cost per (goal|conversion|lead|sale|sign ?up|subscriber)|track (a |my )?(goal|sale|sign ?up|subscriber|lead)s?|lsclk|thank.?you page|aweber|getresponse)/i, - a: 'The conversion pixel counts what happens after the click: a subscriber, a sale, any goal you name. Open Conversions in your Control Room and add a goal (for example subscriber). Then 1) paste the landing tag once on your landing page, 2) paste the goal pixel on your thank-you page, 3) press Send a test conversion (to check your real thank-you page, add &test=1 to its pixel and open the page once; the last test time updates). Every click on your LinkSpin and InstantAdPay ads, your spin links and your Banner Spins (banners that go straight to a page included) carries a click id (lsclk) the tag keeps on your site, so each goal counts once per click, within 30 days of the click, and only for clicks on your own ads and links. Your OWN clicks on your own ads, spin links or Banner Spins are kept as tests and never counted, so test with the button, not by signing up yourself. Reports show conversions and cost per goal by ad campaign, spin link, Banner Spin, page and traffic source, plus how each one was matched (from the address, kept by the tag, LinkSpin\'s cookie, or a 24-hour match). If your autoresponder (Aweber, GetResponse) shows its own thank-you page, set its thank-you redirect to a page on your own site that carries the pixel. A postback set to the event goal tells your tracker too. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://linkspin.app/conversion-tracking' }, + a: 'The conversion pixel counts what happens after the click: a subscriber, a sale, any goal you name. Open Conversions in your Control Room and add a goal (for example subscriber). Then 1) paste the landing tag once on your landing page, 2) paste the goal pixel on your thank-you page, 3) press Send a test conversion (to check your real thank-you page, add &test=1 to its pixel and open the page once; the last test time updates). Every click on your LinkSpin and InstantAdPay ads, your spin links and your Banner Spins (banners that go straight to a page included) carries a click id (lsclk) the tag keeps on your site, so each goal counts once per click, within 30 days of the click, and only for clicks on your own ads and links. Your OWN clicks on your own ads, spin links or Banner Spins are kept as tests and never counted, so test with the button, not by signing up yourself. Reports show conversions and cost per goal by ad campaign, spin link, Banner Spin, page and traffic source, plus how each one was matched (from the address, kept by the tag, LinkSpin\'s cookie, or a 24-hour match). Reports > Conversions is the one place that shows everything together: your goals plus joins, wallets and purchases, with values. People you send to LinkSpin or InstantAdPay count there with no goal and no pixel: the landing tag adds the click id to links to those sites, also through a redirect link of your own, and a spin link pointed straight at them carries it too, so their sign-up, wallet link and every package bought within 30 days of the click count on your click. The value of a purchase is its USD price. Your own account is never counted. This is reporting only: it never changes who a sponsor is or what anyone is paid. If your autoresponder (Aweber, GetResponse) shows its own thank-you page, set its thank-you redirect to a page on your own site that carries the pixel. A postback set to the event goal tells your tracker too. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://linkspin.app/conversion-tracking' }, { id: 'trafficguide', title: 'Which traffic for which offer', q: ['What traffic should I use for my offer?', 'Is pop or push better?', 'Which ad network is best for a crypto offer?'], tags: ['sources', 'traffic guide', 'paid traffic'], re: /((what|which|best|right) (kind|type)s? of (traffic|ads?)|(what|which|best) (traffic|ad network|network)s?\b.{0,40}\b(for|to use|should)|traffic guide|pop(under)?s? (or|vs\.?|versus) push|push (or|vs\.?|versus) (pop|native)|native (or|vs\.?|versus)|what converts|which (format|ad format))/i, a: 'Open the Traffic guide: https://linkspin.app/traffic-guide (also the Traffic guide button on your Sources screen). Pick what you are promoting and it shows which ad formats tend to convert for it and which networks sell those formats. Quick version: free sign-ups, email capture, games and giveaways do best on popunder, push and in-page push (cheap volume, one-step pages). Courses, software and story-style pre-sells do best on native ads. Things people already look for, like advertising tools, do best on search. For a crypto or team-build opportunity, use native or push to a pre-sell or squeeze page and capture the email first; Google, Microsoft, Facebook, Taboola, Revcontent and MGID restrict crypto and income offers, and no network accepts income promises. Networks marked adult-heavy sell a lot of adult traffic, so target their mainstream sites. Whatever you pick, set the network up under Sources so Reports shows what actually converts, and start small.' }, @@ -99,7 +99,7 @@ const CANNED = [ a: 'A spin link is one short link that rotates between every page you promote. Behind it you set destinations with weights, pause any of them, and name a fallback for when everything else is off. Every click is recorded in one hop with the day, country, source and device, bots are filtered on the server, and click ids and sub ids (clickid, subid, s1 to s4 and the usual tracker names) ride through to the destination, so you can split-test by tagging the same link with different sub ids. Reports show it per link and across all of them. Set the hours of the day and week a spin or a destination runs (the local time of your visitor by default), and automatic health checks pause a dead or parked destination for you. You can try a spin with no account on the home page.' }, { id: 'pages', title: 'The page builder', q: ['How do I build a bridge page?', 'Can I make a squeeze page?', 'Where do my leads go?'], tags: ['pages', 'page builder', 'bridge page', 'leads'], re: /(page builder|bridge page|squeeze page|review page|sales page|advertorial|press release|landing page|build (a|me a) page|my pages?|lead capture|leads?\b)/i, - a: 'Pages is the built-in page builder. Paste the address of any offer you promote, LinkSpin scans its headline and points, you add your angle, and you get a bridge, review or squeeze page with your own leads list (CSV or webhook), published on LinkSpin\'s pages domain, lookfirst.page. Pick a design, palette and layout, or a niche preset that sets them for you with a matching hero image. Put the page behind a spin link to send traffic by weight. Sales, advertorial and press-release layouts are on the way. Open Pages in your Control Room; it is free.' }, + a: 'Pages is the built-in page builder. Paste the address of any offer you promote, LinkSpin scans its headline and points, you add your angle, and you get a bridge, review or squeeze page with your own leads list and CSV download (or paste a form from your autoresponder on a squeeze page and the leads go straight to it), published on LinkSpin\'s pages domain, lookfirst.page. Pick a design, palette and layout, or a niche preset that sets them for you with a matching hero image. Put the page behind a spin link to send traffic by weight. Sales, advertorial and press-release layouts are on the way. Open Pages in your Control Room; it is free.' }, { id: 'audiences', title: 'Audiences and retargeting', q: ['How does retargeting work?', 'What is the pixel?', 'Can I show ads only to my visitors?'], tags: ['audiences', 'retargeting', 'pixel'], re: /(audience|retarget|pixel|p\.js|my visitors|show only to|never show to)/i, a: 'Audiences is first-party retargeting. Everyone who views your LinkSpin pages or your zones lands in "My visitors" for 30 days with no setup, and for any other site you control you paste a small pixel tag (/p.js). Then, on any banner or text campaign, choose "show only to" or "never show to" an audience. The match uses a LinkSpin cookie with a 24-hour fallback where browsers block cross-site cookies, and nothing personal is stored. It lives on the Zones screen.' }, @@ -194,8 +194,8 @@ function systemPrompt(kbBlock) { FACTS: - PROHIBITED CONTENT (2026-10-30, Terms section 9, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text. - LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company paid, decided off chain, paid on chain. 3% of every LinkSpin package purchase (the POL actually paid) goes to the buyer's 4th upline on the LinkSpin contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = referral whose first package was $25 or more; same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; company account #1 or nobody qualified = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId); shown on the Wallet screen as 'Level 4 override' with a Polygon link. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split is unchanged. Separate from InstantAdPay's override; qualification does not carry between sites. Never promise amounts. -${refuelFact()}${synFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/, 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. TRAFFIC GUIDE at /traffic-guide (2026-10-28, public, linked from the Sources screen header and each source's detail): pick an offer type (free sign-up or email capture; crypto or team-build opportunity; advertising tools and ad credits; games and play-to-earn; software, apps and AI tools; courses and info products; giveaways and freebies) to see each ad format rated best / good / weak / avoid with a reason, a tip, and the catalog networks that sell the good formats (strict-policy networks Google, Microsoft, Facebook, Taboola, Revcontent, MGID left out for the crypto offer; adult-only TrafficJunky only for games and giveaways); cards for the 8 formats (popunder, push, in-page push, native, search, social, banners, domain redirect: what it is, how you pay, what converts, what struggles, landing page); a table of all 30 catalog networks with the formats each sells, adult-heavy and strict-policy flags and best-for; ground rules (test small, track every click under Sources, one change at a time, block zones that waste money, no income promises, mainstream vs adult inventory). The New source picker shows the same format tags and can be searched by format (push, native...). Never promise results; the guide says Reports are the final word. 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= 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, and so do Banner Spin clicks that go straight to a page (since 2026-10-26; a banner pointed at a spin link gets the spin link's id). SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line , 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. OWN CLICKS (2026-10-26): the goal owner's own click on ANY click type (ads, spin links, Banner Spins) is kept as a test and never counted: a click made while signed in as the owner, or a click or conversion from a browser (network + browser soft key) the owner has signed in from on LinkSpin or InstantAdPay; the Conversions screen says 'N from your own clicks, kept as tests and left out'. To test, use Send a test conversion and the &test=1 page check, never a sign-up of your own. 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, Banner Spin (banners straight to a page), 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. SETUP GUIDE (public, 2026-10-24): ${SITE_URL}/conversion-tracking (InstantAdPay's copy: https://instantadpay.com/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, the last test time updates, then remove it), what to do without code on the thank-you page (image pixel = cookie or 24-hour match; LinkSpin.goal(pixelId, name) from the page's own code for a pop-up form; postbacks), how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest, a Banner Spin banner pointed straight at a page now carries its own click id and counts under By Banner Spin; the member's own clicks on ads, spin links and Banner Spins are all kept as tests). Send members there for any setup question. +${refuelFact()}${synFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotator: one short link, /r/, 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 with a CSV download, or the member pastes an autoresponder form on a squeeze page and LinkSpin restyles it; there is no lead 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. TRAFFIC GUIDE at /traffic-guide (2026-10-28, public, linked from the Sources screen header and each source's detail): pick an offer type (free sign-up or email capture; crypto or team-build opportunity; advertising tools and ad credits; games and play-to-earn; software, apps and AI tools; courses and info products; giveaways and freebies) to see each ad format rated best / good / weak / avoid with a reason, a tip, and the catalog networks that sell the good formats (strict-policy networks Google, Microsoft, Facebook, Taboola, Revcontent, MGID left out for the crypto offer; adult-only TrafficJunky only for games and giveaways); cards for the 8 formats (popunder, push, in-page push, native, search, social, banners, domain redirect: what it is, how you pay, what converts, what struggles, landing page); a table of all 30 catalog networks with the formats each sells, adult-heavy and strict-policy flags and best-for; ground rules (test small, track every click under Sources, one change at a time, block zones that waste money, no income promises, mainstream vs adult inventory). The New source picker shows the same format tags and can be searched by format (push, native...). Never promise results; the guide says Reports are the final word. 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= 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, and so do Banner Spin clicks that go straight to a page (since 2026-10-26; a banner pointed at a spin link gets the spin link's id). SETUP, 3 steps: 1) the LANDING TAG on the landing page, one line , 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. OWN CLICKS (2026-10-26): the goal owner's own click on ANY click type (ads, spin links, Banner Spins) is kept as a test and never counted: a click made while signed in as the owner, or a click or conversion from a browser (network + browser soft key) the owner has signed in from on LinkSpin or InstantAdPay; the Conversions screen says 'N from your own clicks, kept as tests and left out'. To test, use Send a test conversion and the &test=1 page check, never a sign-up of your own. 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, Banner Spin (banners straight to a page), destination page and traffic source, plus CSV export. ONE PLACE TO LOOK (2026-11-07): Reports > Conversions on LinkSpin and the Conversion tracking card on InstantAdPay list goals together with join, wallet and purchase events, with values, each event once; per-link Conv. counts include goals; the CSV holds goal conversions only. NETWORK EVENTS (2026-11-07, reporting only, it never changes sponsors, payouts or anything on chain): the landing tag adds the kept click id to links to instantadpay.com, linkspin.app and the share domains instantadpay.link, ctbgo.com and mylinehq.com, also inside a member's own redirect link when the address is in one of its parameters (spin and Banner Spin links are left alone; a button that navigates by script instead of a link is not covered); a spin link or Banner Spin pointed straight at those sites adds lsclk with no goal needed. InstantAdPay keeps the click 30 days in a first-party cookie, stores it on the account at sign-up and reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and every purchase on its own. Same 30-day rule: an event more than 30 days after the click does not count. The first account on a click owns it. The click owner's own account and own clicks are kept as tests. Postbacks fire for join, wallet and purchase as they do for LinkSpin's own. Nothing is counted back in time: an account without a click stored at sign-up has none. 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. SETUP GUIDE (public, 2026-10-24): ${SITE_URL}/conversion-tracking (InstantAdPay's copy: https://instantadpay.com/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, the last test time updates, then remove it), what to do without code on the thank-you page (image pixel = cookie or 24-hour match; LinkSpin.goal(pixelId, name) from the page's own code for a pop-up form; postbacks), how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest, a Banner Spin banner pointed straight at a page now carries its own click id and counts under By Banner Spin; the member's own clicks on ads, spin links and Banner Spins are all kept as tests). Send members there for any setup question. - 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/.gif on a link domain) and one click address (/c/) 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. - PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor. diff --git a/convtrack.js b/convtrack.js index 6796af9..820e15d 100644 --- a/convtrack.js +++ b/convtrack.js @@ -270,6 +270,16 @@ async function report(owner, days, opts) { return { days: Number(days) || 30, goals: goals.map(g => Object.assign(pubGoal(g), { conv: conv.filter(c => c.px === g.px).length, lastAt: (conv.filter(c => c.px === g.px).pop() || {}).ts || null })), byGoal: out, methods, total: conv.length, selfTests }; } +// goal conversions as rows, own-click tests left out. goalRows() = every row that came through a spin link, in the rotator's own +// shape, so per-link counts include goals (2026-11-07); memoized on the length of the log, the pixel only ever appends to it. +let GR = { n: -1, rows: [] }; +function goalRows() { const c = load().conv; if (GR.n !== c.length) GR = { n: c.length, rows: c.filter(x => x.rot && !x.self).map(x => ({ r: x.rot, lsid: x.click, ev: 'goal: ' + x.goal, ts: x.ts, value: x.value || 0, sr: x.sr })) }; return GR.rows; } +function goalRowsOf(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self); } +// the click-side test of "is this the owner's own": the click was theirs, or the converting browser is one they sign in from +function selfFor(L, owner, sk) { + const st = load(), ad = L.ad, o = norm(owner); + return !!(st.selfIds[L.id] || st.selfIds[L.root] || (ad && ad.owner === o && (ad.self || (ad.sk && isOwnerSk(o, ad.sk)))) || (sk && isOwnerSk(o, sk))); +} // InstantAdPay's view: goals + per IAP campaign conversions (and clicks) for this owner // goal conversions (not the owner's own tests) since a moment, for the Engine Room's goals dial (2026-10-24) function countSince(owner, since) { const o = norm(owner); return load().conv.filter(c => c.owner === o && c.ts >= since && !c.self).length; } @@ -305,4 +315,4 @@ function withClickId(target, id) { const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?'; return base + sep + 'lsclk=' + encodeURIComponent(id) + hash; } -module.exports = { noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS }; +module.exports = { goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS }; diff --git a/netconv.js b/netconv.js new file mode 100644 index 0000000..190f2bc --- /dev/null +++ b/netconv.js @@ -0,0 +1,134 @@ +// Network conversions (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: nothing here touches sponsors, payouts, credits or +// the chain. InstantAdPay reports sign-ups, wallet links and package purchases by accounts that arrived on a LinkSpin click +// (op 'events' on /api/partner/conv, signed); LinkSpin counts them for the click's owner. +// +// - The ledger is DATA_DIR/netconv.jsonl: append-only, one write per event, so the two app copies of a deploy can both add +// to it without rewriting each other (unlike the JSON stores that rewrite the whole file). Each copy re-reads it when its +// size changes. +// - Once: marks.claim is true for exactly one copy; a key already in the ledger is a dup, so a repeat after marks are pruned +// is still refused. join and wallet count once per ROOT click (an ad click and the spin click it led to are one click), and +// each purchase counts by its own key (tx + log index). A click belongs to the first account seen on it. +// - Window: convtrack's rule, 30 days from the real click to the EVENT (not to delivery, so a retry queue never loses one). +// - The click owner's own account, and own clicks, are kept as tests: in the ledger with self:1, never counted, no postback. +// - Each row carries what the click was, so a later event still counts after the hit aged out of the rotator. +// - Spin-link events are mirrored into rotator.conv (per-link counts, sources, Reports) and Banner Spin events into its +// own conv; the mirror is replayed from the ledger on a timer, so a copy that lost a write during a deploy heals. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const EVENTS = ['join', 'wallet', 'purchase']; +let FILE = null, C = null, R = null, B = null, P = null, M = null; +let st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; +const norm = e => String(e || '').trim().toLowerCase(); +const DAY = 86400000; +const acctHash = email => crypto.createHash('sha256').update('netconv|' + norm(email)).digest('hex').slice(0, 16); // never the address itself + +function init(o) { + FILE = path.join(o.dataDir, 'netconv.jsonl'); C = o.convtrack; R = o.rotator; B = o.bannerspin || null; P = o.postbacks || null; M = o.marks; + st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; refresh(); + if (!o.noTimers) { setTimeout(() => syncMirror().catch(() => {}), 30000).unref(); setInterval(() => syncMirror().catch(() => {}), 300000).unref(); } +} +function refresh() { + let size = 0; try { size = fs.statSync(FILE).size; } catch (e) {} + if (size === st.size) return st; + const n = { size, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; + let raw = ''; try { raw = fs.readFileSync(FILE, 'utf8'); } catch (e) {} + for (const line of raw.split('\n')) { + if (!line) continue; let r; try { r = JSON.parse(line); } catch (e) { continue; } + n.rows.push(r); n.keys.add(String(r.k).split('|')[0]); + for (const [m, id] of [[n.byClick, r.click], [n.byRoot, r.root]]) { const a = m.get(id); if (a) a.push(r); else m.set(id, [r]); } + } + st = n; return st; +} + +// the facts of a click, for one owner, as they stand now +function factsOf(L, o) { + const sp = L.spin, ad = L.ad, bs = L.bspin, mineSpin = !!(sp && sp.owner === o), mineAd = !!(ad && ad.owner === o); + return { kind: mineSpin ? 'spin' : (mineAd ? ad.k : (bs ? 'bspin' : (ad ? ad.k : 'spin'))), + camp: mineAd ? ad.camp : undefined, cname: mineAd ? ad.cname : undefined, + rot: mineSpin ? sp.rotation.id : undefined, rcode: mineSpin ? sp.rotation.code : undefined, rname: mineSpin ? sp.rotation.name : undefined, d: mineSpin ? sp.hit.d : undefined, sr: mineSpin ? (sp.hit.sr || undefined) : undefined, + bcode: bs ? bs.spin.code : undefined, src: (sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : ''))) || '', c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.dv : ad && ad.dv)) || '', + q: (sp ? sp.hit.q : (bs ? bs.click.q : undefined)) || undefined }; +} + +// e: { k, ev, click, email, value, ts, tx, sk }. Returns { result }: counted | self | dup | other | expired | nomatch | bad. +// Every one of those is final: the sender stops retrying on any answer. +async function record(e) { + const ev = String(e && e.ev || ''), k = String(e && e.k || '').slice(0, 120), click = String(e && e.click || ''); const email = norm(e && e.email); + if (!EVENTS.includes(ev) || !k || !C.isClickId(click) || !email || email.length > 190) return { result: 'bad' }; + let S = refresh(); if (S.keys.has(k)) return { result: 'dup' }; + const now = Date.now(); const at = Math.min(Number(e.ts) || now, now); + const L = C.lookup(click); const prior = S.byClick.get(click) || null; + if (!L && !prior) return { result: 'nomatch' }; + const root = prior ? prior[0].root : L.root; const clickTs = prior ? prior[0].clickTs : L.ts; + if (at - clickTs > C.WINDOW_MS) return { result: 'expired' }; + const acct = acctHash(email); const seen = S.byRoot.get(root) || []; + if (seen.length && seen[0].acct !== acct) return { result: 'other' }; // one click, one person: the first account on it + if (ev !== 'purchase' && seen.some(r => r.ev === ev)) return { result: 'dup' }; + if (!(await M.claim('net:' + (ev === 'purchase' ? k : root + ':' + ev)))) return { result: 'dup' }; + const owners = L ? [...new Set(L.owners)] : [...new Set((prior || []).map(r => r.owner))]; + const value = ev === 'purchase' ? C.cleanValue(e.value) : 0; + const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : ''; + const tx = String(e.tx || '').slice(0, 80) || undefined; + const rows = owners.map(o => { + const was = (prior || []).find(r => r.owner === o); + const f = L ? factsOf(L, o) : { kind: was.kind, camp: was.camp, cname: was.cname, rot: was.rot, rcode: was.rcode, rname: was.rname, d: was.d, sr: was.sr, bcode: was.bcode, src: was.src, c: was.c, dv: was.dv, q: was.q }; + const self = email === o || !!(was && was.self) || seen.some(r => r.owner === o && r.self) || (L ? C.selfFor(L, o, sk) : false); + const row = Object.assign({ k: owners.length > 1 ? k + '|' + o : k, ev, ts: at, rec: now, value, acct, click, root, clickTs, owner: o, tx, self: self ? 1 : undefined }, f); + for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x]; + return row; + }); + fs.appendFileSync(FILE, rows.map(r => JSON.stringify(r) + '\n').join('')); // one write: the whole event lands or none of it + refresh(); + let counted = false; + for (const r of rows) { + if (r.self) continue; + counted = true; + await mirror(r).catch(err => console.error('netconv mirror', err.message)); + if (P) P.fire(r.owner, ev, { q: r.q || {}, source: r.src, country: r.c, device: r.dv, lsid: click, code: r.rcode || r.bcode || '', sourceId: r.sr || '', payout: value, currency: 'USD', txid: tx || '', label: ev }).catch(err => console.error('netconv postback', err.message)); + } + return { result: counted ? 'counted' : 'self' }; +} +// LinkSpin's own sign-ups, wallets and purchases that arrived on an ad click (a / i ids): the rotator cannot see those clicks +async function fromLinkSpin(lsid, ev, facts) { + const f = facts || {}; if (!EVENTS.includes(ev) || f.key || !f.email) return null; + const k = 'ls:' + ev + ':' + (ev === 'purchase' ? (f.txid || crypto.randomBytes(6).toString('hex')) : acctHash(f.email)); + await record({ k, ev, click: lsid, email: f.email, value: f.payout, ts: Date.now(), tx: f.txid }); + return null; +} +async function mirror(r) { + const key = r.k.split('|')[0]; + if (r.rot) return R.convert(r.click, r.ev, { payout: r.value, label: r.ev === 'purchase' ? 'InstantAdPay' : undefined, key, ts: r.ts, bound: { r: r.rot, d: r.d, sr: r.sr } }); + if (r.kind === 'bspin' && r.click[0] === 'k') return R.convert(r.click, r.ev, { payout: r.value, key, ts: r.ts }); + return null; +} +async function syncMirror() { for (const r of refresh().rows) if (!r.self && r.rot) await mirror(r).catch(() => {}); } + +const mineSince = (o, since) => refresh().rows.filter(r => r.owner === o && r.ts >= since); +const ORDER = ['join', 'lead', 'wallet', 'purchase', 'external']; +// Reports > Conversions: everything once. Rows mirrored into the rotator are read from the rotator (which also holds +// LinkSpin's own joins, wallets, purchases, leads and partner postbacks), the ledger adds only what the rotator cannot +// hold (ad clicks, Banner Spin clicks), Banner Spin's own rows add its site events, goals come from the pixel. +function unified(owner, days) { + const o = norm(owner); const since = Date.now() - Math.max(1, Number(days) || 30) * DAY; + const m = {}; const buyers = new Set(); + const add = (k, v) => { const x = m[k] = m[k] || { k, n: 0, value: 0 }; x.n++; x.value += Number(v) || 0; }; + for (const c of R.convRows(o, since)) { add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); } + if (B && B.convRows) for (const c of B.convRows(o, since)) { if (c.key) continue; add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); } + for (const r of mineSince(o, since)) { if (r.self || r.rot) continue; add(r.ev, r.value); if (r.ev === 'purchase') buyers.add(r.root); } + const goals = {}; for (const c of C.goalRowsOf(o, since)) { const g = goals[c.goal] = goals[c.goal] || { k: 'goal:' + c.goal, n: 0, value: 0 }; g.n++; g.value += c.value || 0; } + const rows = ORDER.filter(k => m[k]).map(k => m[k]).concat(Object.keys(m).filter(k => !ORDER.includes(k)).map(k => m[k]), Object.values(goals).sort((a, b) => b.n - a.n)).map(x => Object.assign(x, { value: Math.round(x.value * 100) / 100 })); + return { rows, joins: (m.join || {}).n || 0, wallets: (m.wallet || {}).n || 0, purchases: (m.purchase || {}).n || 0, buyers: buyers.size, goals: Object.values(goals).reduce((n, g) => n + g.n, 0) }; +} +// InstantAdPay's Campaigns card: the same rows, and the events on each of the member's InstantAdPay ad campaigns +function partner(owner, days) { + const o = norm(owner); const d = Math.max(1, Math.min(90, Number(days) || 30)); const since = Date.now() - d * DAY; + const byCampaign = {}; + for (const r of mineSince(o, since)) { if (r.self || r.kind !== 'iap' || !r.camp) continue; const b = byCampaign[r.camp] = byCampaign[r.camp] || { join: 0, wallet: 0, purchase: 0, value: 0 }; b[r.ev]++; b.value = Math.round((b.value + (r.value || 0)) * 100) / 100; } + const selfEvents = mineSince(o, since).filter(r => r.self).length; + return { rows: unified(o, d).rows, byCampaign, selfEvents, days: d }; +} +function adminCounts() { const a = refresh().rows; return { rows: a.length, counted: a.filter(r => !r.self).length }; } +module.exports = { init, record, fromLinkSpin, unified, partner, syncMirror, adminCounts, EVENTS }; diff --git a/postbacks.js b/postbacks.js index 217c9d4..236e9db 100644 --- a/postbacks.js +++ b/postbacks.js @@ -133,7 +133,7 @@ async function test(owner, id) { // a conversion happened for an account: find the click that brought them, record it on the rotator, fire the owner's postbacks async function convertFor(email, event, facts) { const c = clickOf(email); if (!c) return null; - const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, facts || {}) : null; + const hit = rotator && rotator.convert ? await rotator.convert(c.lsid, event, Object.assign({}, facts || {}, { email: norm(email) })) : null; if (!hit) return null; const ctx = Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: c.lsid, code: hit.code, sourceId: hit.sourceId || '' }, facts || {}); try { await fire(hit.owner, event, ctx); } catch (e) {} diff --git a/public/assets/join.js b/public/assets/join.js index 1212832..165a72c 100644 --- a/public/assets/join.js +++ b/public/assets/join.js @@ -13,7 +13,7 @@ ledger: { eyebrow: 'No back office', h: 'No back office. No payday.', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and the contract holds zero balance.', points: ['Every payout is public. Click it, read it, verify it.', 'The contract has no pause button and no owner power over money.', 'Join free by email. The ledger is one click from your dashboard.'], cta: 'Check the ledger yourself, then decide', sub: 'free account by email' }, two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open level two.', lead: 'Every direct buyer pays you half of their package from their very first purchase. Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', points: ['Half of every direct purchase, instantly.', 'Level 2 at two qualifying buyers, level 3 at five.', 'Your invite link is live the moment you are in.'], cta: 'Start your line. Two buyers is the target.', sub: 'free account by email' }, links: { video: 'links', eyebrow: 'One link, every page you promote', h: 'Stop juggling links.', lead: 'One short link stands in for all of yours. Behind it, the pages you promote, served in turn by the weights you set, with hours, caps and a fallback. The link never changes, so every copy out in the world keeps working.', points: ['Weights, hours of the day, daily caps, a fallback.', 'A report by source, country and device; your tracker click id filled in.', 'Free. Try a spin on the home page with no account.'], cta: 'Make your first spin link', sub: 'free account by email' }, - pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. Get a page.', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list: CSV or webhook.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' }, + pages: { video: 'pages', eyebrow: 'Bridge pages in a minute', h: 'Point it at any offer. Get a page.', lead: 'Paste the address of the offer you promote. LinkSpin reads its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on a clean pages domain. Leads are yours.', points: ['Bridge, review or squeeze. Your colours, a niche hero image.', 'Leads to your own list with a CSV download, or paste your autoresponder form.', 'Put the page behind your spin link and send traffic by weight.'], cta: 'Scan an offer you already promote', sub: 'free account by email' }, zones: { video: 'zones', eyebrow: 'Your site pays you', h: 'One script tag. Ad credits for every viewable view.', lead: 'A zone is an ad slot on your own site in any of nine sizes. Member campaigns show first, then network ads, then a house banner. Viewable impressions pay you ad credits you spend on your own campaigns.', points: ['Viewable = half the banner on screen for one second. Bots never count.', 'Paid ads only on the site you declared.', 'Credits spend on your own banner or text campaign.'], cta: 'Add a zone, paste the tag', sub: 'free account by email' }, audiences: { video: 'audiences', eyebrow: 'Retargeting, built in', h: 'Reach your own visitors again.', lead: 'Everyone who views your pages or your zones is remembered for 30 days in an audience you own. Paste a pixel on any other site you control. Then show a campaign only to them, or never to them.', points: ['My visitors is automatic. Named audiences take one pixel line.', 'Show only to, or never show to, on any banner or text campaign.', 'Honest match: cookie plus a 24-hour fallback, nothing personal stored.'], cta: 'See your audiences', sub: 'free account by email' }, stack: { video: 'stack', eyebrow: 'Three tools, zero dollars', h: 'A rotator, a page builder, an ad slot. Free.', lead: 'Join with just an email and the whole stack is yours: spin links, bridge pages and a zone for your site. View a few ads a day and you earn credits for your first campaign. Buy a package only if you want more.', points: ['No wallet, no card, nothing to install.', 'Spin links, pages and zones never need a package.', 'Packages from $10 when you want more reach.'], cta: 'Start with the free stack', sub: 'type your email, get a code, that is the whole signup' }, diff --git a/public/assets/reports.js b/public/assets/reports.js index 08224fd..c730542 100644 --- a/public/assets/reports.js +++ b/public/assets/reports.js @@ -20,6 +20,7 @@ CR.tile({ k: 'Bots dropped', v: fmt(t.bots), series: sb, delta: CR.delta(b1, b0, 'vs prior'), note: t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : '' }), CR.tile({ k: 'Joins', v: fmt(t.joins), note: t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : '' }), CR.tile({ k: 'Buyers', v: fmt(t.purchases), hi: true, note: t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : '' }), + CR.tile({ k: 'Goals', v: fmt(t.goals) }), CR.tile({ k: 'Partner conversions', v: fmt(t.external) }), // Banner Spin totals beside spin links (2026-10-20) CR.tile({ k: 'Banner views', v: fmt(((s.bannerSpins || {}).totals || {}).imps), note: ((s.bannerSpins || {}).count || 0) + ' Banner Spin' + (((s.bannerSpins || {}).count || 0) === 1 ? '' : 's') }), @@ -34,7 +35,9 @@ const hmax = Math.max(1, ...(s.hours || [])); $('hourBars').innerHTML = (s.hours || []).map((n, i) => '').join(''); const best = (s.hours || []).map((n, i) => [n, i]).sort((a, b) => b[0] - a[0]).slice(0, 3).filter(x => x[0]).map(x => x[1] + ':00'); $('hourNote').textContent = best.length ? 'Busiest hours (UTC): ' + best.join(', ') + '. Hour rules per link come next.' : 'No clicks yet.'; - $('convRows').innerHTML = kv(s.conversions || [], 0); + // one list (2026-11-07): site and network events first, then goals, a value beside anything that has one + const CONV_NAME = { join: 'Joins', lead: 'Leads', wallet: 'Wallets', purchase: 'Purchases', external: 'Partner postbacks' }; + $('convRows').innerHTML = kv((s.conversions || []).map(x => ({ k: (CONV_NAME[x.k] || String(x.k).replace(/^goal:\s*/, 'Goal: ')) + (x.value ? ' \u00b7 $' + Number(x.value).toFixed(2) : ''), n: x.n })), 0); // -- Pages and Zones (2026-10-10): one bar per Central day in the range (empty days are zero), totals, per-item table const dayBars = (barsId, axisId, rows, f, g, empty) => { const map = {}; (rows || []).forEach(r => { map[r.day] = r; }); diff --git a/public/conversion-tracking.html b/public/conversion-tracking.html index 9210238..f0e3239 100644 --- a/public/conversion-tracking.html +++ b/public/conversion-tracking.html @@ -121,6 +121,7 @@
  • 5Counted in ConversionsAgainst the ad, spin link, page and source that sent them, with cost per goal.
  • The id is random. It identifies the click, not the person. Nothing personal is read from your page or sent anywhere. An ad click and the spin-link click it led to count as one click.

    +

    Sending people to LinkSpin or InstantAdPay? Those two count by themselves, with no goal and no pixel. The landing tag adds the click id to your links to either site, also when the address sits inside a redirect link of your own. A spin link or Banner Spin pointed straight at either site carries it too. Then their sign-up, wallet link and each package they buy within 30 days of the click show in Reports under Conversions, purchases with their USD price. This is reporting only. It never changes who a sponsor is or what anyone is paid.

    @@ -227,6 +228,7 @@ CookieExact, through LinkSpin's own cookie. Some browsers block it. 24 h matchThe same network and browser within a day of the click. A good guess, not proof. Test / last testWhen your last test conversion arrived. Tests are recorded apart and never counted. + Joins, wallets, purchasesIn Reports, under Conversions, beside your goals. People who came through your click and signed up, linked a wallet or bought a package on LinkSpin or InstantAdPay. A sign-up and a wallet count once per click, every package counts on its own with its USD price, all within 30 days of the click. Your own account is left out.

    Each goal gets its own report: by ad campaign (LinkSpin and InstantAdPay), by spin link, by Banner Spin, by destination page and by traffic source (a source you named under Sources, or else the referring site or ad placement). Press CSV for every conversion with its time in Central time, goal, value, match method, campaign, spin link, page, source, country and device. The counting rules: each goal counts once per click, only within 30 days of a real click, and only for clicks on your own ads, links and Banner Spins. Your own clicks on any of them (made while signed in, or from a browser you sign in from) are kept as tests: the note at the top of "How sure is each count" says how many.

    @@ -258,7 +260,8 @@
    Will the tags slow down or break my page?
    No. Both load in the background, never stop your page from showing and do nothing visible. If LinkSpin cannot be reached, your page works exactly as before.
    Do I need a separate goal for each link or ad?
    No. One goal covers every ad and spin link you own. Each conversion is counted against whichever click sent that visitor.
    I advertise on InstantAdPay too. Do I set it up twice?
    No. Your InstantAdPay goals are these same goals, held on your LinkSpin account under the same email. One landing tag and one goal pixel count clicks from both sites.
    -
    Is any personal data sent?
    No. The click id is random. No name or email from your page is read or sent.
    +
    Is any personal data sent?
    No. The click id is random. No name or email from your page is read or sent. When someone joins InstantAdPay on your click, the two sites match the event to your click server to server, and your reports show counts and values, never who the person is.
    +
    Why does a sign-up I sent not show?
    The click has to reach the join page. Check that your landing tag is on the page and the link is a real link (a button that only runs a script cannot carry it), and that the visitor opened it from your click within the last 30 days. People who joined before this was switched on on 2026-11-07 cannot be matched afterwards.
    diff --git a/public/conversions.html b/public/conversions.html index b3bac83..0c0d6a2 100644 --- a/public/conversions.html +++ b/public/conversions.html @@ -37,6 +37,7 @@

    Set it up in 3 steps

    +
    Goals show here with their cost. Reports shows everything in one list: goals, plus joins, wallets and purchases on LinkSpin and InstantAdPay.
    1. Landing page: paste the landing tag once, before </body>. It keeps the click id on your own site for 30 days.
    2. diff --git a/public/index.html b/public/index.html index e671b7e..df2978c 100644 --- a/public/index.html +++ b/public/index.html @@ -117,7 +117,7 @@

      Pages

      -

      Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: list, CSV, webhook.

      +

      Point us at any offer. We read its headline and points, you add one line of angle, and you get a bridge, review or squeeze page on your link domain. Leads are yours: your own list and a CSV download, or paste your autoresponder form.

      bridgereviewsqueezeleads: yours
      diff --git a/public/join.html b/public/join.html index e24e590..50d174f 100644 --- a/public/join.html +++ b/public/join.html @@ -107,6 +107,6 @@ body.squeeze .card{position:sticky;top:16px}
    - + diff --git a/public/privacy.html b/public/privacy.html index 9ec00ab..eccf0af 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -30,7 +30,7 @@

    When someone opens one of your spin links or sees a zone on your site, we record the time, the destination chosen, the country, the device type, the referring site and any click id or tracking parameters in the link, plus a daily-salted hash of the visitor that is not reversible to a person. These records power your reports and are kept for the life of the link.

    Conversion tracking

    When someone clicks an ad on LinkSpin or InstantAdPay, or a spin link whose owner tracks goals, we give that click a random click id and add it to the address they land on (as lsclk). We keep the click with its time, campaign, country, device type and where it was clicked, plus a one-way hash of the network address and browser that we use only to match a conversion within 24 hours. We do not store the IP address itself.

    -

    Advertisers who use our landing tag (t.js) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named ls_clk on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (cv.gif or cv.js) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named ls.clk on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click.

    +

    Advertisers who use our landing tag (t.js) keep that click id on their own website for 30 days, in the browser's local storage and a cookie named ls_clk on their site. When the visitor later reaches the advertiser's thank-you page, the goal pixel (cv.gif or cv.js) tells us the goal was reached for that click id, so the advertiser can see how many of their clicks became, say, subscribers or sales, and what each cost. We also set a cookie named ls.clk on our own domain when an ad is clicked, so the pixel can still match where the advertiser's site has no tag. Nothing personal is read or stored by the tag or the pixel: no names, emails or form contents. A conversion only ever counts for the advertiser who owns the click. The tag also adds the click id to links to LinkSpin and InstantAdPay. If you then join InstantAdPay, it keeps the click id with your account and tells LinkSpin about your sign-up, wallet link and package purchases on that click, so the owner of the click sees counts and values in their reports, never who you are.

    Leads on your pages

    Email addresses entered on a page you publish belong to you and are shown only to you. We store them so you can download them or forward them to your own autoresponder. Visitors are told on the page who is collecting their email.

    What we do not collect

    diff --git a/public/reports.html b/public/reports.html index 3aae5be..33ac470 100644 --- a/public/reports.html +++ b/public/reports.html @@ -42,7 +42,7 @@

    Top links

    LinkUniqueClicksConv.

    Your best hours

    0006121823
    -

    Conversions

    Joins, wallets and purchases matched to a click on one of your links, plus anything a partner reported by postback. Your own goals (subscribers, sales) and cost per goal are on Conversions.
    +

    Conversions

    Everything your clicks led to, each event once: your goals, plus joins, wallets and package purchases on LinkSpin and InstantAdPay, and anything a partner reported by postback. People count when they arrive on a click of yours, through your landing tag or a spin link pointed straight at either site, within 30 days of the click. Your own account and own clicks are left out. Set up goals and see cost per goal on Conversions.
    @@ -91,6 +91,6 @@ - + diff --git a/public/t.js b/public/t.js index 210d2a8..a6c2597 100644 --- a/public/t.js +++ b/public/t.js @@ -2,7 +2,8 @@ * * It reads the click id LinkSpin or InstantAdPay put on the link (lsclk, lsid or clickid in the address), keeps it on YOUR * site for 30 days (localStorage + a first-party cookie, both named ls_clk), copies it into hidden form fields named lsclk, - * lsid or clickid, and adds it to links that stay on your site. Nothing personal is read or stored. + * lsid or clickid, and adds it to links that stay on your site. Links to InstantAdPay and LinkSpin carry it too, also inside a + * redirect link of your own, so a sign-up or purchase there is counted on your click. Nothing personal is read or stored. * It never throws and never blocks your page: every step is wrapped, and it only runs after the page has its scripts. */ (function () { @@ -65,7 +66,41 @@ u.searchParams.set('lsclk', id); a.href = u.toString(); } catch (e) {} } - function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a) decorate(a); } catch (er) {} } + // links to the network (2026-11-07): a bridge page's button carries the click to InstantAdPay or LinkSpin, which report sign-ups + // and purchases against it. Also inside a redirect link of the member's own (go.example.com/go?u=https%3A%2F%2Finstantadpay.com...): + // only that one parameter is rewritten, every other one keeps its exact encoding. Spin and Banner Spin links are left alone, they + // make their own click. Only LinkSpin's own id shapes travel, never another network's clickid. Done on load, again when the page + // is ready and at the click, so a page script that rewrites its links first or later does not lose it. + var NET = /*ls-net*/["linkspin.app","instantadpay.com","instantadpay.link","ctbgo.com","mylinehq.com"]/*ls-net*/; + var OURS = /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/; + function netUrl(s) { + try { var u = new URL(s); return /^https?:$/.test(u.protocol) && NET.indexOf(u.hostname.toLowerCase().replace(/^www\./, '')) >= 0 && !/^\/(r|c|i)\//.test(u.pathname) ? u : null; } catch (e) { return null; } + } + function carries(u) { for (var i = 0; i < NAMES.length; i++) if (u.searchParams.has(NAMES[i])) return true; return false; } + function addId(s) { var h = s.indexOf('#'), b = h < 0 ? s : s.slice(0, h), t = h < 0 ? '' : s.slice(h); return b + (b.indexOf('?') < 0 ? '?' : /[?&]$/.test(b) ? '' : '&') + 'lsclk=' + encodeURIComponent(id) + t; } + function network(a) { + try { + if (!OURS.test(id) || a.getAttribute('data-ls-skip') != null) return false; + var href = a.href, n = netUrl(href); + if (n) { if (!carries(n)) a.href = addId(href); return true; } + var u = new URL(href); if (!/^https?:$/.test(u.protocol) || !u.search) return false; + var parts = u.search.slice(1).split('&'), found = false, changed = false; + for (var i = 0; i < parts.length; i++) { + var eq = parts[i].indexOf('='); if (eq < 1) continue; + var v; try { v = decodeURIComponent(parts[i].slice(eq + 1).replace(/\+/g, ' ')); } catch (e) { continue; } + var inner = /^https?:/i.test(v) ? netUrl(v) : null; if (!inner) continue; + found = true; if (carries(inner)) continue; + parts[i] = parts[i].slice(0, eq + 1) + encodeURIComponent(addId(v)); changed = true; + } + if (changed) a.href = href.slice(0, href.indexOf('?') + 1) + parts.join('&') + (u.hash || ''); + return found; + } catch (e) { return false; } + } + function sweep() { try { var l = document.querySelectorAll('a[href]'); for (var i = 0; i < l.length; i++) network(l[i]); } catch (e) {} } + sweep(); + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', sweep); + W.addEventListener('load', sweep); + function onClick(e) { try { var a = e.target && e.target.closest ? e.target.closest('a[href]') : null; if (a && !network(a)) decorate(a); } catch (er) {} } document.addEventListener('click', onClick, true); document.addEventListener('auxclick', onClick, true); } catch (e) { /* never break the member's page */ } diff --git a/qa/netconv.test.mjs b/qa/netconv.test.mjs new file mode 100644 index 0000000..d82ed8d --- /dev/null +++ b/qa/netconv.test.mjs @@ -0,0 +1,210 @@ +// Conversion linkage, LinkSpin half (2026-11-07, reporting only). Throwaway data, no production data, nothing leaves the machine. +// 1) unit: netconv.js + convtrack.js + rotator.js on a temp dir: sign-up, wallet, purchases counted once with values; duplicate +// delivery; own account and own browser kept as tests; 30-day window by event time; first account owns the click; an event +// after the hit aged out of the rotator; InstantAdPay ad clicks; goals and events in one list without counting anything twice; +// per-link counts; postbacks once, never for a test. +// 2) two processes on one data dir (a deploy's overlap): the same events raced from both, each counted once, none lost. +// 3) browser (Playwright, if present): the landing tag on another origin decorates links to the network, directly and inside a +// redirect link (Orlando's go?c=...&u=... shape), keeps existing params, leaves other links alone, survives a page script +// that rewrites the link, and a stored id still decorates on a later page. Spin links are left alone. +// node qa/netconv.test.mjs Env: PORT (default 8983), PW +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import { spawn } from 'node:child_process'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); +const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); +const PORT = Number(process.env.PORT || 8983); +const DAY = 86400000; +let failed = 0, passed = 0; const out = []; +const check = (ok, what, detail) => { out.push((ok ? 'PASS ' : 'FAIL ') + what + (!ok && detail !== undefined ? ' :: ' + (typeof detail === 'string' ? detail : JSON.stringify(detail)) : '')); if (ok) passed++; else failed++; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const rq = (ip, ua) => ({ url: '/r/x', headers: { 'user-agent': ua || 'Mozilla/5.0 UnitUA', 'x-forwarded-for': ip }, socket: {} }); + +// ---------- 1) unit ---------- +const UD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-unit-')); +const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js')); +M.init({ dataDir: UD }); +const fired = []; +const P = { fire: async (o, ev, ctx) => { fired.push({ o, ev, ctx }); return []; } }; +const initAll = () => { R.init({ dataDir: UD, ownHosts: () => ['linkspin.app'], wantsClickId: o => C.goalsOf(o).length > 0, isNetworkHost: h => ['instantadpay.com'].includes(h), goalRows: () => C.goalRows() }); C.init({ dataDir: UD, rotator: R, noTimers: true }); N.init({ dataDir: UD, convtrack: C, rotator: R, postbacks: P, marks: M, noTimers: true }); }; +initAll(); +const OWNER = 'orlando@u.test'; +const rot = (await R.create(OWNER, { name: 'Bridge spin' })).rotation; +await R.addDest(OWNER, rot.id, { url: 'https://instantadpay.com/join/opgnetwerk', weight: 1 }); +const hit = async ip => { const r = await R.resolve(rot.code, rq(ip)); return { id: r.lsid, url: r.url }; }; + +const a = await hit('198.51.100.1'); +check(new URL(a.url).searchParams.get('lsclk') === a.id, 'a spin link straight at InstantAdPay carries lsclk with no goal set up', a.url); +const ev = (k, ev_, click, email, extra) => Object.assign({ k, ev: ev_, click, email, ts: Date.now() }, extra || {}); +let r = await N.record(ev('join:a', 'join', a.id, 'lead1@u.test')); +check(r.result === 'counted', 'sign-up on a spin click counted', r); +check((await N.record(ev('join:a', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'the same sign-up delivered twice counts once'); +check((await N.record(ev('join:other-key', 'join', a.id, 'lead1@u.test'))).result === 'dup', 'a second sign-up on one click counts once'); +check((await N.record(ev('wallet:a', 'wallet', a.id, 'lead1@u.test'))).result === 'counted', 'wallet link counted'); +check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'counted', 'first purchase counted'); +check((await N.record(ev('purchase:0xa:1', 'purchase', a.id, 'lead1@u.test', { value: 5, tx: '0xa' }))).result === 'dup', 'the same purchase delivered twice counts once'); +check((await N.record(ev('purchase:0xb:1', 'purchase', a.id, 'lead1@u.test', { value: 20, tx: '0xb' }))).result === 'counted', 'a second package on the same click counts on its own'); +let u = N.unified(OWNER, 30); +const row = (U, k) => (U.rows.find(x => x.k === k) || { n: 0, value: 0 }); +check(row(u, 'join').n === 1 && row(u, 'wallet').n === 1 && row(u, 'purchase').n === 2 && row(u, 'purchase').value === 25, 'Reports: 1 join, 1 wallet, 2 purchases worth $25.00', u.rows); +check(u.buyers === 1, 'two packages by one click are one buyer', u.buyers); +const link = await R.get(OWNER, rot.id); +check(link.conversions === 4, 'the link shows 4 conversions', link.conversions); +const lst = await R.stats(OWNER, rot.id); +check(lst.conversions.some(x => /^purchase/.test(x.k) && x.n === 2), 'the link stats list both purchases', lst.conversions); +const sum = await R.summary(OWNER, 30); +check(sum.top[0].conv === 4, 'Reports top links: Conv. 4', sum.top[0]); +await N.syncMirror(); +check(N.unified(OWNER, 30).rows.find(x => x.k === 'purchase').n === 2 && (await R.get(OWNER, rot.id)).conversions === 4, 'replaying the ledger into the rotator adds nothing'); +check(fired.filter(f => f.ev === 'join').length === 1 && fired.filter(f => f.ev === 'purchase').length === 2, 'postbacks fire once per counted event', fired.map(f => f.ev)); +check(fired.find(f => f.ev === 'purchase').ctx.payout === 5 && fired.find(f => f.ev === 'purchase').ctx.txid === '0xa', 'the purchase postback carries the value and the tx'); +// a LinkSpin site join on the same click stays one join +await R.convert(a.id, 'join', {}); +check(N.unified(OWNER, 30).rows.find(x => x.k === 'join').n === 1, 'a LinkSpin join on the same click does not add a second join'); + +// own account, own browser +const b = await hit('198.51.100.2'); fired.length = 0; +r = await N.record(ev('join:own', 'join', b.id, 'Orlando@U.test')); +check(r.result === 'self', "the click owner's own account is not counted", r); +r = await N.record(ev('purchase:0xself:1', 'purchase', b.id, 'orlando@u.test', { value: 100 })); +check(r.result === 'self' && fired.length === 0, 'its purchases are not counted and fire no postback', r); +const c1 = await hit('198.51.100.3'); const skO = C.softKey(rq('192.0.2.7', 'OwnerUA')); C.noteOwner(OWNER, skO); +check((await N.record(ev('join:ownsk', 'join', c1.id, 'stranger1@u.test', { sk: skO }))).result === 'self', "a sign-up from a browser the owner signs in from is a test"); +check((await N.record(ev('purchase:0xownsk:1', 'purchase', c1.id, 'stranger1@u.test', { value: 9 }))).result === 'self', 'and stays one on that click'); +const c2 = await hit('198.51.100.4'); C.markSelfClick(c2.id, OWNER, rq('1.1.1.1'), OWNER); +check((await N.record(ev('join:ownclick', 'join', c2.id, 'stranger2@u.test'))).result === 'self', "the owner's own click is a test"); +check(row(N.unified(OWNER, 30), 'purchase').value === 25, 'none of that moved the totals'); + +// window, unknown clicks, first account +const d2 = await hit('198.51.100.6'); const hd2 = R.hitById(d2.id).hit; hd2.ts = Date.now() - 31 * DAY; +check((await N.record(ev('join:late', 'join', d2.id, 'late2@u.test'))).result === 'expired', 'an event more than 30 days after the click does not count'); +const d3 = await hit('198.51.100.7'); R.hitById(d3.id).hit.ts = Date.now() - 31 * DAY; +check((await N.record(ev('join:latedelivery', 'join', d3.id, 'late3@u.test', { ts: Date.now() - 2 * DAY }))).result === 'counted', 'the window runs to the event, so a delayed delivery still counts'); +check((await N.record(ev('join:nosuch', 'join', 'abcdef0123', 'x@u.test'))).result === 'nomatch', 'an unknown click is refused'); +check((await N.record(ev('join:bad', 'nonsense', a.id, 'x@u.test'))).result === 'bad' && (await N.record({ k: 'x' })).result === 'bad', 'bad events are refused'); +const e1 = await hit('198.51.100.8'); +await N.record(ev('join:first', 'join', e1.id, 'first@u.test')); +check((await N.record(ev('purchase:0xsecond:1', 'purchase', e1.id, 'second@u.test', { value: 5 }))).result === 'other', 'a click belongs to the first account on it'); + +// the hit ages out of the rotator: later events still count on the link +const f = await hit('198.51.100.9'); +await N.record(ev('join:aged', 'join', f.id, 'aged@u.test')); +{ const file = path.join(UD, 'rotator.json'); const db = JSON.parse(fs.readFileSync(file, 'utf8')); db.hits = db.hits.filter(h => h.id !== f.id); fs.writeFileSync(file, JSON.stringify(db)); initAll(); } +check(!R.hitById(f.id), 'the hit is gone from the rotator'); +const before = (await R.get(OWNER, rot.id)).conversions; +check((await N.record(ev('purchase:0xaged:1', 'purchase', f.id, 'aged@u.test', { value: 50 }))).result === 'counted', 'a purchase after the hit aged out still counts'); +check((await R.get(OWNER, rot.id)).conversions === before + 1, 'and lands on the link'); + +// InstantAdPay ad click: no rotator, in the ledger, on the campaign +C.importClicks([{ id: 'i0123456789a', camp: 7, cname: 'My ad', owner: 'adv@u.test', ts: Date.now(), sk: '', type: 'banner' }]); +check((await N.record(ev('join:ad', 'join', 'i0123456789a', 'adlead@u.test'))).result === 'counted', 'an InstantAdPay ad click counts'); +await N.record(ev('purchase:0xad:1', 'purchase', 'i0123456789a', 'adlead@u.test', { value: 20 })); +const pa = N.partner('adv@u.test', 30); +check(pa.byCampaign[7] && pa.byCampaign[7].join === 1 && pa.byCampaign[7].purchase === 1 && pa.byCampaign[7].value === 20, 'the campaign shows its join and purchase', pa.byCampaign); +check(row(N.unified('adv@u.test', 30), 'purchase').value === 20, 'ad events are in the one list (not in the rotator)'); +check((await N.record(ev('join:adown', 'join', 'i0123456789a', 'adv@u.test'))).result !== 'counted', "the ad owner's own account is not counted"); + +// goals and events in one list; a goal is not an event and nothing is listed twice +const g = C.createGoal(OWNER, { name: 'subscriber', value: '2' }); const px = g.goal.px; +const gh = await hit('198.51.100.10'); +const fake = { headers: { 'user-agent': 'GoalUA', 'x-forwarded-for': '198.51.100.11' }, socket: {} }; +check(C.record({ px, c: gh.id, m: 'url' }, fake, {}).result === 'counted', 'a goal converts on a spin click'); +await N.record(ev('join:gh', 'join', gh.id, 'goalman@u.test')); +const U2 = N.unified(OWNER, 30); +check(row(U2, 'goal:subscriber').n === 1 && row(U2, 'goal:subscriber').value === 2, 'goals are in the one list with their value', U2.rows); +const before2 = (await R.get(OWNER, rot.id)); +check(before2.conversions >= 2 && before2.convBy['goal: subscriber'] === 1, 'per-link counts include goals', before2.convBy); +const s2 = await R.summary(OWNER, 30); +check(s2.conversions.filter(x => x.k === 'goal: subscriber').length === 1, 'and the top-links count sees it once'); + +// ---------- 2) two processes, one data dir ---------- +{ + const worker = path.join(UD, 'worker.cjs'); const DD = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-race-')); + fs.writeFileSync(worker, ` + const path = require('path'); const site = ${JSON.stringify(site)}; const DD = ${JSON.stringify(DD)}; + const C = require(path.join(site, 'convtrack.js')), R = require(path.join(site, 'rotator.js')), N = require(path.join(site, 'netconv.js')), M = require(path.join(site, 'marks.js')); + M.init({ dataDir: DD }); R.init({ dataDir: DD, ownHosts: () => [] }); C.init({ dataDir: DD, rotator: R, noTimers: true }); N.init({ dataDir: DD, convtrack: C, rotator: R, marks: M, noTimers: true }); + (async () => { const until = Number(process.argv[2]); while (Date.now() < until) await new Promise(r => setTimeout(r, 5)); + const out = []; for (let i = 0; i < 40; i++) out.push((await N.record({ k: 'purchase:0xrace:' + i, ev: 'purchase', click: 'abcdef0123', email: 'race@u.test', value: 1, ts: Date.now() })).result); + out.push((await N.record({ k: 'join:race', ev: 'join', click: 'abcdef0123', email: 'race@u.test', ts: Date.now() })).result); + process.stdout.write(JSON.stringify(out)); })().catch(e => { process.stdout.write(JSON.stringify({ error: e.message })); }); `); + const seed = { v: 1, rotations: [{ id: 1, owner: 'race-owner@u.test', name: 'r', code: 'raceee', fallback: '', destinations: [], created: Date.now(), paused: false, nextDest: 1 }], hits: [{ id: 'abcdef0123', r: 1, d: 0, ts: Date.now(), v: 'x', c: '', s: 'direct', dv: 'desktop', bot: 0 }], conv: [] }; + fs.writeFileSync(path.join(DD, 'rotator.json'), JSON.stringify(seed)); + const until = Date.now() + 1200; + const run = () => new Promise(res => { const p = spawn(process.execPath, [worker, String(until)], { stdio: ['ignore', 'pipe', 'inherit'] }); let o = ''; p.stdout.on('data', c => o += c); p.on('close', () => { try { res(JSON.parse(o)); } catch (e) { res({ error: o }); } }); }); + const [x, y] = await Promise.all([run(), run()]); + const all = [].concat(x, y); + check(Array.isArray(x) && Array.isArray(y), 'both copies ran', { x, y }); + check(all.filter(v => v === 'counted').length === 41, '41 events raced from two copies: exactly 41 counted', all.filter(v => v === 'counted').length); + const rows = fs.readFileSync(path.join(DD, 'netconv.jsonl'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); + check(rows.length === 41 && new Set(rows.map(r => r.k)).size === 41, 'the ledger holds each event once, none lost', rows.length); +} + +// ---------- 3) the landing tag in a browser, on another origin ---------- +const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; +if (fs.existsSync(PW)) { + const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-b-')); fs.mkdirSync(path.join(DATA, 'uploads')); + const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: 'localtest', SITE_HOST: '127.0.0.1:' + PORT }); + for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY', 'LS_SYNC_SECRET']) delete env[k]; + const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: 'ignore' }); + try { + for (let i = 0; i < 40; i++) { try { const r = await fetch('http://127.0.0.1:' + PORT + '/t.js', { signal: AbortSignal.timeout(2000) }); if (r.ok) break; } catch (e) {} await sleep(500); } + const tag = await (await fetch('http://127.0.0.1:' + PORT + '/t.js')).text(); + check(/"instantadpay\.com"/.test(tag) && !tag.includes('/*ls-net*/'), '/t.js is served with the network host list filled in'); + const pw = require(PW); const br = await pw.chromium.launch(); const ctx = await br.newContext(); const page = await ctx.newPage(); + const errors = []; page.on('pageerror', e => errors.push(e.message)); + const BTN = 'https://go.opgnetwerk.test/go?c=bridge-a&u=https%3A%2F%2Finstantadpay.com%2Fjoin%2Fopgnetwerk&keep=a%20b'; + const html = `bridge + IAP through a redirect + LinkSpin through a redirect + direct + share domain + already has one + spin link + other site + redirect to another site + + anchornext + + `; + const later = 'nextx'; + const noid = html; + const bridge = http.createServer((q, s) => { s.writeHead(200, { 'Content-Type': 'text/html' }); s.end(new URL(q.url, 'http://x').pathname === '/next' ? later : noid); }).listen(PORT + 1); + const BR = 'http://localhost:' + (PORT + 1); + const ID = 'abc123def0'; + await page.goto(BR + '/lp?src=banner&lsclk=' + ID); await sleep(700); + const hrefOf = sel => page.$eval(sel, a => a.href); + const wrap = await hrefOf('#wrap'); const wu = new URL(wrap); + check(new URL(wu.searchParams.get('u')).searchParams.get('lsclk') === ID, "Orlando's redirect link: the click id is inside the u address", wrap); + check(new URL(wu.searchParams.get('u')).pathname === '/join/opgnetwerk' && wu.searchParams.get('c') === 'x-banner', 'the redirect link keeps its address and its other params', wrap); + check(new URL(new URL(await hrefOf('#wrapls')).searchParams.get('u')).searchParams.get('lsclk') === ID, 'the LinkSpin button through the redirect too'); + check(await hrefOf('#direct') === 'https://instantadpay.com/join/opgnetwerk?v=play&lsclk=' + ID + '#top', 'a direct link: existing param and #hash stay', await hrefOf('#direct')); + check(new URL(await hrefOf('#share')).searchParams.get('lsclk') === ID, 'share domains are network hosts (www stripped)'); + check(await hrefOf('#has') === 'https://instantadpay.com/join/x?lsclk=abcdef0123', 'a link already carrying a click id is left alone'); + check(await hrefOf("#spin").then(h => h.split("127.0.0.1")[1]) === "/r/abc123", 'spin links are left alone, they make their own click'); + check(await hrefOf('#other') === 'https://bix.example/?a=1' && !/lsclk/.test(await hrefOf('#wrapother')), 'other sites are left alone, redirected or not'); + check(await hrefOf('#skip') === 'https://instantadpay.com/join/y', 'data-ls-skip is respected'); + await page.click('#late-target'); await sleep(600); + check(new URL(page.url()).searchParams.get('lsclk') === ID, 'same-site links still carry it, as before'); + await page.goto(BR + '/next'); await sleep(600); + check(new URL(await hrefOf('#direct')).searchParams.get('lsclk') === ID, 'a later page with no id in the address: the stored id still decorates'); + // a foreign clickid is not one of ours: stored as before, never carried to the network + const c2x = await br.newContext(); const p2 = await c2x.newPage(); + await p2.goto(BR + '/lp?clickid=foreign12345678'); await sleep(600); + check(await p2.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', "another network's clickid never travels to the network"); + // no id at all: the page is untouched + const c3x = await br.newContext(); const p3 = await c3x.newPage(); + await p3.goto(BR + '/lp'); await sleep(500); + check(await p3.$eval('#direct', a => a.href) === 'https://instantadpay.com/join/opgnetwerk?v=play#top', 'no click id: links untouched'); + check(errors.length === 0, 'no page errors', errors); + await br.close(); bridge.close(); + } finally { srv.kill(); } +} else out.push('SKIP browser part (no Playwright at ' + PW + ')'); + +console.log(out.join('\n')); +console.log('\n' + passed + ' passed, ' + failed + ' failed'); +process.exit(failed ? 1 : 0); diff --git a/qa/run.sh b/qa/run.sh index 45c255a..2ce9e8a 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -7,6 +7,7 @@ # bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter # bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression # bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay) +# bash qa/run.sh netconv # conversion linkage: InstantAdPay's joins, wallets, purchases counted once, own account left out, window, aged hits, two copies racing, one Reports list, the landing tag on network links # bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits # bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed # bash qa/run.sh nas # Network Ad Space billing: stop snapshot, active-only reconcile, restart without phantom delivery, the 1/N network + partner-zone rate (stubbed NAS, throwaway data) @@ -67,6 +68,7 @@ elif [ "$MODE" = "member" ]; then start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 node qa/tank-hold.test.mjs || status=1 node qa/profile-policy.test.cjs || status=1 + node qa/netconv.test.mjs || status=1 elif [ "$MODE" = "policy" ]; then node qa/profile-policy.test.cjs || status=1 elif [ "$MODE" = "sponsorfollow" ]; then @@ -83,6 +85,8 @@ elif [ "$MODE" = "loginqueue" ]; then node qa/loginqueue.e2e.mjs || status=1 elif [ "$MODE" = "convpixel" ]; then node qa/convpixel.test.mjs || status=1 +elif [ "$MODE" = "netconv" ]; then + node qa/netconv.test.mjs || status=1 elif [ "$MODE" = "lsid" ]; then node qa/lsid-pixel.test.mjs || status=1 elif [ "$MODE" = "kb" ]; then diff --git a/rotator.js b/rotator.js index fe231ef..f2bc96c 100644 --- a/rotator.js +++ b/rotator.js @@ -13,6 +13,7 @@ const crypto = require('crypto'); let DATA_DIR = null, geo = null, OWN_HOSTS = () => [], SOURCES = null; // SOURCES = sources.js (traffic sources, 2026-10-12) let WANTS_CLICK_ID = () => false; // conversion pixel (2026-10-23): owner -> true when they have a goal, so their destinations get ?lsclk= +let IS_NETWORK = () => false, GOAL_ROWS = () => []; // 2026-11-07: a page on a network host always gets the click id (InstantAdPay reports joins, wallets, purchases against it); goal conversions as rotator-shaped rows for per-link counts const DAY = 86400000; const J = { db: null, @@ -20,7 +21,8 @@ const J = { load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, rotations: [], hits: [], conv: [] }; } if (!this.db.conv) this.db.conv = []; }, save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } }; -function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; J.load(); } +function init(opts) { DATA_DIR = opts.dataDir; geo = opts.geo || null; OWN_HOSTS = opts.ownHosts || (() => []); SOURCES = opts.sources || null; if (opts.wantsClickId) WANTS_CLICK_ID = opts.wantsClickId; if (opts.isNetworkHost) IS_NETWORK = opts.isNetworkHost; if (opts.goalRows) GOAL_ROWS = opts.goalRows; J.load(); } +const convOf = (rid) => J.db.conv.filter(c => c.r === rid).concat(GOAL_ROWS().filter(c => c.r === rid)); // a link's conversions: site and network events, and goals const norm = e => String(e || '').trim().toLowerCase(); const newCode = () => { const a = 'abcdefghjkmnpqrstuvwxyz23456789'; let s = ''; for (let i = 0; i < 6; i++) s += a[crypto.randomInt(a.length)]; return s; }; const BOT = /bot|crawl|spider|slurp|facebookexternalhit|preview|telegrambot|whatsapp|curl|wget|python-requests|headless/i; @@ -83,7 +85,7 @@ function pub(r) { const since7 = Date.now() - 7 * DAY; const perDest = {}; for (const h of hits) { const d = perDest[h.d] = perDest[h.d] || { hits: 0, hits7: 0, uniques: new Set() }; d.hits++; if (h.ts >= since7) d.hits7++; d.uniques.add(h.v); } - const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1; + const conv = convOf(r.id); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1; const since30 = Date.now() - 30 * DAY; return { id: r.id, code: r.code, name: r.name, owner: r.owner, created: r.created, fallback: r.fallback || '', paused: !!r.paused, conversions: conv.length, convBy, hours: r.hours || null, tz: r.tz || 'visitor', offHours30: hits.filter(h => h.oh && h.ts >= since30 && !h.bot).length, fallbackHealth: r.fallbackHealth || null, sourceId: r.sourceId || '', @@ -191,19 +193,27 @@ async function resolve(code, req) { try { const t = new URL(out); if (OWN_HOSTS().includes(t.hostname.toLowerCase()) && !t.searchParams.has('lsid')) { t.searchParams.set('lsid', id); out = t.toString(); } } catch (e) {} // conversion pixel (2026-10-23): when the owner tracks goals, or the click came from an ad, the destination also gets // ?lsclk= for the landing tag (/t.js) to keep. Existing params stay; an lsclk already there is left alone. - if (!bot && (ac || WANTS_CLICK_ID(r.owner))) { try { const t = new URL(out); if (!t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} } + if (!bot) { try { const t = new URL(out); if ((ac || WANTS_CLICK_ID(r.owner) || IS_NETWORK(t.hostname)) && !t.searchParams.has('lsclk')) { t.searchParams.set('lsclk', id); out = t.toString(); } } catch (e) {} } } return { url: out, dest: d, rotation: r, lsid: id }; } // conversions: record an event against the click that brought the person (dedupe per click + event) // Banner Spin clicks (bannerspin.js, 2026-10-18) carry their own click ids ('k' + 11 hex); an id we do not know is handed to it let EXT_CONVERT = null; function setExternalConvert(fn) { EXT_CONVERT = fn; } +// facts.key (netconv.js, 2026-11-07): every purchase InstantAdPay reports counts by its own key, not once per click; facts.bound = +// the click as first recorded, so an event still lands on its link after the hit aged out of the array async function convert(lsid, ev, facts) { - const h = J.db.hits.find(x => x.id === String(lsid)); if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null; + const f = facts || {}; const key = f.key ? String(f.key) : ''; const id = String(lsid); + let h = J.db.hits.find(x => x.id === id); + if (!h && f.bound && f.bound.r) h = { id, r: f.bound.r, d: f.bound.d, sr: f.bound.sr }; + if (!h) return EXT_CONVERT ? EXT_CONVERT(lsid, ev, facts) : null; const r = J.db.rotations.find(x => x.id === h.r); if (!r) return null; - if (!J.db.conv.some(c => c.lsid === h.id && c.ev === ev)) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Date.now(), value: Number(facts && facts.payout || 0) || 0, label: facts && facts.label ? String(facts.label).slice(0, 40) : undefined, sr: h.sr || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); } + const dup = J.db.conv.some(c => key && ev === 'purchase' ? c.key === key : (c.lsid === h.id && c.ev === ev && (ev !== 'purchase' || !c.key))); + if (!dup) { J.db.conv.push({ lsid: h.id, r: r.id, d: h.d, ev, ts: Number(f.ts) || Date.now(), value: Number(f.payout || 0) || 0, label: f.label ? String(f.label).slice(0, 40) : undefined, sr: h.sr || undefined, key: key || undefined }); if (J.db.conv.length > 100000) J.db.conv = J.db.conv.slice(-80000); J.save(); } return { owner: r.owner, code: r.code, rotationId: r.id, q: h.q || {}, s: h.s, c: h.c, dv: h.dv, sourceId: h.sr || '' }; } +// a member's conversions as rows (Reports' one Conversions panel, netconv.unified): goals are added there, never here +function convRows(owner, since) { const ids = new Set(J.db.rotations.filter(r => r.owner === norm(owner)).map(r => r.id)); return J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); } // clicks, uniques and conversions per traffic source over `days` (non-bot), keyed by source id; for the Sources screen and Reports async function sourceCounts(owner, days) { const mine = J.db.rotations.filter(r => r.owner === norm(owner)); const ids = new Set(mine.map(r => r.id)); @@ -211,7 +221,7 @@ async function sourceCounts(owner, days) { const at = sid => (out[sid] = out[sid] || { hits: 0, unique: new Set(), conv: 0, links: 0 }); for (const r of mine) if (r.sourceId) at(r.sourceId).links++; for (const h of J.db.hits) if (h.sr && ids.has(h.r) && h.ts >= since && !h.bot) { const o = at(h.sr); o.hits++; o.unique.add(h.v); } - for (const c of J.db.conv) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++; + for (const c of J.db.conv.concat(GOAL_ROWS())) if (c.sr && ids.has(c.r) && c.ts >= since) at(c.sr).conv++; for (const k in out) out[k].unique = out[k].unique.size; return out; } @@ -229,7 +239,7 @@ async function summary(owner, days) { const dayMap = {}; for (const h of all) { const k = ctDay(h.ts); const d = dayMap[k] = dayMap[k] || { day: k, u: new Set(), b: 0 }; if (h.bot) d.b++; else d.u.add(h.v); } const dlist = Object.values(dayMap).sort((a, b) => a.day < b.day ? -1 : 1).map(d => ({ day: d.day, u: d.u.size, b: d.b })); const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++; - const conv = J.db.conv.filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1; + const conv = J.db.conv.concat(GOAL_ROWS()).filter(c => ids.has(c.r) && c.ts >= since); const convBy = {}; for (const c of conv) convBy[c.ev] = (convBy[c.ev] || 0) + 1; const top = mine.map(r => { const hs = hits.filter(h => h.r === r.id); return { id: r.id, name: r.name, code: r.code, hits: hs.length, unique: new Set(hs.map(h => h.v)).size, conv: conv.filter(c => c.r === r.id).length }; }).sort((a, b) => b.unique - a.unique).slice(0, 10); // traffic sources (2026-10-12): per source, and per placement = the value the network's zone / placement / site macro carried const meta = SOURCES && SOURCES.meta ? SOURCES.meta(owner) : {}; @@ -249,7 +259,7 @@ async function stats(owner, id) { const days = {}; for (const h of hits) { const k = new Date(h.ts).toISOString().slice(0, 10); days[k] = (days[k] || 0) + 1; } const hours = new Array(24).fill(0); for (const h of hits) hours[new Date(h.ts).getUTCHours()]++; const subs = {}; for (const h of hits) if (h.q) for (const [k, v] of Object.entries(h.q)) { const key = k + '=' + v; subs[key] = (subs[key] || 0) + 1; } - const conv = J.db.conv.filter(c => c.r === r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } + const conv = convOf(r.id); const convBy = {}; for (const c of conv) { const k = c.ev + (c.label ? ' · ' + c.label : ''); convBy[k] = (convBy[k] || 0) + 1; } return { rotation: pub(r), country: by('c'), source: by('s'), device: by('dv'), days: Object.entries(days).sort().slice(-30).map(([k, n]) => ({ day: k, n })), hours, bots: J.db.hits.filter(h => h.r === r.id && h.bot).length, best: bestHours(r), offHours: hits.filter(h => h.oh).length, subs: Object.entries(subs).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([k, n]) => ({ k, n })), conversions: Object.entries(convBy).sort((a, b) => b[1] - a[1]).map(([k, n]) => ({ k, n })) }; } @@ -322,5 +332,5 @@ function adminAll() { destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })), hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; }); } -module.exports = { init, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24, +module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24, pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource }; diff --git a/server.js b/server.js index 6d88d28..a18ff22 100644 --- a/server.js +++ b/server.js @@ -65,6 +65,7 @@ const rotator = require('./rotator'); const health = require('./health'); // destination health checks + auto-pause (2026-10-10) 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 netconv = require('./netconv'); // network conversions: InstantAdPay's joins, wallets, purchases counted for the click's owner, reporting only (2026-11-07) 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'); const refuel = require('./refuel'); @@ -706,7 +707,7 @@ async function boot() { setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); - rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0 }); + rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, isNetworkHost: h => networkHosts().includes(String(h || '').toLowerCase().replace(/^www\./, '')), goalRows: () => convtrack.goalRows() }); convtrack.init({ dataDir: DATA_DIR, rotator, bannerspin, campaignOf: id => ads.campaignById(id) }); auth.onSeen((email, req) => convtrack.noteSession(email, req)); // own-click tests (2026-10-26): the soft keys a member signs in from // destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices) @@ -715,8 +716,9 @@ async function boot() { setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000); setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources }); - bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: owner => convtrack.goalsOf(owner).length > 0, withClickId: convtrack.withClickId }); - rotator.setExternalConvert((lsid, ev, facts) => bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks + bannerspin.init({ dataDir: DATA_DIR, uploadsDir: UPLOADS_DIR, rotator, geo, sources, ownHosts, adminEmail: ADMIN_EMAIL, facts: bannerFacts, wantsClickId: (owner, url) => { if (convtrack.goalsOf(owner).length > 0) return true; try { return networkHosts().includes(new URL(url).hostname.toLowerCase().replace(/^www\./, '')); } catch (e) { return false; } }, withClickId: convtrack.withClickId }); + rotator.setExternalConvert((lsid, ev, facts) => /^[ai]/.test(String(lsid)) ? netconv.fromLinkSpin(lsid, ev, facts) : bannerspin.convert(lsid, ev, facts)); // Banner Spin click ids convert like spin-link clicks; ad clicks through the ledger + netconv.init({ dataDir: DATA_DIR, convtrack, rotator, bannerspin, postbacks, marks }); sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } }); zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST }); pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { 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 ''; } } }); @@ -881,6 +883,9 @@ function readRaw(req, maxBytes) { // on the member's thank-you page) can still send it where the browser allows third-party cookies; 30 days like the window. // the image pixel cannot read the thank-you page's address, but a browser that sends the full referrer hands it to us function refClickId(req) { try { const r = new URL(String(req.headers.referer || '')); const v = r.searchParams.get('lsclk') || r.searchParams.get('lsid') || ''; return /^[a-z0-9]{6,24}$/i.test(v) ? v : ''; } catch (e) { return ''; } } +// the sites of the network a click id may travel to (the landing tag's list, 2026-11-07): this site, InstantAdPay, its share domains +const NETWORK_HOSTS = String(process.env.NETWORK_HOSTS || 'instantadpay.com,instantadpay.link,ctbgo.com,mylinehq.com').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); +function networkHosts() { return [...new Set([String(SITE_HOST || '').toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '')].concat(NETWORK_HOSTS))].filter(Boolean); } function clickCookie(id) { return 'ls.clk=' + id + '; Path=/; Max-Age=2592000; ' + (IS_PROD ? 'SameSite=None; Secure' : 'SameSite=Lax'); } // an ad click: record a click id for the campaign and append ?lsclk= to the target (existing params kept, an lsclk // already there left alone). A spin-link target passes it on, so the spin-link click inherits the ad as its source. @@ -1434,7 +1439,7 @@ const server = http.createServer(async (req, res) => { // -- conversion pixel (2026-10-23): /t.js the landing tag, /t.gif its beacon, /cv.gif + /cv.js the goal pixel. Any origin, // never cached, always a 1x1 gif (the member's page never sees an error). X-LS-Result says what happened (tests, debugging). if ((p === '/t.js' || p === '/cv.js') && (req.method === 'GET' || req.method === 'HEAD')) { - try { const body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); } + try { let body = fs.readFileSync(path.join(PUBLIC_DIR, p.slice(1))); if (p === '/t.js') body = String(body).replace(/\/\*ls-net\*\/.*?\/\*ls-net\*\//, JSON.stringify(networkHosts())); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*', 'X-Content-Type-Options': 'nosniff' }); return res.end(req.method === 'HEAD' ? '' : body); } catch (e) { res.writeHead(404); return res.end(); } } if ((p === '/t.gif' || p === '/cv.gif') && req.method === 'GET') { const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length), 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-Robots-Tag': 'noindex' }; @@ -1570,7 +1575,7 @@ const server = http.createServer(async (req, res) => { const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit const set = []; set.push('iap.sponsor=' + tok + cookieTail); // last touch wins - { const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution) + { const lsid = String(u.searchParams.get('lsid') || u.searchParams.get('lsclk') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution); lsclk is what the landing tag carries from a bridge page (2026-11-07) const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup if (ang) set.push('iap.angle=' + angle + cookieTail); if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source @@ -2850,7 +2855,9 @@ const server = http.createServer(async (req, res) => { const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]); // Banner Spins beside spin links (phase 3, 2026-10-20) let bsum = null; try { bsum = await bannerspin.summary(s.email, days); } catch (e) { console.error('bannerspin summary', e.message); } - return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days }), { 'Cache-Control': 'no-store' }); + // one Conversions panel (2026-11-07): site + network events and goals, each once; the tiles follow the same counts + const uni = netconv.unified(s.email, days); + return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, bannerSpins: bsum, days: spins.days, range: days, conversions: uni.rows, totals: Object.assign({}, spins.totals, { joins: uni.joins, wallets: uni.wallets, purchases: uni.buyers, purchaseCount: uni.purchases, goals: uni.goals }) }), { 'Cache-Control': 'no-store' }); } // -- conversion pixel (2026-10-23): goals, per-goal reports, CSV, test. GET and POST (the shell's api() always POSTs). if (p === '/api/my/conversions' && (req.method === 'GET' || req.method === 'POST')) { @@ -2992,9 +2999,11 @@ const server = http.createServer(async (req, res) => { if (p === '/api/partner/conv' && req.method === 'POST') { const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error }); const b = sg.body; const email = String(b.email || '').trim().toLowerCase(); + // InstantAdPay's sign-ups, wallet links and purchases on a LinkSpin click (2026-11-07, reporting only): one answer per event + if (b.op === 'events') { const results = []; for (const ev of (Array.isArray(b.events) ? b.events.slice(0, 200) : [])) { let r = { result: 'bad' }; try { r = await netconv.record(ev); } catch (e) { console.error('netconv', e.message); return json(res, 500, { error: 'not recorded' }); } results.push({ k: String(ev && ev.k || '').slice(0, 120), result: r.result }); } return json(res, 200, { ok: true, results }); } if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return json(res, 400, { error: 'Which member?' }); let r; - if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST }); + if (b.op === 'summary') r = Object.assign(convtrack.partnerSummary(email, b.days), { host: SITE_HOST, network: netconv.partner(email, b.days) }); else if (b.op === 'create') r = convtrack.createGoal(email, { name: b.name, value: b.value }); else if (b.op === 'update') r = convtrack.updateGoal(email, b.px, { name: b.name, value: b.value === null ? 0 : b.value }); // null = clear the default (InstantAdPay sends it for an empty box) else if (b.op === 'remove') r = convtrack.updateGoal(email, b.px, { remove: true });