89b5969b25
- ads.js: a login buy with every slot taken returns full:true and a reserve offer; with reserve:true it is charged the full slot price at once (purchased credits only, credit log 'Login slot reserved (queue #N)') and stored with status 'queued' + queuedAt, no starts/expires, never served or counted as a slot. First paid, first served. - Promotion (promoteLoginQueue): on a slot expiring (scheduleSweep), a member pausing a slot, every new login buy, and a one-minute tick. The oldest reservation becomes active, starts now, ends in 30 days; the owner gets an on-site notice (kind 'notice') and an email unless unsubscribed. - Deploy-overlap safety: the cap decision runs under a lease row in the new app_locks table (one conditional UPDATE takes it, an expired lease can be taken over); every start/cancel/edit is a conditional UPDATE on status='queued', so a reservation starts at most once and a cancel racing a start has exactly one winner. Live login buys and paused-slot resumes also take the lease, so the cap holds for them too. - A freed slot goes to the line first: a paused slot resumes only while live + queued < loginSlotsMax, with a plain message saying the line is ahead. - Cancel before the start: full refund as purchased-grade credits (credit log 'Login slot reservation cancelled: refund'), once. Edit target/image/headline before the start, free. Cancelled reservations can be archived. - Estimated start per place from the live slots' end dates and the reservations ahead, shown in Central time and labelled an estimate. - db.js: campaigns.queued_at BIGINT NULL, app_locks table + 'login_queue' row, all added on boot. - server.js: loginLine in GET /api/my/campaigns, POST /api/my/campaigns/:id/cancel-reservation and /edit-reservation (safe-browsing, reach and image checks), GET /api/admin/login-queue, POST /api/admin/login-queue/:id/cancel, the promotion notice hook and the one-minute tick. - Member UI (my.js, my.html): open slots or the line with place and estimated start on the Login ad form, the button becomes "Reserve the next slot", IAP.confirmBox before paying, In line #N + estimated start in the list, Edit and Cancel and refund. Admin (admin.js, admin.html): Login-ad line card with owner, queued at, place, estimated start, cancel + refund. Tags bumped to 20261023lq. - chatbot.js: new canned 'login-ads' answer and the LOGIN ADS fact updated (6 slots, the paid line, cancel = full refund before start). The knowledge base seeds the new entry on boot. - audit.js: queued/cancelled reservations are not per-day login campaigns. - QA: qa/login-queue.cjs (JSON store end to end) and qa/login-queue-sql.cjs (SQL path guard logic against a fake SQL layer), bash qa/run.sh login-queue. qa/login-slot.mjs pattern follows the refactor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
90 lines
8.5 KiB
JavaScript
90 lines
8.5 KiB
JavaScript
// Counter audit (Marty, 2026-09-15: "buyers will lose confidence if they feel cheated"). Every ad format's
|
|
// recorded impressions are reconciled against the log that proves delivery, and login/featured charging is
|
|
// checked against actual shows. Runs on demand from Admin > Reports and once a day; any issue alerts the admin.
|
|
// DB mode only (production); JSON mode reports "not checked".
|
|
const db = require('./db');
|
|
const fs = require('fs'); const path = require('path');
|
|
let R = null; // { notify(text), dataDir }
|
|
function init(refs) { R = refs; }
|
|
// credits already returned for past counting errors: subtract them so history that was made right does not keep flagging
|
|
function refunded() { const out = {}; try { for (const f of fs.readdirSync(R.dataDir)) if (/^refunds-.*\.json$/.test(f)) for (const i of (JSON.parse(fs.readFileSync(path.join(R.dataDir, f), 'utf8')).items || [])) out[i.id] = (out[i.id] || 0) + Number(i.credits || 0); } catch (e) {} return out; }
|
|
|
|
async function run() {
|
|
const out = { checkedAt: Date.now(), checks: [] };
|
|
if (!db.enabled()) { out.checks.push({ name: 'Counters', ok: true, detail: 'JSON mode: not checked', issues: [] }); return out; }
|
|
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house, expires FROM campaigns WHERE house=0 OR house IS NULL");
|
|
const back = refunded(); for (const c of camps) if (back[c.id]) c.spent = Math.max(0, Number(c.spent) - back[c.id]); // already made right
|
|
const logStart = (await db.q('SELECT MIN(day) d FROM camp_hours'))[0].d; const logStartMs = logStart ? Date.parse(logStart + 'T00:00:00Z') : 0;
|
|
const byType = t => camps.filter(c => c.type === t);
|
|
const add = (name, issues, detail) => out.checks.push({ name, ok: !issues.length, detail, issues });
|
|
// 1. per-view formats: campaign.imps must equal the rows in the log that paid for them
|
|
for (const [type, table, label] of [['video', 'video_seen', 'completed watches'], ['visits', 'visit_seen', 'verified visits'], ['solo', 'solo_inbox', 'inbox deliveries']]) {
|
|
const rows = await db.q('SELECT campaign_id, COUNT(*) n FROM ' + table + ' GROUP BY campaign_id'); const logN = {}; for (const r of rows) logN[r.campaign_id] = Number(r.n);
|
|
// visits are proven by three logs (2026-10-04: 37 false alarms): our viewer (visit_seen), repeat door knocks on Spooky Doors
|
|
// (visit_repeat), and visits delivered on PassiveDrip's PTC page (pdsync.json, read from PassiveDrip, never derived).
|
|
// A counter BELOW its proof is the advertiser getting a visit free; only a counter ABOVE its proof can overcharge them.
|
|
let extra = {};
|
|
if (type === 'visits') {
|
|
for (const r of await db.q('SELECT campaign_id, COUNT(*) n FROM visit_repeat GROUP BY campaign_id')) extra[r.campaign_id] = (extra[r.campaign_id] || 0) + Number(r.n);
|
|
try { const pd = JSON.parse(fs.readFileSync(path.join(R.dataDir, 'pdsync.json'), 'utf8')).served || {}; for (const [id, n] of Object.entries(pd)) extra[id] = (extra[id] || 0) + Number(n || 0); } catch (e) {}
|
|
}
|
|
const issues = []; let tot = 0, logTot = 0, under = 0;
|
|
for (const c of byType(type)) {
|
|
const l = (logN[c.id] || 0) + (extra[c.id] || 0); tot += Number(c.imps); logTot += l;
|
|
if (type === 'visits') { if (Number(c.imps) > l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' counted vs ' + l + ' proven (' + (Number(c.imps) - l) + ' not proven)'); else if (Number(c.imps) < l) under++; }
|
|
else if (Number(c.imps) !== l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' ' + label);
|
|
}
|
|
add(type + ' views vs ' + label, issues, tot + ' views recorded, ' + logTot + ' ' + label + (type === 'visits' ? ' (our viewer + repeat door visits + PassiveDrip)' + (under ? '; ' + under + ' campaign(s) got a visit or two free' : '') : ''));
|
|
}
|
|
// 2. banner/text: imps must equal the hourly log (both bumped on serve)
|
|
{
|
|
const rows = await db.q('SELECT campaign_id, SUM(n) n FROM camp_hours GROUP BY campaign_id'); const h = {}; for (const r of rows) h[r.campaign_id] = Number(r.n);
|
|
const issues = [];
|
|
// only campaigns that started after the hourly log did
|
|
for (const c of camps.filter(c => ['banner', 'text'].includes(c.type) && Number(c.created) >= logStartMs)) { const l = h[c.id] || 0; if (Math.abs(Number(c.imps) - l) > Math.max(5, Math.round(0.02 * Math.max(Number(c.imps), l)))) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' in the hourly log'); }
|
|
add('banner/text views vs hourly log', issues, camps.filter(c => ['banner', 'text'].includes(c.type) && Number(c.created) >= logStartMs).length + ' campaigns compared (started since the hourly log began ' + (logStart || '') + ')');
|
|
}
|
|
// 3. login: days charged vs days shown (a day may only be charged after the ad was shown)
|
|
{
|
|
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 && !['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
|
|
{
|
|
const issues = []; const now = Date.now();
|
|
// counted from when the booking STARTS: a paid booking scheduled for later has no views yet by design
|
|
// (#275 was flagged on 2026-09-27 hours before its 7 PM start)
|
|
for (const c of byType('featured').filter(c => c.status === 'active' && now - Math.max(Number(c.created), Number(c.starts) || 0) > 2 * 3600e3)) if (!Number(c.imps)) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': live with 0 views');
|
|
add('featured: live bookings have views', issues, byType('featured').filter(c => c.status === 'active').length + ' live bookings');
|
|
}
|
|
// 5. clicks can only exceed views where a click precedes the counted view (visits, login)
|
|
{
|
|
const issues = [];
|
|
// only where the buyer was charged: this check protects buyers, and a campaign that never spent a credit
|
|
// cannot have overcharged anyone (#146: a placeholder video that never played, paused by the source
|
|
// sweep, clicks on its button while the player failed, 0 credits spent)
|
|
for (const c of camps.filter(c => !['visits', 'login'].includes(c.type) && Number(c.spent) + Number(c.accrued || 0) > 0 && Number(c.clicks) > Number(c.imps) + 5)) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ' (' + c.type + '): ' + c.clicks + ' clicks vs ' + c.imps + ' views');
|
|
add('clicks vs views', issues, 'campaigns with more clicks than views, where that cannot happen');
|
|
}
|
|
// 6. budgets: spent can never pass budget
|
|
{
|
|
const issues = camps.filter(c => Number(c.spent) + Number(c.accrued || 0) > Number(c.budget) + 1).map(c => '#' + c.id + ' ' + c.name.slice(0, 30) + ': spent ' + (Number(c.spent) + Number(c.accrued || 0)) + ' of ' + c.budget);
|
|
add('spend never exceeds budget', issues, camps.length + ' campaigns');
|
|
}
|
|
return out;
|
|
}
|
|
// the "once a day" memory lives on the volume: a redeploy restarts the process, and Marty got an alert after every deploy (2026-09-15)
|
|
const STATE = () => path.join(R.dataDir, 'audit-state.json');
|
|
function lastAlertDay() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')).lastAlertDay || ''; } catch (e) { return ''; } }
|
|
function setAlertDay(d) { try { fs.writeFileSync(STATE(), JSON.stringify({ lastAlertDay: d })); } catch (e) {} }
|
|
async function dailyTick() {
|
|
try {
|
|
const r = await run(); const bad = r.checks.filter(c => !c.ok); const day = new Date().toISOString().slice(0, 10);
|
|
if (bad.length && lastAlertDay() !== day && R && R.notify) { setAlertDay(day); R.notify('⚠️ InstantAdPay counter audit found ' + bad.length + ' issue' + (bad.length === 1 ? '' : 's') + ': ' + bad.map(c => c.name + ' (' + c.issues.length + ')').join('; ') + '. Admin > Reports > Counters audit.'); }
|
|
return r;
|
|
} catch (e) { console.error('audit', e.message); return null; }
|
|
}
|
|
module.exports = { init, run, dailyTick };
|