Prepaid login-ad slot queue (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line")
When all member login slots are taken the Ads screen offers "Reserve the next slot" instead of a dead button. Same price and checks as a slot (purchased credits only), paid at reserve time; the campaign is 'queued' with queuedAt, never serves and has no 30-day clock. First paid, first served: the member sees their place and an estimated start (Central time, labelled an estimate) built from the live slots' end dates and the line ahead. A freed slot (ended, paused, or found by the new 1-minute tick) goes to the oldest reservation: starts now, expires now + 30 days, never more than loginSlotsMax live. Idempotent across the deploy overlap: JSON mode takes a lock file and records every promotion/cancel in DATA_DIR/login-queue.json, re-read before any change; MySQL mode uses guarded UPDATEs (status + live count in one statement). Owner gets an on-site notice and an email (unsubscribes respected). A paused slot resumes only when live + queued < max. Cancel before start = full refund (credited back as purchased credits; any unburned accrual released). Edits while queued are free and keep the free correction. Admin: Login-ad queue card with cancel + refund, plus the Member content action. New credit activity log (credit-log.json / credit_log table): reserved (queue #N), bought, started, refunds, shown on the Ads screen. Audit skips queued/cancelled login rows. Chatbot CANNED + FACTS updated (6 slots, paid queue, full refund before start). Tags bumped: ads-screen.js, admin.js, my.js 20261023q. Tests: qa/loginqueue.test.cjs (two app copies promoting at once) + qa/loginqueue.e2e.mjs; bash qa/run.sh loginqueue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -36,8 +36,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))) { 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
|
||||
{
|
||||
|
||||
+2
-2
@@ -50,7 +50,7 @@ const CANNED = [
|
||||
a: 'Open Ads in your Control Room (' + SITE_URL + '/ads) and press Edit on the ad. You can change where the click goes, the banner image (upload a new one or paste a link), the headline and line of a text ad, and the ad name. A login ad shows your page itself, so its link is the whole ad. The first edit of every ad is free, your one correction; each edit after that costs a small credit fee (100 credits at the moment, shown before you save), taken from earned credits first. The type, size, budget, countries, schedule and audience stay as they are; for those, start a new ad. A new link is checked the same way as a new ad, so it has to load and, for banner and text ads, allow framing.' },
|
||||
{ id: 'login-ads', title: 'Login ad slots', q: ['How do login ads work?', 'How do I book a login ad?'], tags: ['login ad', 'slot', 'purchased credits'],
|
||||
re: /(log ?-?in|sign ?-?in) (ad|ads|spot|sponsor|slot|slots)|(ad|sponsor) (on|at) (the )?(log ?-?in|sign ?-?in)/i,
|
||||
a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 6 member slots run at once because they share the same sign-ins, first come first served; when all 6 are taken the Ads screen says so and a place opens when a running slot ends its 30 days. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy one from Ads, New ad, Login ad.' },
|
||||
a: 'A login ad is a slot: 1,000 purchased credits buys 30 days of your page, full screen, to every member right after they sign in, with unlimited sign-in impressions and nothing charged per day. At most 6 member slots run at once because they share the same sign-ins. When all 6 are taken you can reserve the next one from the same place: you pay the 1,000 purchased credits now to get your place in line, first paid first served, and your 30 days start the moment a slot frees up (we tell you on the site and by email). The Ads screen shows your place and an estimated start date, which is only an estimate. While you wait you can edit the ad for free, and if you cancel before it starts you get the full 1,000 credits back. A paused slot can only resume when nobody is waiting, because a freed slot goes to the line first. Login ads spend purchased credits only, so earned credits go to banner and text ads instead. Buy or reserve one from Ads, New ad, Login ad.' },
|
||||
{ id: 'vs-iap', title: 'LinkSpin and InstantAdPay: the difference', q: ['What is the difference between LinkSpin and InstantAdPay?', 'Is this the same as InstantAdPay?', 'Why another site?'], tags: ['instantadpay', 'iap', 'sister site', 'network'],
|
||||
re: /(instant ?ad ?pay|[^a-z]iap[^a-z]|differen|same as|another (site|program|property)|why (two|another)|sister (site|property)|which (one|site) (should|do))/i,
|
||||
a: 'InstantAdPay is the ad marketplace: you buy ad packages there, earn credits by viewing ads, and get paid when your line buys. LinkSpin is the tool side of the same network: a link rotator, a page builder and ad zones for your own sites, free with an email address. Its packages buy ad delivery across the LinkSpin viewer, every member zone and the partner network, and they pay your sponsor line the same way, inside the purchase transaction. Same people above and below you, same wallet, and your InstantAdPay username and profile carry over when you sign in with the same email.' },
|
||||
@@ -151,7 +151,7 @@ FACTS:
|
||||
- PACKAGES (priced in dollars, settled in POL at the live rate, 1 credit = 1 cent of ad delivery): $10 door = 1,000 credits, for trying the ads, does NOT count toward qualification; $25 Starter = 2,500; $50 Builder = 5,000; $100 Growth = 10,000; $250 Leader = 25,000; $500 Network = 50,000. Any package of $25 or more makes the buyer a qualifying buyer for their sponsor.
|
||||
- THE SPLIT, same transaction on Polygon, fixed in the contract: 50 percent direct sponsor, 20 percent level 2, 10 percent level 3, 10 percent + 10 percent to the two admin wallets. Level 1 pays from a referral's first qualifying purchase once the sponsor's payouts are on. Level 2 opens after two of the member's people buy a qualifying ($25 or larger) package, level 3 after five. An unfilled tier passes up the line to the next qualified member, then to the platform. Nothing is held, there are no withdrawals, no pending balances. Contract ${CONTRACT} on Polygon, verified on Polygonscan; plain-language review at ${SITE_URL}/contract; live ledger at ${SITE_URL}/ledger with a verify link on every row.
|
||||
- CREDITS VS POL: every member, free ones included, earns CREDITS (zones, the daily ad set with a claim streak, watch-to-earn videos, verified visits, a daily sign-in bonus). Credits buy the member's own banner and text ads (a login-ad slot takes purchased credits only) and NEVER cash out or convert to crypto. POL only reaches a wallet through the contract split when a package sells in the member's line. Never promise or estimate income.
|
||||
- AD FORMATS members buy with credits: banner ads (standard sizes), text ads, full-screen login ads (a flat slot: 1,000 PURCHASED credits for 30 days of unlimited sign-in impressions, never charged per day; at most 6 member slots live at once (raised from 3 on 2026-10-23), first come first served, a 7th is refused until one ends; house login ads only show when no member slot is running; earned credits never fund login ads); EDITING AN AD (2026-10-18): the Edit button on each ad on the Ads screen changes the click link, the banner image (upload or https link), a text ad's headline and line, and the ad name; type, size, budget, countries, schedule and audience cannot change (start a new ad); the first edit of every ad is free, each later edit costs the campaignEditFee, 100 credits by default, earned credits first, then purchased; a new link and a new banner image get the same checks as a new ad, plus solo ads to member inboxes, watch-to-earn video, verified visits. Banner and text ads also run on member zones and the partner network.
|
||||
- AD FORMATS members buy with credits: banner ads (standard sizes), text ads, full-screen login ads (a flat slot: 1,000 PURCHASED credits for 30 days of unlimited sign-in impressions, never charged per day; at most 6 member slots live at once (raised from 3 on 2026-10-23); PAID QUEUE (2026-10-23): when all 6 are taken a member can reserve the next slot by paying the full 1,000 purchased credits now, first paid first served, the 30 days start only when a slot frees (a slot ends or is paused) and the member gets an on-site notice and an email, the Ads screen shows the place in line and an ESTIMATED start date in Central time, edits are free while waiting, cancelling before the start refunds the full amount as purchased credits (a running slot is not refundable), and a paused slot can resume only when live plus waiting slots are under 6; house login ads only show when no member slot is running; earned credits never fund login ads); EDITING AN AD (2026-10-18): the Edit button on each ad on the Ads screen changes the click link, the banner image (upload or https link), a text ad's headline and line, and the ad name; type, size, budget, countries, schedule and audience cannot change (start a new ad); the first edit of every ad is free, each later edit costs the campaignEditFee, 100 credits by default, earned credits first, then purchased; a new link and a new banner image get the same checks as a new ad, plus solo ads to member inboxes, watch-to-earn video, verified visits. Banner and text ads also run on member zones and the partner network.
|
||||
- ACCOUNT: join at ${SITE_URL}/join with email only, a six-digit code, no password. Wallet linking happens inside the Control Room (Credits screen): one signature to link, then payouts switch on by activating (one transaction, gas only) or by buying any package. SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first) and any WalletConnect wallet work; Trust Wallet blocks a buy that spends most of its POL. MoonPay card on-ramp from the Credits screen puts POL on Polygon into the member's own wallet.
|
||||
- SPONSOR: the invite link opened most recently sets the sponsor (30-day cookie), shown on the join page, locked when the account is created; the contract binds the buyer to that sponsor at the first purchase. CARRY-OVER: Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their InstantAdPay sponsor from the network registry automatically when no invite link was used. Wrong sponsor before the first purchase: the admin can move the account. Members should switch on payouts before their people buy.
|
||||
- CONTROL ROOM screens: Links, Pages, Zones (with Audiences), Ads, Credits, Reports, Team (three levels, who has payouts on, who bought, qualifying-buyer counts), Wallet (what was paid to this wallet, payout history). More at ${SITE_URL}/tools: Promo tools, Training, Pipeline (a follow-up board for prospects and directs), My line (including the holding tank: members who joined with no sponsor wait there and can be adopted by a member with payouts on and their own qualifying package), Profile.
|
||||
|
||||
+3
-2
@@ -122,8 +122,9 @@ async function collect(fresh) {
|
||||
detail: { adType: c.type, imageUrl: c.imageUrl, title: c.title, body, width: c.width, height: c.height, budget: c.budget, spent: c.spent, starts: c.starts, expires: c.expires, geo: c.geo, dailyCap: c.dailyCap, audience: c.audience, name: c.name,
|
||||
edits: c.edits || 0, editLog: (c.editLog || []).slice(-5).map(e => ({ ts: e.ts, by: e.by, fields: e.fields, from: e.from, to: e.to, fee: e.fee || 0 })) }, // member edits (first free) + the last few changes
|
||||
counts: { imps: c.imps, impsNas: c.impsNas, clicks: c.clicks }, hosts: [hostOf(c.targetUrl)].concat(urlsIn(c.body).map(hostOf)), flags,
|
||||
actions: (c.status === 'active' ? [{ label: 'Pause ad', path: '/api/admin/campaigns/' + c.id + '/pause', body: {}, warn: 'Pause campaign #' + c.id + '? It stops serving until resumed.' }] : c.status === 'paused' ? [{ label: 'Resume ad', path: '/api/admin/campaigns/' + c.id + '/resume', body: {} }] : [])
|
||||
.concat(c.status !== 'done' ? [{ label: 'Edit ad', edit: true, path: '/api/admin/campaigns/' + c.id + '/edit' }] : []), // free for the admin, the member's free edit untouched
|
||||
actions: (c.status === 'active' ? [{ label: 'Pause ad', path: '/api/admin/campaigns/' + c.id + '/pause', body: {}, warn: 'Pause campaign #' + c.id + '? It stops serving until resumed.' }] : c.status === 'paused' ? [{ label: 'Resume ad', path: '/api/admin/campaigns/' + c.id + '/resume', body: {} }]
|
||||
: c.status === 'queued' ? [{ label: 'Cancel + refund', path: '/api/admin/campaigns/' + c.id + '/cancel-reservation', body: {}, warn: 'Cancel login-slot reservation #' + c.id + '? The ' + c.budget + ' credits paid come back to the member in full and they leave the line.' }] : [])
|
||||
.concat(!['done', 'cancelled'].includes(c.status) ? [{ label: 'Edit ad', edit: true, path: '/api/admin/campaigns/' + c.id + '/edit' }] : []), // free for the admin, the member's free edit untouched
|
||||
search: [c.type, c.targetUrl, c.imageUrl, c.title, body] });
|
||||
}
|
||||
|
||||
|
||||
@@ -137,6 +137,19 @@ async function bootstrap() {
|
||||
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN edits INT NOT NULL DEFAULT 0'); // member edits so far (the first is free), 2026-10-18
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN edit_log MEDIUMTEXT NULL'); // JSON [{ts, by, fields, from, to, fee, paidFrom}], last 50
|
||||
// prepaid login-slot queue (Marty, 2026-10-23): paid at reserve time, status 'queued' until a slot frees
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL'); // when the place in line was paid for (first paid, first served)
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN promoted_at BIGINT NULL'); // when it left the line and its 30 days started
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN refunded INT NOT NULL DEFAULT 0'); // credits handed back on a cancel before start
|
||||
await q(`CREATE TABLE IF NOT EXISTS credit_log (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
ts BIGINT NOT NULL,
|
||||
delta INT NOT NULL,
|
||||
reason VARCHAR(160) NOT NULL,
|
||||
campaign_id INT NULL,
|
||||
INDEX (email, ts)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
// 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
@@ -177,6 +177,11 @@
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-campaigns" hidden>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Login-ad queue</h3><span class="sub" id="lqSub">paid reservations, first paid first served</span></div>
|
||||
<p class="small muted" style="margin:0 0 8px">Members pay in full when they reserve. The oldest reservation starts by itself within a minute of a slot freeing (a slot ends or is paused). Cancel before start refunds the whole amount 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>
|
||||
@@ -507,6 +512,6 @@
|
||||
|
||||
<script src="/assets/common.js?v=20261018p25"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261020m1"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
|
||||
<script src="/assets/admin.js?v=20261023q"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+4
-2
@@ -25,6 +25,7 @@
|
||||
.field{width:100%;box-sizing:border-box}
|
||||
#composer[hidden]{display:none}
|
||||
.where{display:grid;gap:9px}.where div{display:flex;gap:10px;align-items:flex-start}.where b{min-width:60px;color:var(--accent-hi);font:700 11px var(--mono);letter-spacing:.06em;text-transform:uppercase;padding-top:2px}
|
||||
[data-st="queued"]{--st:#7c3aed} [data-st="cancelled"]{--st:#94a3b8} /* prepaid login-slot line (2026-10-23) */
|
||||
@media (max-width:900px){.body{padding:12px 16px}}
|
||||
</style>
|
||||
</head>
|
||||
@@ -64,12 +65,13 @@
|
||||
<div class="tbl cl"><div class="hd"><span>Campaign</span><span>Creative</span><span>Budget</span><span class="r">Views</span><span class="r">Clicks</span><span>Status</span><span></span></div><div id="rows"></div><div class="ft" id="foot"></div></div>
|
||||
<div class="side">
|
||||
<div class="panel"><h2>Earn credits</h2><div class="gauge" id="earnGauge"><i></i><i></i><i></i><i></i><i></i></div><div class="muted" id="earnLine" style="margin-top:8px">loading</div><div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px"><button class="btn blue" type="button" id="earnNext">View an ad</button><button class="btn" type="button" id="earnClaim" hidden>Claim</button></div><div class="muted" id="earnNote" style="margin-top:8px"></div></div>
|
||||
<div class="panel"><h2>Where your ads run</h2><div class="where ink2"><div><b>Banner</b><span>the ad viewer here, every member zone on outside sites, and the partner network</span></div><div><b>Text</b><span>the ad viewer and the partner network</span></div><div><b>Login</b><span>full screen to every member right after they sign in: 1,000 purchased credits for a 30-day slot, 3 slots at a time</span></div></div><div class="muted" id="rateLine" style="margin-top:10px"></div></div>
|
||||
<div class="panel"><h2>Where your ads run</h2><div class="where ink2"><div><b>Banner</b><span>the ad viewer here, every member zone on outside sites, and the partner network</span></div><div><b>Text</b><span>the ad viewer and the partner network</span></div><div><b>Login</b><span id="loginWhere">full screen to every member right after they sign in, for a flat 30-day slot of purchased credits</span></div></div><div class="muted" id="rateLine" style="margin-top:10px"></div></div>
|
||||
<div class="panel" hidden><h2>Credit activity</h2><div id="creditLog" class="ink2" style="font-size:13px"></div></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/cr-shell.js?v=20261023a"></script>
|
||||
<script src="/assets/ads-screen.js?v=20261020s"></script>
|
||||
<script src="/assets/ads-screen.js?v=20261023q"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -261,7 +261,24 @@
|
||||
|
||||
// ── all campaigns ──
|
||||
let allCamps = [];
|
||||
// prepaid login-slot queue (2026-10-23): the line, with admin cancel + full refund
|
||||
async function loadLoginQueue() {
|
||||
try {
|
||||
const r = await api('/api/admin/login-queue'); const q = r.queue || [], L = r.slots || {};
|
||||
$('lqSub').textContent = (L.used || 0) + ' of ' + (L.max || 0) + ' slots live · ' + q.length + ' in line';
|
||||
$('lqTable').innerHTML = q.length ? '<tr><th>Place</th><th>ID</th><th>Owner</th><th>Ad</th><th>Paid</th><th>Reserved</th><th>Est. start (CT)</th><th></th></tr>' + q.map(x => '<tr><td>#' + x.place + '</td><td>#' + x.id + '</td><td><span class="trunc" title="' + esc(x.owner) + '">' + esc(x.owner) + '</span></td><td>' + esc(x.name) + '<div><a class="small trunc" href="' + esc(x.targetUrl) + '" target="_blank" rel="noopener">' + esc(x.targetUrl) + '</a></div></td><td class="mono small">' + (x.budget || 0).toLocaleString() + '</td><td class="small muted">' + when(x.queuedAt) + '</td><td class="small">' + esc(x.estStartCt || 'no estimate') + '</td><td class="act"><button class="btn small sec" type="button" data-lqcancel="' + x.id + '" data-owner="' + esc(x.owner) + '" data-paid="' + (x.budget || 0) + '">Cancel + refund</button></td></tr>').join('') : '<tr><td class="muted">Nobody is waiting for a login-ad slot.</td></tr>';
|
||||
} catch (e) { $('lqSub').textContent = e.message; }
|
||||
}
|
||||
$('lqTable').addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
|
||||
let ok = false; try { ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.owner + '? Their ' + Number(b.dataset.paid).toLocaleString() + ' credits come back in full as purchased credits, and they leave the line.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' }); } catch (err) { ok = false; }
|
||||
if (!ok) return;
|
||||
b.disabled = true;
|
||||
try { const r = await api('/api/admin/campaigns/' + b.dataset.lqcancel + '/cancel-reservation', {}); IAP.status('Reservation #' + b.dataset.lqcancel + ' cancelled, ' + r.refunded + ' credits refunded.', 'ok'); await Promise.all([loadLoginQueue(), loadCampaigns()]); }
|
||||
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
|
||||
});
|
||||
async function loadCampaigns() {
|
||||
loadLoginQueue();
|
||||
const r = await api('/api/admin/campaigns');
|
||||
allCamps = r.campaigns || [];
|
||||
drawCamps();
|
||||
|
||||
+41
-16
@@ -7,13 +7,16 @@
|
||||
const NOTE = {
|
||||
banner: 'Runs in the ad viewer, in every member zone on outside sites, and on the partner network. Views are timed on the server. Spends purchased or earned credits.',
|
||||
text: 'A headline and one line. Runs in the ad viewer and on the partner network. Spends purchased or earned credits.',
|
||||
login: 'Your page, full screen, to every member right after they sign in. A slot is 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once and never charged per day. 3 slots at a time, first come first served. No creative needed: the page is the ad.'
|
||||
login: 'Your page, full screen, to every member right after they sign in. A slot is a flat buy of purchased credits for a fixed run of unlimited sign-in impressions, paid once and never charged per day. No creative needed: the page is the ad.'
|
||||
};
|
||||
// login slots (same rule as InstantAdPay): one flat price, a fixed run, a cap on member slots live at once
|
||||
const slotInfo = () => { const r = (D && D.rates) || {}; const ls = (D && D.loginSlots) || {}; const max = ls.max || r.loginSlotsMax || 3;
|
||||
return { credits: ls.credits || r.loginSlotCredits || 1000, days: ls.days || r.loginSlotDays || 30, max, used: ls.used || 0, free: ls.free != null ? ls.free : max }; };
|
||||
return { credits: ls.credits || r.loginSlotCredits || 1000, days: ls.days || r.loginSlotDays || 30, max, used: ls.used || 0, queued: ls.queued || 0, free: ls.free != null ? ls.free : max }; };
|
||||
// prepaid queue (Marty, 2026-10-23): when every slot is taken you pay now for a place in line; first paid, first served
|
||||
const nextPlace = () => (D && D.loginNext) || { place: 1, estStartCt: null };
|
||||
const estText = ct => ct ? (ct === 'any minute now' ? 'Estimated start: any minute now.' : 'Estimated start: ' + ct + ' (Central time).') + ' This is an estimate: it moves earlier if a running slot is paused, and can move if the number of slots changes.' : 'There is no start estimate yet.';
|
||||
const loginNote = () => { const L = slotInfo();
|
||||
return 'Your page, full screen, to every member right after they sign in. A slot is ' + fmt(L.credits) + ' purchased credits for ' + L.days + ' days of unlimited sign-in impressions, paid once and never charged per day. ' + L.max + ' slots at a time, first come first served. No creative needed: the page is the ad.'; };
|
||||
return 'Your page, full screen, to every member right after they sign in. A slot is ' + fmt(L.credits) + ' purchased credits for ' + L.days + ' days of unlimited sign-in impressions, paid once and never charged per day. ' + L.max + ' slots at a time. When all are taken you can reserve the next one: you pay now, your ' + L.days + ' days start when a slot frees up, first paid first served, and cancelling before it starts refunds you in full. No creative needed: the page is the ad.'; };
|
||||
const host = u => { try { return new URL(u).hostname.replace(/^www\./, ''); } catch (e) { return u; } };
|
||||
async function load() {
|
||||
try { [D, EARN] = await Promise.all([CR.get('/api/my/campaigns'), CR.get('/api/my/earn')]); } catch (e) { CR.sub('could not load'); return; }
|
||||
@@ -29,37 +32,43 @@
|
||||
CR.tile({ k: 'Views delivered', v: fmt(views), series: week ? hours : null, note: week ? fmt(week) + ' in 7 days, by hour' : '' }),
|
||||
CR.tile({ k: 'Today\'s viewing', v: EARN.views + ' / ' + EARN.target, note: EARN.streakDay > 1 ? 'streak day ' + EARN.streakDay : '' })].join('');
|
||||
const r = D.rates || {};
|
||||
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views, ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day login slot (' + slotInfo().free + ' of ' + slotInfo().max + ' open). Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
|
||||
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views, ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day login slot (' + (slotInfo().free ? slotInfo().free + ' of ' + slotInfo().max + ' open' : 'all ' + slotInfo().max + ' taken' + (slotInfo().queued ? ', ' + slotInfo().queued + ' in line' : '') + ', reserve the next one') + '). Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
|
||||
// traffic-light status (2026-10-20): live green, running low amber (80%+ of the budget spent), out red, paused grey
|
||||
const stKey = c => c.scheduled ? 'sched' : c.status === 'active' ? (c.type !== 'login' && c.budget > 0 && c.spent / c.budget >= 0.8 ? 'low' : 'live') : c.status === 'paused' ? 'paused' : c.status === 'out' ? 'out' : c.status === 'done' ? 'ended' : '';
|
||||
const ST_LABEL = { sched: 'Scheduled', live: 'Live', low: 'Running low', paused: 'Paused', out: 'Out of credits', ended: 'Ended' };
|
||||
const stKey = c => c.status === 'queued' ? 'queued' : c.status === 'cancelled' ? 'cancelled' : c.scheduled ? 'sched' : c.status === 'active' ? (c.type !== 'login' && c.budget > 0 && c.spent / c.budget >= 0.8 ? 'low' : 'live') : c.status === 'paused' ? 'paused' : c.status === 'out' ? 'out' : c.status === 'done' ? 'ended' : '';
|
||||
const ST_LABEL = { queued: 'In line', cancelled: 'Cancelled, refunded', sched: 'Scheduled', live: 'Live', low: 'Running low', paused: 'Paused', out: 'Out of credits', ended: 'Ended' };
|
||||
const st = c => { const k = stKey(c); return '<span class="stg" data-st="' + k + '">' + (ST_LABEL[k] || esc(c.status)) + '</span>'; };
|
||||
const cr = c => c.type === 'banner' ? (c.imageUrl ? '<img class="thumb" src="' + esc(c.imageUrl) + '" alt="">' : '') + '<span class="mono muted" style="font-size:11px">' + c.width + 'x' + c.height + '</span>' : c.type === 'text' ? '<b>' + esc(c.title) + '</b><br><span class="muted" style="font-size:12px">' + esc(c.body || '') + '</span>' : '<span class="muted">full page' + (c.type === 'login' && c.expires ? '<br><span style="font-size:12px">' + (c.expires > Date.now() ? 'slot ends ' : 'ended ') + new Date(c.expires).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + '</span>' : '') + '</span>';
|
||||
$('rows').innerHTML = cs.length ? cs.map(c => '<div class="rw st-row" data-st="' + stKey(c) + '"><div><b>' + esc(c.name) + '</b> <span class="tag t">' + esc(c.type) + '</span>' + (c.audience ? ' <span class="tag plain" title="audience">' + esc((((D && D.audiences) || []).find(a => a.id === c.audience) || {}).name || 'audience') + (c.audienceMode === 'exclude' ? ' · excluded' : '') + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '</span></div><div>' + cr(c) + '</div><div><span class="num">' + fmt(c.spent) + '</span><span class="muted"> / ' + fmt(c.budget) + '</span><div class="bar st"><i style="width:' + Math.min(100, Math.round(100 * c.spent / Math.max(1, c.budget))) + '%"></i></div></div><span class="r num">' + fmt(c.imps) + (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network</span>' : '') + '</span><span class="r num">' + fmt(c.clicks) + '</span><span>' + st(c) + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">'
|
||||
const QM = {}; (D.loginQueue || []).forEach(q => { QM[q.id] = q; });
|
||||
const qCell = c => { const q = QM[c.id]; return '<span class="muted">full page<br><span style="font-size:12px"><b>#' + (q ? q.place : '?') + ' in line</b>, paid' + (q && q.estStartCt ? '<br>' + (q.estStartCt === 'any minute now' ? 'starts any minute now' : 'est. start ' + esc(q.estStartCt) + ' CT (an estimate)') : '') + '</span></span>'; };
|
||||
const cr = c => c.status === 'queued' ? qCell(c) : c.status === 'cancelled' ? '<span class="muted">full page<br><span style="font-size:12px">' + fmt(c.refunded || 0) + ' credits refunded</span></span>' : c.type === 'banner' ? (c.imageUrl ? '<img class="thumb" src="' + esc(c.imageUrl) + '" alt="">' : '') + '<span class="mono muted" style="font-size:11px">' + c.width + 'x' + c.height + '</span>' : c.type === 'text' ? '<b>' + esc(c.title) + '</b><br><span class="muted" style="font-size:12px">' + esc(c.body || '') + '</span>' : '<span class="muted">full page' + (c.type === 'login' && c.expires ? '<br><span style="font-size:12px">' + (c.expires > Date.now() ? 'slot ends ' : 'ended ') + new Date(c.expires).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + '</span>' : '') + '</span>';
|
||||
$('rows').innerHTML = cs.length ? cs.map(c => '<div class="rw st-row" data-st="' + stKey(c) + '"><div><b>' + esc(c.name) + '</b> <span class="tag t">' + esc(c.type) + '</span>' + (c.audience ? ' <span class="tag plain" title="audience">' + esc((((D && D.audiences) || []).find(a => a.id === c.audience) || {}).name || 'audience') + (c.audienceMode === 'exclude' ? ' · excluded' : '') + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '</span></div><div>' + cr(c) + '</div><div><span class="num">' + fmt(c.status === 'cancelled' ? 0 : c.spent) + '</span><span class="muted"> / ' + fmt(c.budget) + (c.status === 'queued' ? ' paid' : '') + '</span><div class="bar st"><i style="width:' + (c.status === 'cancelled' ? 0 : Math.min(100, Math.round(100 * c.spent / Math.max(1, c.budget)))) + '%"></i></div></div><span class="r num">' + fmt(c.imps) + (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network</span>' : '') + '</span><span class="r num">' + fmt(c.clicks) + '</span><span>' + st(c) + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">'
|
||||
+ (c.status === 'active' ? '<button class="btn sm" type="button" data-pause="' + c.id + '">Pause</button>' : c.status === 'paused' ? '<button class="btn sm" type="button" data-resume="' + c.id + '">Resume</button>' : '')
|
||||
+ (['active', 'paused', 'out'].includes(c.status) && c.type !== 'login' ? '<button class="btn sm" type="button" data-top="' + c.id + '">Top up</button>' : '')
|
||||
+ (c.status !== 'done' ? '<button class="btn sm" type="button" data-edit="' + c.id + '" title="' + (c.edits ? 'Edit the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (' + fmt(D.editFee) + ' credits)' : 'Fix the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (first edit free)') + '">Edit</button>' : '') + '</span></div>').join('')
|
||||
+ (c.status === 'queued' ? '<button class="btn sm" type="button" data-qcancel="' + c.id + '" title="Leave the line: the ' + fmt(c.budget) + ' credits you paid come back in full">Cancel and refund</button>' : '')
|
||||
+ (!['done', 'cancelled'].includes(c.status) ? '<button class="btn sm" type="button" data-edit="' + c.id + '" title="' + (c.edits ? 'Edit the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (' + fmt(D.editFee) + ' credits)' : 'Fix the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (first edit free)') + '">Edit</button>' : '') + '</span></div>').join('')
|
||||
: '<div class="rw"><span class="muted">No ads yet. Launch one: a banner, a text ad or a login-ad slot.</span></div>';
|
||||
if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '<div class="muted" style="margin-top:8px">Your welcome credits unlock after the short welcome tour on <a href="/tools">the classic dashboard</a>.</div>');
|
||||
$('foot').textContent = 'views = timed views in the ad viewer plus member zones; network = the partner ad network · a paused ad keeps its credits · unspent credits return when an ad ends';
|
||||
$('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause')));
|
||||
$('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume')));
|
||||
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => { const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return; try { await api('/api/my/campaigns/' + b.dataset.top + '/topup', { credits: Number(v.credits) }); toast('Topped up.'); load(); } catch (e) { toast(e.message, true); } }));
|
||||
$('rows').querySelectorAll('[data-qcancel]').forEach(b => b.addEventListener('click', () => cancelReservation(Number(b.dataset.qcancel))));
|
||||
$('rows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openEdit(Number(b.dataset.edit))));
|
||||
{ const w = $('loginWhere'); if (w) w.textContent = 'full screen to every member right after they sign in: ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day slot, ' + slotInfo().max + ' slots at a time. When all are taken, reserve the next one: pay now, it starts when a slot frees, and a cancel before then refunds in full'; }
|
||||
{ const cl = D.creditLog || []; const box = $('creditLog'); if (box) { box.parentElement.hidden = !cl.length; box.innerHTML = cl.map(x => '<div style="display:flex;justify-content:space-between;gap:10px;padding:5px 0;border-bottom:1px solid var(--chrome-line)"><span>' + esc(x.reason) + (x.campaignId ? ' <span class="mono muted" style="font-size:11px">#' + x.campaignId + '</span>' : '') + '<br><span class="muted" style="font-size:11px">' + new Date(x.ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT</span></span><span class="num mono" style="white-space:nowrap">' + (x.delta > 0 ? '+' : '') + (x.delta ? fmt(x.delta) : '') + '</span></div>').join(''); } }
|
||||
slotChip(); if (!$('composer').hidden) setType(TYPE);
|
||||
earnPaint();
|
||||
{ const hm = /^#edit=(\d+)$/.exec(location.hash || ''); if (hm) { history.replaceState(null, '', location.pathname + location.search); openEdit(Number(hm[1])); } } // /tools campaign list links here
|
||||
}
|
||||
// -- edit an ad (2026-10-18): fix the link, the image or the text. The first edit of each ad is free, then D.editFee credits.
|
||||
// Type, size, budget, countries, schedule and audience are the buy itself and stay a new campaign.
|
||||
const feeNote = c => !c.edits ? 'This edit is free (your one free correction).' : (D.editFee ? 'This edit costs ' + fmt(D.editFee) + ' credits.' : 'Edits are free right now.');
|
||||
const feeNote = c => c.status === 'queued' ? 'Edits are free while this ad waits in line, and your one free correction stays for when it runs.' : !c.edits ? 'This edit is free (your one free correction).' : (D.editFee ? 'This edit costs ' + fmt(D.editFee) + ' credits.' : 'Edits are free right now.');
|
||||
async function openEdit(id) {
|
||||
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) { toast('That ad is not in your list.', true); return; }
|
||||
const fields = [{ k: 'name', label: 'Name', value: c.name, max: 60 }, { k: 'targetUrl', label: 'Where the click goes', value: c.targetUrl, mono: true }];
|
||||
if (c.type === 'banner') fields.push({ k: 'imageUrl', label: 'Image URL (' + c.width + 'x' + c.height + ')', value: c.imageUrl || '', mono: true });
|
||||
if (c.type === 'text') fields.push({ k: 'title', label: 'Headline (60)', value: c.title || '', max: 60 }, { k: 'body', label: 'One line (140)', value: c.body || '', max: 140 });
|
||||
const last = (c.editLog || []).slice(-1)[0];
|
||||
const html = '<div class="muted" style="margin:8px 0" id="edFee"><b>' + esc(feeNote(c)) + '</b> ' + (c.edits ? 'Your free correction on this ad is used.' : 'After this one, each edit costs ' + fmt(D.editFee) + ' credits.') + '</div>'
|
||||
const html = '<div class="muted" style="margin:8px 0" id="edFee"><b>' + esc(feeNote(c)) + '</b> ' + (c.status === 'queued' ? '' : c.edits ? 'Your free correction on this ad is used.' : 'After this one, each edit costs ' + fmt(D.editFee) + ' credits.') + '</div>'
|
||||
+ '<div class="muted" style="font-size:12px;margin-bottom:6px">The type, size, budget, countries, schedule and audience stay as they are. To change those, start a new ad.' + (last ? ' Last edited ' + new Date(last.ts).toLocaleString() + '.' : '') + '</div>'
|
||||
+ (c.type === 'banner' ? '<label class="lbl">Or upload a new image (PNG, JPG, WebP, GIF up to 3 MB)<input class="field" id="edFile" type="file" accept="image/png,image/jpeg,image/webp,image/gif"></label><div class="muted" style="margin:6px 0 4px">Preview at real size</div><div id="edPrev" style="max-width:100%;overflow:auto"></div>' : '')
|
||||
+ (c.type === 'login' ? '<div class="muted" style="font-size:12px">A login ad shows the page itself, full screen, so the link is the ad.</div>' : '');
|
||||
@@ -74,12 +83,20 @@
|
||||
const label = { name: 'name', targetUrl: 'link', imageUrl: 'image', title: 'headline', body: 'text line' };
|
||||
const changed = Object.keys(v).filter(k => String(v[k]).trim() !== String(c[k] || '').trim());
|
||||
if (!changed.length) { toast('Nothing changed.'); return; }
|
||||
const ok = await dialog({ title: 'Save the new ' + changed.map(k => label[k]).join(', ') + '?', text: feeNote(c) + (c.edits && D.editFee ? ' It comes out of your earned credits first, then purchased.' : ''), ok: c.edits && D.editFee ? 'Save and pay ' + fmt(D.editFee) : 'Save' });
|
||||
const paidEdit = c.status !== 'queued' && c.edits && D.editFee;
|
||||
const ok = await dialog({ title: 'Save the new ' + changed.map(k => label[k]).join(', ') + '?', text: feeNote(c) + (paidEdit ? ' It comes out of your earned credits first, then purchased.' : ''), ok: paidEdit ? 'Save and pay ' + fmt(D.editFee) : 'Save' });
|
||||
if (!ok) return;
|
||||
const body = {}; changed.forEach(k => { body[k] = v[k].trim(); });
|
||||
try { const r = await api('/api/my/campaigns/' + c.id + '/edit', body); toast('Saved.' + (r.fee ? ' ' + fmt(r.fee) + ' credits charged.' : '') + (r.warn ? ' ' + r.warn : '')); load(); }
|
||||
catch (e) { toast(e.message, true); }
|
||||
}
|
||||
async function cancelReservation(id) {
|
||||
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) return;
|
||||
const q = (D.loginQueue || []).find(x => x.id === id);
|
||||
const ok = await dialog({ title: 'Cancel reservation #' + id + '?', text: 'You leave the line' + (q ? ' (you are #' + q.place + ')' : '') + ' and the ' + fmt(c.budget) + ' credits you paid come back to you in full, as purchased credits. If you reserve again later, you join at the back of the line.', ok: 'Cancel and refund', no: 'Keep my place', danger: true });
|
||||
if (!ok) return;
|
||||
try { const r = await api('/api/my/campaigns/' + id + '/cancel-reservation', {}); toast('Cancelled. ' + fmt(r.refunded) + ' credits refunded.'); load(); } catch (e) { toast(e.message, true); }
|
||||
}
|
||||
async function act(path) { try { await api(path, {}); load(); } catch (e) { toast(e.message, true); } }
|
||||
// -- earn by viewing: the engine's fraud-guarded flow (server-timed dwell + a human check) runs inside /view/<token>
|
||||
function earnPaint() {
|
||||
@@ -111,15 +128,15 @@
|
||||
function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login';
|
||||
const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget');
|
||||
if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; }
|
||||
$('fGo').disabled = full; $('fGo').title = full ? 'All login-ad slots are taken right now' : '';
|
||||
$('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : '';
|
||||
cost(); preview(); }
|
||||
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full)'); }
|
||||
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full, reserve the next)'); }
|
||||
function cost() { const b = Math.floor(Number($('fBudget').value) || 0); const r = D ? D.rates : {}; let s = '';
|
||||
if (TYPE === 'banner') s = 'about ' + fmt(Math.floor(b / (r.bannerCreditsPerBatch || 2) * (r.bannerBatch || 10))) + ' timed views';
|
||||
else if (TYPE === 'text') s = 'about ' + fmt(Math.floor(b / (r.textCreditsPerBatch || 1) * (r.textBatch || 10))) + ' timed views';
|
||||
else { const L = slotInfo(); $('fCost').innerHTML = L.free
|
||||
? '<b>' + fmt(L.credits) + '</b> purchased credits for <b>' + L.days + '</b> days of unlimited sign-in impressions · <b>' + L.free + '</b> of ' + L.max + ' slots open'
|
||||
: 'All <b>' + L.max + '</b> login-ad slots are taken right now. A place opens when a running slot ends its ' + L.days + ' days; check back in a few days.'; return; }
|
||||
: '<span style="display:block;line-height:1.7">All <b>' + L.max + '</b> login-ad slots are taken' + (L.queued ? ', <b>' + L.queued + '</b> paid reservation' + (L.queued === 1 ? '' : 's') + ' in line' : '') + '. Reserve the next one: <b>' + fmt(L.credits) + '</b> purchased credits now and you would be <b>#' + nextPlace().place + '</b> in line. ' + esc(estText(nextPlace().estStartCt)) + ' Cancel before it starts for a full refund.</span>'; return; }
|
||||
$('fCost').innerHTML = b >= 10 ? s.replace(/(about )([\d,]+)/, '$1<b>$2</b>') : 'minimum <b>10</b> credits'; }
|
||||
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><img src="' + esc(IMG) + '" alt="" style="max-width:100%;width:' + sz[0] + 'px;height:auto;border:1px solid var(--chrome-line);background:var(--inset)">'; }
|
||||
else if (TYPE === 'text') p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><div class="panel" style="max-width:420px"><b>' + esc($('fTitle').value || 'Your headline') + '</b><br><span class="ink2">' + esc($('fBody').value || 'One line under it.') + '</span><br><span class="mono muted" style="font-size:11px">' + esc(host($('fTarget').value || 'yoursite.com')) + '</span></div>';
|
||||
@@ -143,8 +160,16 @@
|
||||
if ($('fAud') && $('fAud').value) { body.audience = $('fAud').value; body.audienceMode = $('fAudMode').value; }
|
||||
if (TYPE === 'banner') { body.size = $('fSize').value; body.imageUrl = $('fImage').value.trim(); }
|
||||
if (TYPE === 'text') { body.title = $('fTitle').value; body.body = $('fBody').value; }
|
||||
if (TYPE === 'login' && !slotInfo().free) { // the line: say exactly what happens before any credits move
|
||||
const L = slotInfo(), nx = nextPlace();
|
||||
const ok = await dialog({ title: 'Reserve the next login-ad slot?', text: 'All ' + L.max + ' slots are taken. You pay ' + fmt(L.credits) + ' purchased credits now and get place #' + nx.place + ' in line. Your ' + L.days + ' days start the moment a slot frees up (first paid, first served), and we let you know on the site and by email. ' + estText(nx.estStartCt) + ' Until it starts you can edit it for free, or cancel it for a full refund.', ok: 'Pay ' + fmt(L.credits) + ' and reserve' });
|
||||
if (!ok) return;
|
||||
body.reserve = true;
|
||||
}
|
||||
$('fGo').disabled = true;
|
||||
try { await api('/api/my/campaigns', body); toast(TYPE === 'login' ? 'Launched. Your login-ad slot runs for ' + slotInfo().days + ' days.' : 'Launched. It is live in rotation now.'); $('composer').hidden = true; $('fName').value = ''; load(); } catch (e) { toast(e.message, true); } finally { $('fGo').disabled = TYPE === 'login' && !slotInfo().free; }
|
||||
try { const r = await api('/api/my/campaigns', body); const c = r.campaign || {};
|
||||
toast(c.status === 'queued' ? 'Reserved and paid. You are #' + (c.place || '?') + ' in line. We let you know when it starts.' : TYPE === 'login' ? 'Launched. Your login-ad slot runs for ' + slotInfo().days + ' days.' : 'Launched. It is live in rotation now.');
|
||||
$('composer').hidden = true; $('fName').value = ''; load(); } catch (e) { toast(e.message, true); } finally { $('fGo').disabled = false; }
|
||||
});
|
||||
CR.requireSession(load);
|
||||
})();
|
||||
|
||||
+1
-1
@@ -905,7 +905,7 @@
|
||||
visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' };
|
||||
const whereHint = () => { const el = $('cWhere'); if (!el) return; const t = $('cType').value; let s = WHERE[t] || '';
|
||||
if (t === 'login' && lastRates) s = s.replace('1,000', (lastRates.loginSlotCredits || 1000).toLocaleString()).replace('30 days', (lastRates.loginSlotDays || 30) + ' days').replace('3 slots', (lastRates.loginSlotsMax || 3) + ' slots');
|
||||
if (t === 'login' && lastSlots) s += lastSlots.free ? ' ' + lastSlots.free + ' of ' + lastSlots.max + ' slots open right now.' : ' All ' + lastSlots.max + ' slots are taken right now; a place opens when a running slot ends its ' + lastSlots.days + ' days.';
|
||||
if (t === 'login' && lastSlots) s += lastSlots.free ? ' ' + lastSlots.free + ' of ' + lastSlots.max + ' slots open right now.' : ' All ' + lastSlots.max + ' slots are taken right now. You can reserve the next one on the Ads screen (' + location.origin + '/ads): pay now, it starts when a slot frees, and a cancel before then refunds in full.';
|
||||
el.textContent = s; };
|
||||
whereHint();
|
||||
// runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
|
||||
|
||||
+1
-1
@@ -1012,7 +1012,7 @@
|
||||
<script src="/assets/tools.js?v=20261011a"></script>
|
||||
<script src="/assets/wallet.js?v=20261021a"></script>
|
||||
<script src="/assets/promo.js?v=20261020bs3"></script>
|
||||
<script src="/assets/my.js?v=20261020bs3"></script>
|
||||
<script src="/assets/my.js?v=20261023q"></script>
|
||||
<script src="/assets/chat.js?v=20261016a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// Prepaid login-slot queue, end to end over HTTP (2026-10-23). Boots server.js on its own port with a throwaway, seeded
|
||||
// data dir (JSON store, no DB, no mail, devCode sign-in, NAS off, no chain: free members whose credits are credited
|
||||
// purchased ones), then: six slots full; a buy without reserve is refused with the offer; two members reserve and pay;
|
||||
// place, estimate and credit activity on GET; balances drop; free edit; admin sees the line and cancels one with a full
|
||||
// refund; a running slot is paused and the first reservation starts at once (on-site notice); the paused slot cannot
|
||||
// come back while the line holds the slots; the Ads screen in Playwright (Reserve button, In line row, no page errors).
|
||||
// node qa/loginqueue.e2e.mjs (from the site dir)
|
||||
// Env: PORT (default 8971), PW (playwright package dir), SHOTS (default D:/tmp/login-queue)
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const PORT = Number(process.env.PORT || 8971);
|
||||
const SHOTS = process.env.SHOTS || 'D:/tmp/login-queue';
|
||||
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
|
||||
const ADMIN_PW = 'localtest-lq';
|
||||
const results = []; let failed = 0;
|
||||
const check = (ok, what, detail) => { results.push((ok ? 'PASS ' : 'FAIL ') + what + (detail ? ' :: ' + detail : '')); if (!ok) failed++; };
|
||||
const DAY = 86400000, now = Date.now();
|
||||
|
||||
// ── seed: six filler owners with a live slot each (ends on day 1..6), and two members A and B with 2,000 credited purchased credits ──
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lq-e2e-'));
|
||||
fs.mkdirSync(path.join(DATA, 'uploads'));
|
||||
const em = n => n + '@lq.test';
|
||||
const names = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'a', 'b'];
|
||||
const accounts = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: names.length, positions: {} };
|
||||
for (const n of names) { accounts.byEmail[em(n)] = { email: em(n), username: 'lq' + n, code: 'lq' + n, memberId: 0, created: now - DAY, sponsorRef: '' }; accounts.byCode['lq' + n] = em(n); }
|
||||
fs.writeFileSync(path.join(DATA, 'accounts.json'), JSON.stringify(accounts));
|
||||
const earned = {}; for (const n of names) earned[em(n)] = { balance: n.startsWith('f') ? 0 : 2000, grade: n.startsWith('f') ? 0 : 2000, welcomed: true };
|
||||
fs.writeFileSync(path.join(DATA, 'earned.json'), JSON.stringify(earned));
|
||||
fs.writeFileSync(path.join(DATA, 'adrates.json'), JSON.stringify({ loginSlotsMax: 6 }));
|
||||
const camps = [1, 2, 3, 4, 5, 6].map(i => ({ id: i, owner: em('f' + i), memberId: 0, type: 'login', name: 'Filler ' + i, targetUrl: 'https://example.com/f' + i, imageUrl: null, title: null, body: '30',
|
||||
budget: 1000, spent: 1000, accrued: 0, imps: 0, clicks: 0, batchImps: 0, status: 'active', created: now - 29 * DAY, expires: now + i * DAY }));
|
||||
fs.writeFileSync(path.join(DATA, 'campaigns.json'), JSON.stringify({ v: 1, nextId: 7, burnsPending: [], campaigns: camps }));
|
||||
fs.mkdirSync(SHOTS, { recursive: true });
|
||||
|
||||
const site = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@lq.test' });
|
||||
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'ENGINE_KEY_FILE', 'LS_SYNC_SECRET', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_KEY', 'SENDGRID_API_KEY']) delete env[k];
|
||||
const log = fs.createWriteStream(path.join(SHOTS, 'server.log'));
|
||||
const srv = spawn(process.execPath, ['server.js'], { cwd: site, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
srv.stdout.pipe(log); srv.stderr.pipe(log);
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
function req(method, p, o) {
|
||||
o = o || {};
|
||||
return new Promise((resolve, reject) => {
|
||||
const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) QA' }, o.headers || {});
|
||||
if (o.cookie) headers.Cookie = o.cookie; if (o.ip) headers['X-Forwarded-For'] = o.ip;
|
||||
let body = o.body; if (body && !Buffer.isBuffer(body)) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; }
|
||||
if (body) headers['Content-Length'] = body.length;
|
||||
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, buf, json: j }); }); });
|
||||
r.on('error', reject); if (body) r.write(body); r.end();
|
||||
});
|
||||
}
|
||||
async function signIn(email) {
|
||||
const ip = '10.9.' + crypto.randomInt(250) + '.' + crypto.randomInt(250);
|
||||
const s = await req('POST', '/api/auth/email/start', { ip, body: { email, fts: Date.now() - 8000, hp_field_x9: '', pick: null } });
|
||||
if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.buf.toString().slice(0, 200));
|
||||
const v = await req('POST', '/api/auth/email/verify', { ip, body: { email, code: s.json.devCode } });
|
||||
const sc = [].concat(v.headers['set-cookie'] || []).map(c => c.split(';')[0]).join('; ');
|
||||
if (!sc) throw new Error('no session cookie for ' + email);
|
||||
return sc;
|
||||
}
|
||||
const err = r => (r.json && r.json.error) || ('HTTP ' + r.status);
|
||||
const ADMIN = { Authorization: 'Bearer ' + ADMIN_PW };
|
||||
const loginBody = (name, extra) => Object.assign({ type: 'login', name, targetUrl: 'https://example.com/' + name.toLowerCase().replace(/\W+/g, '-'), budget: 1000 }, extra || {});
|
||||
|
||||
let browser = null; const pageErrors = [];
|
||||
try {
|
||||
for (let i = 0; i < 40; i++) { try { const r = await req('GET', '/api/config'); if (r.status === 200) break; } catch (e) {} await sleep(500); }
|
||||
const cA = await signIn(em('a')), cB = await signIn(em('b')), cF1 = await signIn(em('f1'));
|
||||
const camps = async c => (await req('GET', '/api/my/campaigns', { cookie: c })).json;
|
||||
|
||||
const g0 = await camps(cA);
|
||||
check(g0.loginSlots && g0.loginSlots.max === 6 && g0.loginSlots.used === 6 && g0.loginSlots.free === 0, 'six slots live, none free', JSON.stringify(g0.loginSlots));
|
||||
check(g0.loginNext && g0.loginNext.place === 1 && /\d{4}$/.test(g0.loginNext.estStartCt || ''), 'a new reservation would be #1 with an estimated date', JSON.stringify(g0.loginNext));
|
||||
const avA0 = g0.availableCredits;
|
||||
|
||||
const no = await req('POST', '/api/my/campaigns', { cookie: cA, body: loginBody('A slot') });
|
||||
check(no.status === 400 && no.json.canReserve === true && /reserve the next slot/i.test(err(no)), 'buy without reserve: refused with the reserve offer', err(no));
|
||||
check((await camps(cA)).availableCredits === avA0, 'the refused buy charged nothing', String(avA0));
|
||||
|
||||
const ra = await req('POST', '/api/my/campaigns', { cookie: cA, body: loginBody('A slot', { reserve: true }) });
|
||||
check(ra.status === 200 && ra.json.campaign.status === 'queued' && ra.json.campaign.place === 1, 'A reserves: queued, #1', err(ra) + ' ' + JSON.stringify(ra.json && ra.json.campaign && { s: ra.json.campaign.status, p: ra.json.campaign.place }));
|
||||
const rb = await req('POST', '/api/my/campaigns', { cookie: cB, body: loginBody('B slot', { reserve: true }) });
|
||||
check(rb.status === 200 && rb.json.campaign.status === 'queued' && rb.json.campaign.place === 2, 'B reserves: queued, #2', err(rb));
|
||||
const QA = ra.json.campaign.id, QB = rb.json.campaign.id;
|
||||
|
||||
const g1 = await camps(cA), gb1 = await camps(cB);
|
||||
check(g1.availableCredits === avA0 - 1000, 'A paid now: available down by 1,000', avA0 + ' -> ' + g1.availableCredits);
|
||||
check(gb1.availableCredits === 1000, 'B paid now: available 2,000 -> 1,000', String(gb1.availableCredits));
|
||||
check(g1.loginQueue.length === 1 && g1.loginQueue[0].id === QA && g1.loginQueue[0].place === 1 && g1.loginQueue[0].estStart === now + DAY, 'A sees place #1, estimate = when slot 1 ends', JSON.stringify(g1.loginQueue));
|
||||
check(gb1.loginQueue[0].place === 2 && gb1.loginQueue[0].estStart === now + 2 * DAY && /^[A-Z][a-z]{2} \d{1,2}, \d{4}$/.test(gb1.loginQueue[0].estStartCt), 'B sees place #2, estimate = when slot 2 ends (Central date)', JSON.stringify(gb1.loginQueue));
|
||||
check(g1.creditLog[0] && g1.creditLog[0].reason === 'Login slot reserved (queue #1)' && g1.creditLog[0].delta === -1000, 'credit activity: Login slot reserved (queue #1)', JSON.stringify(g1.creditLog));
|
||||
check(gb1.creditLog[0] && gb1.creditLog[0].reason === 'Login slot reserved (queue #2)', 'credit activity: Login slot reserved (queue #2)', JSON.stringify(gb1.creditLog));
|
||||
check(g1.loginSlots.queued === 2 && g1.loginSlots.free === 0 && g1.loginNext.place === 3, 'the line is 2 long; next would be #3', JSON.stringify([g1.loginSlots, g1.loginNext]));
|
||||
|
||||
const ed = await req('POST', '/api/my/campaigns/' + QA + '/edit', { cookie: cA, body: { targetUrl: 'https://example.com/a-fixed' } });
|
||||
check(ed.status === 200 && ed.json.fee === 0 && ed.json.campaign.edits === 0, 'edit while queued: free, free correction kept', err(ed));
|
||||
const ps = await req('POST', '/api/my/campaigns/' + QA + '/resume', { cookie: cA });
|
||||
check(ps.status === 400 && /in line/.test(err(ps)), 'a reservation cannot be resumed into a slot by hand', err(ps));
|
||||
|
||||
const aq = await req('GET', '/api/admin/login-queue', { headers: ADMIN });
|
||||
check(aq.status === 200 && aq.json.queue.map(x => x.id).join() === QA + ',' + QB && aq.json.slots.used === 6, 'admin sees the line in order', JSON.stringify(aq.json && aq.json.queue.map(x => [x.id, x.place])));
|
||||
check((await req('GET', '/api/admin/login-queue')).status === 401, 'admin queue needs admin');
|
||||
const ac = await req('POST', '/api/admin/campaigns/' + QB + '/cancel-reservation', { headers: ADMIN });
|
||||
check(ac.status === 200 && ac.json.refunded === 1000, 'admin cancels B: 1,000 refunded', err(ac));
|
||||
const gb2 = await camps(cB);
|
||||
check(gb2.availableCredits === 2000 && gb2.campaigns.find(c => c.id === QB).status === 'cancelled', 'B back to 2,000 available, ad cancelled', String(gb2.availableCredits));
|
||||
check(/Login slot reservation cancelled: refund/.test(gb2.creditLog[0].reason) && gb2.creditLog[0].delta === 1000, 'credit activity: the refund line', JSON.stringify(gb2.creditLog[0]));
|
||||
const ac2 = await req('POST', '/api/my/campaigns/' + QB + '/cancel-reservation', { cookie: cB });
|
||||
check(ac2.status === 400 && (await camps(cB)).availableCredits === 2000, 'a second cancel refunds nothing', err(ac2));
|
||||
|
||||
// B reserves again (back of the line, #2), then f1 pauses: A starts at once, B moves to #1
|
||||
const rb2 = await req('POST', '/api/my/campaigns', { cookie: cB, body: loginBody('B again', { reserve: true }) });
|
||||
check(rb2.status === 200 && rb2.json.campaign.place === 2, 'B reserves again at the back (#2)', err(rb2));
|
||||
const pz = await req('POST', '/api/my/campaigns/1/pause', { cookie: cF1 });
|
||||
check(pz.status === 200, 'f1 pauses its running slot', err(pz));
|
||||
const g2 = await camps(cA); const a2 = g2.campaigns.find(c => c.id === QA);
|
||||
check(a2.status === 'active' && a2.promotedAt && Math.abs(a2.expires - a2.promotedAt - 30 * DAY) < 5, 'A started right away, 30 days from now', JSON.stringify({ s: a2.status, p: a2.promotedAt, e: a2.expires }));
|
||||
check(g2.availableCredits === avA0 - 1000, 'starting charged A nothing more', String(g2.availableCredits));
|
||||
const msgs = (await req('GET', '/api/my/messages', { cookie: cA })).json;
|
||||
check(msgs.items.some(m => /Your login ad is live/.test(m.subject || '')), 'A got the on-site notice', JSON.stringify(msgs.items.map(m => m.subject)));
|
||||
const gb3 = await camps(cB);
|
||||
check(gb3.loginQueue[0] && gb3.loginQueue[0].place === 1, 'B moved up to #1', JSON.stringify(gb3.loginQueue));
|
||||
const rs = await req('POST', '/api/my/campaigns/1/resume', { cookie: cF1 });
|
||||
check(rs.status === 400 && /reservation/.test(err(rs)), 'f1 cannot resume while the line holds the slots', err(rs));
|
||||
|
||||
// ── the Ads screen ──
|
||||
try {
|
||||
const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default;
|
||||
browser = await chromium.launch();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });
|
||||
await ctx.addCookies(cB.split('; ').map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
|
||||
await ctx.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} }); // the login-sponsor interstitial already ran this session
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', e => pageErrors.push(e.message));
|
||||
page.on('console', m => { if (m.type() === 'error' && !/favicon|Failed to load resource/.test(m.text())) pageErrors.push('console: ' + m.text()); });
|
||||
await page.goto('http://127.0.0.1:' + PORT + '/ads', { waitUntil: 'networkidle' });
|
||||
try { await page.waitForSelector('#rows .rw', { timeout: 10000 }); } catch (e) { await page.screenshot({ path: path.join(SHOTS, 'ads-fail.png'), fullPage: true }); throw new Error(String(e.message).slice(0, 80) + ' :: page: ' + (await page.locator('body').innerText()).split(/\s+/).join(' ').slice(0, 300) + ' :: errors: ' + pageErrors.join(' / ')); }
|
||||
const rowText = await page.locator('#rows').textContent();
|
||||
check(/In line/.test(rowText) && /#1 in line/.test(rowText) && /Cancel and refund/.test(rowText), 'Ads screen row: In line, #1, Cancel and refund', rowText.replace(/\s+/g, ' ').slice(0, 300));
|
||||
check(/Cancelled, refunded/.test(rowText), 'Ads screen row: the cancelled one shows refunded', '');
|
||||
const cl = await page.locator('#creditLog').textContent();
|
||||
check(/Login slot reserved \(queue #2\)/.test(cl) && /cancelled: refund/.test(cl), 'Credit activity panel lists the reserve and the refund', cl.replace(/\s+/g, ' ').slice(0, 200));
|
||||
await page.click('#newBtn'); await page.click('#typeChips .chip[data-t="login"]');
|
||||
const btn = await page.locator('#fGo').textContent(), dis = await page.locator('#fGo').isDisabled(), costTxt = await page.locator('#fCost').textContent();
|
||||
check(btn === 'Reserve the next slot' && !dis, 'composer: Reserve the next slot (enabled, not a dead button)', btn + ' disabled=' + dis);
|
||||
check(/#2 in line/.test(costTxt) && /estimate/i.test(costTxt) && /full refund/.test(costTxt), 'composer says place, estimate and refund rule', costTxt);
|
||||
await page.screenshot({ path: path.join(SHOTS, 'ads-reserve.png'), fullPage: true });
|
||||
await page.fill('#fName', 'B third'); await page.fill('#fTarget', 'https://example.com/b-third');
|
||||
await page.click('#fGo');
|
||||
await page.waitForSelector('#crModalHost .modal', { timeout: 5000 });
|
||||
const dlg = await page.locator('#crModalHost .modal').textContent();
|
||||
check(/Reserve the next login-ad slot/.test(dlg) && /full refund/.test(dlg) && /estimate/i.test(dlg), 'reserve asks first, in an in-page dialog', dlg.replace(/\s+/g, ' ').slice(0, 260));
|
||||
await page.screenshot({ path: path.join(SHOTS, 'ads-reserve-dialog.png') });
|
||||
await page.click('#dlgNo'); // do not reserve a third
|
||||
check(!/\u2014/.test(rowText + costTxt + dlg), 'no em dashes in the new copy');
|
||||
check(!pageErrors.length, 'no page errors', pageErrors.join(' | '));
|
||||
} catch (e) { check(false, 'Playwright pass ran', e.message); }
|
||||
} catch (e) {
|
||||
check(false, 'run completed', e.stack || e.message);
|
||||
} finally {
|
||||
if (browser) await browser.close().catch(() => {});
|
||||
srv.kill();
|
||||
await sleep(300);
|
||||
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||
}
|
||||
console.log(results.join('\n'));
|
||||
console.log('\n' + (results.length - failed) + ' passed, ' + failed + ' failed (screenshots + server log in ' + SHOTS + ')');
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -0,0 +1,203 @@
|
||||
// Prepaid login-slot queue (Marty, 2026-10-23: "they need to pay for the slot now to get a place in line").
|
||||
// Unit test on ads.js directly: a throwaway DATA_DIR, the JSON store (no DATABASE_URL), a fake chain (free members, so
|
||||
// every credit is engine-side), no server, no mail, no network. Checks:
|
||||
// 6 slots filled; a 7th buy is refused unless it reserves; two reservations pay now (balances drop, credit activity);
|
||||
// places and estimated start dates; a reservation never serves; free edit while queued; owner cannot resume it;
|
||||
// one slot expires -> two app copies (child processes on the same DATA_DIR, the deploy overlap) promote at the same
|
||||
// moment -> the first reservation starts exactly once, one notice; the stale copy adopts it and never re-promotes;
|
||||
// cancel the second -> full refund, once; a paused slot frees its place to the line and cannot resume while the line
|
||||
// holds the slots; raising the slot count lets it back in.
|
||||
// node qa/loginqueue.test.cjs
|
||||
'use strict';
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
for (const k of ['DATABASE_URL', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'OUTBOUND', 'ENGINE_KEY']) delete process.env[k];
|
||||
const SITE = path.join(__dirname, '..');
|
||||
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'lq-unit-'));
|
||||
const ads = require(path.join(SITE, 'ads.js'));
|
||||
const chain = { creditBalance: async () => 0 };
|
||||
|
||||
let passed = 0, failed = 0; const results = [];
|
||||
async function t(name, fn) { try { await fn(); passed++; results.push('ok ' + name); } catch (e) { failed++; results.push('FAIL ' + name + '\n ' + String(e && e.stack || e).split('\n').slice(0, 4).join('\n ')); } }
|
||||
const DAY = 86400000;
|
||||
const em = n => n.toLowerCase() + '@lq.test';
|
||||
const owners = ['f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'A', 'B', 'C', 'D'];
|
||||
const earned = {}; for (const o of owners) earned[em(o)] = { balance: 3000, grade: 3000, welcomed: true }; // credited purchased credits
|
||||
fs.writeFileSync(path.join(DATA, 'earned.json'), JSON.stringify(earned));
|
||||
const login = (name, extra) => Object.assign({ type: 'login', name, targetUrl: 'https://example.com/' + encodeURIComponent(name), budget: 1000 }, extra || {});
|
||||
const grade = async o => (await ads.earnedSplit(em(o))).grade;
|
||||
const notes = [];
|
||||
|
||||
// one more app copy on the same volume (what a deploy overlap is): load ads.js fresh, wait for a shared start moment,
|
||||
// run the promotion, report what it promoted and what it notified
|
||||
function copy(startAt, tag) {
|
||||
const code = `
|
||||
const path = require('path'); const fs = require('fs');
|
||||
const ads = require(${JSON.stringify(path.join(SITE, 'ads.js'))});
|
||||
ads.init({ dataDir: ${JSON.stringify(DATA)}, chain: { creditBalance: async () => 0 } });
|
||||
const told = []; ads.setLoginQueueNotifier(async c => { told.push(c.id); });
|
||||
const go = async () => { const out = await ads.promoteLoginQueue(); process.stdout.write(JSON.stringify({ tag: ${JSON.stringify(tag)}, promoted: out.map(c => c.id), told })); };
|
||||
setTimeout(go, Math.max(0, ${startAt} - Date.now()));`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const env = Object.assign({}, process.env); delete env.DATABASE_URL;
|
||||
const p = spawn(process.execPath, ['-e', code], { cwd: SITE, env });
|
||||
let out = '', err = ''; p.stdout.on('data', d => out += d); p.stderr.on('data', d => err += d);
|
||||
p.on('close', c => { try { resolve(JSON.parse(out.slice(out.lastIndexOf('{"tag"')))); } catch (e) { reject(new Error('copy ' + tag + ' exit ' + c + ': ' + out + err)); } });
|
||||
});
|
||||
}
|
||||
|
||||
(async () => {
|
||||
ads.init({ dataDir: DATA, chain });
|
||||
ads.setRates({ loginSlotsMax: 6 });
|
||||
ads.setLoginQueueNotifier(async (c, info) => { notes.push({ id: c.id, info }); });
|
||||
const F = {}, Q = {};
|
||||
|
||||
await t('estimate math: live end dates, open places start now, each place ahead takes a full run', () => {
|
||||
const now = 1e12;
|
||||
const e6 = [1, 2, 3, 4, 5, 6].map(d => now + d * DAY);
|
||||
assert.deepStrictEqual(ads._estimateStarts(e6, 6, 2, now, 30), [now + DAY, now + 2 * DAY]);
|
||||
assert.deepStrictEqual(ads._estimateStarts(e6.slice(0, 5), 6, 2, now, 30), [now, now + DAY]); // one open place: now
|
||||
assert.deepStrictEqual(ads._estimateStarts([now + DAY], 1, 3, now, 30), [now + DAY, now + 31 * DAY, now + 61 * DAY]);
|
||||
assert.deepStrictEqual(ads._estimateStarts([Infinity], 1, 1, now, 30), [null]); // legacy slot with no end: no estimate
|
||||
});
|
||||
|
||||
await t('six member slots fill; slots read full', async () => {
|
||||
for (let i = 1; i <= 6; i++) {
|
||||
const r = await ads.createCampaign(em('f' + i), 0, login('fill' + i), []);
|
||||
assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.campaign.status, 'active');
|
||||
F[i] = r.campaign.id;
|
||||
(await ads.campaignById(F[i])).expires = Date.now() + i * DAY; // staggered ends: slot i frees on day i
|
||||
}
|
||||
const ls = await ads.loginSlots();
|
||||
assert.deepStrictEqual([ls.max, ls.used, ls.queued, ls.free], [6, 6, 0, 0]);
|
||||
});
|
||||
|
||||
await t('a 7th buy is refused with the reserve offer, and nothing is charged', async () => {
|
||||
const r = await ads.createCampaign(em('A'), 0, login('A slot'), []);
|
||||
assert.ok(r.error && r.full && r.canReserve, JSON.stringify(r));
|
||||
assert.ok(/reserve the next slot/i.test(r.error) && !/—/.test(r.error), r.error);
|
||||
assert.strictEqual(await grade('A'), 3000);
|
||||
});
|
||||
|
||||
await t('two reservations pay now: queued, places 1 and 2, balances down 1000 each, credit activity written', async () => {
|
||||
const a = await ads.createCampaign(em('A'), 0, login('A slot', { reserve: true }), []);
|
||||
const b = await ads.createCampaign(em('B'), 0, login('B slot', { reserve: true }), []);
|
||||
assert.ok(a.ok && b.ok, JSON.stringify([a, b]));
|
||||
Q.A = a.campaign.id; Q.B = b.campaign.id;
|
||||
assert.strictEqual(a.campaign.status, 'queued'); assert.strictEqual(b.campaign.status, 'queued');
|
||||
assert.strictEqual(a.campaign.place, 1); assert.strictEqual(b.campaign.place, 2);
|
||||
assert.strictEqual(a.campaign.expires, null, 'no 30-day clock while queued');
|
||||
assert.strictEqual(await grade('A'), 2000); assert.strictEqual(await grade('B'), 2000);
|
||||
const la = await ads.creditLog(em('A')), lb = await ads.creditLog(em('B'));
|
||||
assert.strictEqual(la[0].reason, 'Login slot reserved (queue #1)'); assert.strictEqual(la[0].delta, -1000);
|
||||
assert.strictEqual(lb[0].reason, 'Login slot reserved (queue #2)');
|
||||
const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued, ls.free], [6, 2, 0]);
|
||||
});
|
||||
|
||||
await t('places and estimated starts: #1 when slot 1 ends, #2 when slot 2 ends, Central-time date labels', async () => {
|
||||
const q = await ads.loginQueue();
|
||||
assert.deepStrictEqual(q.map(x => [x.id, x.place]), [[Q.A, 1], [Q.B, 2]]);
|
||||
const e1 = (await ads.campaignById(F[1])).expires, e2 = (await ads.campaignById(F[2])).expires;
|
||||
assert.strictEqual(q[0].estStart, e1); assert.strictEqual(q[1].estStart, e2);
|
||||
assert.ok(/^[A-Z][a-z]{2} \d{1,2}, \d{4}$/.test(q[0].estStartCt), q[0].estStartCt);
|
||||
const mine = await ads.myLoginQueue(em('B')); assert.strictEqual(mine.length, 1); assert.strictEqual(mine[0].place, 2);
|
||||
const nx = await ads.loginNext(); assert.strictEqual(nx.place, 3); assert.strictEqual(nx.estStart, (await ads.campaignById(F[3])).expires);
|
||||
});
|
||||
|
||||
await t('a reservation never serves', async () => {
|
||||
for (let i = 0; i < 60; i++) { const s = await ads.serve('login', {}); assert.ok(s && ![Q.A, Q.B].includes(s.id), 'served ' + (s && s.id)); }
|
||||
});
|
||||
|
||||
await t('edits while queued are free and keep the free correction; owner cannot pause/resume a reservation', async () => {
|
||||
const r = await ads.editCampaign(em('A'), Q.A, { targetUrl: 'https://example.com/A-new' }, { fee: 100, ids: [] });
|
||||
assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.fee, 0); assert.strictEqual(r.campaign.edits, 0);
|
||||
const r2 = await ads.editCampaign(em('A'), Q.A, { name: 'A slot renamed' }, { fee: 100, ids: [] });
|
||||
assert.ok(r2.ok && r2.fee === 0 && r2.campaign.edits === 0, JSON.stringify(r2));
|
||||
assert.strictEqual(await grade('A'), 2000);
|
||||
for (const st of ['active', 'paused']) { const s = await ads.setStatus(em('A'), Q.A, st); assert.ok(s.error && /in line/.test(s.error), JSON.stringify(s)); }
|
||||
assert.strictEqual((await ads.campaignById(Q.A)).status, 'queued');
|
||||
});
|
||||
|
||||
await t('slot 1 expires; two app copies promote at the same moment: #1 starts exactly once, one notice', async () => {
|
||||
(await ads.campaignById(F[1])).expires = Date.now() - 1000;
|
||||
await ads.click(F[1]); // any write: the store on disk now has slot 1 ended (the copies read the disk)
|
||||
const at = Date.now() + 700;
|
||||
const [x, y] = await Promise.all([copy(at, 'x'), copy(at, 'y')]);
|
||||
const all = x.promoted.concat(y.promoted), told = x.told.concat(y.told);
|
||||
assert.deepStrictEqual(all, [Q.A], JSON.stringify([x, y]));
|
||||
assert.deepStrictEqual(told, [Q.A], 'one notice: ' + JSON.stringify([x, y]));
|
||||
const L = JSON.parse(fs.readFileSync(path.join(DATA, 'login-queue.json'), 'utf8'));
|
||||
assert.deepStrictEqual(Object.keys(L.promoted), [String(Q.A)]);
|
||||
assert.ok(!fs.existsSync(path.join(DATA, 'login-queue.lock')), 'lock released');
|
||||
});
|
||||
|
||||
await t('the stale copy (this process still had #1 queued) adopts the start and promotes nothing; again: nothing', async () => {
|
||||
const before = notes.length;
|
||||
const p1 = await ads.promoteLoginQueue(), p2 = await ads.promoteLoginQueue();
|
||||
assert.deepStrictEqual(p1, []); assert.deepStrictEqual(p2, []);
|
||||
assert.strictEqual(notes.length, before, 'no second notice');
|
||||
const a = await ads.campaignById(Q.A);
|
||||
assert.strictEqual(a.status, 'active'); assert.ok(Math.abs(a.expires - (a.promotedAt + 30 * DAY)) < 5, 'runs 30 days from its start');
|
||||
assert.ok(a.promotedAt > Date.now() - 60000);
|
||||
assert.strictEqual((await ads.campaignById(Q.B)).status, 'queued'); // six live again: B waits
|
||||
const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued], [6, 1]);
|
||||
assert.strictEqual((await ads.loginQueue())[0].place, 1, 'B moved up to #1');
|
||||
assert.strictEqual(await grade('A'), 2000, 'promotion charges nothing more');
|
||||
});
|
||||
|
||||
await t('cancel the second before start: full refund, once; it cannot be resumed or edited after', async () => {
|
||||
const r = await ads.cancelLoginReservation(em('B'), Q.B);
|
||||
assert.ok(r.ok, JSON.stringify(r)); assert.strictEqual(r.refunded, 1000);
|
||||
assert.strictEqual(await grade('B'), 3000);
|
||||
assert.strictEqual((await ads.creditLog(em('B')))[0].reason, 'Login slot reservation cancelled: refund');
|
||||
assert.strictEqual((await ads.creditLog(em('B')))[0].delta, 1000);
|
||||
const again = await ads.cancelLoginReservation(em('B'), Q.B); assert.ok(again.error, JSON.stringify(again));
|
||||
assert.strictEqual(await grade('B'), 3000, 'no double refund');
|
||||
assert.ok((await ads.setStatus(em('B'), Q.B, 'active')).error);
|
||||
assert.ok((await ads.editCampaign(em('B'), Q.B, { name: 'x' }, { fee: 0 })).error);
|
||||
assert.ok((await ads.cancelLoginReservation(em('A'), Q.A)).error, 'a started slot is not refundable');
|
||||
assert.ok((await ads.cancelLoginReservation(em('C'), Q.B)).error, 'not your reservation');
|
||||
});
|
||||
|
||||
await t('a paused slot frees its place to the line, and cannot resume while the line holds the slots', async () => {
|
||||
const c = await ads.createCampaign(em('C'), 0, login('C slot', { reserve: true }), []);
|
||||
assert.strictEqual(c.campaign.status, 'queued'); Q.C = c.campaign.id;
|
||||
const p = await ads.setStatus(em('f2'), F[2], 'paused'); assert.ok(p.ok, JSON.stringify(p));
|
||||
assert.strictEqual((await ads.campaignById(Q.C)).status, 'active', 'C took the paused slot');
|
||||
const d = await ads.createCampaign(em('D'), 0, login('D slot', { reserve: true }), []);
|
||||
assert.strictEqual(d.campaign.status, 'queued'); Q.D = d.campaign.id;
|
||||
const r1 = await ads.setStatus(em('f2'), F[2], 'active');
|
||||
assert.ok(r1.error && /reservation/.test(r1.error), JSON.stringify(r1));
|
||||
ads.setRates({ loginSlotsMax: 7 }); // one more place, but D is waiting: D gets it, f2 still waits
|
||||
const r2 = await ads.setStatus(em('f2'), F[2], 'active');
|
||||
assert.ok(r2.error, JSON.stringify(r2));
|
||||
assert.strictEqual((await ads.campaignById(Q.D)).status, 'active', 'the line goes first');
|
||||
ads.setRates({ loginSlotsMax: 8 }); // now a place is open with nobody waiting
|
||||
const r3 = await ads.setStatus(em('f2'), F[2], 'active'); assert.ok(r3.ok, JSON.stringify(r3));
|
||||
const ls = await ads.loginSlots(); assert.deepStrictEqual([ls.used, ls.queued, ls.free], [8, 0, 0]);
|
||||
});
|
||||
|
||||
await t('admin cancel refunds any owner in full', async () => {
|
||||
ads.setRates({ loginSlotsMax: 8 });
|
||||
const e = await ads.createCampaign(em('A'), 0, login('A second', { reserve: true }), []);
|
||||
assert.strictEqual(e.campaign.status, 'queued');
|
||||
assert.strictEqual(await grade('A'), 1000);
|
||||
const r = await ads.cancelLoginReservation(null, e.campaign.id, { admin: true });
|
||||
assert.ok(r.ok && r.refunded === 1000, JSON.stringify(r));
|
||||
assert.strictEqual(await grade('A'), 2000);
|
||||
assert.ok(/by the admin/.test((await ads.creditLog(em('A')))[0].reason));
|
||||
});
|
||||
|
||||
await t('no notice went out for anything but the promotions; the promotion notice carries the run', () => {
|
||||
assert.deepStrictEqual(notes.map(n => n.id), [Q.C, Q.D]); // A's notice came from the other app copy
|
||||
assert.strictEqual(notes[0].info.days, 30); assert.ok(notes[0].info.endsCt);
|
||||
});
|
||||
|
||||
console.log(results.join('\n'));
|
||||
console.log('\n' + passed + ' passed, ' + failed + ' failed (data dir ' + DATA + ')');
|
||||
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
|
||||
process.exit(failed ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -7,6 +7,7 @@
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard
|
||||
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
|
||||
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
|
||||
# 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/.
|
||||
set -u
|
||||
@@ -35,6 +36,9 @@ elif [ "$MODE" = "member" ]; then
|
||||
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||
node qa/sponsorfollow.test.cjs || status=1
|
||||
node qa/carry-hold.test.cjs || status=1
|
||||
elif [ "$MODE" = "loginqueue" ]; then
|
||||
node qa/loginqueue.test.cjs || status=1
|
||||
node qa/loginqueue.e2e.mjs || status=1
|
||||
elif [ "$MODE" = "lsid" ]; then
|
||||
node qa/lsid-pixel.test.mjs || status=1
|
||||
elif [ "$MODE" = "kb" ]; then
|
||||
|
||||
@@ -611,6 +611,17 @@ async function boot() {
|
||||
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
||||
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
||||
// prepaid login-slot queue (Marty, 2026-10-23): a freed slot goes to the oldest paid reservation within the minute
|
||||
setInterval(() => ads.promoteLoginQueue().catch(e => console.error('login queue', e.message)), 60 * 1000);
|
||||
ads.setLoginQueueNotifier(async (c, info) => {
|
||||
const subject = 'Your login ad is live: ' + c.name;
|
||||
const text = 'Good news. Your reserved login-ad slot "' + c.name + '" (#' + c.id + ') reached the front of the line and started just now.\n\n'
|
||||
+ 'Your page ' + c.targetUrl + ' now shows full screen to every member right after they sign in, for ' + info.days + ' days, until ' + info.endsCt + ' (Central time). '
|
||||
+ 'You paid for it when you reserved, so nothing more is charged.\n\nSee it on the Ads screen: ' + SITE_URL + '/ads';
|
||||
const html = '<p>' + text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>') + '</p>';
|
||||
try { await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [c.owner], subject, html, 'notice'); } catch (e) { console.error('login queue notice', e.message); }
|
||||
try { if (mailer.hasKey() && !(await drip.isUnsubscribed(c.owner))) await mailer.send(c.owner, subject, text + '\n\nStop these emails: ' + drip.unsubUrl(c.owner) + '\n\nLinkSpin'); } catch (e) { console.error('login queue email', e.message); }
|
||||
});
|
||||
// follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot)
|
||||
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig });
|
||||
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
||||
@@ -3388,7 +3399,10 @@ const server = http.createServer(async (req, res) => {
|
||||
let gauntletPending = false;
|
||||
if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; }
|
||||
const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) };
|
||||
out.loginSlots = await ads.loginSlots(); // { max, used, free, credits, days }: the Ads screen shows how many are open
|
||||
out.loginSlots = await ads.loginSlots(); // { max, used, queued, free, credits, days }: the Ads screen shows how many are open
|
||||
out.loginQueue = await ads.myLoginQueue(s.email); // my paid reservations: place in line + estimated start (Central)
|
||||
out.loginNext = await ads.loginNext(); // the place and estimated start a new reservation would get
|
||||
out.creditLog = await ads.creditLog(s.email, 20); // credit activity (login slots, reservations, refunds)
|
||||
out.editFee = editFee(); // credits per edit after each campaign's free one (the editor says which this is)
|
||||
out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id));
|
||||
out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days
|
||||
@@ -3443,6 +3457,13 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
m = /^\/api\/my\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); // a queued login slot: cancel before start = full refund
|
||||
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+)\/(pause|resume)$/.exec(p);
|
||||
if (m && req.method === 'POST') {
|
||||
const s = await auth.fromRequest(req);
|
||||
@@ -3547,6 +3568,16 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await editAd(m[1], await readBody(req), { admin: true });
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/login-queue' && req.method === 'GET') { // the paid login-slot line, oldest first
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, { queue: await ads.loginQueue(), slots: await ads.loginSlots() });
|
||||
}
|
||||
m = /^\/api\/admin\/campaigns\/(\d+)\/cancel-reservation$/.exec(p); // admin cancel + full refund of a queued login slot
|
||||
if (m && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const r = await ads.cancelLoginReservation(null, m[1], { admin: true });
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p);
|
||||
if (m && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
|
||||
Reference in New Issue
Block a user