Files
martbost fa5acf0745 Network rate 4:1 (Marty approved 2026-10-27): syndicated delivery costs 1/synRateDivisor of the on-site rate, going forward
rates.synRateDivisor (default 4, Admin > Rates; 1 = the old rule). Network Ad Space impressions charge 1 credit per
impressionsPerCredit x N views (banner 20, text 40 at N=4), through the same chargeCredits path (earned pool first,
then on-chain burn), with their own credit-log line "Network views (1/4 rate)". Fractions are exact: the cumulative
served count carries the remainder. The budget is the limit: NAS bookings, resume, top-up and daily allowances are
sized at the network rate, and a live ad booked at the old rate is topped up once to what its budget now buys.
PassiveDrip: N partner visits use up 1 pack visit (floor on the cumulative count), every partner visit counted in
the new syn_imps column, PD offered visits left x N. Nothing already charged changes. Member Campaigns: network views
and partner visits marked "at 1/4", a note under the table, a Network rate chip. Chatbot canned answer + live AI fact.
Cache tags bumped. QA: qa/run.sh nas (served 8, restart 9, ratio 15), chatbot-sync, run.sh member all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:05:43 -05:00

82 lines
6.3 KiB
JavaScript

// Syndicated rate (Marty, 2026-10-27, approved 4:1): delivery off instantadpay.com costs 1/synRateDivisor of the on-site rate.
// JSON store, NAS layer stubbed, throwaway data dir: no server, DB, chain, NAS or PassiveDrip. node qa/nas-ratio.mjs
// Covers: N=4 NAS views charge 1 credit per 20 banner views, fractions carried exactly, own credit-log line, budget is the
// limit (exhaustion stops the NAS ad with the true count), a lowered rate tops NAS up to what the budget now buys, N=1 is the
// old rule, on-site batches unchanged, PassiveDrip: 4 partner visits use 1 pack visit, all counted in synImps, PD offered x4.
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const require = createRequire(import.meta.url);
delete process.env.DATABASE_URL;
const ok = [], bad = [];
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-ratio-'));
const nas = require('../nas.js');
const rows = {}; const calls = { topUp: [], deactivate: 0 };
nas.enabled = () => true;
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; calls.deactivate++; return { ok: true, served }; };
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp.push([id, add]); return { ok: true }; };
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; return { ok: true }; };
const ads = require('../ads.js');
const OWNER = 'ratio@qa.test', FILE = path.join(DATA, 'campaigns.json');
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
const visits = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'visits', name: 'QA visits ' + id, targetUrl: 'https://example.com/v', body: '100', budget: 300, spent: 300, accrued: 0, imps: 10, clicks: 0, status: 'active', created: Date.now() }, x || {});
const seed = camps => { fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: camps, burnsPending: [] })); ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } }); };
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
const used = c => (c.spent || 0) + (c.accrued || 0);
const deliver = (id, n) => { rows[id].remaining -= n; };
seed([banner(9001), visits(9101)]);
await ads.addEarned(OWNER, 100000);
t('default divisor is 4', ads.synRateDivisor() === 4, String(ads.synRateDivisor()));
rows[9001] = { assigned: 20000, remaining: 20000 }; rows[9002] = { assigned: 200, remaining: 200 };
deliver(9001, 1000); await ads.reconcileNas();
t('N=4: 1,000 network banner views charge 50 credits (1 per 20)', used(C(9001)) === 50, String(used(C(9001))));
deliver(9001, 10); await ads.reconcileNas();
t('10 more views: no whole credit yet', used(C(9001)) === 50, String(used(C(9001))));
deliver(9001, 10); await ads.reconcileNas();
t('10 more: the fraction completes one credit (exact)', used(C(9001)) === 51, String(used(C(9001))));
const log = (await ads.creditActivity(OWNER, 50)).filter(i => i.delta < 0);
t('credit log line names the network rate', log.some(i => /^Network views \(1\/4 rate\): /.test(i.note) && i.delta === -51), JSON.stringify(log.map(i => i.note + ' ' + i.delta)));
// on-site batches unchanged
for (let i = 0; i < 10; i++) await ads.serve('banner', { width: 728, height: 90 });
t('on-site: 10 views still charge 2 credits', used(C(9001)) === 53, String(used(C(9001))));
// budget is the limit
seed([C(9001), C(9101), banner(9002, { budget: 10 })]);
const onsite2 = used(C(9002));
deliver(9002, 200); await ads.reconcileNas();
const x = C(9002);
t('budget is the limit: the network charge stops at the budget', used(x) === 10 && x.status === 'out', JSON.stringify({ used: used(x), onsite2, st: x.status }));
t('exhaustion stops the NAS ad', calls.deactivate >= 1 && rows[9002].remaining === 0);
// rate lowered: NAS gets topped up to what the budget now buys
ads.setRates({ synRateDivisor: 1 });
rows[9003] = { assigned: 1000, remaining: 1000 };
seed([C(9001), C(9002), C(9101), banner(9003)]);
deliver(9003, 500); await ads.reconcileNas();
t('N=1 (old rule): 500 network views charge 100 credits', used(C(9003)) === 100, String(used(C(9003))));
ads.setRates({ synRateDivisor: 4 });
const before = calls.topUp.length; await ads.reconcileNas();
const tu = calls.topUp.slice(before).find(x => x[0] === 9003);
t('rate lowered to 1/4: NAS is topped up to what the 900 credits left now buy (18,000 views)', tu && rows[9003].remaining === 18000, JSON.stringify({ tu, row: rows[9003] }));
await ads.reconcileNas();
t('and not topped up again on the next pass', calls.topUp.slice(before).filter(x => x[0] === 9003).length === 1);
// PassiveDrip
let a = await ads.applyExternalVisits(9101, Math.floor(7 / 4) - Math.floor(0 / 4), 'PassiveDrip', 7);
let v = C(9101);
t('PD: 7 partner visits use up 1 pack visit', a.applied === 1 && v.imps === 11, JSON.stringify(a) + ' imps ' + v.imps);
t('PD: all 7 counted as partner visits', v.synImps === 7, String(v.synImps));
a = await ads.applyExternalVisits(9101, Math.floor(8 / 4) - Math.floor(7 / 4), 'PassiveDrip', 1);
v = C(9101);
t('PD: the 8th completes the second pack visit (fraction carried)', v.imps === 12 && v.synImps === 8, JSON.stringify({ imps: v.imps, syn: v.synImps }));
const pd = require('../pdsync.js'); pd.init({ dataDir: DATA, ads });
const L = (await pd.listing()).find(c => c.id === 9101);
t('pdsync offers PD the visits left x 4 (88 x 4 = 352)', L && L.visitsLeft === 352, JSON.stringify(L));
console.log('PASS ' + ok.length);
for (const b of bad) console.log('FAIL ' + b);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(bad.length ? 1 : 0);