06f0a87452
1. Own clicks: auth.onSeen notes the soft key of every InstantAdPay session (lsconv.noteSession, once per 6 h per email + soft key) and the click push carries them as owners [{owner, sk, ts}] (requeued on a failed push), so LinkSpin keeps members' own clicks on their ads, spin links and Banner Spins as tests. /api/ads/click flags a click self for conversions when signed in as the owner OR from a browser the owner signs in from; whether the click is counted and billed is unchanged (still the signed-in check). Linked positions share the owner's email.
2. Send a test conversion now loads the member's real LinkSpin pixel in test mode from the browser (cv.gif?px=..&test=1, reads X-LS-Result: test, the same request LinkSpin's button makes) and falls back to the signed partner call (op test) when the browser cannot load it; CSP connect-src adds https://linkspin.app. The card shows "N from your own clicks, kept as tests and left out" (selfTests from LinkSpin's summary).
4. Cost per goal (30 days): /api/my/conversions returns spend30 = each campaign's spend over the same 30 days from credit_log (ads.spendSince: delivery, login, buy, refund rows by Central day, ref = campaign id). Campaign lines read "Goals and cost per goal (30 days)"; a campaign started inside the window with no log rows uses its spend since start (labelled in the tooltip); an older campaign with no spend on record shows no cost rather than a lifetime figure.
Copy: Conversion tracking card note, /conversion-tracking (test button, own clicks, cost per goal (30 days) row). Chatbot CANNED + FACTS, KNOWLEDGE_DATE 2026-10-26. my.js ?v=20261026cv.
QA: convpixel all passed (new: owners pushed without raw IP, own-browser click self=1 and stranger 0, no re-push within 6 h, spend30 = 200 of the window with the 40-day-old row and another member left out, 50/200 credits each vs lifetime 75, no-log old campaign shows no cost, new campaign uses spend since start, own-click count on the card, test button loads cv.gif?px&test=1 in the browser (routed locally) and falls back to op test); fuel all pass (engine.js / engine-room.js / kit.js untouched, byte-identical with LinkSpin); member walk 0 bugs; public 0 bugs (known /shorts ellipsis warning).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
27 KiB
JavaScript
260 lines
27 KiB
JavaScript
// Conversion pixel, InstantAdPay half (2026-10-23), end to end against a LOCAL copy and a MOCK LinkSpin.
|
|
// node qa/convpixel.test.mjs (or: bash qa/run.sh convpixel)
|
|
// Boots server.js on its own port with a throwaway DATA_DIR seeded with two advertisers and a few campaigns (JSON store,
|
|
// DATABASE_URL blank, no mail key, devCode sign-in, a minimal environment so no live secret can leak in), LS_URL pointing at a
|
|
// mock LinkSpin on localhost that verifies the HMAC on every call, records the pushed clicks and answers op summary.
|
|
// Nothing touches production or a real member. Checks: lsclk on the 302 (existing params and #hash kept, a LinkSpin /r/ link
|
|
// gets it, an existing lsclk is never replaced, an unparsable target goes out unchanged), the click rows pushed with a valid
|
|
// signature and the contract fields, the owner's own click flagged self=1 and not counted, the proxies, the Campaigns pane
|
|
// showing goals and cost per goal (300 credits / 4 = 75), LinkSpin down: pane still loads, panel says so, rows kept and
|
|
// pushed once it is back. 2026-10-26: own soft keys pushed as owners and an own-browser click flagged self (billing
|
|
// unchanged), Send a test conversion loads the real pixel in test mode (routed in the browser, nothing leaves the machine)
|
|
// with the partner call as fallback, the own-click test count on the card, cost per goal (30 days) from the credit log.
|
|
// Exit code 1 on any failure.
|
|
import http from 'node:http';
|
|
import crypto from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { spawn } from 'node:child_process';
|
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
|
|
const SITE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
const PORT = Number(process.env.CONV_PORT || 8831), MPORT = PORT + 1;
|
|
const B = 'http://127.0.0.1:' + PORT, MOCK = 'http://127.0.0.1:' + MPORT;
|
|
const SECRET = 'qa-convpixel-' + crypto.randomBytes(24).toString('hex'); // throwaway, 32+ chars
|
|
const ADMIN = 'localtest';
|
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-conv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
|
|
const OUT = path.join(SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
|
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (!cond && extra ? ' ' + extra : '')); if (!cond) fails++; };
|
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 15000)) { try { const v = await fn(); if (v) return v; } catch (e) {} await sleep(400); } return null; }
|
|
|
|
// ---- seed: two advertisers, campaigns with every target shape ----
|
|
const now = Date.now();
|
|
const acct = (email, username, code) => ({ email, pass: null, sponsorRef: '', code, username, address: null, created: now - 5 * 86400000, lastSeen: now - 3600000, memberId: 0 });
|
|
const A1 = 'qa-adv@example.com', A2 = 'qa-adv2@example.com';
|
|
{ const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} };
|
|
for (const a of [acct(A1, 'qaadv', 'cqaadv1'), acct(A2, 'qaadvtwo', 'cqaadv2')]) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; }
|
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(db)); }
|
|
const camp = (id, owner, name, targetUrl, spent) => ({ id, owner, memberId: 0, type: 'banner', name, targetUrl, imageUrl: 'https://example.com/b.png', title: null, body: null,
|
|
budget: 1000, spent, accrued: 0, imps: 50, clicks: 0, batchImps: 0, width: 468, height: 60, status: 'paused', created: now - 86400000 });
|
|
const T1 = 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world#top';
|
|
const CAMPS = [camp(1, A1, 'QA landing', T1, 300), camp(2, A1, 'QA spin link', 'https://linkspin.app/r/abc12', 120),
|
|
camp(3, A1, 'QA has lsclk', 'https://adv.example/p?lsclk=keepme', 0), camp(4, A1, 'QA odd target', 'adv.example/no-scheme', 0), camp(5, A2, 'QA other', 'https://other.example/', 50),
|
|
Object.assign(camp(6, A1, 'QA old no log', 'https://adv.example/old', 500), { created: now - 60 * 86400000 }), Object.assign(camp(7, A1, 'QA new no log', 'https://adv.example/new', 90), { created: now - 3 * 86400000 })];
|
|
// cost per goal (30 days): campaign 1 spent 150 today + 50 five days ago inside the window, 100 forty days ago outside it
|
|
const ctd = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
|
const cl = (t, delta, ref) => ({ email: A1, ts: t, day: ctd(t), delta, kind: 'delivery', note: 'Ad views: QA landing', ref: String(ref) });
|
|
fs.writeFileSync(path.join(DATA, 'credit-log.json'), JSON.stringify({ items: [cl(now - 40 * 86400000, -100, 1), cl(now - 5 * 86400000, -50, 1), cl(now - 60000, -150, 1), Object.assign(cl(now - 60000, -999, 1), { email: A2 })] }));
|
|
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 6, campaigns: CAMPS, burnsPending: [] }));
|
|
|
|
// ---- mock LinkSpin ----
|
|
const PX1 = 'px0123456789', PX2 = 'pxabcdef0123';
|
|
const mock = { clicks: new Map(), owners: [], badSig: 0, calls: [], down: false, goals: { [A1]: [{ px: PX1, name: 'subscriber', value: null, created: now - 86400000, conv: 6, convDays: 30, lastAt: now - 3600000, lastTest: null }, { px: PX2, name: 'sale', value: 19.95, created: now - 86400000, conv: 1, convDays: 30, lastAt: now - 7200000, lastTest: null }] } };
|
|
const verify = (ts, sig, raw) => { if (!ts || !sig || Math.abs(Date.now() - Number(ts)) > 300000) return false; const want = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); return want.length === String(sig).length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(String(sig))); };
|
|
const send = (res, code, obj) => { res.writeHead(code, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(obj)); };
|
|
function mockHandler(req, res) {
|
|
let raw = ''; req.on('data', c => raw += c); req.on('end', () => {
|
|
if (mock.down) { res.writeHead(503); return res.end('down'); }
|
|
if (req.method !== 'POST') return send(res, 404, { error: 'not found' });
|
|
if (!verify(req.headers['x-ls-ts'], req.headers['x-ls-sig'], raw)) { mock.badSig++; return send(res, 401, { error: 'bad signature' }); }
|
|
const b = JSON.parse(raw || '{}');
|
|
if (req.url === '/api/partner/clicks') { for (const c of b.clicks || []) mock.clicks.set(c.id, c); for (const o of b.owners || []) mock.owners.push(o); return send(res, 200, { ok: true, n: (b.clicks || []).length, owners: (b.owners || []).length }); }
|
|
if (req.url === '/api/partner/conv') {
|
|
mock.calls.push(b); const email = String(b.email || '');
|
|
const goals = mock.goals[email] || (mock.goals[email] = []);
|
|
if (b.op === 'summary') return send(res, 200, { ok: true, goals, byCampaign: email === A1 ? { 1: { clicks: 9, conv: { [PX1]: 4, [PX2]: 1 }, value: { [PX2]: 19.95 } }, 2: { clicks: 3, conv: {} }, 6: { clicks: 4, conv: { [PX1]: 2 } }, 7: { clicks: 5, conv: { [PX1]: 3 } } } : {}, methods: { url: 2, stored: 2, cookie: 1, soft: 1 }, selfTests: email === A1 ? 3 : 0, host: 'linkspin.app' });
|
|
if (b.op === 'create') { const g = { px: 'px' + crypto.randomBytes(5).toString('hex'), name: b.name, value: b.value == null ? null : b.value, created: Date.now(), conv: 0, convDays: 30, lastAt: null, lastTest: null }; goals.push(g); return send(res, 200, { ok: true, goal: g }); }
|
|
if (b.op === 'remove') { const i = goals.findIndex(g => g.px === b.px); if (i < 0) return send(res, 404, { error: 'No such goal.' }); goals.splice(i, 1); return send(res, 200, { ok: true }); }
|
|
if (b.op === 'test') { const g = goals.find(x => x.px === b.px); if (!g) return send(res, 404, { error: 'No such goal.' }); g.lastTest = Date.now(); return send(res, 200, { ok: true, at: g.lastTest }); }
|
|
return send(res, 400, { error: 'unknown op' });
|
|
}
|
|
return send(res, 404, { error: 'not found' }); // registry sync and anything else: ignored
|
|
});
|
|
}
|
|
let mockSrv = http.createServer(mockHandler); await new Promise(r => mockSrv.listen(MPORT, '127.0.0.1', r));
|
|
|
|
// ---- the local copy, minimal environment (no live secrets can ride along) ----
|
|
const ENV = {};
|
|
for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) ENV[k] = process.env[k];
|
|
Object.assign(ENV, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, DATABASE_URL: '', LS_SYNC_SECRET: SECRET, LS_URL: MOCK });
|
|
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env: ENV, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
|
|
let browser = null;
|
|
const cleanup = async () => { try { if (browser) await browser.close(); } catch (e) {} try { srv.kill(); } catch (e) {} try { mockSrv.close(); } catch (e) {} await sleep(300); try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {} };
|
|
|
|
try {
|
|
const up = await waitFor(async () => (await fetch(B + '/api/config')).ok, 30000);
|
|
if (!up) throw new Error('local server did not come up:\n' + srvLog.slice(-2000));
|
|
const api = async (p, body, hdr) => { const r = await fetch(B + p, { method: body ? 'POST' : 'GET', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: body ? JSON.stringify(body) : undefined }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; };
|
|
const click = async (id, hdr) => { const r = await fetch(B + '/api/ads/click/' + id, { redirect: 'manual', headers: Object.assign({ 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148', Referer: 'https://instantadpay.com/ledger?secret=1' }, hdr || {}) }); return { status: r.status, loc: r.headers.get('location') }; };
|
|
async function signIn(email) {
|
|
const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000, fage: 5000 });
|
|
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
|
|
return (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
|
|
}
|
|
const ID = /lsclk=(i[0-9a-f]{11})(?=$|[&#])/;
|
|
|
|
// 1. click ids on the redirect
|
|
const c1 = await click(1);
|
|
const id1 = (ID.exec(c1.loc || '') || [])[1];
|
|
ok(c1.status === 302 && !!id1, 'click -> 302 with lsclk=i+11 hex', c1.status + ' ' + c1.loc);
|
|
ok(c1.loc === 'https://adv.example/landing?utm_source=iap&x=a%2Cb&q=hello+world&lsclk=' + id1 + '#top', 'existing params kept byte for byte, lsclk before the #hash', c1.loc);
|
|
const c2 = await click(2); const id2 = (ID.exec(c2.loc || '') || [])[1];
|
|
ok(!!id2 && c2.loc === 'https://linkspin.app/r/abc12?lsclk=' + id2, 'a LinkSpin /r/ spin link gets lsclk', c2.loc);
|
|
const c3 = await click(3);
|
|
ok(c3.loc === 'https://adv.example/p?lsclk=keepme', 'an existing lsclk is never replaced', c3.loc);
|
|
const c4 = await click(4);
|
|
ok(c4.status === 302 && c4.loc === 'adv.example/no-scheme', 'an unparsable target redirects unchanged', c4.status + ' ' + c4.loc);
|
|
const c1b = await click(1); const id1b = (ID.exec(c1b.loc || '') || [])[1];
|
|
ok(id1b && id1b !== id1, 'every click gets its own id');
|
|
|
|
// 2. pushed to the mock, signed, with the contract fields
|
|
const got = await waitFor(() => mock.clicks.has(id1) && mock.clicks.has(id2) && mock.clicks.has(id1b), 15000);
|
|
ok(!!got, 'click rows pushed to LinkSpin /api/partner/clicks within ~3 s', [...mock.clicks.keys()].join(','));
|
|
ok(mock.badSig === 0, 'every push carried a valid HMAC signature', 'bad: ' + mock.badSig);
|
|
const r1 = mock.clicks.get(id1) || {};
|
|
ok(r1.camp === 1 && r1.cname === 'QA landing' && r1.type === 'banner' && r1.owner === A1, 'row: camp, cname, type, owner', JSON.stringify(r1));
|
|
ok(r1.spent === 300 && r1.self === 0 && r1.target === T1, 'row: spent 300, self 0, target', JSON.stringify(r1));
|
|
ok(/^s:[0-9a-f]{20}$/.test(r1.sk || '') && r1.dv === 'mobile' && r1.pl === 'instantadpay.com/ledger' && Math.abs(r1.ts - Date.now()) < 120000, 'row: soft key, device, placement (query dropped), ts', JSON.stringify(r1));
|
|
const ip = '127.0.0.1', ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) Mobile/15E148';
|
|
const sks = ['s:' + crypto.createHash('sha256').update(ip + '|' + ua).digest('hex').slice(0, 20), 's:' + crypto.createHash('sha256').update('::ffff:127.0.0.1|' + ua).digest('hex').slice(0, 20)];
|
|
ok(sks.includes(r1.sk), 'soft key = sha256(ip|ua) first 20 hex, no raw IP in the row', r1.sk);
|
|
ok(!JSON.stringify([...mock.clicks.values()]).includes('127.0.0.1'), 'no raw IP anywhere in the pushed rows');
|
|
ok(!mock.clicks.has('keepme') && [...mock.clicks.values()].filter(r => r.camp === 3).length === 1, 'the click on the lsclk target is still recorded (its own id), the URL untouched');
|
|
|
|
// 3. the owner's own click: still an id, flagged self, not counted as a click
|
|
const ck1 = await signIn(A1);
|
|
const before = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
|
|
const clicksBefore = ((before && before.campaigns) || []).find(c => c.id === 1);
|
|
const own = await click(1, { Cookie: ck1 }); const idOwn = (ID.exec(own.loc || '') || [])[1];
|
|
ok(!!idOwn, 'own click still gets a click id (so the owner can test)', own.loc);
|
|
ok(!!(await waitFor(() => mock.clicks.get(idOwn), 10000)) && mock.clicks.get(idOwn).self === 1, 'own click pushed with self=1', JSON.stringify(mock.clicks.get(idOwn)));
|
|
const after = (await api('/api/my/campaigns', null, { Cookie: ck1 })).j;
|
|
const clicksAfter = ((after && after.campaigns) || []).find(c => c.id === 1);
|
|
ok(clicksBefore && clicksAfter && clicksAfter.clicks === clicksBefore.clicks && clicksBefore.clicks === 2, 'own click not counted (clicks stay 2)', JSON.stringify([clicksBefore && clicksBefore.clicks, clicksAfter && clicksAfter.clicks]));
|
|
// fix 1 (2026-10-26): the soft keys the owner signs in from go to LinkSpin as owners; a click from that browser while
|
|
// signed out is flagged self for conversions (billing unchanged: it is still a counted click)
|
|
const skNode = ['127.0.0.1', '::ffff:127.0.0.1'].map(x => 's:' + crypto.createHash('sha256').update(x + '|node').digest('hex').slice(0, 20));
|
|
ok(!!(await waitFor(() => mock.owners.some(o => o.owner === A1 && skNode.includes(o.sk)), 10000)), "owner's session soft key pushed to LinkSpin as owners (no raw IP)", JSON.stringify(mock.owners));
|
|
ok(!JSON.stringify(mock.owners).includes('127.0.0.1'), 'no raw IP in the owners rows');
|
|
const ownSk = await click(1, { 'User-Agent': 'node' }); const idOwnSk = (ID.exec(ownSk.loc || '') || [])[1];
|
|
ok(!!(await waitFor(() => mock.clicks.get(idOwnSk), 10000)) && mock.clicks.get(idOwnSk).self === 1, "a click from the owner's own browser, signed out, is pushed self=1", JSON.stringify(mock.clicks.get(idOwnSk)));
|
|
const strangerC = await click(1, { 'User-Agent': 'Mozilla/5.0 Stranger QA' }); const idStr = (ID.exec(strangerC.loc || '') || [])[1];
|
|
ok(!!(await waitFor(() => mock.clicks.get(idStr), 10000)) && mock.clicks.get(idStr).self === 0, "a stranger's click is still self=0");
|
|
const nOwners = mock.owners.length; await api('/api/my/campaigns', null, { Cookie: ck1 }); await sleep(3500);
|
|
ok(mock.owners.length === nOwners, 'the same session soft key is not pushed again within 6 h');
|
|
|
|
// 4. proxies
|
|
const sum = await api('/api/my/conversions', null, { Cookie: ck1 });
|
|
ok(sum.j && sum.j.ok === true && sum.j.goals.length === 2 && sum.j.byCampaign['1'].conv[PX1] === 4, 'GET /api/my/conversions relays the LinkSpin summary', JSON.stringify(sum.j).slice(0, 200));
|
|
ok(sum.j && sum.j.spend30 && sum.j.spend30['1'] === 200 && sum.j.spend30['6'] == null && sum.j.spend30['7'] == null && sum.j.spendSince > Date.now() - 31 * 86400000, 'spend30 from the credit log: campaign 1 = 150 + 50 inside the 30 days (the 100 from 40 days ago and another member\'s row left out)', JSON.stringify(sum.j && sum.j.spend30));
|
|
const lastSum = mock.calls.filter(c => c.op === 'summary').pop();
|
|
ok(lastSum && lastSum.email === A1 && lastSum.days === 30, 'summary asked for the signed-in email, 30 days', JSON.stringify(lastSum));
|
|
const nSum = mock.calls.filter(c => c.op === 'summary').length; await api('/api/my/conversions', null, { Cookie: ck1 });
|
|
ok(mock.calls.filter(c => c.op === 'summary').length === nSum, 'summary cached (second call within 60 s does not hit LinkSpin)');
|
|
ok((await api('/api/my/conversions')).status === 401, 'signed out: 401');
|
|
const bad = await api('/api/my/conversions/goal', { op: 'create', name: ' ' }, { Cookie: ck1 });
|
|
ok(bad.status === 400, 'create without a name refused locally');
|
|
const cr = await api('/api/my/conversions/goal', { op: 'create', name: 'Free Report', value: '7.5' }, { Cookie: ck1 });
|
|
ok(cr.j && cr.j.ok && cr.j.goal && /^px[0-9a-f]{10}$/.test(cr.j.goal.px) && cr.j.goal.name === 'free-report' && cr.j.goal.value === 7.5, 'create relays op create (name normalized, value number)', JSON.stringify(cr.j));
|
|
const ts = await api('/api/my/conversions/test', { px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
|
|
ok(ts.j && ts.j.ok && ts.j.at, 'test relays op test', JSON.stringify(ts.j));
|
|
const rm = await api('/api/my/conversions/goal', { op: 'remove', px: cr.j && cr.j.goal && cr.j.goal.px }, { Cookie: ck1 });
|
|
ok(rm.j && rm.j.ok, 'remove relays op remove');
|
|
const rm2 = await api('/api/my/conversions/goal', { op: 'remove', px: 'px9999999999' }, { Cookie: ck1 });
|
|
ok(rm2.status === 400 && rm2.j && rm2.j.error === 'No such goal.', 'LinkSpin plain-words error passed through as 400', JSON.stringify(rm2));
|
|
ok(mock.calls.every(c => c.email === A1), 'every conv call carried only the signed-in email');
|
|
|
|
// 5. the Campaigns pane in a real browser
|
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
|
browser = await chromium.launch();
|
|
async function pane(cookie, shot) {
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
|
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
|
const [k, v] = cookie.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
|
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
|
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
|
|
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
|
|
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
|
|
const st = await page.evaluate(() => ({
|
|
rows: document.querySelectorAll('#campList .camp-table tbody tr').length,
|
|
line1: (document.querySelector('[data-convcamp="1"]') || {}).textContent || '', line1Hidden: !!(document.querySelector('[data-convcamp="1"]') || {}).hidden,
|
|
line5Hidden: (document.querySelector('[data-convcamp="5"]') || { hidden: true }).hidden,
|
|
line6: (document.querySelector('[data-convcamp="6"]') || {}).textContent || '', line7: (document.querySelector('[data-convcamp="7"]') || {}).textContent || '', title1: (document.querySelector('[data-convcamp="1"]') || {}).title || '',
|
|
card: !document.getElementById('convCard').hidden, status: document.getElementById('convStatus').textContent,
|
|
goals: document.querySelectorAll('#convGoals tbody tr').length, convCells: [...document.querySelectorAll('#convGoals td[data-l="Conversions (30 days)"]')].map(td => (td.firstChild && td.firstChild.textContent || '').trim()), landing: (document.getElementById('convLanding') || {}).value || '', img: (document.getElementById('convImg') || {}).value || '',
|
|
js: (document.getElementById('convJs') || {}).value || '', tip: document.getElementById('convCard').textContent }));
|
|
await page.screenshot({ path: path.join(OUT, shot), fullPage: true }).catch(() => {});
|
|
await ctx.close(); return { st, errs };
|
|
}
|
|
const p1 = await pane(ck1, 'convpixel-pane.png');
|
|
ok(p1.st.rows >= 4 && p1.st.card, 'Campaigns pane loads with the Conversion tracking card', JSON.stringify(p1.st).slice(0, 200));
|
|
ok(!p1.st.line1Hidden && /cost per goal \(30 days\)/.test(p1.st.line1) && /subscriber 4 \(50 credits each\)/.test(p1.st.line1) && /sale 1 \(200 credits each\)/.test(p1.st.line1), 'campaign row: cost per goal (30 days) = 200 credits spent in the 30 days / 4 = 50 (not lifetime 300 / 4 = 75)', p1.st.line1);
|
|
ok(/same 30 days/.test(p1.st.title1), 'its tooltip says the spend is the same 30 days', p1.st.title1);
|
|
ok(/subscriber 2/.test(p1.st.line6) && !/credits each/.test(p1.st.line6) && /no spend on record/.test(p1.st.line6), 'an older campaign with no spend in the log shows no cost per goal rather than a lifetime figure', p1.st.line6);
|
|
ok(/subscriber 3 \(30 credits each\)/.test(p1.st.line7), 'a campaign started inside the window with no log rows uses its spend since start (90 / 3 = 30)', p1.st.line7);
|
|
ok(/3 from your own clicks, kept as tests/.test(p1.st.status), 'card shows the own-click test count (selfTests from LinkSpin)', p1.st.status);
|
|
ok(!/\$/.test(p1.st.line1), 'cost per goal is in credits, never dollars');
|
|
ok(JSON.stringify(p1.st.convCells) === '["6","1"]', 'goal rows show the conversion count, not the 30-day window (convDays is the window length)', JSON.stringify(p1.st.convCells));
|
|
ok(p1.st.goals === 2 && p1.st.landing === '<script async src="https://linkspin.app/t.js?px=' + PX1 + '"></script>', 'goal list + landing tag snippet', p1.st.landing);
|
|
ok(p1.st.img === '<img src="https://linkspin.app/cv.gif?px=' + PX1 + '&goal=subscriber" width="1" height="1" alt="" style="display:none">' && p1.st.js === '<script async src="https://linkspin.app/cv.js?px=' + PX1 + '&goal=subscriber"></script>', 'goal pixel image + JS snippets match the contract', p1.st.img + ' | ' + p1.st.js);
|
|
ok(/Thank You Page: custom page/.test(p1.st.tip) && /Thank-you page: custom URL/.test(p1.st.tip) && /24-hour match/.test(p1.st.tip), 'autoresponder advice + match legend present');
|
|
ok(/url 2, stored 2, cookie 1, soft 1/.test(p1.st.status), 'match methods line', p1.st.status);
|
|
ok(!p1.errs.length, 'no page errors', p1.errs.join(' | '));
|
|
// fix 2 (2026-10-26): Send a test conversion loads the REAL pixel in test mode. The browser's request to linkspin.app is
|
|
// routed here (nothing leaves the machine): PX1 answers X-LS-Result: test like LinkSpin; PX2 answers unknown, so the
|
|
// card falls back to the signed partner call (op test).
|
|
{
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 1000 } });
|
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} });
|
|
const [k, v] = ck1.split(';')[0].split('='); await ctx.addCookies([{ name: k, value: v, url: B }]);
|
|
const pixelHits = [];
|
|
await ctx.route(/^https:\/\/linkspin\.app\/cv\.gif/, route => { const u = new URL(route.request().url()); pixelHits.push(u.search); const px = u.searchParams.get('px'); const g = (mock.goals[A1] || []).find(x => x.px === px);
|
|
const good = px === PX1 && u.searchParams.get('test') === '1' && g; if (good) g.lastTest = Date.now();
|
|
return route.fulfill({ status: 200, headers: { 'Content-Type': 'image/gif', 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'X-LS-Result', 'X-LS-Result': good ? 'test' : 'unknown' }, body: Buffer.from('R0lGODlhAQABAAAAACw=', 'base64') }); });
|
|
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
|
|
await page.goto(B + '/my', { waitUntil: 'domcontentloaded' }); await page.waitForTimeout(2500);
|
|
await page.evaluate(() => { document.querySelectorAll('.modal-back,.lgate,.iap-welcome').forEach(m => m.hidden = true); });
|
|
await page.click('.bo-menu [data-pane="campaigns"]'); await page.waitForTimeout(2500);
|
|
const testsBefore = mock.calls.filter(c => c.op === 'test').length;
|
|
await page.click('[data-convtest="' + PX1 + '"]'); await page.waitForTimeout(2000);
|
|
const msg1 = await page.evaluate(() => document.body.innerText);
|
|
const last1 = await page.evaluate(px => { const b = document.querySelector('[data-convtest="' + px + '"]'); const tr = b && b.closest('tr'); const td = tr && tr.querySelector('td[data-l="Last test"]'); return td ? td.textContent.trim() : ''; }, PX1);
|
|
ok(pixelHits.some(q => q.includes('px=' + PX1) && q.includes('test=1')), 'Send a test conversion loads the real pixel cv.gif?px=..&test=1 from the browser', JSON.stringify(pixelHits));
|
|
ok(/received by your real pixel/.test(msg1) && last1 && last1 !== 'never' && mock.calls.filter(c => c.op === 'test').length === testsBefore, 'pixel answered test: Last test updates, no partner fallback needed', last1);
|
|
await page.click('[data-convtest="' + PX2 + '"]'); await page.waitForTimeout(2000);
|
|
const msg2 = await page.evaluate(() => document.body.innerText);
|
|
const tcall = mock.calls.filter(c => c.op === 'test').pop();
|
|
ok(pixelHits.some(q => q.includes('px=' + PX2)) && tcall && tcall.px === PX2 && /recorded through InstantAdPay/.test(msg2), 'pixel did not confirm: falls back to the signed partner call (op test)', JSON.stringify(tcall));
|
|
ok(!errs.length, 'no page errors during the tests', errs.join(' | '));
|
|
await page.screenshot({ path: path.join(OUT, 'convpixel-test-button.png'), fullPage: true }).catch(() => {});
|
|
await ctx.close();
|
|
}
|
|
|
|
// 6. LinkSpin down: the pane still loads, the panel says so, campaign rows omit the goal line; clicks are kept and pushed later
|
|
mock.down = true;
|
|
const ck2 = await signIn(A2);
|
|
const down = await api('/api/my/conversions', null, { Cookie: ck2 });
|
|
ok(down.j && down.j.ok === false && down.j.reason === 'down' && /did not answer/.test(down.j.error), 'proxy says LinkSpin is down in plain words', JSON.stringify(down.j));
|
|
const p2 = await pane(ck2, 'convpixel-down.png');
|
|
ok(p2.st.rows >= 1 && p2.st.card && /did not answer/.test(p2.st.status) && p2.st.line5Hidden, 'LinkSpin down: Campaigns pane still loads, no goal line, panel explains', JSON.stringify(p2.st).slice(0, 220));
|
|
ok(!p2.errs.length, 'no page errors while LinkSpin is down', p2.errs.join(' | '));
|
|
const cd = await click(5); const idDown = (ID.exec(cd.loc || '') || [])[1];
|
|
ok(!!idDown, 'clicks still get ids while LinkSpin is down');
|
|
await sleep(4000);
|
|
ok(!mock.clicks.has(idDown), 'nothing marked pushed while LinkSpin refuses');
|
|
mock.down = false;
|
|
ok(!!(await waitFor(() => mock.clicks.has(idDown), 30000)), 'row kept and pushed once LinkSpin is back (retry with backoff)');
|
|
const adm = await api('/api/admin/lssync', null, { Authorization: 'Bearer ' + ADMIN });
|
|
ok(adm.j && adm.j.conv && adm.j.conv.on === true && adm.j.conv.pushed >= 5, 'admin lssync view carries conv push stats', JSON.stringify(adm.j && adm.j.conv));
|
|
} catch (e) { ok(false, 'run', e.stack); }
|
|
finally {
|
|
await cleanup();
|
|
fs.writeFileSync(path.join(OUT, 'convpixel-server.log'), srvLog);
|
|
console.log(fails ? fails + ' FAILED' : 'all passed');
|
|
process.exit(fails ? 1 : 0);
|
|
}
|