diff --git a/postbacks.js b/postbacks.js new file mode 100644 index 0000000..7cb103c --- /dev/null +++ b/postbacks.js @@ -0,0 +1,141 @@ +// Postback rails (LinkSpin, 2026-09-29). Outbound: a member's tracker or traffic network is told, server to +// server, when a click on one of their links converts (join, wallet, purchase, or a partner-reported event), +// with the click id that came in on the link. Inbound: a partner reports a conversion against our click id +// with the member's partner key. Every delivery is logged; nothing member-supplied is trusted: +// https/http only, no private or internal hosts (checked by name AND by resolved address), short timeouts, +// small bodies, per-member rate cap, auto-disable after repeated failures, and only the member's own clicks. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const dns = require('dns').promises; +const net = require('net'); + +let DATA_DIR = null, ownHosts = () => [], rotator = null; +const J = { db: null, FILE: () => path.join(DATA_DIR, 'postbacks.json'), + load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { v: 1, items: [], log: [], keys: {}, clicks: {} }; } for (const k of ['items', 'log']) if (!Array.isArray(this.db[k])) this.db[k] = []; for (const k of ['keys', 'clicks']) if (!this.db[k]) this.db[k] = {}; }, + save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} } }; +function init(opts) { DATA_DIR = opts.dataDir; ownHosts = opts.ownHosts || (() => []); rotator = opts.rotator; J.load(); } +const norm = e => String(e || '').trim().toLowerCase(); +const EVENTS = ['join', 'wallet', 'purchase', 'external']; +const MACRO = /\{([a-z0-9_]{1,24})\}/gi; + +function isPrivateIp(ip) { + if (net.isIPv4(ip)) { const p = ip.split('.').map(Number); return p[0] === 10 || p[0] === 127 || p[0] === 0 || (p[0] === 169 && p[1] === 254) || (p[0] === 172 && p[1] >= 16 && p[1] <= 31) || (p[0] === 192 && p[1] === 168) || (p[0] === 100 && p[1] >= 64 && p[1] <= 127); } + if (net.isIPv6(ip)) { const l = ip.toLowerCase(); return l === '::1' || l === '::' || l.startsWith('fc') || l.startsWith('fd') || l.startsWith('fe80') || l.startsWith('::ffff:'); } + return true; +} +function validateUrl(template) { + const t = String(template || '').trim(); + if (!t) return 'Give the postback a URL.'; + if (t.length > 1500) return 'That URL is too long.'; + if (!/^https?:\/\//i.test(t)) return 'The URL must start with http:// or https://.'; + let u; try { u = new URL(t.replace(MACRO, 'x')); } catch (e) { return 'That is not a valid URL.'; } + const h = u.hostname.toLowerCase(); + if (!h.includes('.') || /(^|\.)(localhost|local|internal|lan|home|arpa)$/.test(h)) return 'The URL must point at a public host.'; + if (net.isIP(h) && isPrivateIp(h)) return 'Private network addresses are not allowed.'; + if (ownHosts().map(x => String(x).toLowerCase()).includes(h)) return 'A postback cannot point back at LinkSpin.'; + return null; +} +async function hostIsPublic(hostname) { + if (net.isIP(hostname)) return !isPrivateIp(hostname); + try { const rs = await dns.lookup(hostname, { all: true }); return rs.length > 0 && rs.every(r => !isPrivateIp(r.address)); } catch (e) { return false; } +} +function fill(template, vals) { return String(template).replace(MACRO, (m, k) => { const key = k.toLowerCase(); return encodeURIComponent(vals[key] == null ? '' : String(vals[key]).slice(0, 200)); }); } + +// -- member config +function mine(owner) { return J.db.items.filter(p => p.owner === norm(owner)); } +function pubItem(p) { return { id: p.id, name: p.name, url: p.url, method: p.method, events: p.events, enabled: !!p.enabled, created: p.created, fails: p.fails || 0, lastStatus: p.lastStatus || null, lastAt: p.lastAt || 0, sent: p.sent || 0 }; } +async function list(owner) { return mine(owner).map(pubItem); } +async function create(owner, body) { + if (mine(owner).length >= 20) return { error: 'Up to 20 postbacks per account.' }; + const name = String(body.name || '').trim().slice(0, 60) || 'Postback'; + const bad = validateUrl(body.url); if (bad) return { error: bad }; + const events = (Array.isArray(body.events) ? body.events : String(body.events || '').split(',')).map(x => String(x).trim().toLowerCase()).filter(x => EVENTS.includes(x)); + if (!events.length) return { error: 'Pick at least one event.' }; + const p = { id: crypto.randomBytes(5).toString('hex'), owner: norm(owner), name, url: String(body.url).trim(), method: String(body.method || 'GET').toUpperCase() === 'POST' ? 'POST' : 'GET', events, enabled: true, created: Date.now(), fails: 0, sent: 0 }; + J.db.items.push(p); J.save(); return { ok: true, postback: pubItem(p) }; +} +async function update(owner, id, body) { + const p = J.db.items.find(x => x.id === id && x.owner === norm(owner)); if (!p) return { error: 'No such postback.' }; + if (body.remove) { J.db.items = J.db.items.filter(x => x !== p); J.save(); return { ok: true, removed: true }; } + if (body.name != null) p.name = String(body.name).trim().slice(0, 60) || p.name; + if (body.url != null) { const bad = validateUrl(body.url); if (bad) return { error: bad }; p.url = String(body.url).trim(); p.fails = 0; } + if (body.events != null) { const ev = (Array.isArray(body.events) ? body.events : String(body.events).split(',')).map(x => String(x).trim().toLowerCase()).filter(x => EVENTS.includes(x)); if (ev.length) p.events = ev; } + if (body.method != null) p.method = String(body.method).toUpperCase() === 'POST' ? 'POST' : 'GET'; + if (body.enabled != null) { p.enabled = !!body.enabled; if (p.enabled) p.fails = 0; } + J.save(); return { ok: true, postback: pubItem(p) }; +} +async function logFor(owner, n) { return J.db.log.filter(l => l.owner === norm(owner)).slice(-(n || 50)).reverse(); } + +// -- partner key (inbound) +function partnerKey(owner) { const o = norm(owner); if (!J.db.keys[o]) { J.db.keys[o] = crypto.randomBytes(12).toString('hex'); J.save(); } return J.db.keys[o]; } +function rotateKey(owner) { const o = norm(owner); J.db.keys[o] = crypto.randomBytes(12).toString('hex'); J.save(); return J.db.keys[o]; } +function ownerOfKey(key) { const k = String(key || ''); if (!/^[a-f0-9]{24}$/.test(k)) return null; for (const [o, v] of Object.entries(J.db.keys)) if (v === k) return o; return null; } + +// -- click binding (which click brought this account) +function bindClick(email, lsid) { const e = norm(email); if (!e || !/^[a-z0-9]{6,20}$/i.test(String(lsid || ''))) return; if (J.db.clicks[e]) return; J.db.clicks[e] = { lsid: String(lsid), ts: Date.now() }; J.save(); } +function clickOf(email) { return J.db.clicks[norm(email)] || null; } + +// -- delivery +const rate = {}; // owner -> [timestamps] +function rateOk(owner) { const now = Date.now(); const a = (rate[owner] = (rate[owner] || []).filter(t => now - t < 3600000)); if (a.length >= 300) return false; a.push(now); return true; } +async function deliver(p, url, ctx) { + const t0 = Date.now(); let status = 0, ok = false, note = ''; + try { + const u = new URL(url); if (!(await hostIsPublic(u.hostname))) { note = 'host resolves to a private address'; } + else { + const ctl = new AbortController(); const tm = setTimeout(() => ctl.abort(), 8000); + const r = await fetch(url, { method: p.method, redirect: 'manual', signal: ctl.signal, headers: { 'User-Agent': 'LinkSpin-Postback/1.0' }, body: p.method === 'POST' ? '' : undefined }); + clearTimeout(tm); status = r.status; ok = r.status >= 200 && r.status < 400; try { note = (await r.text()).slice(0, 120); } catch (e) {} + } + } catch (e) { note = String(e && e.message || e).slice(0, 120); } + p.lastStatus = status || note.slice(0, 40); p.lastAt = Date.now(); if (ok) { p.sent = (p.sent || 0) + 1; p.fails = 0; } else { p.fails = (p.fails || 0) + 1; if (p.fails >= 10) p.enabled = false; } + J.db.log.push({ ts: t0, owner: p.owner, pb: p.id, name: p.name, event: ctx.event, lsid: ctx.lsid || '', url: url.slice(0, 300), status, ok, ms: Date.now() - t0, note, test: !!ctx.test }); + if (J.db.log.length > 2000) J.db.log = J.db.log.slice(-1500); + J.save(); return { ok, status, note }; +} +// fire every enabled postback of `owner` that listens to `event`; ctx carries the click's params and the event facts +async function fire(owner, event, ctx) { + const o = norm(owner); const out = []; + for (const p of J.db.items.filter(x => x.owner === o && x.enabled && x.events.includes(event))) { + if (!rateOk(o)) break; + const q = (ctx.q || {}); + const vals = { clickid: q.clickid || q.cid || q.click_id || '', subid: q.subid || q.sub_id || q.s1 || '', s1: q.s1 || q.sub1 || '', s2: q.s2 || q.sub2 || '', s3: q.s3 || q.sub3 || '', s4: q.s4 || q.sub4 || '', s5: q.s5 || q.sub5 || '', source: ctx.source || '', event, payout: ctx.payout != null ? ctx.payout : '', currency: ctx.currency || 'USD', txid: ctx.txid || '', lsid: ctx.lsid || '', code: ctx.code || '', country: ctx.country || '', device: ctx.device || '' }; + for (const [k, v] of Object.entries(q)) if (/^(utm_[a-z]+|sub\d|s\d|aff_sub\d?|t\d)$/.test(k) && vals[k] == null) vals[k] = v; + const url = fill(p.url, vals); + let r = await deliver(p, url, Object.assign({}, ctx, { event })); + if (!r.ok && !ctx.test) { await new Promise(res => setTimeout(res, 4000)); r = await deliver(p, url, Object.assign({}, ctx, { event })); } + out.push({ id: p.id, name: p.name, ok: r.ok, status: r.status, note: r.note }); + } + return out; +} +async function test(owner, id) { + const p = J.db.items.find(x => x.id === id && x.owner === norm(owner)); if (!p) return { error: 'No such postback.' }; + const ev = p.events[0] || 'join'; + const url = fill(p.url, { clickid: 'test-click-123', subid: 'test-sub', s1: 'test-s1', s2: '', s3: '', s4: '', s5: '', source: 'test', event: ev, payout: '0.00', currency: 'USD', txid: '0xtest', lsid: 'testlsid', code: 'test', country: 'US', device: 'desktop' }); + const r = await deliver(p, url, { event: ev, lsid: 'testlsid', test: true }); + return { ok: r.ok, status: r.status, note: r.note, url }; +} +// 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; + 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 }, facts || {}); + try { await fire(hit.owner, event, ctx); } catch (e) {} + return hit; +} +// a partner reported a conversion against one of our click ids +async function inbound(key, body) { + const owner = ownerOfKey(key); if (!owner) return { error: 'Unknown partner key.' }; + const lsid = String(body.lsid || body.clickid || '').trim(); if (!/^[a-z0-9]{6,20}$/i.test(lsid)) return { error: 'lsid is required.' }; + const event = 'external'; const value = Number(body.value || body.payout || 0) || 0; const label = String(body.event || body.name || 'conversion').slice(0, 40); + const hit = rotator && rotator.convert ? await rotator.convert(lsid, event, { payout: value, label }) : null; + if (!hit) return { error: 'No click with that lsid.' }; + if (hit.owner !== owner) return { error: 'That click is not yours.' }; + const ctx = { q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid, code: hit.code, payout: value, currency: String(body.currency || 'USD').slice(0, 6), txid: String(body.txid || '').slice(0, 80), label }; + try { await fire(owner, event, ctx); } catch (e) {} + return { ok: true, recorded: event, lsid }; +} +module.exports = { init, EVENTS, validateUrl, list, create, update, logFor, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound }; diff --git a/public/assets/cr-shell.js b/public/assets/cr-shell.js new file mode 100644 index 0000000..18174df --- /dev/null +++ b/public/assets/cr-shell.js @@ -0,0 +1,90 @@ +// LinkSpin Control Room shell (2026-09-29): the frame every workspace screen shares. +// Rail + topbar, session check, in-shell sign-in (email code, same endpoints as the dashboard), +// fetch helper, toast, in-page dialogs (never native prompt/confirm). Pages: put content in +//
, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb). +window.CR = (function () { + const $ = id => document.getElementById(id); + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const fmt = n => Number(n || 0).toLocaleString(); + const NAV = [ + ['links', 'Links', '/links', ''], + ['pages', 'Pages', '/pages', ''], + ['zones', 'Zones', '/zones', ''], + ['reports', 'Reports', '/reports', ''], + ['team', 'Team', '/team', ''], + ['wallet', 'Wallet', '/wallet', ''], + ]; + // screens not built yet fall back to the classic dashboard pane so nothing is a dead end + const FALLBACK = { pages: '/my#promo', zones: '/my#campaigns', team: '/my#line', wallet: '/my#wallet' }; + const BUILT = new Set(['links', 'reports', 'team', 'wallet']); + let ME = null, toastT; + function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); } + async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; } + async function get(path) { const r = await (await fetch(path, { headers: { Accept: 'application/json' } })).json(); if (r.error) throw new Error(r.error); return r; } + function copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } } + function dialog(opts) { + return new Promise(resolve => { + let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); } + host.innerHTML = ''; + const back = document.createElement('div'); back.className = 'modal-back'; + back.innerHTML = ''; + host.appendChild(back); + const done = v => { host.innerHTML = ''; resolve(v); }; + back.querySelector('#dlgNo').addEventListener('click', () => done(null)); + back.addEventListener('click', e => { if (e.target === back) done(null); }); + back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); }); + const first = back.querySelector('input,textarea'); if (first) { first.focus(); if (first.select) first.select(); } + back.addEventListener('keydown', e => { if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); }); + }); + } + function mount(o) { + const page = $('page'); if (!page) return; + const app = document.createElement('div'); app.className = 'app'; + app.innerHTML = '' + + '

' + esc(o.title || '') + '

' + esc(o.sub || '') + '' + (o.actions || '') + '
'; + page.parentNode.insertBefore(app, page); app.querySelector('#crBody').appendChild(page); + $('crUserBtn').addEventListener('click', async e => { e.preventDefault(); if (!ME || !ME.signedIn) return signInFlow(() => location.reload()); const v = await dialog({ title: ME.username ? '@' + ME.username : (ME.email || 'Account'), text: 'Signed in on LinkSpin. Your classic dashboard is still at /my.', ok: 'Sign out', no: 'Close', danger: true }); if (v) { try { await api('/api/auth/logout'); } catch (er) {} location.reload(); } }); + } + const sub = t => { const s = $('crSub'); if (s) s.textContent = t; }; + async function me(force) { if (ME && !force) return ME; try { ME = await (await fetch('/api/me', { headers: { Accept: 'application/json' } })).json(); } catch (e) { ME = { signedIn: false }; } return ME; } + // sign-in inside the shell: email -> six-digit code, on the same endpoints and guards as the dashboard. + const FTS = Date.now(); + async function signInFlow(onReady) { + let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); } + host.innerHTML = ''; + const email = $('siEmail'), code = $('siCode'), go = $('siGo'), msg = $('siMsg'); let stage = 'email'; + email.focus(); + const say = (t, bad) => { msg.textContent = t; msg.className = bad ? 'bad' : 'muted'; }; + async function step() { + try { + if (stage === 'email') { + const e = email.value.trim(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return say('That email address does not look right.', true); + go.disabled = true; say('Sending…'); + // the sign-up guard refuses a form younger than a few seconds (bot defence); wait it out instead of bouncing the person + const wait = FTS + 4500 - Date.now(); if (wait > 0) await new Promise(r => setTimeout(r, wait)); + const r = await api('/api/auth/email/start', { email: e, fts: FTS, hp_field_x9: '', pick: null }); + go.disabled = false; + if (r.challenge) { say('One more check is needed for this address. Use the classic dashboard sign-in this once.', true); return; } + $('siCodeRow').hidden = false; code.focus(); stage = 'code'; go.textContent = 'Sign in'; + if (r.devCode) code.value = r.devCode; + say(r.sent ? 'Code sent. Check your inbox, and spam the first time.' : 'Code filled in (local dev).'); + } else { + go.disabled = true; say('Checking…'); + await api('/api/auth/email/verify', { email: email.value.trim(), code: code.value.trim() }); + host.innerHTML = ''; ME = null; await me(true); toast('You are in'); onReady && onReady(ME); + } + } catch (e) { go.disabled = false; say(e.message, true); } + } + go.addEventListener('click', step); + host.querySelector('.modal').addEventListener('keydown', e => { if (e.key === 'Enter') step(); }); + } + async function requireSession(onReady) { const m = await me(); if (m && m.signedIn) return onReady(m); signInFlow(onReady); } + return { esc, fmt, api, get, copy, dialog, toast, mount, sub, me, requireSession, signInFlow }; +})(); diff --git a/public/assets/links.js b/public/assets/links.js index 367d9d6..55444f3 100644 --- a/public/assets/links.js +++ b/public/assets/links.js @@ -1,68 +1,45 @@ -// LinkSpin Links workspace (Control Room, first real screen, 2026-09-29). Talks to the existing rotator API: -// GET /api/my/rotations, POST /api/my/rotations, POST /api/my/rotations/:id, POST .../dest, POST .../dest/:did, GET .../stats +// LinkSpin Links workspace (Control Room). Rotator API + postbacks + share kit. Uses the shared shell (cr-shell.js). (function () { - const $ = id => document.getElementById(id); - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const fmt = n => Number(n || 0).toLocaleString(); - let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = ''; - let toastT; - function toast(msg, bad) { const t = $('toast'); t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 1800); } - async function api(path, body) { const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) throw new Error(r.error); return r; } - function copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } } - // in-page dialogs (never native prompt/confirm) - function dialog(opts) { - return new Promise(resolve => { - const host = $('modalHost'); host.innerHTML = ''; - const back = document.createElement('div'); back.className = 'modal-back'; - back.innerHTML = ''; - host.appendChild(back); - const done = v => { host.innerHTML = ''; resolve(v); }; - back.querySelector('#dlgNo').addEventListener('click', () => done(null)); - back.addEventListener('click', e => { if (e.target === back) done(null); }); - back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); }); - const first = back.querySelector('input'); if (first) { first.focus(); first.select(); back.addEventListener('keydown', e => { if (e.key === 'Enter') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); }); } - }); - } + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog; + let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '', PB = null; + CR.mount({ active: 'links', title: 'Links', sub: 'loading', actions: '' }); const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code; const clicks7 = r => r.hits7 || 0; const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' }; async function load(keep) { - let r; try { r = await (await fetch('/api/my/rotations', { headers: { Accept: 'application/json' } })).json(); } catch (e) { r = { error: 'network' }; } - if (r.error) { $('signin').hidden = false; $('ws').hidden = true; $('tbSub').textContent = 'not signed in'; return; } + let r; try { r = await CR.get('/api/my/rotations'); } catch (e) { CR.sub('could not load'); return; } ROT = (r.rotations || []).slice().sort((a, b) => clicks7(b) - clicks7(a)); HOSTS = r.hosts || []; - $('signin').hidden = true; $('ws').hidden = false; const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0); - $('tbSub').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days'; + CR.sub(ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days'); renderList(); - if (keep && SEL != null) { const s = ROT.find(x => x.id === SEL); if (s) return select(s.id, true); } + const want = SEL != null ? SEL : (Number(location.hash.slice(1)) || null); + if (want != null && ROT.find(x => x.id === want)) return select(want, true); if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; } - else if (SEL == null) select(ROT[0].id, true); + else select(ROT[0].id, true); } function renderList() { const q = FILTER.trim().toLowerCase(); const rows = ROT.filter(x => !q || x.name.toLowerCase().includes(q) || x.code.includes(q)); $('listCount').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's'); $('items').innerHTML = rows.length ? rows.map(x => { const h = health(x); return '
' - + '
' + esc(x.name) + (h.cls !== 'ok' ? ' ' + h.t + '' : '') + '
' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '
' + + '
' + esc(x.name) + (h.cls !== 'ok' ? ' ' + h.t + '' : '') + (x.conversions ? ' ' + x.conversions + ' conv' : '') + '
' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '
' + '
' + fmt(clicks7(x)) + '7 d
'; }).join('') : '
' + (ROT.length ? 'No link matches that filter.' : 'No links yet.') + '
'; $('items').querySelectorAll('.item').forEach(el => { const go = () => select(Number(el.dataset.id)); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); }); } async function select(id, quiet) { SEL = id; const r = ROT.find(x => x.id === id); if (!r) return; + if (String(location.hash.slice(1)) !== String(id)) history.replaceState(null, '', '#' + id); $('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus'); $('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id)); $('dName').textContent = r.name; $('dUrl').textContent = linkUrl(r); const h = health(r); $('dLive').innerHTML = '' + h.t + ''; $('pauseBtn').textContent = r.paused ? 'Resume' : 'Pause'; $('fallback').value = r.fallback || ''; - const bots = r.bots || 0; - $('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(bots)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]] + $('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(r.bots || 0)], ['Conversions', fmt(r.conversions || 0)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]] .map(([k, v], i) => '
' + k + '' + v + '
').join(''); - renderDest(r); + renderDest(r); renderShare(r); if (!quiet) window.scrollTo({ top: 0 }); loadStats(r.id); } @@ -80,19 +57,49 @@ $('destRows').querySelectorAll('[data-t]').forEach(b => b.addEventListener('click', async () => { const d = r.destinations.find(q => q.id === Number(b.dataset.t)); try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { active: !d.active }); load(true); } catch (e) { toast(e.message, true); } })); $('destRows').querySelectorAll('[data-x]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this destination?', text: 'Its click history stays in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/rotations/' + r.id + '/dest/' + b.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } })); } + function renderShare(r) { + const url = linkUrl(r); + const kit = [ + ['Short post', 'One link, every page I promote, in turn. Take a look: ' + url], + ['Email or Telegram line', 'Here is the link I use for everything: ' + url + ' (it always sends you to the right page).'], + ['Tracker-ready link', url + '?clickid={clickid}&s1={source} (replace the braces with your network\'s macros)'], + ['Sub-id split test', url + '?s1=email-A and ' + url + '?s1=email-B (each shows up under Sources)'], + ]; + $('shareKit').innerHTML = kit.map(([t, body], i) => '
' + esc(t) + '
' + esc(body) + '
').join(''); + $('shareKit').querySelectorAll('[data-cp]').forEach(b => b.addEventListener('click', () => CR.copy($('kit-' + b.dataset.cp).textContent))); + } + const kv = rows => rows && rows.length ? rows.map(x => '' + esc(x.k) + '' + fmt(x.n) + '').join('') : 'nothing yet'; async function loadStats(id) { - let s = STATS[id]; if (!s) { try { s = await (await fetch('/api/my/rotations/' + id + '/stats')).json(); } catch (e) { s = null; } if (!s || s.error) return; STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); } + let s = STATS[id]; if (!s) { try { s = await CR.get('/api/my/rotations/' + id + '/stats'); } catch (e) { return; } STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); } if (SEL !== id) return; const hmax = Math.max(1, ...s.hours); $('hourBars').innerHTML = s.hours.map((n, i) => '').join(''); - const kv = rows => rows.length ? rows.map(x => '' + esc(x.k) + '' + fmt(x.n) + '').join('') : 'nothing yet'; - $('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country); + $('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country); $('subRows').innerHTML = kv(s.subs); $('convRows').innerHTML = kv(s.conversions); const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.length ? dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ') : ''; const days = s.days || []; const dmax = Math.max(1, ...days.map(d => d.n)); $('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))'; $('dayBars').innerHTML = days.length ? days.map(d => '').join('') : ''; $('dayAxis').innerHTML = days.length ? '' + days[0].day + '' + days[days.length - 1].day + '' : 'no clicks recorded yet'; } - // actions + // postbacks (account level) + async function loadPb() { + try { PB = await CR.get('/api/my/postbacks'); } catch (e) { return; } + $('pbInUrl').textContent = PB.inboundUrl + '?key=' + PB.key + '&lsid={lsid}&event=sale&value=0.00'; + const rows = PB.postbacks || []; + $('pbRows').innerHTML = rows.length ? rows.map(p => '
' + esc(p.name) + '
' + p.method + ' · sent ' + fmt(p.sent) + (p.lastAt ? ' · last ' + esc(String(p.lastStatus)) : '') + '
' + esc(p.url) + '
' + p.events.map(e => '' + e + '').join(' ') + '
' + (p.enabled ? 'ON' : 'OFF' + (p.fails >= 10 ? ' · failed 10x' : '') + '') + '
').join('') + : '
No postbacks yet. Add your tracker\'s postback URL and pick which events fire it.
'; + const log = PB.log || []; $('pbFoot').textContent = log.length ? 'last delivery: ' + new Date(log[0].ts).toLocaleString() + ' · ' + log[0].name + ' · ' + log[0].event + ' · ' + (log[0].ok ? 'ok ' + log[0].status : 'failed ' + (log[0].status || log[0].note)) + ' · ' + log.filter(l => l.ok).length + ' of the last ' + log.length + ' succeeded' : 'no deliveries yet'; + $('pbRows').querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', async () => { b.disabled = true; try { const r = await api('/api/my/postbacks/' + b.dataset.test, { test: true }); toast(r.ok ? 'Test delivered, HTTP ' + r.status : 'Test failed: ' + (r.status || r.note), !r.ok); } catch (e) { toast(e.message, true); } b.disabled = false; loadPb(); })); + $('pbRows').querySelectorAll('[data-tog]').forEach(b => b.addEventListener('click', async () => { const p = rows.find(x => x.id === b.dataset.tog); try { await api('/api/my/postbacks/' + p.id, { enabled: !p.enabled }); loadPb(); } catch (e) { toast(e.message, true); } })); + $('pbRows').querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this postback?', ok: 'Remove', danger: true })) return; try { await api('/api/my/postbacks/' + b.dataset.del, { remove: true }); loadPb(); } catch (e) { toast(e.message, true); } })); + $('pbRows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => pbForm(rows.find(x => x.id === b.dataset.edit)))); + } + async function pbForm(p) { + const ev = (PB && PB.events) || ['join', 'wallet', 'purchase', 'external']; + const v = await dialog({ title: p ? 'Edit postback' : 'New postback', text: 'Your tracker or network gives you a postback URL with macros. Paste it; LinkSpin fills the click id it saw on the link.', + fields: [{ k: 'name', label: 'Name', value: p ? p.name : '', placeholder: 'BeMob', max: 60 }, { k: 'url', label: 'URL template', value: p ? p.url : '', placeholder: 'https://tracker.example/postback?cid={clickid}&payout={payout}&txid={txid}', mono: true, type: 'url' }, { k: 'events', label: 'Events, comma separated: ' + ev.join(', '), value: p ? p.events.join(',') : 'join,purchase' }, { k: 'method', label: 'Method, GET or POST', value: p ? p.method : 'GET', max: 4 }], ok: p ? 'Save' : 'Create' }); + if (!v) return; + try { if (p) await api('/api/my/postbacks/' + p.id, v); else await api('/api/my/postbacks', v); toast(p ? 'Saved' : 'Postback added'); loadPb(); } catch (e) { toast(e.message, true); } + } async function newSpin() { const v = await dialog({ title: 'New spin', text: 'Name it for you, not for visitors. You add the pages next.', fields: [{ k: 'name', label: 'Name', placeholder: 'IAP main invite', max: 80 }, { k: 'url', label: 'First page to send people to (optional)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' }); if (!v || !v.name.trim()) return; @@ -100,16 +107,16 @@ } $('newBtn').addEventListener('click', newSpin); $('newBtn2').addEventListener('click', newSpin); $('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); }); - $('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) copy(linkUrl(r)); }); + $('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) CR.copy(linkUrl(r)); }); $('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); }); $('renameBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: r.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/rotations/' + r.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } }); $('pauseBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { paused: !r.paused }); toast(r.paused ? 'Live again' : 'Paused: visitors go to the fallback'); load(true); } catch (e) { toast(e.message, true); } }); - $('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; toast('Deleted'); load(); } catch (e) { toast(e.message, true); } }); + $('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; history.replaceState(null, '', location.pathname); toast('Deleted'); load(); } catch (e) { toast(e.message, true); } }); $('addBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const url = $('addUrl').value.trim(); if (!url) { $('addUrl').focus(); return; } try { await api('/api/my/rotations/' + r.id + '/dest', { url, label: $('addLabel').value, weight: $('addWeight').value }); $('addUrl').value = ''; $('addLabel').value = ''; toast('Destination added'); load(true); } catch (e) { toast(e.message, true); } }); $('addUrl').addEventListener('keydown', e => { if (e.key === 'Enter') $('addBtn').click(); }); $('fallback').addEventListener('change', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { fallback: $('fallback').value.trim() }); toast('Fallback saved'); load(true); } catch (e) { toast(e.message, true); } }); - $('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); })); + $('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report', 'share'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); })); + $('pbNew').addEventListener('click', () => pbForm(null)); $('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches; - load(); - setInterval(() => { if (!document.hidden) load(true); }, 60000); + CR.requireSession(() => { load(); loadPb(); setInterval(() => { if (!document.hidden) load(true); }, 60000); }); })(); diff --git a/public/assets/reports.js b/public/assets/reports.js new file mode 100644 index 0000000..44ee01f --- /dev/null +++ b/public/assets/reports.js @@ -0,0 +1,27 @@ +// LinkSpin Reports: one view across every link the member owns (rotator.summary via /api/my/reports). +(function () { + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt; + let RANGE = 30; + CR.mount({ active: 'reports', title: 'Reports', sub: 'loading', actions: '
' }); + $('range').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { RANGE = Number(b.dataset.d); $('range').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); load(); })); + const kv = (rows, total) => rows && rows.length ? rows.map(x => '' + esc(x.k) + '' + fmt(x.n) + (total ? ' ' + Math.round(x.n / total * 100) + '%' : '') + '').join('') : 'nothing yet'; + async function load() { + let s; try { s = await CR.get('/api/my/reports?days=' + RANGE); } catch (e) { CR.sub('could not load'); return; } + const t = s.totals || {}; + CR.sub(RANGE + ' days · ' + fmt(s.links || 0) + ' link' + (s.links === 1 ? '' : 's') + ' · Central time days'); + $('tiles').innerHTML = [['Served', fmt(t.served), ''], ['Unique', fmt(t.unique), ''], ['Bots dropped', fmt(t.bots), t.served ? Math.round(t.bots / (t.served + t.bots) * 100) + '% of hits' : ''], ['Joins', fmt(t.joins), t.unique ? (t.joins / t.unique * 100).toFixed(1) + '% of unique' : ''], ['Buyers', fmt(t.purchases), t.joins ? Math.round(t.purchases / t.joins * 100) + '% of joins' : ''], ['Partner conversions', fmt(t.external), '']] + .map(([k, v, n], i) => '
' + k + '' + v + '' + (n ? '' + n + '' : '') + '
').join(''); + const days = s.days || []; const dmax = Math.max(1, ...days.map(d => Math.max(d.u, d.b))); + $('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))'; + $('dayBars').innerHTML = days.map(d => '').join(''); + $('dayAxis').innerHTML = days.length ? '' + days[0].day + '' + days[Math.floor(days.length / 2)].day + '' + days[days.length - 1].day + '' : 'no clicks yet'; + $('srcRows').innerHTML = kv(s.source, t.unique); $('geoRows').innerHTML = kv(s.country, t.unique); + const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · '); + $('topRows').innerHTML = (s.top || []).length ? s.top.map(x => '
' + esc(x.name) + '
' + esc(x.code) + '
' + fmt(x.unique) + '' + fmt(x.hits) + '' + fmt(x.conv) + '
').join('') : '
No links yet.
'; + 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); + } + CR.requireSession(load); +})(); diff --git a/public/assets/team.js b/public/assets/team.js new file mode 100644 index 0000000..50c9f0a --- /dev/null +++ b/public/assets/team.js @@ -0,0 +1,41 @@ +// LinkSpin Team: the line as a working table (dashboard + line + carry APIs from the engine). +(function () { + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt; + let D = null, LINE = null, LEVEL = 1, FILTERS = new Set(), ME = null; + CR.mount({ active: 'team', title: 'Team', sub: 'loading' }); + const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; + const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + ' h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' d ago'; }; + const pol = wei => { try { return (Number(BigInt(wei || '0') / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } }; + function rows() { + const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); let ms = L ? L.members.slice() : []; + const f = { today: m => (m.lastSeen || 0) >= dayStart(), wallet: m => !!m.wallet, nopay: m => !!m.wallet && !m.activated, nowallet: m => !m.wallet }; + for (const k of FILTERS) ms = ms.filter(f[k]); + ms.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0)); + return ms; + } + function render() { + const ms = rows(); const L = (LINE && LINE.levels || []).find(x => x.level === LEVEL); const total = L ? L.members.length : 0; + $('rows').innerHTML = ms.length ? ms.map(m => { const today = (m.lastSeen || 0) >= dayStart(); + return '
' + esc(m.name) + (m.own ? ' YOURS' : '') + '
' + (m.memberId ? '#' + m.memberId + ' · ' : '') + 'joined ' + new Date(m.joined).toLocaleDateString() + (m.bought ? ' · $20+ buy' : '') + (m.buyers ? ' · ' + m.buyers + ' qualifying' : '') + '
' + + '' + (today ? 'today' : ago(m.lastSeen)) + '' + + '' + (m.activated ? 'payouts on' : m.wallet ? 'wallet, payouts off' : 'no wallet') + '' + + '' + (m.earnedWei && m.earnedWei !== '0' ? '+' + pol(m.earnedWei) + ' POL' : '0') + '' + + '' + (m.sponsor ? 'via ' + esc(m.sponsor) : (m.email ? esc(m.email) : '')) + '
'; }).join('') + : '
' + (total ? 'Nobody matches those filters.' : 'Nobody on this level yet. Share your link, or put it in a spin.') + '
'; + $('foot').textContent = 'level ' + LEVEL + ' · ' + ms.length + (ms.length !== total ? ' of ' + total : '') + ' · surf earnings and full activity are in the classic dashboard for now'; + } + async function load() { + try { [D, LINE, ME] = await Promise.all([CR.get('/api/my/dashboard'), CR.get('/api/my/line'), CR.me()]); } catch (e) { CR.sub('could not load'); return; } + const counts = (LINE.counts || []); const refs = D.referrals || []; + CR.sub((counts[0] || 0) + ' direct' + (counts[0] === 1 ? '' : 's') + ' · ' + ((counts[1] || 0) + (counts[2] || 0)) + ' deeper'); + $('tiles').innerHTML = [['Directs', fmt(counts[0] || 0), refs.filter(r => r.activated).length + ' with payouts on'], ['Levels 2 and 3', fmt((counts[1] || 0) + (counts[2] || 0)), (counts[1] || 0) + ' · ' + (counts[2] || 0)], ['Qualifying buyers', fmt(D.buyerCount || 0), (D.buyerCount || 0) >= 5 ? 'level 3 open' : (D.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'], ['Paid by the line', pol(D.earnedWei || '0') + ' POL', (D.earnCount || 0) + ' payouts']] + .map(([k, v, n], i) => '
' + k + '' + v + '' + n + '
').join(''); + const inv = 'https://' + location.host + '/join/' + (ME.username || ME.refCode || ME.memberId || ''); $('invite').textContent = inv; $('copyInvite').onclick = () => CR.copy(inv); + $('sponsor').innerHTML = ME.sponsorName ? '' + esc(ME.sponsorName) + '' + (ME.sponsorId ? ' #' + ME.sponsorId + '' : '') + '
Carried over from the network where you first joined. Nothing to set up, nothing anyone can change.
' : (ME.sponsorId ? 'member #' + ME.sponsorId + '' : 'Not set. Your first purchase locks a sponsor.'); + try { const c = await CR.get('/api/my/carry'); const cl = (c.claims || []).filter(x => x.sponsor === (ME.email || '').toLowerCase()); if (cl.length) { $('claimPanel').hidden = false; $('claims').innerHTML = cl.length + ' of your people can use every tool now; their first purchase waits up to ' + (c.claimDays || 3) + ' days for you to link a wallet and switch on payouts, then walks up your line.'; } } catch (e) {} + render(); + } + document.querySelectorAll('.lvl [data-l]').forEach(b => b.addEventListener('click', () => { LEVEL = Number(b.dataset.l); document.querySelectorAll('.lvl [data-l]').forEach(x => x.classList.toggle('on', x === b)); render(); })); + $('chips').querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (FILTERS.has(k)) FILTERS.delete(k); else FILTERS.add(k); b.classList.toggle('on', FILTERS.has(k)); render(); })); + CR.requireSession(load); +})(); diff --git a/public/assets/wallet-screen.js b/public/assets/wallet-screen.js new file mode 100644 index 0000000..1acad8a --- /dev/null +++ b/public/assets/wallet-screen.js @@ -0,0 +1,25 @@ +// LinkSpin Wallet: paid-to-this-wallet, credits, positions, payout history (engine APIs). Connect/buy stay on /my#wallet for now. +(function () { + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt; + CR.mount({ active: 'wallet', title: 'Wallet', sub: 'loading' }); + const pol = wei => { try { return (Number(BigInt(wei || '0') / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } }; + async function load() { + let D, ME, POS = [], E = null; + try { [D, ME] = await Promise.all([CR.get('/api/my/dashboard'), CR.me()]); } catch (e) { CR.sub('could not load'); return; } + try { POS = await CR.get('/api/my/positions'); } catch (e) {} + try { E = await CR.get('/api/my/activity'); } catch (e) {} + const addr = ME.address || ''; const on = !!ME.memberId; + CR.sub(addr ? addr.slice(0, 6) + '…' + addr.slice(-4) + (on ? ' · payouts on' : ' · payouts off') : 'no wallet linked'); + $('tiles').innerHTML = [['Paid to this wallet', pol(D.earnedWei || '0') + ' POL', (D.earnCount || 0) + ' transactions'], ['Credits', fmt((D.credits || 0) + (D.earnedCredits || 0)), fmt(D.credits || 0) + ' purchased · ' + fmt(D.earnedCredits || 0) + ' earned'], ['In campaigns', fmt(D.inCampaigns || 0), 'reserved by live campaigns'], ['Qualifying buyers', fmt(D.buyerCount || 0), (D.buyerCount || 0) >= 5 ? 'level 3 open' : (D.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers']] + .map(([k, v, n], i) => '
' + k + '' + v + '' + n + '
').join(''); + $('walletBox').innerHTML = addr ? '
' + esc(addr) + '
' + (on ? 'PAYOUTS ON · member #' + ME.memberId + '' : 'WALLET LINKED · PAYOUTS OFF
Switch payouts on so the people you bring pay you from their first purchase.
') + '
' : 'No wallet linked yet.
Link one to be paid. Your email account keeps working either way.
'; + const pays = E && Array.isArray(E.earnings) ? E.earnings : []; + $('payRows').innerHTML = pays.length ? pays.slice(0, 25).map(x => '
' + new Date((x.ts || 0) * (x.ts > 1e12 ? 1 : 1000)).toLocaleString() + '' + esc(x.buyerName || x.fromName || (x.buyerId ? 'member #' + x.buyerId : x.type === 'AwardPaid' ? 'award' : 'member')) + '' + (x.tier ? 'L' + x.tier + ' · ' + (x.tier === 1 ? '50%' : x.tier === 2 ? '20%' : '10%') : (x.type === 'AwardPaid' ? 'award' : '')) + '' + (x.priceCents ? '$' + (x.priceCents / 100) : '') + '+' + pol(x.amountWei || '0') + ' POL' + (x.tx ? '' + esc(String(x.tx).slice(0, 10)) + '…' : '') + '
').join('') + : '
No payouts yet. They appear here the moment someone in your line buys.
'; + $('payFoot').textContent = 'every line is a Polygon transaction · nothing is held by the site'; + const rows = Array.isArray(POS) ? POS : (POS && (POS.positions || POS.list)) || []; + $('posRows').innerHTML = rows.length ? rows.map(p => '
' + (p.main ? 'Main position' : 'Position') + ' ' + (p.memberId ? '#' + p.memberId : 'not on chain yet') + '
' + esc(String(p.address || '').slice(0, 10)) + '…
' + fmt(p.avail || 0) + '' + (p.memberId ? 'ACTIVE' : 'PENDING') + '
').join('') + : '
' + (addr ? 'Main wallet only.' : 'No positions yet.') + '
'; + } + CR.requireSession(load); +})(); diff --git a/public/links.html b/public/links.html index 7c6d434..88c828d 100644 --- a/public/links.html +++ b/public/links.html @@ -6,9 +6,9 @@ Links · LinkSpin - + -
- -
-
-

Links

- loading - - +
+
+
+

Links

by clicks, 7 days
+
+
- - - -