// Prepaid login-ad line (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line"). // node qa/login-queue.cjs // Store-level test of ads.js in JSON mode on a throwaway data dir (no server, no DB, no chain: a fake chain returns // made-up on-chain balances for made-up members). Nothing here can reach production or a real member. // Covers: fill 6 slots, a 7th buy is refused with the reserve offer, reserve 2 (balances drop at once, credit log lines), // places + estimated starts, one slot expires -> two concurrent promoters start the first reservation exactly once // (owner notified once, cap never exceeded), cancel the second -> full refund once, edit before start is free, // a freed slot goes to the line before a paused slot, paused-resume blocked while the line is non-empty, earned credits // never pay. Exit 1 on any failure. 'use strict'; delete process.env.DATABASE_URL; // JSON store, always const fs = require('fs'); const os = require('os'); const path = require('path'); const ads = require('../ads'); const DAY = 86400000; let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; }; const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-')); const onchain = {}; // memberId -> on-chain credits (fake) ads.init({ dataDir, chain: { creditBalance: async id => onchain[id] || 0 } }); ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 }); const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); }); const tick = () => new Promise(r => setTimeout(r, 30)); const M = n => ({ email: 'lq' + n + '@qa.test', id: 500 + n }); const avail = async n => (await ads.balances([M(n).id], M(n).email)).available; const buy = (n, extra) => ads.createCampaign(M(n).email, M(n).id, Object.assign({ type: 'login', name: 'QA login ' + n, targetUrl: 'https://example.com/' + n, budget: 1000 }, extra || {}), [M(n).id]); const row = async id => ads.campaignById(id); // JSON mode: the live row const live = async () => (await ads.adminLoginQueue()).used; (async () => { for (let n = 1; n <= 14; n++) onchain[M(n).id] = 5000; // 1. six slots fill and go live, each paid up front const slot = {}; for (let n = 1; n <= 6; n++) { const r = await buy(n); slot[n] = r.campaign && r.campaign.id; ok(r.ok && r.campaign.status === 'active', 'slot ' + n + ' of 6 goes live', JSON.stringify(r).slice(0, 160)); } ok(await avail(1) === 4000, 'a live slot drops the balance by 1,000', String(await avail(1))); // give the six slots distinct end dates: slot n ends in n days for (let n = 1; n <= 6; n++) (await row(slot[n])).expires = Date.now() + n * DAY; // 2. the seventh buy is refused with the reserve offer, nothing charged let r = await buy(7); ok(r.error && r.full === true && r.place === 1 && /reserve the next slot/i.test(r.error), 'all 6 taken: plain buy refused with a reserve offer (place #1)', JSON.stringify(r).slice(0, 220)); ok(await avail(7) === 5000, 'the refused buy charged nothing', String(await avail(7))); // 3. reserve two: paid now, status queued, no clock, credit log line const q7 = await buy(7, { reserve: true }), q8 = await buy(8, { reserve: true }); ok(q7.ok && q7.queued && q7.place === 1 && q7.campaign.status === 'queued', 'member 7 reserves: queued, place #1', JSON.stringify(q7).slice(0, 200)); ok(q8.ok && q8.queued && q8.place === 2, 'member 8 reserves: place #2', JSON.stringify(q8).slice(0, 120)); ok(await avail(7) === 4000 && await avail(8) === 4000, 'both balances dropped by 1,000 at reserve time', (await avail(7)) + ' / ' + (await avail(8))); const c7 = await row(q7.campaign.id); ok(c7.status === 'queued' && !c7.expires && !c7.starts && c7.queuedAt > 0 && (c7.spent + (c7.accrued || 0)) === 1000, 'a reservation has no start/end yet, a queuedAt stamp, and is fully charged', JSON.stringify({ s: c7.status, e: c7.expires, st: c7.starts, q: c7.queuedAt, spent: c7.spent, acc: c7.accrued })); const log7 = await ads.creditActivity(M(7).email); ok(log7.some(i => /^Login slot reserved \(queue #1\)/.test(i.note) && i.delta === -1000), 'credit log: "Login slot reserved (queue #1)" -1000', JSON.stringify(log7.map(i => i.note + ' ' + i.delta))); ok(await live() === 6, 'reservations do not count as live slots', String(await live())); ok(!(await ads.serve('login', {})) || ![q7.campaign.id, q8.campaign.id].includes((await ads.serve('login', {})).id), 'a reservation never serves'); { let served = new Set(); for (let i = 0; i < 60; i++) { const s = await ads.serve('login', {}); if (s) served.add(s.id); } ok(!served.has(q7.campaign.id) && !served.has(q8.campaign.id), 'sixty serves: never a queued ad', [...served].join(',')); } // 4. places and estimated starts: #1 when slot 1 ends (1 day), #2 when slot 2 ends (2 days), a new one at slot 3 (3 days) let A = await ads.adminLoginQueue(); const near = (a, b) => a && Math.abs(a - b) < 5000; ok(A.queue.length === 2 && A.queue[0].id === q7.campaign.id && A.queue[0].place === 1 && A.queue[1].place === 2, 'admin view: the line in paid order', JSON.stringify(A.queue.map(x => [x.id, x.place]))); ok(near(A.queue[0].estStart, (await row(slot[1])).expires) && near(A.queue[1].estStart, (await row(slot[2])).expires), 'estimated starts follow the live slots\' end dates', JSON.stringify(A.queue.map(x => x.estStart))); const V = await ads.loginQueueView(M(8).email); ok(V.free === 0 && V.nextPlace === 3 && near(V.nextEstStart, (await row(slot[3])).expires) && V.mine.length === 1 && V.mine[0].place === 2 && !JSON.stringify(V).includes(M(7).email), 'member view: own place #2, next place #3 at slot 3\'s end, nobody else\'s email', JSON.stringify(V).slice(0, 260)); // estimator alone: 6 slots ending day 1..6, 8 waiting -> the 7th starts when the first reservation's 30 days end { const now = 1e12; const e = ads.estimateStarts(6, [1, 2, 3, 4, 5, 6].map(d => now + d * DAY), 8, now, 30 * DAY); ok(e[0] === now + DAY && e[5] === now + 6 * DAY && e[6] === now + 31 * DAY && e[7] === now + 32 * DAY, 'estimator: a full round, then reservations wait on reservations', JSON.stringify(e.map(x => (x - now) / DAY))); } // 5. edit before the start: free, place unchanged const before = await avail(8); r = await ads.editLoginReservation(M(8).email, q8.campaign.id, { targetUrl: 'https://example.org/new', title: 'New headline' }); ok(r.ok && (await row(q8.campaign.id)).targetUrl === 'https://example.org/new' && await avail(8) === before, 'edit a reservation: saved, nothing charged', JSON.stringify(r).slice(0, 120)); r = await ads.editLoginReservation(M(7).email, q8.campaign.id, { targetUrl: 'https://evil.example' }); ok(r.error, 'another member cannot edit it', JSON.stringify(r)); r = await ads.setStatus(M(7).email, q7.campaign.id, 'paused'); ok(r.error && /waiting in line/.test(r.error), 'a reservation cannot be paused', JSON.stringify(r)); // 6. slot 1 expires -> two promoters at once: the first reservation starts exactly once (await row(slot[1])).expires = Date.now() - 1000; const [p1, p2] = await Promise.all([ads.promoteLoginQueue(), ads.promoteLoginQueue()]); await tick(); const started = [...p1.promoted, ...p2.promoted]; ok(started.length === 1 && started[0].id === q7.campaign.id, 'two concurrent promoters: exactly one start, the oldest paid', JSON.stringify([p1, p2]).slice(0, 200)); const s7 = await row(q7.campaign.id); ok(s7.status === 'active' && Math.abs(s7.starts - Date.now()) < 5000 && Math.abs(s7.expires - (s7.starts + 30 * DAY)) < 5 && s7.body === '30', 'the started ad: active, starts now, ends in 30 days', JSON.stringify({ st: s7.status, starts: s7.starts, expires: s7.expires })); ok(notified.length === 1 && notified[0] === q7.campaign.id, 'its owner is notified once', JSON.stringify(notified)); ok(await live() === 6, 'the cap holds: 6 live', String(await live())); r = await ads.promoteLoginQueue(); ok(!r.promoted.length, 'a third promoter finds nothing to do (slots full)'); ok(await avail(7) === 4000, 'starting charged nothing more', String(await avail(7))); // 7. cancel the second reservation: full refund, exactly once r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id); ok(r.ok && r.refunded === 1000, 'cancel before the start refunds the full 1,000', JSON.stringify(r)); ok(await avail(8) === 5000, 'member 8 balance back to 5,000', String(await avail(8))); const sp8 = await ads.earnedSplit(M(8).email); ok(sp8.grade === 1000, 'the refund is purchased-grade (same kind as paid)', JSON.stringify(sp8)); const log8 = await ads.creditActivity(M(8).email); ok(log8.some(i => /^Login slot reservation cancelled: refund/.test(i.note) && i.delta === 1000), 'credit log: "Login slot reservation cancelled: refund" +1000', JSON.stringify(log8.map(i => i.note + ' ' + i.delta))); r = await ads.cancelLoginReservation(M(8).email, q8.campaign.id); ok(r.error && await avail(8) === 5000, 'a second cancel refunds nothing', JSON.stringify(r)); r = await ads.cancelLoginReservation(M(7).email, q7.campaign.id); ok(r.error && /already started/.test(r.error) && await avail(7) === 4000, 'a started ad cannot be cancelled for a refund', JSON.stringify(r)); ok((await row(q8.campaign.id)).status === 'cancelled', 'cancelled stays cancelled'); r = await ads.archive(M(8).email, q8.campaign.id); ok(r.ok && r.freed === 0, 'a cancelled reservation can be archived, freeing 0', JSON.stringify(r)); // 8. a freed slot goes to the line before a paused slot const q9 = await buy(9, { reserve: true }); ok(q9.queued && q9.place === 1, 'member 9 reserves: place #1'); r = await ads.setStatus(M(2).email, slot[2], 'paused'); await tick(); ok(r.ok && (await row(q9.campaign.id)).status === 'active', 'pausing slot 2 hands its place to the line at once', (await row(q9.campaign.id)).status); ok(notified.includes(q9.campaign.id), 'member 9 notified'); r = await ads.setStatus(M(2).email, slot[2], 'active'); ok(r.error && /taken/.test(r.error), 'slot 2 cannot resume while all 6 are live', JSON.stringify(r)); // 9. paused-resume blocked while the line is non-empty, even with a slot free const q10 = await buy(10, { reserve: true }); (await row(slot[3])).expires = Date.now() - 1000; // slot 3 ends; no tick yet: 5 live, 1 waiting ok(await live() === 5, 'slot 3 ended: 5 live, 1 waiting', String(await live())); r = await ads.setStatus(M(2).email, slot[2], 'active'); ok(r.error && /line goes first/.test(r.error) && (await row(slot[2])).status === 'paused', 'resume refused while the line is non-empty (the line goes first)', JSON.stringify(r)); r = await buy(11); // a new plain buy also respects the line: the freed slot went to member 10, member 11 is offered a reservation ok((await row(q10.campaign.id)).status === 'active', 'a new buy first starts the waiting reservation (member 10 live)', (await row(q10.campaign.id)).status); ok(r.error && r.full === true, 'and member 11 is offered the line, not the slot', JSON.stringify(r).slice(0, 160)); ok(await live() === 6, 'still 6 live', String(await live())); // 10. with nobody waiting and a slot open, the paused slot resumes (await row(slot[4])).expires = Date.now() - 1000; r = await ads.setStatus(M(2).email, slot[2], 'active'); ok(r.ok && (await row(slot[2])).status === 'active' && await live() === 6, 'slot open and nobody waiting: the paused slot resumes', JSON.stringify(r).slice(0, 120)); // 11. earned (viewing) credits never pay for a reservation await ads.addEarned(M(12).email, 5000); onchain[M(12).id] = 0; r = await buy(12, { reserve: true }); ok(r.error && /purchased credits only/.test(r.error), 'earned credits cannot buy a reservation', JSON.stringify(r).slice(0, 160)); ok((await ads.adminLoginQueue()).queue.length === 0, 'nothing was queued for it'); // 12. admin cancel refunds the owner in full const q13 = await buy(13, { reserve: true }); r = await ads.cancelLoginReservation(null, q13.campaign.id, { admin: true }); ok(r.ok && r.refunded === 1000 && await avail(13) === 5000, 'admin cancel: full refund to the owner', JSON.stringify(r)); fs.rmSync(dataDir, { recursive: true, force: true }); console.log(fails ? fails + ' FAILED' : 'ALL PASS'); process.exit(fails ? 1 : 0); })().catch(e => { console.error(e); process.exit(1); });