Ad editing: fix the link, image, text or name of a running ad; first edit free, then campaignEditFee credits

Orlando (#30) could only pause, resume or top up a banner or login ad with a wrong link.
- POST /api/my/campaigns/<id>/edit (owner) and /api/admin/campaigns/<id>/edit (any ad, free,
  never uses the member's free edit). Banner: link, image, name. Text: link, headline, line, name.
  Login and the rest: link, name. Type, size, budget, geo, schedule, audience are refused.
- Create and edit share one path: checkName/checkTarget/checkBannerImage/checkTextCopy in ads.js
  (validate() now calls them) and adChecks() in server.js (frame check + a new banner image check:
  loads, is a real PNG/JPG/GIF/WebP, up to 3 MB; own uploads read off the volume).
- Fee: campaigns.edits counts member edits; the first is free, each later one costs the site
  setting campaignEditFee (default 100, admin Settings). Charged from the engine pool via
  spendEarned (earned first, then credited purchased); with neither, a burn row on the
  best-funded position (the normal burn queue). Guarded claim so two saves cannot both be free;
  a failed save refunds exactly what was taken.
- History: campaigns.edit_log (ts, by, fields, old/new values, fee), last 50.
- NAS: clicks already route through /api/ads/click/<id>, so a new link needs no write; a new
  image or text goes to the NAS row via nas.updateCreative. Failures never block the edit and
  retry on the next reconcile pass. Open ad-viewer tokens get the new link.
- UI: Edit button on the Ads screen (CR.dialog editor, real-size preview, upload, free/fee note
  and confirm), /ads#edit=<id> deep link from the /tools list, admin Member content shows edit
  count + history with an Edit action. Chatbot canned answer + FACTS.
- qa/adedit.mjs: 51 checks against a throwaway DATA_DIR, Playwright screenshots in D:/tmp/ad-edit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-18 19:24:05 -05:00
parent 77c2037dee
commit 7be213311f
13 changed files with 444 additions and 18 deletions
+27 -1
View File
@@ -545,6 +545,7 @@
if (d.imageUrl) line(ctImg(d.imageUrl, true) + (d.width ? ' <span class="muted small">' + d.width + '×' + d.height + '</span>' : ''));
if (d.title || d.body) line((d.title ? '<b>' + esc(ctCut(d.title, 100)) + '</b> ' : '') + esc(ctCut(d.body, 200)));
line('Budget ' + ctN(d.budget) + ' · spent ' + ctN(d.spent) + ' · left ' + ctN(Math.max(0, (d.budget || 0) - (d.spent || 0))) + (d.dailyCap ? ' · cap ' + ctN(d.dailyCap) + '/day' : '') + (d.geo ? ' · tiers ' + esc(d.geo) : '') + (d.starts ? ' · starts ' + ctWhen(d.starts) : '') + (d.expires ? ' · ends ' + ctWhen(d.expires) : ''));
if (d.edits || (d.editLog && d.editLog.length)) line('Edited by the member ' + ctN(d.edits) + ' time' + (d.edits === 1 ? '' : 's') + (d.edits ? ' (first free)' : '') + (d.editLog || []).slice().reverse().map(e => '<div class="small muted">' + ctWhen(e.ts) + ' · ' + esc(e.by === 'admin' ? 'admin' : 'member') + (e.fee ? ' · ' + ctN(e.fee) + ' cr' : ' · free') + ' · ' + (e.fields || []).map(k => esc(k) + ': <s>' + esc(ctCut((e.from || {})[k], 50)) + '</s> &rarr; ' + esc(ctCut((e.to || {})[k], 50))).join('; ') + '</div>').join(''));
} else if (r.type === 'postback') {
line('<span class="mono small">' + esc(ctCut(d.postbackUrl, 110)) + '</span>');
line(esc(d.method) + ' · ' + esc((d.events || []).join(', ')) + (d.lastStatus ? ' · last ' + esc(d.lastStatus) + ' ' + ctWhen(d.lastAt) : ''));
@@ -623,11 +624,36 @@
const m = e.target.closest('[data-ctmember]'); if (m) { e.preventDefault(); setPane('members'); return openMember(m.dataset.ctmember); }
const b = e.target.closest('[data-ctact]'); if (!b || b.disabled) return;
const [i, j] = b.dataset.ctact.split(':').map(Number); const r = CT.data && CT.data.items[i]; const a = r && r.actions[j]; if (!a) return;
if (a.edit) return ctEditAd(r, a);
if (a.warn && !await IAP.confirmBox(a.warn, { title: a.label, ok: a.label, cancel: 'Cancel' })) return;
b.disabled = true;
try { await api(a.path, a.body || {}, 'POST'); IAP.status(a.label + ': done.', 'ok'); await loadContent(true); } catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
});
// admin edit of any member ad (2026-10-18): the same checks as a member edit, free, and the member keeps their free one
function ctEditAd(r, a) {
const d = r.detail || {}; const t = d.adType;
const F = [['name', 'Name', d.name || r.title, 60], ['targetUrl', 'Where the click goes', r.url, 0]];
if (t === 'banner') F.push(['imageUrl', 'Image URL (' + d.width + 'x' + d.height + ')', d.imageUrl, 0]);
if (t === 'text') F.push(['title', 'Headline (60)', d.title, 60], ['body', 'One line (140)', d.body, 140]);
const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200';
back.innerHTML = '<div class="modal-card" role="dialog" aria-modal="true" style="max-width:780px"><h3 style="margin:0 0 8px">Edit ad #' + esc(r.id) + ' (' + esc(t) + ')</h3><p class="muted small" style="margin:0 0 8px">Free from admin; the member keeps their free correction. Type, size, budget, countries, schedule and audience stay a new campaign.</p>'
+ F.map(f => '<label class="small" style="display:block;margin-top:8px">' + esc(f[1]) + '<input data-k="' + f[0] + '" value="' + esc(f[2] || '') + '"' + (f[3] ? ' maxlength="' + f[3] + '"' : '') + ' style="width:100%" autocomplete="off"></label>').join('')
+ (t === 'banner' ? '<div id="aePrev" style="margin-top:8px;max-width:100%;overflow:auto"></div>' : '')
+ '<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px"><button type="button" class="btn sec small" data-x="no">Cancel</button><button type="button" class="btn small" data-x="ok">Save</button></div></div>';
document.body.appendChild(back);
const im = back.querySelector('[data-k="imageUrl"]'); const paint = () => { const p = back.querySelector('#aePrev'); if (p) p.innerHTML = ctSafe(im.value.trim()) ? '<img src="' + esc(im.value.trim()) + '" alt="" style="width:' + d.width + 'px;height:' + d.height + 'px;display:block" referrerpolicy="no-referrer">' : ''; };
if (im) { im.addEventListener('input', paint); paint(); }
back.addEventListener('click', async e => {
const x = e.target.closest('[data-x]'); if (e.target === back || (x && x.dataset.x === 'no')) return back.remove(); if (!x) return;
const body = {}; F.forEach(f => { const v = back.querySelector('[data-k="' + f[0] + '"]').value.trim(); if (v !== String(f[2] || '').trim()) body[f[0]] = v; });
if (!Object.keys(body).length) return IAP.status('Nothing changed.', 'bad');
x.disabled = true;
try { const res = await api(a.path, body, 'POST'); back.remove(); IAP.status('Ad #' + r.id + ' saved' + (res.network === 'retrying' ? ' (the network copy retries on the next pass)' : '') + '.', 'ok'); await loadContent(true); }
catch (err) { IAP.status(err.message, 'bad'); x.disabled = false; }
});
}
// ── link domains: channel per domain, last safety check, burned flag; check now / clear / pull (2026-10-10) ──
async function loadDomains() {
const d = await api('/api/admin/domains');
@@ -976,7 +1002,7 @@
}));
// site settings: key / value rows; booleans as checkboxes, numbers stay numbers
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, echo = shared payments topic; comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)' };
const SITE_META = { noPayoutIds: 'No-payout positions (member #s, comma): linkage only, no buys from them, no joins routed under them', siteName: 'Site name', tagline: 'Tagline', rehearsal: 'Testnet rehearsal banner', defaultSponsorId: 'Fallback sponsor (member #)', walletConnectProjectId: 'WalletConnect project id', moonpayPublicKey: 'MoonPay public key', telegramBotToken: 'Telegram proof feed: bot token', telegramChatId: 'Telegram proof feed: chat id', telegramTopicId: 'Telegram proof feed: topic id (optional)', telegramEvents: 'Telegram proof feed: events (payouts | payouts+purchases | all)', telegramCtaUrl: 'Telegram proof feed: join link under each post', aiCreditsPerGen: 'AI Copy Engine: credits per generation after the free allowance', aiFreeSurge: 'AI Copy Engine: free generations a month at Surge', aiFreeCircuit: 'AI Copy Engine: free generations a month at Circuit', aiFreeNexus: 'AI Copy Engine: free generations a month at Nexus', snapshotEnabled: 'Daily growth snapshot to Telegram (1/0)', snapshotHourUtc: 'Daily growth snapshot: hour (UTC; 14 = 9 AM Central)', snapshotTargets: 'Daily growth snapshot: targets (feed = proof channel, echo = shared payments topic; comma list)', pipelineMode: 'Pipeline board: off (coming soon card) | preview (admin account only) | on (everyone)', pipelineEta: 'Pipeline: opening date shown on the coming-soon card (e.g. Sep 28)', memberWeeklyEmail: 'Weekly member email to everyone active (1) or only sponsors with a line (0)', leaderboardWeeklyPrize: 'Leaderboard: weekly prize text (optional; blank shows the credit ladder)', leaderboardMonthlyPrize: 'Leaderboard: monthly prize text (optional)', leaderboardWeeklyCredits: 'Leaderboard: weekly credits for 1st,2nd,3rd… (e.g. 1000,500,250; blank = none)', leaderboardMonthlyCredits: 'Leaderboard: monthly credits for 1st,2nd,3rd… (e.g. 5000,2500,1000)', leaderboardAnnounceGeneral: 'Leaderboard: announce winners in the main group too (1/0)', telegramEchoChatId: 'Telegram echo (shared payments topic): chat id', telegramEchoTopicId: 'Telegram echo: topic id', telegramEchoEvents: 'Telegram echo: events (payouts | payouts+purchases | all)', legacyCreditsAdvertiser: 'Legacy welcome credits: former advertisers', legacyCreditsEarner: 'Legacy welcome credits: former earners', pnlFixedMonthlyUsd: 'P&L: fixed monthly cost (USD)', campaignEditFee: 'Ad edits: credits per edit after the first, free one on each ad (0 = always free)' };
function drawSite() {
const wrap = $('siteForm');
wrap.innerHTML = Object.entries(siteObj).map(([k, v]) => '<div class="kv-row"><span class="k" title="' + esc(k) + '">' + esc(SITE_META[k] || humanize(k)) + '</span>'