Prepaid login-ad line: when all member slots are taken, members pay now to reserve the next one (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line")
- 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>
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
// Prepaid login-ad line, MySQL code path (2026-10-23).
|
||||
// node qa/login-queue-sql.cjs
|
||||
// There is no MySQL on the test machine, so this swaps db.js for an in-memory fake that understands exactly the SQL the
|
||||
// line uses and runs each statement atomically after a random 0-3 ms wait, so concurrent callers interleave BETWEEN
|
||||
// statements the way two app copies do during a deploy overlap. That tests the guard logic of the SQL path (the
|
||||
// app_locks lease and the conditional UPDATE ... WHERE status='queued'), not MySQL itself: real InnoDB locking, the
|
||||
// schema migration and mysql2's affectedRows semantics are not exercised here. Unknown SQL throws, so a statement
|
||||
// this fake does not model fails the test instead of passing silently. Exit 1 on failure.
|
||||
'use strict';
|
||||
const path = require('path');
|
||||
const DAY = 86400000;
|
||||
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
|
||||
|
||||
// ---- the fake ----
|
||||
const T = { campaigns: [], locks: {}, earned: {}, log: [] }; let nextId = 1;
|
||||
const wait = () => new Promise(r => setTimeout(r, Math.floor(Math.random() * 4)));
|
||||
const norm = s => String(s).replace(/\s+/g, ' ').trim();
|
||||
const liveRows = now => T.campaigns.filter(c => c.type === 'login' && c.status === 'active' && c.house === 0 && (c.expires == null || c.expires > now));
|
||||
async function q(sql, p) {
|
||||
await wait();
|
||||
const s = norm(sql); p = p || [];
|
||||
let m;
|
||||
if (s.startsWith('INSERT IGNORE INTO app_locks')) { if (!T.locks[p[0]]) T.locks[p[0]] = { holder: null, until: 0 }; return { affectedRows: 1 }; }
|
||||
if (s === 'UPDATE app_locks SET holder=?, lease_until=? WHERE name=? AND (holder IS NULL OR lease_until<?)') {
|
||||
const L = T.locks[p[2]]; if (L && (L.holder === null || L.until < p[3])) { L.holder = p[0]; L.until = p[1]; return { affectedRows: 1 }; } return { affectedRows: 0 };
|
||||
}
|
||||
if (s === 'UPDATE app_locks SET holder=NULL, lease_until=0 WHERE name=? AND holder=?') {
|
||||
const L = T.locks[p[0]]; if (L && L.holder === p[1]) { L.holder = null; L.until = 0; return { affectedRows: 1 }; } return { affectedRows: 0 };
|
||||
}
|
||||
if (s === "SELECT COUNT(*) n FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return [{ n: liveRows(p[0]).length }];
|
||||
if (s === "SELECT expires FROM campaigns WHERE type='login' AND status='active' AND house=0 AND (expires IS NULL OR expires>?)") return liveRows(p[0]).map(c => ({ expires: c.expires }));
|
||||
if ((m = /^SELECT \* FROM campaigns WHERE type='login' AND status='queued' AND house=0 ORDER BY queued_at ASC, id ASC( LIMIT (\d+))?$/.exec(s))) {
|
||||
const rows = T.campaigns.filter(c => c.type === 'login' && c.status === 'queued' && c.house === 0).sort((a, b) => (a.queued_at - b.queued_at) || (a.id - b.id));
|
||||
return (m[2] ? rows.slice(0, Number(m[2])) : rows).map(c => Object.assign({}, c));
|
||||
}
|
||||
if (s === "UPDATE campaigns SET status='active', starts=?, expires=?, body=? WHERE id=? AND type='login' AND status='queued'") {
|
||||
const c = T.campaigns.find(x => x.id === p[3] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
|
||||
c.status = 'active'; c.starts = p[0]; c.expires = p[1]; c.body = p[2]; return { affectedRows: 1 };
|
||||
}
|
||||
if (s === "UPDATE campaigns SET status='cancelled' WHERE id=? AND type='login' AND status='queued'") {
|
||||
const c = T.campaigns.find(x => x.id === p[0] && x.type === 'login' && x.status === 'queued'); if (!c) return { affectedRows: 0 };
|
||||
c.status = 'cancelled'; return { affectedRows: 1 };
|
||||
}
|
||||
if (s === 'SELECT * FROM campaigns WHERE id=?') return T.campaigns.filter(c => c.id === p[0]).map(c => Object.assign({}, c));
|
||||
if (s === 'SELECT * FROM campaigns WHERE owner_email=? ORDER BY id DESC') return T.campaigns.filter(c => c.owner_email === p[0]).sort((a, b) => b.id - a.id).map(c => Object.assign({}, c));
|
||||
if (s === 'UPDATE campaigns SET status=? WHERE id=? AND owner_email=?') { const c = T.campaigns.find(x => x.id === p[1] && x.owner_email === p[2]); if (!c) return { affectedRows: 0 }; c.status = p[0]; return { affectedRows: 1 }; }
|
||||
if (s.startsWith('INSERT INTO earned_credits (email,balance,purchase_grade,granted_welcome,updated)')) {
|
||||
const e = T.earned[p[0]] = T.earned[p[0]] || { balance: 0, grade: 0 }; e.balance += p[1]; e.grade += p[2]; return { affectedRows: 1 };
|
||||
}
|
||||
if (s.startsWith('INSERT INTO credit_log')) { T.log.push({ email: p[0], delta: p[3], kind: p[4], note: p[5], ref: p[6] }); return { affectedRows: 1 }; }
|
||||
throw new Error('fake db: unmodelled SQL: ' + s);
|
||||
}
|
||||
const fake = { enabled: () => true, q, init: async () => true };
|
||||
const dbPath = require.resolve(path.join(__dirname, '..', 'db.js'));
|
||||
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: fake };
|
||||
const fs = require('fs'); const os = require('os');
|
||||
const ads = require('../ads');
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-loginq-sql-'));
|
||||
ads.init({ dataDir, chain: { creditBalance: async () => 0 } });
|
||||
ads.setRates({ loginSlotsMax: 6, loginSlotCredits: 1000, loginSlotDays: 30 });
|
||||
const notified = []; ads.onLoginPromoted(async c => { notified.push(c.id); });
|
||||
|
||||
const row = (o) => { const c = Object.assign({ id: nextId++, owner_email: 'x@qa.test', member_id: 1, house: 0, type: 'login', name: 'QA', target_url: 'https://example.com', image_url: null, title: null, body: '30', budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batch_imps: 0, status: 'active', created: Date.now(), expires: Date.now() + 10 * DAY, starts: Date.now(), queued_at: null }, o); T.campaigns.push(c); return c; };
|
||||
const reset = () => { T.campaigns = []; T.locks = {}; T.earned = {}; T.log = []; notified.length = 0; };
|
||||
const live = () => liveRows(Date.now()).length;
|
||||
const tick = () => new Promise(r => setTimeout(r, 30));
|
||||
|
||||
(async () => {
|
||||
// 1. one slot frees, two queued, five promoters at once: exactly one start, the oldest
|
||||
for (let round = 0; round < 25; round++) {
|
||||
reset();
|
||||
const slots = []; for (let i = 0; i < 6; i++) slots.push(row({ owner_email: 's' + i + '@qa.test', expires: Date.now() + (i + 1) * DAY }));
|
||||
const a = row({ owner_email: 'a@qa.test', status: 'queued', queued_at: 1000, expires: null, starts: null });
|
||||
const b = row({ owner_email: 'b@qa.test', status: 'queued', queued_at: 2000, expires: null, starts: null });
|
||||
slots[0].expires = Date.now() - 1000;
|
||||
const res = await Promise.all([1, 2, 3, 4, 5].map(() => ads.promoteLoginQueue()));
|
||||
await tick();
|
||||
const started = res.flatMap(r => r.promoted.map(c => c.id));
|
||||
const good = started.length === 1 && started[0] === a.id && a.status === 'active' && b.status === 'queued' && live() === 6 && notified.length === 1 && T.locks.login_queue.holder === null;
|
||||
if (!good || round === 24) ok(good, 'round ' + (round + 1) + '/25: five concurrent promoters, one free slot -> exactly one start (the oldest), 6 live, one notice, lock released', JSON.stringify({ started, a: a.status, b: b.status, live: live(), notified, lock: T.locks.login_queue }));
|
||||
if (!good) break;
|
||||
}
|
||||
// 2. two free slots, three queued, concurrent promoters: exactly two start, the two oldest, never over the cap
|
||||
{
|
||||
reset();
|
||||
for (let i = 0; i < 4; i++) row({});
|
||||
const q = [3000, 1000, 2000].map(t => row({ status: 'queued', queued_at: t, expires: null, starts: null }));
|
||||
const res = await Promise.all([1, 2, 3].map(() => ads.promoteLoginQueue()));
|
||||
const started = res.flatMap(r => r.promoted.map(c => c.id)).sort();
|
||||
ok(started.length === 2 && started.join() === [q[1].id, q[2].id].sort().join() && q[0].status === 'queued' && live() === 6, 'two slots free: the two oldest start, the third waits, cap 6', JSON.stringify({ started, live: live() }));
|
||||
}
|
||||
// 3. a cancel racing a start: exactly one wins, the refund is paid only if the cancel won
|
||||
{
|
||||
let bad = 0;
|
||||
for (let round = 0; round < 40; round++) {
|
||||
reset();
|
||||
for (let i = 0; i < 5; i++) row({});
|
||||
const a = row({ owner_email: 'race@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||
const [cn, pr] = await Promise.all([ads.cancelLoginReservation('race@qa.test', a.id), ads.promoteLoginQueue()]);
|
||||
const refunded = (T.earned['race@qa.test'] || { balance: 0 }).balance;
|
||||
const cancelWon = !!cn.ok, startWon = pr.promoted.length === 1;
|
||||
if (cancelWon === startWon || (cancelWon && (a.status !== 'cancelled' || refunded !== 1000)) || (startWon && (a.status !== 'active' || refunded !== 0))) bad++;
|
||||
}
|
||||
ok(bad === 0, '40 rounds of cancel vs start on the same reservation: always exactly one winner, refund only when the cancel won', bad + ' bad rounds');
|
||||
}
|
||||
// 4. a lease held by the other app copy: the tick backs off; an expired lease is taken over
|
||||
{
|
||||
reset();
|
||||
for (let i = 0; i < 5; i++) row({});
|
||||
const a = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 10000 };
|
||||
let r = await ads.promoteLoginQueue();
|
||||
ok(r.busy === true && !r.promoted.length && a.status === 'queued' && T.locks.login_queue.holder === 'other-copy', 'lease held by the other copy: no start, the tick backs off, the lease is untouched', JSON.stringify(r));
|
||||
T.locks.login_queue.until = Date.now() - 1; // that copy died holding it
|
||||
r = await ads.promoteLoginQueue();
|
||||
ok(r.promoted.length === 1 && a.status === 'active' && T.locks.login_queue.holder === null, 'an expired lease is taken over, the reservation starts, the lease is released', JSON.stringify({ n: r.promoted.length, lock: T.locks.login_queue }));
|
||||
}
|
||||
// 5. resume rule in SQL mode: a paused slot stays paused while the line is non-empty, even with a slot free
|
||||
{
|
||||
reset();
|
||||
for (let i = 0; i < 4; i++) row({});
|
||||
const p = row({ owner_email: 'pz@qa.test', status: 'paused' });
|
||||
const w = row({ status: 'queued', queued_at: 1, expires: null, starts: null });
|
||||
T.locks.login_queue = { holder: 'other-copy', until: Date.now() + 60000 }; // keep the line from starting w during the check
|
||||
const t0 = Date.now(); let r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||
ok(r.error && /busy/.test(r.error) && p.status === 'paused' && Date.now() - t0 >= 3000, 'resume waits for the lease and gives up cleanly while another copy holds it', JSON.stringify(r));
|
||||
T.locks.login_queue = { holder: null, until: 0 };
|
||||
// 4 live + 1 waiting = 5 of 6: one place is open, so the paused slot may resume
|
||||
r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||
ok(r.ok && p.status === 'active', '4 live + 1 waiting of 6: a place is open, the paused slot resumes', JSON.stringify(r).slice(0, 100));
|
||||
p.status = 'paused'; row({}); // now 5 live + 1 waiting = 6
|
||||
r = await ads.setStatus('pz@qa.test', p.id, 'active');
|
||||
ok(r.error && /line goes first/.test(r.error) && p.status === 'paused', '5 live + 1 waiting of 6: resume refused, the line goes first', JSON.stringify(r));
|
||||
r = await ads.setStatus(w.owner_email, w.id, 'active');
|
||||
ok(r.error && /already in line/.test(r.error), 'a reservation cannot be "resumed" past the line', JSON.stringify(r));
|
||||
}
|
||||
// 6. cancel refunds once, at purchase grade, with the ledger line
|
||||
{
|
||||
reset();
|
||||
const a = row({ owner_email: 'c@qa.test', status: 'queued', queued_at: 1, expires: null, starts: null, spent: 600, accrued: 400 });
|
||||
const r1 = await ads.cancelLoginReservation('c@qa.test', a.id), r2 = await ads.cancelLoginReservation('c@qa.test', a.id);
|
||||
const e = T.earned['c@qa.test'];
|
||||
ok(r1.ok && r1.refunded === 1000 && r2.error && e.balance === 1000 && e.grade === 1000, 'cancel: 1,000 back once (spent + accrued), purchased grade; the second cancel pays nothing', JSON.stringify({ r1, r2, e }));
|
||||
ok(T.log.some(l => l.delta === 1000 && /^Login slot reservation cancelled: refund/.test(l.note) && l.kind === 'refund'), 'credit_log row "Login slot reservation cancelled: refund"', JSON.stringify(T.log));
|
||||
const r3 = await ads.cancelLoginReservation('someone@else.test', a.id);
|
||||
ok(r3.error === 'No such reservation.', 'another member cannot cancel it or learn its state', JSON.stringify(r3));
|
||||
}
|
||||
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); });
|
||||
@@ -0,0 +1,131 @@
|
||||
// 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); });
|
||||
+1
-1
@@ -27,7 +27,7 @@ t('same total as 30 days at the old daily rate',
|
||||
const src = require('fs').readFileSync(new URL('../ads.js', import.meta.url), 'utf8');
|
||||
|
||||
t('buying a slot charges the whole price up front',
|
||||
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, v\.c\.budget, 'Login-ad slot/.test(src));
|
||||
/Login-ad slot \(/.test(src) && /chargeCredits\(campaign\.id, (v\.)?c\.budget, 'Login-ad slot/.test(src));
|
||||
t('a slot gets an end date at purchase',
|
||||
/out\.expires = Date\.now\(\) \+ days \* 86400000/.test(src));
|
||||
t('the MySQL daily meter skips slot campaigns',
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
||||
# bash qa/run.sh sov-passes # pass tiers (Explorer/Champion/Sovereign/Legend): store unit checks + admin buys Explorer + Sovereign with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
|
||||
# bash qa/run.sh login-queue # prepaid login-ad line: JSON store end to end + the MySQL path's lease/guard logic against a fake SQL layer (no server, throwaway data)
|
||||
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
|
||||
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
|
||||
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
|
||||
@@ -49,6 +50,9 @@ elif [ "$MODE" = "gamepass" ]; then
|
||||
elif [ "$MODE" = "sov-passes" ]; then
|
||||
node qa/sov-passes-store.cjs || status=1
|
||||
node qa/sov-passes-local.mjs || status=1
|
||||
elif [ "$MODE" = "login-queue" ]; then
|
||||
node qa/login-queue.cjs || status=1
|
||||
node qa/login-queue-sql.cjs || status=1
|
||||
elif [ "$MODE" = "gamepass-games" ]; then
|
||||
node qa/gamepass-games.cjs || status=1
|
||||
elif [ "$MODE" = "earn" ]; then
|
||||
|
||||
Reference in New Issue
Block a user