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:
martbost
2026-10-23 07:14:57 -05:00
parent c45f1769e7
commit 89b5969b25
13 changed files with 455 additions and 12 deletions
BIN
View File
Binary file not shown.
+2 -2
View File
@@ -48,8 +48,8 @@ async function run() {
{
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
const issues = [];
for (const c of byType('login').filter(c => !c.expires)) { const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires).length + ' per-day campaigns compared (30-day slots are paid up front)');
for (const c of byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status))) { /* a reservation in the login-ad line is paid up front and has no end date yet (2026-10-23) */ const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status)).length + ' per-day campaigns compared (30-day slots are paid up front)');
}
// 4. featured: a live booking older than two hours must have views
{
+5 -1
View File
@@ -78,6 +78,10 @@ const CANNED = [
{ id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'],
re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i,
a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
// 2026-10-23 (Marty: "they need to pay for the slot now to get a place in line"): 6 member slots, then a prepaid line
{ id: 'login-ads', title: 'Login ads: slots and the paid line', q: ['How do login ads work?', 'All login ad slots are taken, what now?', 'Can I reserve a login ad slot?', 'Can I cancel my login ad reservation?'], tags: ['login ad', 'login slot', 'reserve', 'queue', 'line', 'refund'],
re: /(log ?in.?ads?|sign.?in ads?|log ?in (ad )?(slots?|sponsor)|(reserve|reservation|queue|place in line|waiting list).{0,40}log ?in|log ?in.{0,40}(slots?|reserve|reservation|queue|place in line|waiting list)|reserve (a |the )?(next )?slot)/i,
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
// signed out, and the honest answer reads far better than letting it look like a fault.
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
@@ -244,7 +248,7 @@ ${passTiersFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends.
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the buy is refused until one ends, and a paused slot can only be resumed while a slot is open. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18 and 2026-10-23): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the member can RESERVE THE NEXT SLOT (since 2026-10-23): they pay the full slot price right then (same purchased-credits-only rule, balance drops at once, credit log 'Login slot reserved (queue #N)'), the ad waits in a paid line, first paid first served, and its 30 days do not start until its turn. Members > Campaigns shows their place in line and an ESTIMATED start date in Central time, worked out from the live slots' end dates and the reservations ahead; it is only an estimate because a slot ends early if its owner archives it. The oldest reservation starts automatically the moment a slot frees (a slot expires, or its owner pauses it to end or archive it; also checked every minute), and the owner gets an on-site notice and an email. Before it starts the owner can edit the link, image or headline for free, or cancel for a FULL refund (credited back as purchased credits, credit log 'Login slot reservation cancelled: refund'); after it starts normal slot rules apply. A freed slot goes to the line first: a paused slot can only be resumed while live slots plus reservations leave a place open, otherwise the owner is told the line is ahead of them. The admin can see the line and cancel-and-refund a reservation. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check.
- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.)
- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet.
+11
View File
@@ -138,6 +138,17 @@ async function bootstrap() {
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
// prepaid login-ad line (2026-10-23): status 'queued' = paid and waiting for a slot (never serves), 'cancelled' = refunded
// before it started; queued_at orders the line (first paid, first served). status is VARCHAR(12), so no change there.
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL');
// short lease locks shared by every app copy (two run for ~30 s on each deploy): one conditional UPDATE takes a lock
// (holder IS NULL OR lease_until < now), the holder clears it, and an expired lease can be taken over after a crash
await q(`CREATE TABLE IF NOT EXISTS app_locks (
name VARCHAR(40) PRIMARY KEY,
holder VARCHAR(60) NULL,
lease_until BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
await q("INSERT IGNORE INTO app_locks (name, holder, lease_until) VALUES ('login_queue', NULL, 0)");
// linked positions: extra wallets owned by one email account (Qualified Start).
// Each is its own on-chain member sponsored by the account's main member.
await q(`CREATE TABLE IF NOT EXISTS positions (
+6 -1
View File
@@ -232,6 +232,11 @@
</div>
<div class="pane" id="pane-campaigns" hidden>
<div class="card">
<div class="card-head"><h3>Login-ad line</h3><span class="sub" id="lqSub">paid reservations waiting for a slot</span></div>
<p class="small muted" style="margin:0 0 10px">When every member slot is taken, a member can pay now to reserve the next one. The oldest paid reservation starts the moment a slot frees (on expiry, on a pause, and on a one-minute check), before any paused slot can come back. Estimated starts assume every live slot runs its full term. Cancel gives the full price back as purchased credits.</p>
<div class="tablewrap"><table class="adm-table" id="lqTable"></table></div>
</div>
<div class="card">
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
@@ -606,6 +611,6 @@
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261022gpk"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
<script src="/assets/admin.js?v=20261023lq"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
</body>
</html>
+21
View File
@@ -256,10 +256,31 @@
// ── all campaigns ──
let allCamps = [];
async function loadCampaigns() {
loadLoginLine().catch(e => IAP.status(e.message, 'bad'));
const r = await api('/api/admin/campaigns');
allCamps = r.campaigns || [];
drawCamps();
}
// prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time.
const lqWhen = ts => ts ? esc(ctWhen(ts)) : '<span class="muted">unknown</span>'; // ctWhen (below) prints Central time
async function loadLoginLine() {
const d = await api('/api/admin/login-queue');
$('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open';
$('lqTable').innerHTML = '<tr><th>Place</th><th>ID</th><th>Owner</th><th>Campaign</th><th>Paid</th><th>Queued at</th><th>Estimated start</th><th></th></tr>'
+ (d.queue.length ? d.queue.map(c => '<tr><td><b>#' + c.place + '</b></td><td>#' + c.id + '</td><td><span class="trunc" title="' + esc(c.owner) + '">' + esc(c.owner) + '</span></td>'
+ '<td>' + esc(c.name) + '<div><a class="small trunc" href="' + esc(c.targetUrl) + '" target="_blank" rel="noopener">' + esc(c.targetUrl) + '</a></div></td>'
+ '<td class="mono small">' + Number(c.paid || 0).toLocaleString() + '</td><td class="small muted">' + lqWhen(c.queuedAt) + '</td><td class="small">' + lqWhen(c.estStart) + '</td>'
+ '<td class="act"><button class="btn small sec" data-lqcancel="' + c.id + '" data-lqowner="' + esc(c.owner) + '" data-lqpaid="' + Number(c.paid || 0) + '">Cancel + refund</button></td></tr>').join('')
: '<tr><td colspan="8" class="muted">Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.</td></tr>');
}
document.addEventListener('click', async e => {
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' });
if (!ok) return;
b.disabled = true;
try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); }
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
function drawCamps() {
const q = ($('campFilter').value || '').trim().toLowerCase();
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
+68 -6
View File
@@ -1068,6 +1068,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
const r = await (await fetch('/api/my/campaigns')).json();
if (r.error) return;
lastRates = r.rates;
lastLoginLine = r.loginLine || null; loginLineHint();
if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.';
// populate the banner-size dropdown once (ids map to NAS width/height)
if (r.bannerSizes && $('cSize') && !$('cSize').options.length)
@@ -1107,10 +1108,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
+ (((r.doorStats && r.doorStats[c.id]) || c.placement === 'golden' || c.placement === 'doors') ? (ds => '<div class="muted small" title="Spooky Doors: every door opened on this pack, and how many different players opened one">\u{1F383} ' + ds.doors.toLocaleString() + ' door' + (ds.doors === 1 ? '' : 's') + ' opened \u00b7 ' + ds.players.toLocaleString() + ' player' + (ds.players === 1 ? '' : 's') + '</div>')((r.doorStats && r.doorStats[c.id]) || { doors: 0, players: 0 }) : '') + '</td>'
: c.type === 'featured' ? '<td class="num" data-l="Spent"><span class="muted small" title="featured runs are paid in full when booked (' + (r.rates.featuredPerDay || 40) + ' credits a day); nothing more is charged while the run is live">paid up front</span></td><td class="num" data-l="Run">' + featRun(c) + '</td>'
: '<td class="num" data-l="Spent">' + c.spent + '</td><td class="num" data-l="Budget">' + c.budget + '</td>')
+ '<td data-l="Status">' + (c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
+ '<td data-l="Status">' + (c.status === 'queued' ? queuedCell(c) : c.status === 'cancelled' ? '<span class="muted" title="cancelled before it started; the full price came back to your balance">cancelled, refunded</span>' : c.status === 'out' ? (c.type === 'visits' ? '<span class="badge">pack delivered</span>' : '<span class="badge amber">budget spent</span>') : c.status === 'done' ? '<span class="muted">' + (c.type === 'featured' ? 'run ended' : 'ended') + '</span>' : c.scheduled ? '<span class="badge">scheduled</span>' : c.status) + '</td>'
+ '<td class="act">' + (c.status === 'active' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="pause">Pause</button>'
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>' : '')
+ (['paused', 'out', 'done'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
: c.status === 'paused' ? '<button class="btn small sec" data-camp="' + c.id + '" data-act="resume">Resume</button>'
: c.status === 'queued' ? '<button class="btn small sec" data-qedit="' + c.id + '">Edit</button> <button class="btn small quiet" data-qcancel="' + c.id + '" data-qname="' + esc(c.name || ('#' + c.id)) + '" data-qpaid="' + Number(c.spent || 0) + '">Cancel and refund</button>' : '')
+ (['paused', 'out', 'done', 'cancelled'].includes(c.status) ? ' <button class="btn small quiet" data-arch="' + c.id + '" data-archname="' + esc(c.name || ('#' + c.id)) + '" data-archleft="' + Math.max(0, (c.budget || 0) - (c.spent || 0)) + '" title="move it out of this list, keep its numbers">Archive</button>' : '')
+ (c.type === 'featured' ? ' <button class="btn small sec" data-extend="' + c.id + '" title="book more days at the daily rate">Extend run</button>'
: c.type === 'visits' ? ' <button class="btn small sec" data-morevisits="' + c.id + '" data-vper="' + placeCost(c.doorOnly ? c.placement : 'all', r.rates) + '" data-vdoor="' + (c.doorOnly ? (c.placement === 'golden' ? 'golden' : 'doors') : '') + '">' + (c.doorOnly ? 'Buy more doors' : 'Buy more visits') + '</button>'
: c.type === 'login' ? '' // a login slot is a flat 30-day buy: nothing to top up
@@ -1142,6 +1144,27 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
await loadCampaigns(); loadDashboard();
} catch (e) { IAP.status(e.message, 'bad'); }
}));
// prepaid login-ad line (2026-10-23): a reservation can be edited for free and cancelled for the full price back until it starts
el.querySelectorAll('button[data-qcancel]').forEach(b => b.addEventListener('click', async () => {
const paid = Number(b.dataset.qpaid) || 0;
const ok = await IAP.confirmBox('You give up your place in line and the full ' + paid.toLocaleString() + ' credits come back to your balance right away, as purchased credits. You can reserve again later, at the back of the line.',
{ title: 'Cancel ' + b.dataset.qname + '?', ok: 'Cancel and refund', cancel: 'Keep my place' });
if (!ok) return;
b.disabled = true;
try { const x = await api('/api/my/campaigns/' + b.dataset.qcancel + '/cancel-reservation'); IAP.status('Reservation cancelled. ' + Number(x.refunded || 0).toLocaleString() + ' credits are back in your balance.', 'ok'); await loadCampaigns(); loadDashboard(); }
catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; await loadCampaigns(); }
}));
el.querySelectorAll('button[data-qedit]').forEach(b => b.addEventListener('click', async () => {
const c = r.campaigns.find(x => x.id === Number(b.dataset.qedit)); if (!c) return;
const target = await IAP.ask({ title: 'Edit your reserved login ad', text: 'Target URL: the page members see when they sign in. Editing is free until the ad starts.', value: c.targetUrl || '', placeholder: 'https://', ok: 'Next' });
if (target === null) return;
const image = await IAP.ask({ title: 'Image (optional)', text: 'A direct image link (.png or .jpg) shown as the clickable creative. Leave it empty for a plain link card.', value: c.imageUrl || '', placeholder: 'https://', ok: 'Next' });
if (image === null) return;
const title = await IAP.ask({ title: 'Headline (optional)', text: 'Shown on the link card when there is no image. Up to 60 characters.', value: c.title || '', placeholder: 'Visit today\'s sponsor', ok: 'Save changes' });
if (title === null) return;
try { await api('/api/my/campaigns/' + c.id + '/edit-reservation', { targetUrl: target.trim(), imageUrl: image.trim(), title: title.trim() }); IAP.status('Saved. Your place in line is unchanged.', 'ok'); await loadCampaigns(); }
catch (e) { IAP.status(e.message, 'bad'); }
}));
el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => {
try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); }
catch (e) { IAP.status(e.message, 'bad'); }
@@ -1178,6 +1201,28 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
} catch (e) {}
}
let lastRates = null;
let lastLoginLine = null; // { max, used, queued, free, credits, days, nextPlace, nextEstStart, mine: [{ id, place, estStart }] }
// every date about the login-ad line is shown in Central time, Marty's clock
function ctWhen(ts) { return new Date(ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central'; }
function queuedCell(c) {
const m = lastLoginLine && (lastLoginLine.mine || []).find(x => x.id === c.id);
return '<span class="badge amber" title="paid in full; it starts on its own when a slot frees">In line' + (m ? ' #' + m.place : '') + '</span>'
+ '<div class="muted small">' + (m && m.estStart ? 'Estimated start ' + esc(ctWhen(m.estStart)) : 'Start date not known yet') + '</div>';
}
// the Login ad form: open slots, or the paid line with this buyer's place and estimated start
function loginLineHint() {
const el = $('cLoginLine'); const isLogin = $('cType') && $('cType').value === 'login';
if (el) el.hidden = !isLogin || !lastLoginLine;
if ($('createCampBtn')) $('createCampBtn').textContent = isLogin && lastLoginLine && !lastLoginLine.free ? 'Reserve the next slot' : 'Launch campaign';
if (!el || !isLogin || !lastLoginLine) return;
const L = lastLoginLine;
el.textContent = L.free
? L.free + ' of ' + L.max + ' login-ad slots open now. Yours goes live the moment you launch: ' + Number(L.credits).toLocaleString() + ' purchased credits for ' + L.days + ' days.'
: 'All ' + L.max + ' login-ad slots are taken' + (L.queued ? ' and ' + L.queued + ' paid ' + (L.queued === 1 ? 'reservation is' : 'reservations are') + ' in line' : '') + '. You can reserve the next slot: you pay the same '
+ Number(L.credits).toLocaleString() + ' purchased credits now and take place #' + L.nextPlace + ' in line. Your ' + L.days + ' days start when your turn comes, not before.'
+ (L.nextEstStart ? ' Estimated start: ' + ctWhen(L.nextEstStart) + '. That is an estimate: a slot can end early if its owner archives it, which moves the line forward.' : '')
+ ' Until it starts you can edit it for free, or cancel it for every credit back.';
}
function soloHint() {
if (!lastRates || $('cType').value !== 'solo') return;
const cost = lastRates.soloCostPerRecipient || 5;
@@ -1241,6 +1286,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
// runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
function applyType() { // hoisted: loadCampaigns may run before this line is reached
whereHint();
loginLineHint();
const t = $('cType').value;
$('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
if ($('cImageHint')) $('cImageHint').hidden = t !== 'banner';
@@ -1360,7 +1406,14 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
const t = $('cType').value;
const isVideo = t === 'video', isFeat = t === 'featured';
if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value);
await api('/api/my/campaigns', { type: t, name: $('cName').value,
// login ad with every slot taken: pay now for a place in line (Marty, 2026-10-23), after one plain confirmation
const confirmReserve = async (place, est) => IAP.confirmBox('Every login-ad slot is taken right now. Reserving charges the full ' + Number((lastLoginLine && lastLoginLine.credits) || (lastRates && lastRates.loginSlotCredits) || 0).toLocaleString()
+ ' purchased credits now and puts you at place #' + place + ' in line. Your ad starts on its own when a slot frees, and runs its full ' + ((lastLoginLine && lastLoginLine.days) || 30) + ' days from then.'
+ (est ? '\n\nEstimated start: ' + ctWhen(est) + '. That is an estimate: a slot can end early if its owner archives it.' : '')
+ '\n\nUntil it starts you can edit it for free, or cancel it and get every credit back.', { title: 'Reserve the next login-ad slot?', ok: 'Pay now and reserve', cancel: 'Not now' });
let reserve = false;
if (t === 'login' && lastLoginLine && !lastLoginLine.free) { if (!(await confirmReserve(lastLoginLine.nextPlace, lastLoginLine.nextEstStart))) return; reserve = true; }
const sendCamp = extra => api('/api/my/campaigns', Object.assign({ type: t, name: $('cName').value,
targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value,
title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value,
body: t === 'solo' ? soloBody : $('cBody').value,
@@ -1373,9 +1426,18 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0,
endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0,
ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value,
budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) });
budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * placeCost(visitPlace())) : Number($('cBudget').value) }, extra || {}));
let res;
try { res = await sendCamp({ reserve }); }
catch (e) { // the last slot went while the form was open: offer the line instead of a dead end
if (!(t === 'login' && e.data && e.data.full)) throw e;
if (!(await confirmReserve(e.data.place, e.data.estStart))) { await loadCampaigns(); return; }
res = await sendCamp({ reserve: true });
}
const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null;
IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
if (res && res.queued) IAP.status('Reserved and paid. You are #' + res.place + ' in line' + (res.estStart ? ', estimated start ' + ctWhen(res.estStart) : '') + '. We will tell you on site and by email the moment it goes live.', 'ok');
else if (t === 'login' && reserve) IAP.status('A slot opened up while you were deciding, so your login ad is live now.', 'ok');
else IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
// clear EVERY field so no target/creative carries into the next campaign
['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel',
'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt']
+2 -1
View File
@@ -528,6 +528,7 @@
<option value="visits">Verified visits (guaranteed unique)</option>
</select></p>
<p class="small muted" id="cWhere" style="margin:-4px 0 10px"></p>
<p class="small" id="cLoginLine" hidden style="grid-column:1/-1;margin:-4px 0 10px"></p>
<p><input id="cName" placeholder="Campaign name" style="width:100%"></p>
<p id="cBudgetRow"><input id="cBudget" type="number" placeholder="Budget (credits)" min="10" style="width:100%"></p>
<p id="cCapRow" style="grid-column:1/-1"><input id="cDailyCap" type="number" placeholder="Daily cap in credits (optional) — paces the budget across days" min="10" style="width:100%">
@@ -1188,7 +1189,7 @@
<script src="/assets/wallet.js?v=20260911a"></script>
<script src="/assets/promo.js?v=20261016p"></script>
<script src="/assets/support.js?v=20261016a"></script>
<script src="/assets/my.js?v=20261022gpw"></script>
<script src="/assets/my.js?v=20261023lq"></script>
<script src="/assets/chat.js?v=20261016n"></script>
</body>
</html>
+151
View File
@@ -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); });
+131
View File
@@ -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
View File
@@ -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',
+4
View File
@@ -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
+53
View File
@@ -571,6 +571,25 @@ async function boot() {
creditsFor: async email => { const v = await adminMember.view(email); return (v && v.credits && v.credits.available) || 0; },
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
});
// prepaid login-ad line (2026-10-23): when a reservation starts, its owner gets an on-site notice (kind 'notice', never the
// sign-in pop) and an email unless they unsubscribed. ads.js calls this once per start, from the one copy that won it.
ads.onLoginPromoted(async c => {
const owner = String(c.owner || '').toLowerCase(); if (!owner) return;
const name = c.name || ('campaign #' + c.id);
const until = new Date(Number(c.expires)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' Central';
const days = Number(c.body) || ads.rates().loginSlotDays || 30;
const subject = 'Your login ad "' + name + '" is live';
const text = 'Your place in line came up. Your reserved login-ad slot has started, so "' + name + '" now shows full screen to members as they sign in, for ' + days + ' days, until ' + until + '.\n\n'
+ 'You paid for it when you reserved, so nothing more is charged. See it in Members > Campaigns: https://instantadpay.com/my#campaigns\n\nInstantAdPay';
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const html = '<p>Your place in line came up. Your reserved login-ad slot has started, so <b>' + esc(name) + '</b> now shows full screen to members as they sign in, for ' + days + ' days, until ' + esc(until) + '.</p>'
+ '<p>You paid for it when you reserved, so nothing more is charged. See it in <a href="/my#campaigns">Members &gt; Campaigns</a>.</p>';
try { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [owner], subject, html, 'notice'); } catch (e) { console.error('login line inbox', e.message); }
const stopped = drip && drip.isUnsubscribed ? await drip.isUnsubscribed(owner).catch(() => false) : false;
if (!stopped && mailer.hasKey()) { try { await mailer.send(owner, subject, text); } catch (e) { console.error('login line mail', e.message); } }
console.log('login line: #' + c.id + ' started for ' + owner.replace(/^(.).*(@.*)$/, '$1***$2'));
});
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login line', e.message)), 60 * 1000); // safety net: a slot that expired between changes
setTimeout(() => refill.tick().catch(e => console.error('refill', e.message)), 90000);
setInterval(() => refill.tick().catch(e => console.error('refill', e.message)), 20 * 60 * 1000);
setInterval(() => friday.tick().catch(e => console.error('friday', e.message)), 5 * 60 * 1000);
@@ -4665,6 +4684,7 @@ const server = http.createServer(async (req, res) => {
out.earnedReserved = pool.earnedReserved;
out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns
out.availableCredits = pool.available;
out.loginLine = await ads.loginQueueView(s.email); // login-ad slots: open now, the paid line, this member's places + estimated starts
return json(res, 200, out);
}
if (p === '/api/my/campaigns' && req.method === 'POST') {
@@ -4725,6 +4745,28 @@ const server = http.createServer(async (req, res) => {
const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active');
return json(res, r.error ? 400 : 200, r);
}
// prepaid login-ad line (2026-10-23): cancel a reservation before it starts (full refund), or edit it for free
m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const r = await ads.cancelLoginReservation(s.email, m[1]);
return json(res, r.error ? 400 : 200, r);
}
m = /^\/api\/my\/campaigns\/(\d+)\/edit-reservation$/.exec(p);
if (m && req.method === 'POST') {
const s = await auth.fromRequest(req);
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
if (b.targetUrl !== undefined) {
const t = String(b.targetUrl || '').trim();
{ const sb = await sbcheck.check(t); if (!sb.ok) return json(res, 400, { error: sb.reason }); }
{ const rc = await reach.check(t); if (!rc.ok) return json(res, 400, { error: rc.reason }); }
}
if (b.imageUrl) { const ic = await imageCheck(b.imageUrl); if (!ic.ok) return json(res, 400, { error: ic.reason }); }
const r = await ads.editLoginReservation(s.email, m[1], b);
return json(res, r.error ? 400 : 200, r);
}
// -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL
if (p === '/api/admin/auth/start' && req.method === 'POST') {
@@ -4923,6 +4965,17 @@ const server = http.createServer(async (req, res) => {
console.log('admin stop campaign', c.id, owner, String(b.reason || '').slice(0, 80), JSON.stringify({ freed: a.freed }));
return json(res, a.error ? 400 : 200, Object.assign({ id: c.id, owner }, a));
}
if (p === '/api/admin/login-queue' && req.method === 'GET') { // the prepaid login-ad line, oldest paid first (2026-10-23)
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await ads.adminLoginQueue());
}
m = /^\/api\/admin\/login-queue\/(\d+)\/cancel$/.exec(p);
if (m && req.method === 'POST') { // admin cancel = the same full refund the owner would get
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const r = await ads.cancelLoginReservation(null, m[1], { admin: true });
if (!r.error) console.log('admin cancelled login reservation', r.id, String(r.owner || '').replace(/^(.).*(@.*)$/, '$1***$2'), 'refunded', r.refunded);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/campaigns' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER });