89b5969b25
- ads.js: a login buy with every slot taken returns full:true and a reserve offer; with reserve:true it is charged the full slot price at once (purchased credits only, credit log 'Login slot reserved (queue #N)') and stored with status 'queued' + queuedAt, no starts/expires, never served or counted as a slot. First paid, first served. - Promotion (promoteLoginQueue): on a slot expiring (scheduleSweep), a member pausing a slot, every new login buy, and a one-minute tick. The oldest reservation becomes active, starts now, ends in 30 days; the owner gets an on-site notice (kind 'notice') and an email unless unsubscribed. - Deploy-overlap safety: the cap decision runs under a lease row in the new app_locks table (one conditional UPDATE takes it, an expired lease can be taken over); every start/cancel/edit is a conditional UPDATE on status='queued', so a reservation starts at most once and a cancel racing a start has exactly one winner. Live login buys and paused-slot resumes also take the lease, so the cap holds for them too. - A freed slot goes to the line first: a paused slot resumes only while live + queued < loginSlotsMax, with a plain message saying the line is ahead. - Cancel before the start: full refund as purchased-grade credits (credit log 'Login slot reservation cancelled: refund'), once. Edit target/image/headline before the start, free. Cancelled reservations can be archived. - Estimated start per place from the live slots' end dates and the reservations ahead, shown in Central time and labelled an estimate. - db.js: campaigns.queued_at BIGINT NULL, app_locks table + 'login_queue' row, all added on boot. - server.js: loginLine in GET /api/my/campaigns, POST /api/my/campaigns/:id/cancel-reservation and /edit-reservation (safe-browsing, reach and image checks), GET /api/admin/login-queue, POST /api/admin/login-queue/:id/cancel, the promotion notice hook and the one-minute tick. - Member UI (my.js, my.html): open slots or the line with place and estimated start on the Login ad form, the button becomes "Reserve the next slot", IAP.confirmBox before paying, In line #N + estimated start in the list, Edit and Cancel and refund. Admin (admin.js, admin.html): Login-ad line card with owner, queued at, place, estimated start, cancel + refund. Tags bumped to 20261023lq. - chatbot.js: new canned 'login-ads' answer and the LOGIN ADS fact updated (6 slots, the paid line, cancel = full refund before start). The knowledge base seeds the new entry on boot. - audit.js: queued/cancelled reservations are not per-day login campaigns. - QA: qa/login-queue.cjs (JSON store end to end) and qa/login-queue-sql.cjs (SQL path guard logic against a fake SQL layer), bash qa/run.sh login-queue. qa/login-slot.mjs pattern follows the refactor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
132 lines
12 KiB
JavaScript
132 lines
12 KiB
JavaScript
// 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); });
|