1c2ef3780c
When all member login slots are taken the Ads screen offers "Reserve the next slot" instead of a dead button. Same price and checks as a slot (purchased credits only), paid at reserve time; the campaign is 'queued' with queuedAt, never serves and has no 30-day clock. First paid, first served: the member sees their place and an estimated start (Central time, labelled an estimate) built from the live slots' end dates and the line ahead. A freed slot (ended, paused, or found by the new 1-minute tick) goes to the oldest reservation: starts now, expires now + 30 days, never more than loginSlotsMax live. Idempotent across the deploy overlap: JSON mode takes a lock file and records every promotion/cancel in DATA_DIR/login-queue.json, re-read before any change; MySQL mode uses guarded UPDATEs (status + live count in one statement). Owner gets an on-site notice and an email (unsubscribes respected). A paused slot resumes only when live + queued < max. Cancel before start = full refund (credited back as purchased credits; any unburned accrual released). Edits while queued are free and keep the free correction. Admin: Login-ad queue card with cancel + refund, plus the Member content action. New credit activity log (credit-log.json / credit_log table): reserved (queue #N), bought, started, refunds, shown on the Ads screen. Audit skips queued/cancelled login rows. Chatbot CANNED + FACTS updated (6 slots, paid queue, full refund before start). Tags bumped: ads-screen.js, admin.js, my.js 20261023q. Tests: qa/loginqueue.test.cjs (two app copies promoting at once) + qa/loginqueue.e2e.mjs; bash qa/run.sh loginqueue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
15 KiB
JavaScript
176 lines
15 KiB
JavaScript
// Prepaid login-slot queue, end to end over HTTP (2026-10-23). Boots server.js on its own port with a throwaway, seeded
|
|
// data dir (JSON store, no DB, no mail, devCode sign-in, NAS off, no chain: free members whose credits are credited
|
|
// purchased ones), then: six slots full; a buy without reserve is refused with the offer; two members reserve and pay;
|
|
// place, estimate and credit activity on GET; balances drop; free edit; admin sees the line and cancels one with a full
|
|
// refund; a running slot is paused and the first reservation starts at once (on-site notice); the paused slot cannot
|
|
// come back while the line holds the slots; the Ads screen in Playwright (Reserve button, In line row, no page errors).
|
|
// node qa/loginqueue.e2e.mjs (from the site dir)
|
|
// Env: PORT (default 8971), PW (playwright package dir), SHOTS (default D:/tmp/login-queue)
|
|
import { pathToFileURL } from 'node:url';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import http from 'node:http';
|
|
import crypto from 'node:crypto';
|
|
import { spawn } from 'node:child_process';
|
|
|
|
const PORT = Number(process.env.PORT || 8971);
|
|
const SHOTS = process.env.SHOTS || 'D:/tmp/login-queue';
|
|
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
|
const ADMIN_PW = 'localtest-lq';
|
|
const results = []; let failed = 0;
|
|
const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; };
|
|
const DAY = 86400000, now = Date.now();
|
|
|
|
// ── seed: six filler owners with a live slot each (ends on day 1..6), and two members A and B with 2,000 credited purchased credits ──
|
|
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lq-e2e-'));
|
|
fs.mkdirSync(path.join(DATA, 'uploads'));
|
|
const em = n => n + '@lq.test';
|
|
const names = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'a', 'b'];
|
|
const accounts = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: names.length, positions: {} };
|
|
for (const n of names) { accounts.byEmail[em(n)] = { email: em(n), username: 'lq' + n, code: 'lq' + n, memberId: 0, created: now - DAY, sponsorRef: '' }; accounts.byCode['lq' + n] = em(n); }
|
|
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
|
|
const earned = {}; for (const n of names) earned[em(n)] = { balance: n.startsWith('f') ? 0 : 2000, grade: n.startsWith('f') ? 0 : 2000, welcomed: true };
|
|
fs.writeFileSync(path.join(DATA, 'earned.json'), JSON.stringify(earned));
|
|
fs.writeFileSync(path.join(DATA, 'adrates.json'), JSON.stringify({ loginSlotsMax: 6 }));
|
|
const camps = [1, 2, 3, 4, 5, 6].map(i => ({ id: i, owner: em('f' + i), memberId: 0, type: 'login', name: 'Filler ' + i, targetUrl: 'https://example.com/f' + i, imageUrl: null, title: null, body: '30',
|
|
budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batchImps: 0, status: 'active', created: now - 29 * DAY, expires: now + i * DAY }));
|
|
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 7, burnsPending: [], campaigns: camps }));
|
|
fs.mkdirSync(SHOTS, { recursive: true });
|
|
|
|
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
|
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@lq.test' });
|
|
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'ENGINE_KEY_FILE', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_KEY', 'SENDGRID_API_KEY']) delete env[k];
|
|
const log = fs.createWriteStream(path.join(SHOTS, 'server.log'));
|
|
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
srv.stdout.pipe(log); srv.stderr.pipe(log);
|
|
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
function req(method, p, o) {
|
|
o = o || {};
|
|
return new Promise((resolve, reject) => {
|
|
const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) QA' }, o.headers || {});
|
|
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip;
|
|
let body = o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; }
|
|
if (body) headers['Content-Length'] = body.length;
|
|
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, buf, json: j }); }); });
|
|
r.on('error', reject); if (body) r.write(body); r.end();
|
|
});
|
|
}
|
|
async function signIn(email) {
|
|
const ip = '10.9.' + crypto.randomInt(250) + '.' + crypto.randomInt(250);
|
|
const s = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } });
|
|
if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.buf.toString().slice(0, 200));
|
|
const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: s.json.devCode } });
|
|
const sc = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
|
|
if (!sc) throw new Error('no session cookie for ' + email);
|
|
return sc;
|
|
}
|
|
const err = r => (r.json && r.json.error) || ('HTTP ' + r.status);
|
|
const ADMIN = { Authorization: 'Bearer ' + ADMIN_PW };
|
|
const loginBody = (name, extra) => Object.assign({ type: 'login', name, targetUrl: 'https://example.com/' + name.toLowerCase().replace(/\W+/g, '-'), budget: 1000 }, extra || {});
|
|
|
|
let browser = null; const pageErrors = [];
|
|
try {
|
|
for (let i = 0; i < 40; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) break; } catch (e) {} await sleep(500); }
|
|
const cA = await signIn(em('a')), cB = await signIn(em('b')), cF1 = await signIn(em('f1'));
|
|
const camps = async c => (await req('GET', '/api/my/campaigns', { cookie: c })).json;
|
|
|
|
const g0 = await camps(cA);
|
|
check(g0.loginSlots && g0.loginSlots.max === 6 && g0.loginSlots.used === 6 && g0.loginSlots.free === 0, 'six slots live, none free', JSON.stringify(g0.loginSlots));
|
|
check(g0.loginNext && g0.loginNext.place === 1 && /\d{4}$/.test(g0.loginNext.estStartCt || ''), 'a new reservation would be #1 with an estimated date', JSON.stringify(g0.loginNext));
|
|
const avA0 = g0.availableCredits;
|
|
|
|
const no = await req('POST', '/api/my/campaigns', { cookie: cA, body: loginBody('A slot') });
|
|
check(no.status === 400 && no.json.canReserve === true && /reserve the next slot/i.test(err(no)), 'buy without reserve: refused with the reserve offer', err(no));
|
|
check((await camps(cA)).availableCredits === avA0, 'the refused buy charged nothing', String(avA0));
|
|
|
|
const ra = await req('POST', '/api/my/campaigns', { cookie: cA, body: loginBody('A slot', { reserve: true }) });
|
|
check(ra.status === 200 && ra.json.campaign.status === 'queued' && ra.json.campaign.place === 1, 'A reserves: queued, #1', err(ra) + ' ' + JSON.stringify(ra.json && ra.json.campaign && { s: ra.json.campaign.status, p: ra.json.campaign.place }));
|
|
const rb = await req('POST', '/api/my/campaigns', { cookie: cB, body: loginBody('B slot', { reserve: true }) });
|
|
check(rb.status === 200 && rb.json.campaign.status === 'queued' && rb.json.campaign.place === 2, 'B reserves: queued, #2', err(rb));
|
|
const QA = ra.json.campaign.id, QB = rb.json.campaign.id;
|
|
|
|
const g1 = await camps(cA), gb1 = await camps(cB);
|
|
check(g1.availableCredits === avA0 - 1000, 'A paid now: available down by 1,000', avA0 + ' -> ' + g1.availableCredits);
|
|
check(gb1.availableCredits === 1000, 'B paid now: available 2,000 -> 1,000', String(gb1.availableCredits));
|
|
check(g1.loginQueue.length === 1 && g1.loginQueue[0].id === QA && g1.loginQueue[0].place === 1 && g1.loginQueue[0].estStart === now + DAY, 'A sees place #1, estimate = when slot 1 ends', JSON.stringify(g1.loginQueue));
|
|
check(gb1.loginQueue[0].place === 2 && gb1.loginQueue[0].estStart === now + 2 * DAY && /^[A-Z][a-z]{2} \d{1,2}, \d{4}$/.test(gb1.loginQueue[0].estStartCt), 'B sees place #2, estimate = when slot 2 ends (Central date)', JSON.stringify(gb1.loginQueue));
|
|
check(g1.creditLog[0] && g1.creditLog[0].reason === 'Login slot reserved (queue #1)' && g1.creditLog[0].delta === -1000, 'credit activity: Login slot reserved (queue #1)', JSON.stringify(g1.creditLog));
|
|
check(gb1.creditLog[0] && gb1.creditLog[0].reason === 'Login slot reserved (queue #2)', 'credit activity: Login slot reserved (queue #2)', JSON.stringify(gb1.creditLog));
|
|
check(g1.loginSlots.queued === 2 && g1.loginSlots.free === 0 && g1.loginNext.place === 3, 'the line is 2 long; next would be #3', JSON.stringify([g1.loginSlots, g1.loginNext]));
|
|
|
|
const ed = await req('POST', '/api/my/campaigns/' + QA + '/edit', { cookie: cA, body: { targetUrl: 'https://example.com/a-fixed' } });
|
|
check(ed.status === 200 && ed.json.fee === 0 && ed.json.campaign.edits === 0, 'edit while queued: free, free correction kept', err(ed));
|
|
const ps = await req('POST', '/api/my/campaigns/' + QA + '/resume', { cookie: cA });
|
|
check(ps.status === 400 && /in line/.test(err(ps)), 'a reservation cannot be resumed into a slot by hand', err(ps));
|
|
|
|
const aq = await req('GET', '/api/admin/login-queue', { headers: ADMIN });
|
|
check(aq.status === 200 && aq.json.queue.map(x => x.id).join() === QA + ',' + QB && aq.json.slots.used === 6, 'admin sees the line in order', JSON.stringify(aq.json && aq.json.queue.map(x => [x.id, x.place])));
|
|
check((await req('GET', '/api/admin/login-queue')).status === 401, 'admin queue needs admin');
|
|
const ac = await req('POST', '/api/admin/campaigns/' + QB + '/cancel-reservation', { headers: ADMIN });
|
|
check(ac.status === 200 && ac.json.refunded === 1000, 'admin cancels B: 1,000 refunded', err(ac));
|
|
const gb2 = await camps(cB);
|
|
check(gb2.availableCredits === 2000 && gb2.campaigns.find(c => c.id === QB).status === 'cancelled', 'B back to 2,000 available, ad cancelled', String(gb2.availableCredits));
|
|
check(/Login slot reservation cancelled: refund/.test(gb2.creditLog[0].reason) && gb2.creditLog[0].delta === 1000, 'credit activity: the refund line', JSON.stringify(gb2.creditLog[0]));
|
|
const ac2 = await req('POST', '/api/my/campaigns/' + QB + '/cancel-reservation', { cookie: cB });
|
|
check(ac2.status === 400 && (await camps(cB)).availableCredits === 2000, 'a second cancel refunds nothing', err(ac2));
|
|
|
|
// B reserves again (back of the line, #2), then f1 pauses: A starts at once, B moves to #1
|
|
const rb2 = await req('POST', '/api/my/campaigns', { cookie: cB, body: loginBody('B again', { reserve: true }) });
|
|
check(rb2.status === 200 && rb2.json.campaign.place === 2, 'B reserves again at the back (#2)', err(rb2));
|
|
const pz = await req('POST', '/api/my/campaigns/1/pause', { cookie: cF1 });
|
|
check(pz.status === 200, 'f1 pauses its running slot', err(pz));
|
|
const g2 = await camps(cA); const a2 = g2.campaigns.find(c => c.id === QA);
|
|
check(a2.status === 'active' && a2.promotedAt && Math.abs(a2.expires - a2.promotedAt - 30 * DAY) < 5, 'A started right away, 30 days from now', JSON.stringify({ s: a2.status, p: a2.promotedAt, e: a2.expires }));
|
|
check(g2.availableCredits === avA0 - 1000, 'starting charged A nothing more', String(g2.availableCredits));
|
|
const msgs = (await req('GET', '/api/my/messages', { cookie: cA })).json;
|
|
check(msgs.items.some(m => /Your login ad is live/.test(m.subject || '')), 'A got the on-site notice', JSON.stringify(msgs.items.map(m => m.subject)));
|
|
const gb3 = await camps(cB);
|
|
check(gb3.loginQueue[0] && gb3.loginQueue[0].place === 1, 'B moved up to #1', JSON.stringify(gb3.loginQueue));
|
|
const rs = await req('POST', '/api/my/campaigns/1/resume', { cookie: cF1 });
|
|
check(rs.status === 400 && /reservation/.test(err(rs)), 'f1 cannot resume while the line holds the slots', err(rs));
|
|
|
|
// ── the Ads screen ──
|
|
try {
|
|
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
|
browser = await chromium.launch();
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
|
await ctx.addCookies(cB.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
|
await ctx.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} }); // the login-sponsor interstitial already ran this session
|
|
const page = await ctx.newPage();
|
|
page.on('pageerror', e => pageErrors.push(e.message));
|
|
page.on('console', m => { if (m.type() === 'error' && !/favicon|Failed to load resource/.test(m.text())) pageErrors.push('console: ' + m.text()); });
|
|
await page.goto('http://127.0.0.1:' + PORT + '/ads', { waitUntil: 'networkidle' });
|
|
try { await page.waitForSelector('#rows .rw', { timeout: 10000 }); } catch (e) { await page.screenshot({ path: path.join(SHOTS, 'ads-fail.png'), fullPage: true }); throw new Error(String(e.message).slice(0, 80) + ' :: page: ' + (await page.locator('body').innerText()).split(/\s+/).join(' ').slice(0, 300) + ' :: errors: ' + pageErrors.join(' / ')); }
|
|
const rowText = await page.locator('#rows').textContent();
|
|
check(/In line/.test(rowText) && /#1 in line/.test(rowText) && /Cancel and refund/.test(rowText), 'Ads screen row: In line, #1, Cancel and refund', rowText.replace(/\s+/g, ' ').slice(0, 300));
|
|
check(/Cancelled, refunded/.test(rowText), 'Ads screen row: the cancelled one shows refunded', '');
|
|
const cl = await page.locator('#creditLog').textContent();
|
|
check(/Login slot reserved \(queue #2\)/.test(cl) && /cancelled: refund/.test(cl), 'Credit activity panel lists the reserve and the refund', cl.replace(/\s+/g, ' ').slice(0, 200));
|
|
await page.click('#newBtn'); await page.click('#typeChips .chip[data-t="login"]');
|
|
const btn = await page.locator('#fGo').textContent(), dis = await page.locator('#fGo').isDisabled(), costTxt = await page.locator('#fCost').textContent();
|
|
check(btn === 'Reserve the next slot' && !dis, 'composer: Reserve the next slot (enabled, not a dead button)', btn + ' disabled=' + dis);
|
|
check(/#2 in line/.test(costTxt) && /estimate/i.test(costTxt) && /full refund/.test(costTxt), 'composer says place, estimate and refund rule', costTxt);
|
|
await page.screenshot({ path: path.join(SHOTS, 'ads-reserve.png'), fullPage: true });
|
|
await page.fill('#fName', 'B third'); await page.fill('#fTarget', 'https://example.com/b-third');
|
|
await page.click('#fGo');
|
|
await page.waitForSelector('#crModalHost .modal', { timeout: 5000 });
|
|
const dlg = await page.locator('#crModalHost .modal').textContent();
|
|
check(/Reserve the next login-ad slot/.test(dlg) && /full refund/.test(dlg) && /estimate/i.test(dlg), 'reserve asks first, in an in-page dialog', dlg.replace(/\s+/g, ' ').slice(0, 260));
|
|
await page.screenshot({ path: path.join(SHOTS, 'ads-reserve-dialog.png') });
|
|
await page.click('#dlgNo'); // do not reserve a third
|
|
check(!/\u2014/.test(rowText + costTxt + dlg), 'no em dashes in the new copy');
|
|
check(!pageErrors.length, 'no page errors', pageErrors.join(' | '));
|
|
} catch (e) { check(false, 'Playwright pass ran', e.message); }
|
|
} catch (e) {
|
|
check(false, 'run completed', e.stack || e.message);
|
|
} finally {
|
|
if (browser) await browser.close().catch(() => {});
|
|
srv.kill();
|
|
await sleep(300);
|
|
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
|
}
|
|
console.log(results.join('\n'));
|
|
console.log('\n' + (results.length - failed) + ' passed, ' + failed + ' failed (screenshots + server log in ' + SHOTS + ')');
|
|
process.exit(failed ? 1 : 0);
|