From 9be58bd5efd7890846b188fb2cc43c8e271ffb9d Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 16 Oct 2026 16:51:30 -0500 Subject: [PATCH] Help desk: support tickets for members (Help pane), the public /support page with private ticket links, chatbot hand-off, and an admin Support pane - tickets.js: one shared desk (platform iap now, linkspin later), dual-mode store (MySQL tables tickets + ticket_messages, else support.json); refs IAP-<1000+id> / LS-; private no-login link /support/t/. signed with DATA_DIR/support.key (or SUPPORT_SECRET); ingestEmail() ready for the support@ intake step (threads by Message-ID, then [ref] in the subject from the same sender) - Member Help pane (/my#help): list with status + unread badge, new ticket (category, subject, message, up to 2 screenshots via /api/my/upload), thread + reply (a reply reopens a closed ticket) - Public /support: name, email, category, subject, message behind the sign-up walls (honeypot, form age, per-IP limits with the icon check, global cap) plus a per-email cap; confirmation email with the ref and the private link - Chatbot: CANNED + systemPrompt know the help desk; answers that cannot help (or "talk to a human") offer "Send this to support", which files the last turns as a ticket (members: Help pane; signed out: email + the same guard) - Admin Support pane: open / waiting / closed / all, platform, category, search; open-count badge; ticket view with requester account info, internal notes, status/priority/category, saved replies (site setting supportTemplates); deep link /admin#support?t= - Notifications: new ticket / member reply -> Telegram to Marty's private chat only (supportTelegramChat, default 1289244227, site bot then Hermes fallback, never a group or the Discord relay) + email to ADMIN_EMAIL, max one per ticket per 10 min; Marty's reply -> email "[IAP-1042] subject" + a 'notice' inbox message for members, bursts batched - support* settings are kept out of /api/config; Support link in the site footer, home footer, member page foot, terms and privacy; "Contact support" errors point at /support - QA walk: member Help ticket flow, admin Support pane + deep link, internal-note leak check, public /support + private link + tampered token + form-age refusal - Cache tags: common.js 20261016a, chat.js 20261016a, my.js 20261016r, admin.js 20261016sp, support.js 20261016a Co-Authored-By: Claude Opus 5.5 --- blog.js | 2 +- chatbot.js | 19 ++- db.js | 33 ++++ leaderboard.js | 2 +- public/admin.html | 27 +++- public/assets/admin.js | 104 ++++++++++++- public/assets/chat.js | 63 +++++++- public/assets/common.js | 5 +- public/assets/my.js | 9 +- public/assets/support.js | 194 +++++++++++++++++++++++ public/contract.html | 4 +- public/disclaimer.html | 2 +- public/earning.html | 2 +- public/facts.html | 2 +- public/friday.html | 2 +- public/games.html | 2 +- public/index.html | 6 +- public/join.html | 2 +- public/launch.html | 2 +- public/ledger.html | 4 +- public/my.html | 14 +- public/partners.html | 2 +- public/plays.html | 2 +- public/presentation.html | 2 +- public/privacy.html | 4 +- public/support.html | 27 ++++ public/terms.html | 4 +- public/tx.html | 2 +- public/wall.html | 2 +- public/wallets.html | 2 +- public/wednesday.html | 2 +- qa/walk.mjs | 98 +++++++++++- releases.js | 2 +- server.js | 165 +++++++++++++++++++- tickets.js | 323 +++++++++++++++++++++++++++++++++++++++ 35 files changed, 1078 insertions(+), 59 deletions(-) create mode 100644 public/assets/support.js create mode 100644 public/support.html create mode 100644 tickets.js diff --git a/blog.js b/blog.js index b74dd44..a129041 100644 --- a/blog.js +++ b/blog.js @@ -108,7 +108,7 @@ function head(o) { + '
'; } function tail() { - return '
'; + return ''; } const authorBox = () => '
InstantAdPay
' + AUTHOR + 'Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.
'; const cardHtml = p => '' + (p.cover ? '' : '') + '

' + esc(p.title) + '

' + esc(p.excerpt) + '

' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '

'; diff --git a/chatbot.js b/chatbot.js index 95f9fb9..1e38e3d 100644 --- a/chatbot.js +++ b/chatbot.js @@ -21,7 +21,10 @@ function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- const KNOWLEDGE_DATE = '2026-10-16'; // bump whenever the canned answers / prompt are brought up to date +const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const CANNED = [ + { re: SUPPORT_RE, handoff: true, + a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' }, { re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i, a: 'The Game Pass is $5 for 7 days and covers all nine games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the Pass badge. Caps are account-wide and reset at midnight Central. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Buy it in Members > Games > Game Pass: it costs 500 purchased credits (credits from a package you bought; earned credits do not count). If you have none, buy a $5 package and the pass starts the moment it settles, and you keep every credit of the package for your ads. Buying while a pass is active adds 7 days.' }, { re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i, @@ -129,6 +132,7 @@ function systemPrompt() { FACTS: - ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref= link. +- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time. - PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide. - WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money. - FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises. @@ -206,14 +210,15 @@ FACTS: - Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/ (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public. - The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys. -PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile. Public: /join/ (invite page, ?v=angle), /wall/, /b//, /handout/, /ledger, /tx/, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix. +PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/ (invite page, ?v=angle), /wall/, /b//, /handout/, /ledger, /tx/, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix. RULES: - 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above. - Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor. - Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes. - NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen. -- No em dashes. If you do not know, say so and point to /contract or the ledger.`; +- No em dashes. If you do not know, say so and point to /contract or the ledger. +- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.`; } function askAI(message, historyText) { @@ -254,22 +259,24 @@ function askAI(message, historyText) { }); } +const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i; async function answer(message, historyText) { const msg = String(message || '').trim(); if (!msg) return { error: 'Say something first.' }; - for (const c of CANNED) if (c.re.test(msg)) return { reply: c.a, canned: true }; - if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it.' }; + for (const c of CANNED) if (c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true }; // One retry: the usual failure is a single provider dropping the request, and asking // again almost always lands. Only after both fail do we admit defeat. for (let attempt = 0; attempt < 2; attempt++) { - try { return { reply: await askAI(msg, historyText) }; } + // handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16) + try { const reply = await askAI(msg, historyText); return Object.assign({ reply }, UNSURE_RE.test(reply) ? { handoff: true } : {}); } catch (e) { console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message); if (attempt === 0) await new Promise(r => setTimeout(r, 700)); } } // Never a dead end: say plainly that it was us, and offer a person. - return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, the plain-language contract review at https://instantadpay.com/contract and the live ledger at https://instantadpay.com/ledger cover most of the deep questions, and your sponsor can be reached from Members > My line.' }; + return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true }; } module.exports = { init, answer, enabled, KNOWLEDGE_DATE }; diff --git a/db.js b/db.js index db17c49..02f125d 100644 --- a/db.js +++ b/db.js @@ -332,6 +332,39 @@ async function bootstrap() { await alterSafe('ALTER TABLE accounts ADD COLUMN joined_via VARCHAR(20) NULL'); // ?v= angle the lead came in on await alterSafe('ALTER TABLE accounts ADD COLUMN joined_ref VARCHAR(80) NULL'); // referring domain of the first join-page visit await alterSafe('ALTER TABLE accounts ADD COLUMN wall_offers VARCHAR(2000) NULL'); // JSON [{title,bannerUrl,targetUrl}] for wall positions 2-3 (unlock at 2 / 5 qualifying buyers) + // help desk (2026-10-16, tickets.js): one shared desk for IAP and, later, LinkSpin; email_message_id threads inbound mail + await q(`CREATE TABLE IF NOT EXISTS tickets ( + id INT AUTO_INCREMENT PRIMARY KEY, + ref VARCHAR(20) NOT NULL UNIQUE, + platform VARCHAR(12) NOT NULL DEFAULT 'iap', + source VARCHAR(12) NOT NULL DEFAULT 'form', + email VARCHAR(190) NOT NULL, + name VARCHAR(80) NULL, + username VARCHAR(30) NULL, + subject VARCHAR(160) NOT NULL, + category VARCHAR(40) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'open', + priority VARCHAR(8) NOT NULL DEFAULT 'normal', + created BIGINT NOT NULL, + updated BIGINT NOT NULL, + last_member_at BIGINT NULL, + last_admin_at BIGINT NULL, + admin_unread TINYINT NOT NULL DEFAULT 0, + member_unread TINYINT NOT NULL DEFAULT 0, + INDEX (email), INDEX (status, updated), INDEX (platform, updated) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); + await q(`CREATE TABLE IF NOT EXISTS ticket_messages ( + id INT AUTO_INCREMENT PRIMARY KEY, + ticket_id INT NOT NULL, + author VARCHAR(8) NOT NULL, + body TEXT NOT NULL, + internal TINYINT NOT NULL DEFAULT 0, + attachments VARCHAR(400) NULL, + created BIGINT NOT NULL, + email_message_id VARCHAR(250) NULL, + via VARCHAR(12) NOT NULL DEFAULT 'web', + INDEX (ticket_id), INDEX (email_message_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); } // one-time import: only when the tables are empty and JSON files exist diff --git a/leaderboard.js b/leaderboard.js index 23c3207..56694d7 100644 --- a/leaderboard.js +++ b/leaderboard.js @@ -141,7 +141,7 @@ async function renderPage() { const w = winners(); if (w.length) h += '

Past winners

' + w.slice(0, 12).map(x => '
' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + ': ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '
').join(''); h += '

Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.

'; - h += ''; + h += ''; return h; } module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds }; diff --git a/public/admin.html b/public/admin.html index a220c67..caa7764 100644 --- a/public/admin.html +++ b/public/admin.html @@ -96,6 +96,7 @@ + @@ -272,6 +273,28 @@ + + - - + + diff --git a/public/assets/admin.js b/public/assets/admin.js index 85d898b..b2f4761 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -44,16 +44,18 @@ }); // ── panes ── - const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' }; - const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings }; + const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' }; + const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings }; function setPane(name) { + const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email) if (!TITLES[name]) name = 'overview'; document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; }); document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name)); $('boTitle').textContent = TITLES[name]; - if (location.hash.slice(1) !== name) history.replaceState(null, '', '#' + name); + const keepQ = name === 'support' && paneQ ? '?' + paneQ : ''; + if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ); $('adminArea').classList.remove('side-open'); - loaders[name]().catch(e => IAP.status(e.message, 'bad')); + return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad')); } document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane))); document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); }); @@ -72,6 +74,7 @@ $('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : ''); } catch (e) {} setPane(location.hash.slice(1) || 'overview'); + supportBadge(); } // ── overview ── @@ -822,6 +825,99 @@ } catch (e) { $('audSub').textContent = e.message; } } if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit)); + // ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ── + const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' }; + const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' }; + const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : ''; + const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '$1'); + let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = []; + async function supportBadge() { + try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; } + } + async function loadSupport(q) { + const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1]; + if (ref) return openTicket(ref); + $('spView').hidden = true; $('spList').hidden = false; + const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString(); + const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]); + spTemplates = tp.templates || []; spCats = r.categories || spCats; + const c = r.counts || {}; + $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || ''); + $('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread'; + const chip = (v, label, n) => ''; + $('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All'); + if (!$('spCategory').options.length) $('spCategory').innerHTML = '' + spCats.map(x => '').join(''); + $('spTable').innerHTML = 'TicketSubjectFromCategoryStatusLast activity' + + (r.tickets.length ? r.tickets.map(t => '' + (t.adminUnread ? '● ' : '') + esc(t.ref) + + (t.platform !== 'iap' ? ' ' + esc(t.platform) + '' : '') + (t.priority === 'high' ? ' high' : '') + '' + + '' + (t.adminUnread ? '' + esc(t.subject) + '' : esc(t.subject)) + '
' + esc(t.source) + '
' + + '' + esc(t.name || '') + '
' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '
' + + '' + esc(t.category) + '' + esc(SP_STATUS[t.status] || t.status) + '' + esc(ctWhen(t.updated)) + '').join('') + : 'No tickets here.'); + drawTemplates(); + } + $('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + $('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + $('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); }); + $('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } }); + async function openTicket(ref) { + const v = await api('/api/admin/support/' + encodeURIComponent(ref)); + if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} } + if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other']; + drawTicket(v); supportBadge(); + } + function drawTicket(v) { + const t = v.ticket, rq = v.requester || {}; + $('spList').hidden = true; $('spView').hidden = false; + const sel = (id, opts, cur) => ''; + const stOpts = Object.entries(SP_STATUS); + $('spView').innerHTML = '

‹ All tickets

' + + '

' + esc(t.subject) + '

' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + '
' + + '
' + + '' + + '
' + + '

Requester

' + (rq.member ? 'member account' : 'no account with this email') + '
' + + kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [ + ['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' · open member card'], + ['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '' + esc(v.link) + '']])) + + '
' + + '

Thread

' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + '
' + + v.messages.map(m => '
' + + '
' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '' + esc(ctWhen(m.created)) + '
' + + '
' + spLink(m.body) + '
' + + ((m.attachments || []).length ? '
' + m.attachments.map(a => 'attachment').join('') + '
' : '') + '
').join('') + + '
' + + '

Reply

emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '
' + + '

' + + '' + + '

' + + '' + + '

'; + $('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }); + const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } }; + $('spSt').addEventListener('change', () => patch({ status: $('spSt').value })); + $('spPr').addEventListener('change', () => patch({ priority: $('spPr').value })); + $('spCat').addEventListener('change', () => patch({ category: $('spCat').value })); + if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); }); + $('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; }); + $('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; }); + $('spSend').addEventListener('click', busy($('spSend'), async () => { + const internal = $('spInternal').checked; + if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return; + drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value })); + supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok'); + })); + } + function drawTemplates() { + $('spTpls').innerHTML = spTemplates.map((x, i) => '
' + + '
').join('') || '

No saved replies. Add one below.

'; + } + const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value })); + $('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); }); + $('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); }); + $('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); })); + async function loadReports() { loadAudit(); const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]); diff --git a/public/assets/chat.js b/public/assets/chat.js index 5b69934..2abc6da 100644 --- a/public/assets/chat.js +++ b/public/assets/chat.js @@ -1,4 +1,6 @@ // 24/7 assistant widget: floating bubble, slide-up panel, /api/chat. +// Hand-off (help desk, 2026-10-16): when the answer cannot help, or they ask for a person, the widget offers +// "Send this to support", which files the last few turns as a ticket (members: their Help pane; signed out: their email). (function () { const root = document.createElement('div'); root.id = 'iapChat'; @@ -11,6 +13,7 @@ + '' + '
' + '
' + + '' + ''; document.body.appendChild(root); @@ -18,6 +21,7 @@ const msgs = $('iapChatMsgs'); const input = $('iapChatIn'); let history = []; + const turns = []; // { who: 'me' | 'bot', text } for the support hand-off const add = (text, who) => { const d = document.createElement('div'); @@ -29,11 +33,18 @@ msgs.scrollTop = msgs.scrollHeight; return d; }; + function offerHandoff() { + if (msgs.querySelector('.ch-handoff')) return; + const d = document.createElement('div'); d.className = 'ch-m bot ch-handoff'; + d.innerHTML = ''; + d.querySelector('button').addEventListener('click', handoff); + msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; + } async function send() { const q = input.value.trim(); if (!q) return; input.value = ''; - add(q, 'me'); + add(q, 'me'); turns.push({ who: 'me', text: q }); const wait = add('…', 'bot'); try { const r = await (await fetch('/api/chat', { method: 'POST', @@ -41,12 +52,61 @@ body: JSON.stringify({ message: q, history: history.slice(-4).join(' | ') }) })).json(); wait.remove(); add(r.reply || r.error || 'No answer came back. Try again.', 'bot'); + if (r.reply) turns.push({ who: 'bot', text: r.reply }); history.push('Q: ' + q, 'A: ' + (r.reply || '')); + if (r.handoff) offerHandoff(); } catch (e) { wait.remove(); add('Connection hiccup. Try that again.', 'bot'); + offerHandoff(); } } + async function post(body) { + const g = window.IAP && IAP.guard; + if (g) await g.formSettled(); + return (await fetch('/api/support/chatbot', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(Object.assign({ transcript: turns.slice(-8), fts: g ? g.FORM_TS : 0, fage: g ? Date.now() - g.FORM_TS : 0 }, body)) })).json(); + } + function done(r) { + const old = msgs.querySelector('.ch-handoff'); if (old) old.remove(); + const f = msgs.querySelector('.ch-hform'); if (f) f.remove(); + add(r.member ? 'Sent to support as ticket ' + r.ref + '. Marty will reply in Help in your dashboard and by email: ' + location.origin + r.link + : 'Sent to support as ticket ' + r.ref + '. We emailed you a private link to follow it, and Marty will reply there: ' + location.origin + r.link, 'bot'); + } + async function handoff(e) { + if (e && e.preventDefault) e.preventDefault(); + if (msgs.querySelector('.ch-hform')) return; + let me = null; try { me = await (await fetch('/api/me')).json(); } catch (err) {} + if (me && me.signedIn && me.email) { + const ok = window.IAP && IAP.confirmBox ? await IAP.confirmBox('Send this chat to support as a ticket? Marty will reply in Help in your dashboard and by email.', { ok: 'Send it', cancel: 'Not now' }) : true; + if (!ok) return; + try { const r = await post({}); if (r.error) throw new Error(r.error); done(r); } catch (err) { add(err.message || 'Could not send it. Try the Help tab in your dashboard.', 'bot'); } + return; + } + // signed out: an email so Marty can reply, plus the same invisible walls as sign-up + const d = document.createElement('div'); d.className = 'ch-m bot ch-hform'; + d.innerHTML = 'Where should Marty reply?' + + '' + + '' + + '' + + '' + + ' '; + msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; + $('iapChatEmail').focus(); + $('iapChatGo').addEventListener('click', async () => { + const btn = $('iapChatGo'); if (btn.disabled) return; btn.disabled = true; $('iapChatErr').textContent = ''; + try { + let pick = null, r = null; + for (let i = 0; i < 4; i++) { + r = await post({ email: $('iapChatEmail').value.trim(), note: $('iapChatNote').value.trim(), hp_field_x9: window.IAP && IAP.guard ? IAP.guard.hpValue($('iapChatHp')) : '', pick }); + if (r.challenge && window.IAP && IAP.guard) { pick = await IAP.guard.iconCheck($('iapChatCheck'), r.challenge, r.error); continue; } + break; + } + if (!r || r.error) throw new Error((r && r.error) || 'Could not send it.'); + done(r); + } catch (err) { $('iapChatErr').textContent = err.message; btn.disabled = false; } + }); + } $('iapChatBtn').addEventListener('click', () => { const p = $('iapChatPanel'); p.hidden = !p.hidden; @@ -54,5 +114,6 @@ }); $('iapChatClose').addEventListener('click', () => { $('iapChatPanel').hidden = true; }); $('iapChatSend').addEventListener('click', send); + $('iapChatHuman').addEventListener('click', handoff); input.addEventListener('keydown', e => { if (e.key === 'Enter') send(); }); })(); diff --git a/public/assets/common.js b/public/assets/common.js index 04841a6..15d2b10 100644 --- a/public/assets/common.js +++ b/public/assets/common.js @@ -56,7 +56,7 @@ window.IAP = (function () { f.innerHTML = '
© ' + new Date().getFullYear() + ' InstantAdPay
' + ''; + + 'Platform factsSupportTermsPrivacyDisclaimer'; document.body.appendChild(f); } async function refreshNavWallet() { @@ -263,7 +263,8 @@ window.IAP = (function () { } function ask(o) { return dialog(Object.assign({ type: 'text', value: '', placeholder: '' }, o || {})); } function confirmBox(text, o) { return dialog(Object.assign({ type: 'none', text, ok: 'Yes', cancel: 'No' }, o || {})); } - return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $ }; + return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $, + guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by the support form and the chatbot hand-off })(); // shown inside someone else's frame (traffic exchanges, 2026-10-03): sign-in, join and off-site links open in a new tab, // because browsers refuse our session cookie inside another site's frame diff --git a/public/assets/my.js b/public/assets/my.js index c62430b..5e01190 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -783,9 +783,9 @@ } // ── back-office menu: hash-routed panes ─────────────── - const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'games', 'wallet', 'profile']; + const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; const TITLES = { overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', - earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', games: 'Games', + earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', wallet: 'Wallet & account', profile: 'Profile' }; function setPane(name) { const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) @@ -808,8 +808,10 @@ if (name === 'training') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } if (name === 'pipeline') loadPipeline(); if (name === 'games') loadGames(paneQ); + if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer - if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name); + const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket + if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); } document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane))); @@ -877,6 +879,7 @@ $('earnGate').hidden = !!me.memberId; if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } loadDashboard(); + if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket const who = []; if (me.email) who.push(me.email); diff --git a/public/assets/support.js b/public/assets/support.js new file mode 100644 index 0000000..f0f6d14 --- /dev/null +++ b/public/assets/support.js @@ -0,0 +1,194 @@ +// Help desk front end (2026-10-16): the public /support form, the private ticket link page (/support/t/) +// and the member Help pane (/my#help). Server side: tickets.js + the /api/support, /api/my/support routes. +// Times show in US Central, like the rest of the site's support copy. +window.IAPSupport = (function () { + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const CATS = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other']; + const STATUS = { open: 'Open', waiting_on_member: 'Waiting on you', closed: 'Closed' }; + const when = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : ''; + const linkify = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '$1'); + async function call(path, body, method) { + const o = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} }; + if (body !== undefined) { o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); } + const r = await (await fetch(path, o)).json(); + if (r.error && !r.challenge) { const e = new Error(r.error); e.data = r; throw e; } + return r; + } + (function css() { + if (document.getElementById('supCss')) return; + const st = document.createElement('style'); st.id = 'supCss'; + st.textContent = '.sup-form label{display:block;font-size:13px;color:var(--muted);margin:12px 0 4px}.sup-form input,.sup-form select,.sup-form textarea{width:100%;box-sizing:border-box}' + + '.sup-row{display:flex;gap:10px;align-items:center;justify-content:space-between;padding:12px 4px;border-bottom:1px solid var(--line);cursor:pointer}.sup-row:last-child{border-bottom:0}.sup-row:hover{background:rgba(67,232,195,.04)}' + + '.sup-row .sr-main{min-width:0;flex:1}.sup-row .sr-sub{font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sup-row .sr-meta{font-size:12px;color:var(--muted)}' + + '.sup-st{font-size:11.5px;font-weight:700;border-radius:999px;padding:2px 10px;border:1px solid var(--line-strong);white-space:nowrap}.sup-st.open{color:var(--mint);border-color:rgba(67,232,195,.5)}.sup-st.waiting_on_member{color:#f2c94c;border-color:rgba(242,201,76,.5)}.sup-st.closed{color:var(--muted)}' + + '.sup-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--amber,#ffb238);margin-right:6px;vertical-align:1px}' + + '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:rgba(4,8,7,.35)}.sup-msg.admin{border-color:rgba(67,232,195,.45);background:rgba(67,232,195,.06)}.sup-msg.system{opacity:.8}' + + '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}' + + '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}' + + '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}'; + document.head.appendChild(st); + })(); + const catOptions = sel => CATS.map(c => '' + esc(c) + '').join(''); + const AUTHOR = { member: 'You', admin: 'Marty, InstantAdPay support', system: 'InstantAdPay' }; + function threadHtml(v) { + const t = v.ticket; + return '

' + esc(t.subject) + '

' + esc(STATUS[t.status] || t.status) + '
' + + '

' + esc(t.ref) + ' · ' + esc(t.category) + ' · opened ' + esc(when(t.created)) + '

' + + v.messages.map(m => '
' + esc(AUTHOR[m.author] || m.author) + '' + esc(when(m.created)) + '
' + + '
' + linkify(m.body) + '
' + + ((m.attachments || []).length ? '
' + m.attachments.map(a => 'attachment').join('') + '
' : '') + '
').join('') + + (t.status === 'closed' ? '

This ticket is closed. Write below and it opens again.

' : ''); + } + function replyBox(id, withAttach) { + return '
' + + (withAttach ? attachRow(id) : '') + + '
'; + } + // up to 2 screenshots per message, through the member upload path (signed-in only) + const attachRow = id => '
'; + function wireAttach(id) { + const list = []; const inp = document.getElementById(id + 'File'); if (!inp) return () => []; + const draw = () => { document.getElementById(id + 'Att').innerHTML = list.map(u => 'screenshot').join(''); }; + inp.addEventListener('change', async () => { + for (const f of [...inp.files]) { + if (list.length >= 2) { IAP.status('Two images per message at most.', 'bad'); break; } + try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); if (r.type !== 'image') throw new Error('Images only, please.'); list.push(r.url); draw(); } + catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); } + } + inp.value = ''; + }); + return () => list.slice(); // read at send time + } + + // ── member Help pane ── + let helpState = { open: null }; + async function badge() { + try { const r = await call('/api/my/support'); const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; } return r; } catch (e) { return null; } + } + async function help(paneQ) { + const host = document.getElementById('helpBody'); if (!host) return; + const want = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(paneQ || '') || [])[1]; + if (want) return openMine(want); + helpState.open = null; + host.innerHTML = '

Loading your tickets…

'; + let r; try { r = await call('/api/my/support'); } catch (e) { host.innerHTML = '

Could not load your tickets. ' + esc(e.message) + '

'; return; } + const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; } + host.innerHTML = '

Help and support

' + + '

Stuck on something? Send Marty a ticket. He reads every one and replies here, and you get an email when he does. The quickest answers to common questions are in Training and the chat bubble.

' + + '' + + '

Your tickets

' + r.tickets.length + '
' + + (r.tickets.length ? r.tickets.map(t => '
' + (t.unread ? '' : '') + esc(t.subject) + '
' + + '
' + esc(t.ref) + ' · ' + esc(t.category) + ' · updated ' + esc(when(t.updated)) + '
' + esc(STATUS[t.status] || t.status) + '
').join('') + : '

No tickets yet. When you send one, it shows up here with Marty\'s replies.

') + '
'; + host.querySelectorAll('.sup-row').forEach(el => el.addEventListener('click', () => { history.replaceState(null, '', '#help?t=' + el.dataset.ref); openMine(el.dataset.ref); })); + document.getElementById('helpNewBtn').addEventListener('click', () => newForm()); + if (/(?:^|&)new=1/.test(paneQ || '')) newForm(); + } + function newForm() { + const box = document.getElementById('helpNew'); if (!box) return; + box.hidden = false; + box.innerHTML = '

New ticket

' + + '' + + '' + + '' + + attachRow('hn') + + '
'; + const atts = wireAttach('hn'); + document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; }); + const send = document.getElementById('hnSend'); + send.addEventListener('click', async () => { + if (send.disabled) return; send.disabled = true; + try { + const r = await call('/api/my/support', { category: document.getElementById('hnCat').value, subject: document.getElementById('hnSubject').value, body: document.getElementById('hnBody').value, attachments: atts() }); + IAP.status('Sent. Your ticket is ' + r.ref + '. Marty will reply here and by email.', 'ok'); + history.replaceState(null, '', '#help?t=' + r.ref); openMine(r.ref); + } catch (e) { document.getElementById('hnMsg').textContent = e.message; } + finally { send.disabled = false; } + }); + document.getElementById('hnSubject').focus(); + } + async function openMine(ref) { + const host = document.getElementById('helpBody'); if (!host) return; + helpState.open = ref; + host.innerHTML = '

Loading…

'; + let v; try { v = await call('/api/my/support/' + encodeURIComponent(ref)); } catch (e) { host.innerHTML = '

' + esc(e.message) + '

Back to your tickets

'; wireBack(); return; } + drawMine(v); + badge(); + } + const wireBack = () => { const a = document.getElementById('helpBack'); if (a) a.addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#help'); help(''); }); }; + function drawMine(v) { + const host = document.getElementById('helpBody'); + host.innerHTML = '

‹ All your tickets

' + threadHtml(v) + '
' + replyBox('hr', true) + '
'; + wireBack(); + const atts = wireAttach('hr'); + const btn = document.getElementById('hrSend'); + btn.addEventListener('click', async () => { + if (btn.disabled) return; btn.disabled = true; + try { const nv = await call('/api/my/support/' + encodeURIComponent(v.ticket.ref) + '/reply', { body: document.getElementById('hrBody').value, attachments: atts() }); drawMine(nv); IAP.status('Reply sent.', 'ok'); } + catch (e) { document.getElementById('hrMsg').textContent = e.message; } + finally { btn.disabled = false; } + }); + } + + // ── public /support page and the private ticket link ── + async function page() { + const host = document.getElementById('supMain'); if (!host) return; + const m = /^\/support\/t\/([A-Za-z0-9_.-]{20,80})$/.exec(location.pathname); + if (m) return tokenPage(host, m[1]); + let me = null; try { me = await (await fetch('/api/me')).json(); } catch (e) {} + const signedIn = !!(me && me.signedIn && me.email); + host.innerHTML = (signedIn ? '

You are signed in as ' + esc(me.username ? '@' + me.username : me.email) + '. Your tickets and Marty\'s replies live in Help in your dashboard, which is the easiest place to follow up. This form works too and files the ticket under your account.

' : '') + + '
' + + '' + + (signedIn ? '' : '' + + '') + + '' + + '' + + '' + + '' + + '
' + + '
'; + const f = document.getElementById('supForm'); + f.addEventListener('submit', async e => { + e.preventDefault(); + const btn = document.getElementById('supSend'); if (btn.disabled) return; btn.disabled = true; + const msg = document.getElementById('supMsg'); msg.textContent = 'Sending…'; + const val = id => { const el = document.getElementById(id); return el ? el.value : ''; }; + try { + const g = IAP.guard; await g.formSettled(); + let pick = null, r = null; + for (let i = 0; i < 4; i++) { + r = await call('/api/support', { name: val('supName'), email: val('supEmail'), category: val('supCat'), subject: val('supSubject'), body: val('supBody'), + fts: g.FORM_TS, fage: Date.now() - g.FORM_TS, hp_field_x9: g.hpValue(document.getElementById('supHp')), pick }); + if (r.challenge) { msg.textContent = ''; pick = await g.iconCheck(document.getElementById('supCheck'), r.challenge, r.error); continue; } + break; + } + if (!r || !r.ok) throw new Error('Could not verify. Refresh the page and try again.'); + host.innerHTML = '

Got it. Your ticket is ' + esc(r.ref) + '.

' + + '

Marty reads every ticket and replies as soon as he can. ' + (r.member ? 'His reply shows up in Help in your dashboard and in your email.' : 'We just emailed you a private link to this ticket, so you can check on it or add more detail without signing in. If it does not arrive, look in spam or promotions.') + '

' + + '

' + (r.member ? 'Open it in Help' : 'View your ticket') + 'Back to InstantAdPay

'; + window.scrollTo(0, 0); + } catch (err) { msg.textContent = err.message; } + finally { btn.disabled = false; } + }); + } + async function tokenPage(host, tok) { + const h = document.querySelector('.sectionhead h2'); if (h) h.innerHTML = 'Your support ticket'; + host.innerHTML = '

Loading your ticket…

'; + let v; try { v = await call('/api/support/t/' + encodeURIComponent(tok)); } catch (e) { host.innerHTML = '

' + esc(e.message) + '

Send a new ticket

'; return; } + const draw = v2 => { + host.innerHTML = '
' + threadHtml(v2) + '
' + replyBox('tk', false) + + '

Keep this link private: anyone with it can read and answer this ticket. Members can also follow up from Help in the dashboard, where screenshots can be attached.

'; + const btn = document.getElementById('tkSend'); + btn.addEventListener('click', async () => { + if (btn.disabled) return; btn.disabled = true; + try { const nv = await call('/api/support/t/' + encodeURIComponent(tok) + '/reply', { body: document.getElementById('tkBody').value }); draw(nv); IAP.status('Reply sent. Marty will see it.', 'ok'); } + catch (e) { document.getElementById('tkMsg').textContent = e.message; } + finally { btn.disabled = false; } + }); + }; + draw(v); + } + return { help, badge, page, CATS, STATUS, when, esc, linkify }; +})(); +if (document.getElementById('supMain')) IAPSupport.page(); diff --git a/public/contract.html b/public/contract.html index 79a1bc7..a6d11e9 100644 --- a/public/contract.html +++ b/public/contract.html @@ -142,8 +142,8 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
- + - + diff --git a/public/disclaimer.html b/public/disclaimer.html index 21dad43..85e20b4 100644 --- a/public/disclaimer.html +++ b/public/disclaimer.html @@ -26,7 +26,7 @@

You decide whether, and how much, to spend. Never spend more than you can afford to lose.

- + diff --git a/public/earning.html b/public/earning.html index 83ec347..511eca1 100644 --- a/public/earning.html +++ b/public/earning.html @@ -84,6 +84,6 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/facts.html b/public/facts.html index 4edc6fc..4d14919 100644 --- a/public/facts.html +++ b/public/facts.html @@ -121,7 +121,7 @@ - + diff --git a/public/friday.html b/public/friday.html index b222a61..bff3e5b 100644 --- a/public/friday.html +++ b/public/friday.html @@ -71,6 +71,6 @@ - + diff --git a/public/games.html b/public/games.html index 3ee86fa..a7b3ee6 100644 --- a/public/games.html +++ b/public/games.html @@ -78,6 +78,6 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/index.html b/public/index.html index fcc118d..db26703 100644 --- a/public/index.html +++ b/public/index.html @@ -492,7 +492,7 @@
-
InstantAdPay · every payment verifiable on-chain · live ledger · view the contract ↗
+
InstantAdPay · every payment verifiable on-chain · live ledger · view the contract ↗ · support
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
@@ -500,9 +500,9 @@ - + - + diff --git a/public/join.html b/public/join.html index 1f0edec..26413d9 100644 --- a/public/join.html +++ b/public/join.html @@ -157,7 +157,7 @@ InstantAdPay · Contract · Terms · Privacy · Disclaimer - + diff --git a/public/launch.html b/public/launch.html index ef7d0dd..bd2c774 100644 --- a/public/launch.html +++ b/public/launch.html @@ -105,7 +105,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/ledger.html b/public/ledger.html index 4d1ffbf..ee850d9 100644 --- a/public/ledger.html +++ b/public/ledger.html @@ -40,9 +40,9 @@
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
- + - + diff --git a/public/my.html b/public/my.html index c407e0c..6f5baed 100644 --- a/public/my.html +++ b/public/my.html @@ -143,6 +143,7 @@ + @@ -1072,6 +1073,11 @@ + + @@ -1168,10 +1175,11 @@ - + - - + + + diff --git a/public/partners.html b/public/partners.html index b2ab5b2..4d2b3d9 100644 --- a/public/partners.html +++ b/public/partners.html @@ -130,7 +130,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.
- + diff --git a/public/plays.html b/public/plays.html index daf01ab..9540e3a 100644 --- a/public/plays.html +++ b/public/plays.html @@ -193,7 +193,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.
- + diff --git a/public/presentation.html b/public/presentation.html index 6d962e6..3b8f114 100644 --- a/public/presentation.html +++ b/public/presentation.html @@ -86,6 +86,6 @@
InstantAdPay is the Polygon hub of the Crypto Team Build Network.
- + diff --git a/public/privacy.html b/public/privacy.html index 8a08a3f..a909cf3 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -24,12 +24,12 @@

Sharing

Your username, public profile, and public wall are visible to others by design, and on-chain transactions are public by nature. We share data with infrastructure providers (hosting, email delivery) only as needed to operate the service, and when required by law.

Your choices

-

You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us. Note that on-chain records cannot be deleted by anyone.

+

You can edit your profile, adjust notification and chat settings, and request account deletion by contacting us through the support page or at support@instantadpay.com. Note that on-chain records cannot be deleted by anyone.

Security

We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.

- + diff --git a/public/support.html b/public/support.html new file mode 100644 index 0000000..cdcc26e --- /dev/null +++ b/public/support.html @@ -0,0 +1,27 @@ + + + + +Support | InstantAdPay + + + + + + + +
+
+

Support

+

Ask for help

+

Tell us what is going on and Marty will reply by email. Members can also open Help in the dashboard, and you can email support@instantadpay.com. Quick answers to common questions are in the chat bubble and on the platform facts page.

+
+

Loading…

+

We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.

+
+ + + + + + diff --git a/public/terms.html b/public/terms.html index 52c796e..18b3c59 100644 --- a/public/terms.html +++ b/public/terms.html @@ -35,10 +35,10 @@

To the fullest extent permitted by law, InstantAdPay and its operators are not liable for indirect, incidental, or consequential damages, or for losses arising from crypto volatility, irreversible transactions, third-party sites, or your own decisions.

10. Changes and termination

We may update these Terms and the Platform, and continued use means you accept the changes. We may discontinue features. The immutable contract's rules cannot be changed by anyone, including us.

-

See also the Disclaimer and Privacy Policy.

+

See also the Disclaimer and Privacy Policy. Questions: the support page or support@instantadpay.com.

- + diff --git a/public/tx.html b/public/tx.html index bbd9b7a..e16ee66 100644 --- a/public/tx.html +++ b/public/tx.html @@ -34,7 +34,7 @@

← Back to the live ledger · Read the contract review

- + diff --git a/public/wall.html b/public/wall.html index 256234e..6ae8557 100644 --- a/public/wall.html +++ b/public/wall.html @@ -47,7 +47,7 @@ - + diff --git a/public/wallets.html b/public/wallets.html index c9b7808..8500752 100644 --- a/public/wallets.html +++ b/public/wallets.html @@ -122,7 +122,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.
- + diff --git a/public/wednesday.html b/public/wednesday.html index e8b141b..c9e4ad5 100644 --- a/public/wednesday.html +++ b/public/wednesday.html @@ -64,6 +64,6 @@ - + diff --git a/qa/walk.mjs b/qa/walk.mjs index 5ca154a..59d6efc 100644 --- a/qa/walk.mjs +++ b/qa/walk.mjs @@ -61,7 +61,7 @@ if (MODE === 'public' || MODE === 'all') { const page = await ctx.newPage(); const bag = watch(page, LIVE); const PUBLIC = ['/', '/ledger', '/contract', '/terms', '/privacy', '/disclaimer', '/wall/martbost', '/join/martbost', '/join/martbost?v=instant', '/join/martbost?v=adspend', '/join/martbost?v=free', '/join/martbost?v=ledger', '/join/martbost?v=two', - '/admin', '/my', '/shorts', '/presentation', '/presentation?ref=martbost', '/nope-404']; + '/admin', '/my', '/shorts', '/presentation', '/presentation?ref=martbost', '/support', '/nope-404']; for (const p of PUBLIC) { const label = 'LIVE ' + p; try { @@ -101,7 +101,7 @@ if (MODE === 'member' || MODE === 'all') { await page.waitForSelector('#mcVerifyBtn:not([hidden])'); await page.click('#mcVerifyBtn'); await page.waitForTimeout(2000); if (await page.$('#onboardModal:not([hidden])')) { await page.fill('#obUsername', 'qawalker'); await page.click('#obSave'); await page.waitForTimeout(1200); } await hide(page); flush(bag, L + 'sign-in'); - const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'games', 'wallet', 'profile']; + const PANES = ['overview', 'line', 'pipeline', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile']; for (const pn of PANES) { const label = L + 'my#' + pn; await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200); await hide(page); @@ -147,6 +147,29 @@ if (MODE === 'member' || MODE === 'all') { const rj = await page.request.get(LOCAL + '/join/' + tok + '?ref=' + tok, { maxRedirects: 0 }); if (rj.status() !== 200) note('bug', L + 'viral/join', '/join keeps its own ?ref handling, got ' + rj.status()); console.log('ok viral links: builder + redirect + cookie'); + // help desk (2026-10-16): Help pane -> new ticket -> thread -> reply; the ref is reused by the admin Support walk below + let helpRef = ''; + await page.click('.bo-menu [data-pane="help"]'); await page.waitForTimeout(800); await hide(page); + await page.click('#helpNewBtn').catch(() => note('bug', L + 'my#help', 'no New ticket button')); + await page.waitForTimeout(300); + await page.click('#hnSend'); await page.waitForTimeout(600); + if (!(await page.$eval('#hnMsg', e => e.textContent.trim()).catch(() => ''))) note('warn', L + 'my#help', 'empty ticket showed no validation message'); + await page.selectOption('#hnCat', 'Wallet & payouts').catch(() => {}); + await page.fill('#hnSubject', 'QA walk: payout question'); + await page.fill('#hnBody', 'This is the QA walk testing the help desk. Line two.\nhttps://instantadpay.com/ledger'); + await page.click('#hnSend'); await page.waitForTimeout(1500); await hide(page); + helpRef = (/#help\?t=((?:IAP|LS)-\d+)/.exec(page.url()) || [])[1] || ''; + if (!helpRef || !(await page.$('#hrSend'))) note('bug', L + 'my#help', 'new ticket did not open its thread: ' + page.url()); + else { + await page.fill('#hrBody', 'QA walk follow-up reply.'); await page.click('#hrSend'); await page.waitForTimeout(1200); + const n = await page.$$eval('#helpBody .sup-msg', els => els.length).catch(() => 0); + if (n < 2) note('bug', L + 'my#help', 'reply did not show in the thread (' + n + ' messages)'); + await page.click('#helpBack'); await page.waitForTimeout(900); + if (!(await page.$('#helpBody .sup-row[data-ref="' + helpRef + '"]'))) note('bug', L + 'my#help', 'ticket missing from the list'); + await domChecks(page, L + 'my#help (ticket)'); console.log('ok Help pane ticket', helpRef); + } + flush(bag, L + 'my#help (ticket)'); + await page.screenshot({ path: OUT + '/my-help-ticket.png' }).catch(() => {}); const chat = await page.$('#chatMenuBtn'); if (chat) { await chat.click(); await page.waitForTimeout(800); await domChecks(page, L + 'messages'); flush(bag, L + 'messages'); } const lo = await page.$('#logoutLink'); if (lo) { await lo.click(); await page.waitForTimeout(1000); } if (!(await page.$('#authArea:not([hidden])'))) note('bug', L + 'logout', 'auth card not shown after log out'); @@ -154,7 +177,7 @@ if (MODE === 'member' || MODE === 'all') { // admin await page.goto(LOCAL + '/admin', { waitUntil: 'networkidle' }); await page.fill('#adEmail', process.env.ADMIN_EMAIL || 'martybostick@gmail.com'); await page.click('#adSend'); await page.waitForSelector('#adVerify:not([hidden])'); await page.click('#adVerify'); await page.waitForTimeout(1200); - for (const pn of ['overview', 'house', 'campaigns', 'members', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'settings']) { + for (const pn of ['overview', 'house', 'campaigns', 'members', 'support', 'reports', 'traffic', 'blog', 'releases', 'pnl', 'gamepass', 'settings']) { const label = L + 'admin#' + pn; await page.click('.bo-menu [data-pane="' + pn + '"]'); await page.waitForTimeout(1200); const vis = await page.evaluate(id => { const el = document.getElementById('pane-' + id); return el && !el.hidden && el.offsetHeight > 40; }, pn); @@ -163,11 +186,80 @@ if (MODE === 'member' || MODE === 'all') { await page.screenshot({ path: OUT + '/admin-' + pn + '.png' }).catch(() => {}); console.log('ok', label); } + // admin Support pane: the member's ticket is listed, opens, takes an internal note and a reply; the member then sees the reply and an unread badge + if (helpRef) { + await page.click('.bo-menu [data-pane="support"]'); await page.waitForTimeout(1000); + if (!(await page.$('#spTable [data-spref="' + helpRef + '"]'))) note('bug', L + 'admin#support', 'ticket ' + helpRef + ' not in the open list'); + const badge = await page.$eval('#supBadge', e => e.hidden ? '' : e.textContent).catch(() => ''); + if (!badge) note('bug', L + 'admin#support', 'no open-count badge in the menu'); + await page.click('#spTable [data-spref="' + helpRef + '"]').catch(() => {}); await page.waitForTimeout(1000); + if (!(await page.$('#spBody'))) note('bug', L + 'admin#support', 'ticket view did not open'); + else { + if (!/member account/.test(await page.$eval('#spView', e => e.textContent))) note('bug', L + 'admin#support', 'requester not recognised as a member'); + await page.check('#spInternal'); await page.fill('#spBody', 'QA internal note, never shown to the member.'); await page.click('#spSend'); await page.waitForTimeout(1000); + await page.selectOption('#spTpl', '0').catch(() => {}); await page.waitForTimeout(200); + if (!(await page.$eval('#spBody', e => e.value).catch(() => ''))) note('bug', L + 'admin#support', 'saved reply did not insert'); + await page.click('#spSend'); await page.waitForTimeout(400); + const ok = await page.$('#dlgOk'); if (ok) await ok.click(); else note('bug', L + 'admin#support', 'no in-page confirm before sending'); + await page.waitForTimeout(1200); + const txt = await page.$eval('#spView', e => e.textContent).catch(() => ''); + if (!/internal note/.test(txt) || !/Waiting on member/.test(await page.$eval('#spSt', e => e.selectedOptions[0].textContent).catch(() => ''))) note('bug', L + 'admin#support', 'note/reply/status not reflected'); + await page.selectOption('#spPr', 'high'); await page.waitForTimeout(800); + await domChecks(page, L + 'admin#support (ticket)'); console.log('ok admin Support ticket', helpRef); + } + flush(bag, L + 'admin#support (ticket)'); + await page.screenshot({ path: OUT + '/admin-support-ticket.png' }).catch(() => {}); + await page.goto(LOCAL + '/admin#support?t=' + helpRef, { waitUntil: 'networkidle' }); await page.waitForTimeout(1000); + if (!(await page.$('#spBody'))) note('bug', L + 'admin#support', 'deep link #support?t= did not open the ticket'); + flush(bag, L + 'admin#support (deep link)'); + } await page.click('.bo-menu [data-pane="house"]'); await page.waitForTimeout(500); for (const t of ['banner', 'text', 'login', 'solo', 'video', 'featured', 'visits']) { await page.selectOption('#hType', t); await page.waitForTimeout(120); } await page.selectOption('#hType', 'text'); await page.click('#hCreate'); await page.waitForTimeout(800); if (!(await page.$('#hErr:not([hidden])'))) note('warn', L + 'admin house form', 'empty submit showed no validation message'); flush(bag, L + 'admin house form'); + // member sees Marty's reply: badge, thread without the internal note + if (helpRef) { + await page.goto(LOCAL + '/my', { waitUntil: 'networkidle' }); + if (await page.$('#mcEmail:not([hidden])') && await page.$('#authArea:not([hidden])')) { + await page.fill('#mcEmail', 'qa-walk@example.com'); await page.click('#mcSendBtn'); await page.waitForSelector('#mcVerifyBtn:not([hidden])'); await page.click('#mcVerifyBtn'); await page.waitForTimeout(2000); + } + await hide(page); await page.waitForTimeout(800); + if (!(await page.$eval('#helpBadge', e => !e.hidden).catch(() => false))) note('bug', L + 'my#help', 'no unread badge after the admin replied'); + await page.waitForTimeout(1500); await page.goto(LOCAL + '/my#help?t=' + helpRef); await page.waitForTimeout(1500); // same document: the hash change opens the ticket await hide(page); + const th = await page.$eval('#helpBody', e => e.textContent).catch(() => ''); + if (!/Marty, InstantAdPay support/.test(th)) note('bug', L + 'my#help', 'admin reply not shown to the member'); + if (/QA internal note/.test(th)) note('bug', L + 'my#help', 'INTERNAL NOTE LEAKED to the member'); + flush(bag, L + 'my#help (reply seen)'); console.log('ok member sees reply, no internal note'); + } + // public /support (signed out): the form, the guard, the private ticket link + { + const pctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true }); + await pctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); } catch (e) {} }); + const pp = await pctx.newPage(); const pbag = watch(pp, LOCAL); + await pp.goto(LOCAL + '/support', { waitUntil: 'networkidle' }); await pp.waitForTimeout(800); + await domChecks(pp, L + '/support'); + if (!(await pp.$('#supForm'))) note('bug', L + '/support', 'form did not render'); + else { + await pp.fill('#supName', 'QA Visitor'); await pp.fill('#supEmail', 'qa-visitor@example.com'); + await pp.fill('#supSubject', 'QA: cannot sign in'); await pp.fill('#supBody', 'The sign-in code never arrives. QA walk.'); + await pp.click('#supSend'); await pp.waitForTimeout(3500); + const tl = await pp.$eval('#supMain a.btn[href^="/support/t/"]', e => e.getAttribute('href')).catch(() => ''); + if (!tl) note('bug', L + '/support', 'no confirmation with a private ticket link: ' + (await pp.$eval('#supMsg', e => e.textContent).catch(() => ''))); + else { + await pp.goto(LOCAL + tl, { waitUntil: 'networkidle' }); await pp.waitForTimeout(800); + if (!(await pp.$('#tkSend'))) note('bug', L + '/support/t', 'private ticket page did not render'); + else { await pp.fill('#tkBody', 'Adding one more detail.'); await pp.click('#tkSend'); await pp.waitForTimeout(1000); if ((await pp.$$('.sup-msg')).length < 2) note('bug', L + '/support/t', 'reply on the private link did not show'); } + await domChecks(pp, L + '/support/t'); console.log('ok /support + private link'); + const bad = await pp.request.get(LOCAL + '/api/support/t/' + tl.split('/').pop().slice(0, -4) + 'AAAA'); + if (bad.status() !== 404) note('bug', L + '/support/t', 'a tampered token was accepted: ' + bad.status()); + } + const bot = await pp.request.post(LOCAL + '/api/support', { data: { email: 'qa-bot@example.com', subject: 'x bot', body: 'bot body here', fts: Date.now(), fage: 10 } }); + if (bot.status() !== 400) note('bug', L + '/api/support', 'instant (form-age 10ms) post was not refused: ' + bot.status()); + } + await pp.screenshot({ path: OUT + '/support-public.png' }).catch(() => {}); + flush(pbag, L + '/support'); await pctx.close(); + } await ctx.close(); } await browser.close(); diff --git a/releases.js b/releases.js index d0a2644..041c2ea 100644 --- a/releases.js +++ b/releases.js @@ -64,7 +64,7 @@ function renderPage() { h += '

Release notes

'; h += v.notes.length ? v.notes.map(n => '

' + esc(n.title) + n.tags.map(tagChip).join('') + '

' + fmt(n.date) + '

' + bodyHtml(n.body) + '
').join('') : '

No notes yet.

'; h += '

Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.

'; - h += ''; + h += ''; return h; } module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES }; diff --git a/server.js b/server.js index 2493357..621873d 100644 --- a/server.js +++ b/server.js @@ -59,9 +59,10 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S const refill = require('./refill'); const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20) const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16) const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) -const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/presentation']); +const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/presentation', '/support']); let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute) const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY) @@ -530,6 +531,7 @@ async function boot() { // 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 }); + tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram }); badge.init({ publicDir: PUBLIC_DIR }); gamestats.init({ dataDir: DATA_DIR }); snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, publicDir: PUBLIC_DIR, games: gamestats, launchesToday: () => GAMES().filter(g => (g.soon && g.soon.opens === todayCT()) || (g.season && g.season.start === todayCT())).map(g => g.name), @@ -703,6 +705,8 @@ function siteConfig() { geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else // Game Pass (2026-10-16, docs/GAME-PASS.md): off until Marty flips it; caps apply from capsStartDate (Central), before it polgrant allows everything and only records gamePassEnabled: '0', gamePassPriceCredits: 500, gamePassDays: 7, capFreeDaily: 0.30, capFreeTotal: 2.0, capPassDaily: 1.50, capPassTotal: 5.0, capsStartDate: '', passTournamentPct: 5, + supportTelegramChat: '1289244227', // help desk pings: Marty's PRIVATE chat only (a positive user id; group/channel ids are refused). Sent with telegramBotToken, Hermes bot as fallback + supportTemplates: '', // help desk saved replies, JSON [{name, body}] (Admin > Support > Saved replies); empty = the built-in set telegramGamesChatId: '', telegramGamesTopicId: '661565', // Game Achievements topic for the weekly Pass Tournament post (chat blank = the shared echo chat) pnlFixedMonthlyUsd: 0 }, saved); @@ -990,6 +994,55 @@ function tgSendAs(token, chatId, text, threadId) { rq.end(body); }); } +// Help desk pings (2026-10-16): Marty's PRIVATE Telegram chat only, never a group, topic or feed. tgSendAs skips the +// Discord relay entirely. Site bot (telegramBotToken) first, Marty's Hermes bot if that one cannot reach him. +async function supportTelegram(text) { + const sc = siteConfig(); + const chat = String(sc.supportTelegramChat || '1289244227').trim(); + if (!/^\d{4,15}$/.test(chat)) { console.error('support ping refused: supportTelegramChat must be a private chat id (positive number), not', chat); return false; } + let ok = false; + const site = String(sc.telegramBotToken || '').trim(), hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); + if (site) ok = await tgSendAs(site, chat, text); + if (!ok && hermes) ok = await tgSendAs(hermes, chat, text); + if (!ok) console.error('support ping not delivered (chat ' + chat + ', site bot ' + (site ? 'set' : 'missing') + ', hermes ' + (hermes ? 'set' : 'missing') + ')'); + return ok; +} +// Public support form + signed-out chatbot hand-off: the sign-up guard's walls (honeypot, form age, per-IP limits with the +// icon check once tripped, a global cap) plus a hard per-email cap. Returns null to allow, or { status, body }. +const SUPPORT_LIMITS = { ipHour: 5, ipDay: 15, emailHour: 3, emailDay: 8, globalPerMin: 20, minFormMs: 2000 }; +const supportHits = new Map(); // 'ip:' | 'em:' | 'tk:' -> [timestamps, 24h] +const supportChal = new Map(); // ip -> { chal, passUntil } +const supportGlobal = { minute: 0, n: 0 }; +const supportRecent = (k, ms) => { const now = Date.now(); const t = (supportHits.get(k) || []).filter(ts => now - ts < 86400000); supportHits.set(k, t); return t.filter(ts => now - ts < ms).length; }; +const supportMark = k => { const t = supportHits.get(k) || []; t.push(Date.now()); supportHits.set(k, t); if (supportHits.size > 5000) for (const [kk, v] of supportHits) if (!v.length || Date.now() - v[v.length - 1] > 86400000) supportHits.delete(kk); }; +const supportFlood = (k, n, ms) => { if (supportRecent(k, ms) >= n) return true; supportMark(k); return false; }; // signed-in and private-link replies: a plain cap +function supportGuard(req, b, email) { + const now = Date.now(); + const hpRaw = String(b.hp_field_x9 || '').trim(); + const hp = !!hpRaw && hpRaw.toLowerCase() !== email; // own email = phone autofill, not a bot + const fts = Number(b.fts) || 0; + const fage = (b.fage !== undefined && b.fage !== null && b.fage !== '' && Number.isFinite(Number(b.fage))) ? Number(b.fage) : (fts ? now - fts : -1); + if (fage < SUPPORT_LIMITS.minFormMs) { guardLog(req, 'support form-age', b); return { status: 400, body: { error: 'Give the page a few seconds, then send again.' } }; } + if (fage > 12 * 3600 * 1000) { guardLog(req, 'support form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then send again.' } }; } + const minute = Math.floor(now / 60000); + if (supportGlobal.minute !== minute) { supportGlobal.minute = minute; supportGlobal.n = 0; } + if (supportGlobal.n >= SUPPORT_LIMITS.globalPerMin) { guardLog(req, 'support global-limit', b); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } + if (supportRecent('em:' + email, 3600000) >= SUPPORT_LIMITS.emailHour || supportRecent('em:' + email, 86400000) >= SUPPORT_LIMITS.emailDay) { + guardLog(req, 'support email-limit', b); + return { status: 429, body: { error: 'You have sent several tickets already. Reply on the one you have open (the link is in your confirmation email) and Marty will see it there.' } }; + } + const ip = clientIp(req); + const limited = hp || supportRecent('ip:' + ip, 3600000) >= SUPPORT_LIMITS.ipHour || supportRecent('ip:' + ip, 86400000) >= SUPPORT_LIMITS.ipDay; + const rec = supportChal.get(ip) || { chal: null, passUntil: 0 }; + if (limited && now >= rec.passUntil) { + const pick = String(b.pick || ''); + if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } + else { guardLog(req, pick ? 'support wrong-pick' : hp ? 'support honeypot-challenge' : 'support ip-limit', b); const challenge = codeChallenge(rec); supportChal.set(ip, rec); if (supportChal.size > 5000) supportChal.clear(); return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send it.', challenge } }; } + supportChal.set(ip, rec); + } + supportGlobal.n += 1; supportMark('ip:' + ip); supportMark('em:' + email); + return null; +} function fraudAlert(email, fc, spAcct, blocked) { try { const sc = siteConfig(); @@ -1911,7 +1964,7 @@ const server = http.createServer(async (req, res) => { const c = chain.getConfig(); // public copy of the site settings: never anything that looks like a credential const pubSite = {}; - for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k)) pubSite[k] = v; + for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k) && !/^support/.test(k)) pubSite[k] = v; // support* = help desk internals (Marty's chat id, saved replies) return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId, chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0], emailAuth: mailer.hasKey() || !IS_PROD }, pubSite)); @@ -2043,6 +2096,48 @@ const server = http.createServer(async (req, res) => { return json(res, r.error ? 400 : 200, r); } + // -- help desk, public side (2026-10-16, tickets.js): /support form, the private no-login ticket link, the chatbot hand-off + if (p === '/api/support' && req.method === 'POST') { + const b = await readBody(req); + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; // signed in: the ticket is theirs, whatever was typed + const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'That email address does not look right.' }); + const guard = supportGuard(req, b, email); + if (guard) return json(res, guard.status, guard.body); + const r = await tickets.create({ source: 'public', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, subject: b.subject, category: b.category, body: b.body }); + if (r.error) return json(res, 400, r); + return json(res, 200, { ok: true, ref: r.ticket.ref, token: r.token, member: !!acct }); + } + m = /^\/api\/support\/t\/([A-Za-z0-9_.-]{20,80})(\/reply)?$/.exec(p); + if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { + const t = await tickets.byToken(m[1]); + if (!t) return json(res, 404, { error: 'This ticket link is not valid. Open the newest email about your ticket, or send a new one.' }); + if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); + const b = await readBody(req); + if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); + const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, via: 'link' }); + return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); + } + if (p === '/api/support/chatbot' && req.method === 'POST') { + const b = await readBody(req); + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; + const email = acct ? acct.email : String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return json(res, 400, { error: 'Add your email so Marty can reply.', needEmail: true }); + if (acct) { if (supportFlood('em:' + email, 5, 3600000)) return json(res, 429, { error: 'You have sent several tickets in the last hour. Open Help in your dashboard to add to one.' }); } + else { const guard = supportGuard(req, b, email); if (guard) return json(res, guard.status, guard.body); } + const tr = Array.isArray(b.transcript) ? b.transcript : []; + const turns = tr.slice(-8).map(x => ((x && x.who === 'me') ? 'Me: ' : 'Assistant: ') + String((x && x.text) || '').replace(/\s+/g, ' ').trim().slice(0, 600)).filter(x => x.length > 6); + const firstQ = tr.find(x => x && x.who === 'me' && String(x.text || '').trim()); + const note = String(b.note || '').trim().slice(0, 2000); + const body = (note ? note + '\n\n' : '') + (turns.length ? 'From the chat assistant:\n' + turns.join('\n') : '(sent from the chat assistant)'); + const r = await tickets.create({ source: 'chatbot', email, name: b.name || (acct && acct.username) || '', username: acct && acct.username, category: 'Other', + subject: 'Chat: ' + (firstQ ? String(firstQ.text).replace(/\s+/g, ' ').trim().slice(0, 100) : 'question for support'), body }); + if (r.error) return json(res, 400, r); + return json(res, 200, { ok: true, ref: r.ticket.ref, member: !!acct, link: acct ? '/my#help?t=' + r.ticket.ref : '/support/t/' + r.token }); + } + // -- accounts: email + password is the normal join path (wallet comes // out only at purchase / payout-activation time and gets linked then) if (p === '/api/signup' && req.method === 'POST') { @@ -2108,7 +2203,7 @@ const server = http.createServer(async (req, res) => { const via = parseCookies(req)['iap.angle'] || (pend && pend.via) || ''; const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || (pend && pend.joinedRef) || null; if (ref && !parseCookies(req)['iap.sponsor']) console.log('sponsor recovered without cookie', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'ref', ref, pageTok(b.ref) ? '(page token)' : '(remembered from the code request)'); - if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support.' }); + if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }); let fraudFlags = []; const existing = await accounts.byEmail(e); const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up @@ -2198,7 +2293,7 @@ const server = http.createServer(async (req, res) => { if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }, cors); } if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }, cors); emailCodes.delete(e); - if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support.' }, cors); + if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support at instantadpay.com/support.' }, cors); const pend = pendingSponsor.get(e); const ref = pageTok(b.ref) || (pend && pend.ref) || ''; const via = String(b.game); const srcTag = String(b.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30); @@ -2812,7 +2907,7 @@ const server = http.createServer(async (req, res) => { const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); const b = await readBody(req); - if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support.' }); + if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' }); const r = await tank.adopt(s.email, b.who, b.note); if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12) pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() }); @@ -2959,7 +3054,7 @@ const server = http.createServer(async (req, res) => { // a username is permanent once set: the invite link, the public wall and every // banner already printed carry it (Marty, 2026-09-10) if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) - return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support if it truly has to change.' }); + return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support (instantadpay.com/support) if it truly has to change.' }); const r = await accounts.setUsername(s.email, b.username); // First time a username is set (onboarding): now there's a real name to // show, so notify the sponsor here rather than at signup (where it'd just @@ -3794,6 +3889,29 @@ const server = http.createServer(async (req, res) => { } return json(res, 200, { ok: true, sent: recipients.length }); } + // -- help desk, member side (2026-10-16): the Help pane lists, opens and answers this member's tickets + if (p === '/api/my/support' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (req.method === 'GET') return json(res, 200, { tickets: await tickets.memberList(s.email), unread: await tickets.memberUnread(s.email), categories: tickets.CATEGORIES }); + const b = await readBody(req); + if (supportFlood('em:' + String(s.email).toLowerCase(), 5, 3600000)) return json(res, 429, { error: 'You have opened several tickets in the last hour. Add to one of those instead.' }); + const a = await accounts.byEmail(s.email); + const r = await tickets.create({ source: 'form', email: s.email, name: (a && a.username) || '', username: a && a.username, subject: b.subject, category: b.category, body: b.body, attachments: b.attachments }); + return json(res, r.error ? 400 : 200, r.error ? r : { ok: true, ref: r.ticket.ref }); + } + m = /^\/api\/my\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); + if (m && (req.method === 'GET' || (m[2] && req.method === 'POST'))) { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = await tickets.byRef(m[1]); + if (!t || t.email !== String(s.email).toLowerCase()) return json(res, 404, { error: 'Ticket not found.' }); + if (req.method === 'GET') return json(res, 200, await tickets.memberView(t)); + const b = await readBody(req); + if (supportFlood('tk:' + t.id, 20, 3600000)) return json(res, 429, { error: 'That is a lot of messages in an hour. Give Marty a moment to catch up.' }); + const r = await tickets.addMessage(t.id, { author: 'member', body: b.body, attachments: b.attachments }); + return json(res, r.error ? 400 : 200, r.error ? r : await tickets.memberView(r.ticket)); + } // -- sponsor messages: this member's inbox from their upline if (p === '/api/my/messages' && req.method === 'GET') { const s = await auth.fromRequest(req); @@ -4421,6 +4539,38 @@ const server = http.createServer(async (req, res) => { if (!isAdmin(req)) return json(res, 200, { admin: false }); return json(res, 200, { admin: true, email: ADMIN_EMAIL }); } + // -- help desk, admin side (2026-10-16): the Support pane + if (p === '/api/admin/support' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, Object.assign(await tickets.adminList({ status: u.searchParams.get('status'), platform: u.searchParams.get('platform'), category: u.searchParams.get('category'), q: u.searchParams.get('q') }), + { categories: tickets.CATEGORIES, platforms: tickets.PLATFORMS })); + } + if (p === '/api/admin/support/counts' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await tickets.counts()); + } + if (p === '/api/admin/support/templates' && (req.method === 'GET' || req.method === 'PUT')) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const read = () => { const v = siteConfig().supportTemplates; let a = v; if (typeof v === 'string') { try { a = JSON.parse(v); } catch (e) { a = null; } } return Array.isArray(a) && a.length ? a : tickets.DEFAULT_TEMPLATES; }; + if (req.method === 'GET') return json(res, 200, { templates: read() }); + const b = await readBody(req); + const list = (Array.isArray(b.templates) ? b.templates : []).map(t => ({ name: String((t && t.name) || '').trim().slice(0, 60), body: String((t && t.body) || '').trim().slice(0, 3000) })).filter(t => t.name && t.body).slice(0, 30); + const cur = siteConfig(); cur.supportTemplates = list; fs.writeFileSync(SITE_FILE, JSON.stringify(cur, null, 2)); + return json(res, 200, { ok: true, templates: read() }); + } + m = /^\/api\/admin\/support\/((?:IAP|LS)-\d{4,9})(\/reply)?$/.exec(p); + if (m) { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const t = await tickets.byRef(m[1]); + if (!t) return json(res, 404, { error: 'Ticket not found.' }); + if (m[2] && req.method === 'POST') { const b = await readBody(req); const r = await tickets.addMessage(t.id, { author: 'admin', body: b.body, internal: !!b.internal, status: b.status, attachments: b.attachments }); if (r.error) return json(res, 400, r); } + else if (!m[2] && req.method === 'PATCH') { const r = await tickets.setFields(t.id, await readBody(req)); if (r.error) return json(res, 400, r); } + else if (m[2] || req.method !== 'GET') return json(res, 405, { error: 'method' }); + const v = await tickets.adminView(t.id); + const a = await accounts.byEmail(v.ticket.email); + v.requester = a ? { member: true, email: a.email, username: a.username || '', memberId: a.memberId || 0, wallet: !!a.address, created: a.created || 0, lastSeen: a.lastSeen || 0 } : { member: false, email: v.ticket.email }; + return json(res, 200, v); + } if (p === '/api/admin/refill' && req.method === 'GET') { // who was told their ads ran out, and what they did next if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, refill.stats()); @@ -4842,7 +4992,7 @@ const server = http.createServer(async (req, res) => { + '' + '
' + esc(label) + ' badge for @' + esc(un) + '

@' + esc(un) + ' unlocked ' + label + '

' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

' + 'Join @' + esc(un) + '\u2019s line free

Advertising with a performance referral program. Not an investment; no income is guaranteed.

' - + ''; + + ''; res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); return res.end(html); } @@ -4872,6 +5022,7 @@ const server = http.createServer(async (req, res) => { return res.end(blog.renderPost(post, related)); } if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html')); + if (p === '/support' || /^\/support\/t\/[A-Za-z0-9_.-]{20,80}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'support.html')); // help desk (2026-10-16): the form, and the private ticket link if (p === '/friday') return sendFile(res, path.join(PUBLIC_DIR, 'friday.html')); if (p === '/wednesday') return sendFile(res, path.join(PUBLIC_DIR, 'wednesday.html')); if (p === '/refuel') return sendFile(res, path.join(PUBLIC_DIR, 'refuel.html')); // Drip Runner refuel visit (2026-09-30) diff --git a/tickets.js b/tickets.js new file mode 100644 index 0000000..4b599e8 --- /dev/null +++ b/tickets.js @@ -0,0 +1,323 @@ +// Help desk (Marty, 2026-10-16): one shared support desk in the IAP admin portal. A member emailed +// support@instantadpay.com when it did not exist, so nobody had a way to ask for help. Tickets come in +// from the member Help pane ('form'), the public /support page ('public'), the chatbot hand-off +// ('chatbot') and, in a later step, inbound mail to support@ ('email'). LinkSpin tickets will land on +// this same desk later (platform 'linkspin'). Only Marty answers for now, from his admin login. +// +// Refs: IAP-<1000 + id> (LS-<1000 + id> for LinkSpin), one id sequence for the whole desk, so a ref +// always names one ticket. The private no-login link is /support/t/.<32-char HMAC>, signed over +// the ticket id and requester email (DATA_DIR/support.key, or SUPPORT_SECRET), nothing stored. +// +// Email intake (next step) plugs in through ingestEmail({ from, name, subject, text, messageId, +// inReplyTo, references }): it threads by stored Message-ID first, then by the [IAP-1042] ref in the +// subject (only when the sender matches the ticket's email), else opens a new ticket (source 'email'). +// +// Dual-mode store like the other modules (MySQL when DATABASE_URL is set, JSON on the volume). +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const db = require('./db'); + +let DATA_DIR = null, deps = {}; +const SITE = 'https://instantadpay.com'; +const CATEGORIES = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other']; +const STATUSES = ['open', 'waiting_on_member', 'closed']; +const PRIORITIES = ['normal', 'high']; +const PLATFORMS = ['iap', 'linkspin']; +const SOURCES = ['form', 'public', 'chatbot', 'email']; +const PREFIX = { iap: 'IAP', linkspin: 'LS' }; +const REF_BASE = 1000; +const DEFAULT_TEMPLATES = [ + { name: 'Thanks, looking into it', body: 'Thanks for writing in. I am looking into this now and will reply here as soon as I have an answer.\n\nMarty' }, + { name: 'Sign-in code help', body: 'Sign-in codes come from no-reply@instantadpay.com and work for 15 minutes. If one does not arrive, check your spam or promotions folder, then request a fresh code at https://instantadpay.com/my. Each code replaces the one before it, so use the newest.\n\nMarty' }, + { name: 'Payouts are on-chain', body: 'Every payout is paid by the contract in the same transaction as the purchase, straight to the wallet on your account, and you can check each one on the live ledger: https://instantadpay.com/ledger. If a payout passed you by, it is usually because payouts were not switched on yet or a level was not open. Your Earnings tab shows the trace for each purchase.\n\nMarty' }, + { name: 'Solved, closing', body: 'Glad that is sorted. I will close this ticket now. If anything else comes up, reply here and it opens again.\n\nMarty' } +]; + +const refOf = (id, platform) => (PREFIX[platform] || 'IAP') + '-' + (REF_BASE + Number(id)); +function parseRef(s) { + const m = /\b(IAP|LS)-(\d{4,9})\b/i.exec(String(s || '')); + if (!m) return null; + const id = Number(m[2]) - REF_BASE; + return id > 0 ? { ref: m[1].toUpperCase() + '-' + m[2], id } : null; +} +const clean = (s, n) => String(s == null ? '' : s).replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').trim().slice(0, n); +const oneLine = (s, n) => clean(s, 2000).replace(/\s+/g, ' ').slice(0, n); +const ATT_RE = /^\/uploads\/[a-z0-9]{24}\.(?:png|jpg|webp|gif)$/; +const atts = a => (Array.isArray(a) ? a : []).map(String).filter(x => ATT_RE.test(x)).slice(0, 2); +const lc = e => String(e || '').trim().toLowerCase(); + +// ---- signed private link ---- +let SECRET = ''; +function secret() { + if (process.env.SUPPORT_SECRET && process.env.SUPPORT_SECRET.length >= 32) return process.env.SUPPORT_SECRET; + if (SECRET) return SECRET; + const f = path.join(DATA_DIR, 'support.key'); + try { SECRET = fs.readFileSync(f, 'utf8').trim(); } catch (e) {} + if (SECRET.length < 32) { + const s = crypto.randomBytes(32).toString('hex'); + try { fs.writeFileSync(f, s, { flag: 'wx', mode: 0o600 }); SECRET = s; } // wx: the other copy during a deploy overlap may have written it first + catch (e) { try { SECRET = fs.readFileSync(f, 'utf8').trim(); } catch (e2) { SECRET = s; } } + } + return SECRET; +} +const sig = t => crypto.createHmac('sha256', secret()).update('support:' + t.id + ':' + lc(t.email)).digest('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, 32); +const tokenFor = t => t.ref + '.' + sig(t); +const linkFor = t => SITE + '/support/t/' + tokenFor(t); +const TOKEN_RE = /^((?:IAP|LS)-\d{4,9})\.([A-Za-z0-9_-]{32})$/; + +// ---- stores ---- +const J = { + db: null, + FILE: () => path.join(DATA_DIR, 'support.json'), + load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { nextId: 1, nextMsg: 1, tickets: [], messages: [] }; } }, + save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }, + d() { if (!this.db) this.load(); return this.db; }, + async insertTicket(t) { const d = this.d(); const id = d.nextId++; d.tickets.push(Object.assign({}, t, { id, ref: refOf(id, t.platform) })); this.save(); return id; }, + async updateTicket(id, f) { const t = this.d().tickets.find(x => x.id === Number(id)); if (t) { Object.assign(t, f); this.save(); } }, + async getTicket(id) { const t = this.d().tickets.find(x => x.id === Number(id)); return t ? Object.assign({}, t) : null; }, + async list(f) { + let rows = this.d().tickets.slice(); + if (f.email) rows = rows.filter(t => t.email === f.email); + if (f.status) rows = rows.filter(t => t.status === f.status); + if (f.platform) rows = rows.filter(t => t.platform === f.platform); + if (f.category) rows = rows.filter(t => t.category === f.category); + if (f.q) { const q = f.q.toLowerCase(); rows = rows.filter(t => [t.ref, t.email, t.name, t.username, t.subject].some(v => String(v || '').toLowerCase().includes(q))); } + return rows.sort((a, b) => b.updated - a.updated).slice(0, f.limit || 200).map(t => Object.assign({}, t)); + }, + async insertMessage(m) { const d = this.d(); const id = d.nextMsg++; d.messages.push(Object.assign({}, m, { id })); this.save(); return id; }, + async messages(ticketId, internal) { return this.d().messages.filter(m => m.ticketId === Number(ticketId) && (internal || !m.internal)).sort((a, b) => a.id - b.id).map(m => Object.assign({}, m)); }, + async byMessageId(mids) { const s = new Set(mids); const m = this.d().messages.find(x => x.emailMessageId && s.has(x.emailMessageId)); return m ? m.ticketId : 0; }, + async counts() { const out = { open: 0, waiting_on_member: 0, closed: 0, unread: 0 }; for (const t of this.d().tickets) { out[t.status] = (out[t.status] || 0) + 1; if (t.adminUnread) out.unread++; } return out; }, + async memberUnread(email) { return this.d().tickets.filter(t => t.email === email && t.memberUnread).length; } +}; +const tRow = r => r ? ({ id: r.id, ref: r.ref, platform: r.platform, source: r.source, email: r.email, name: r.name || '', username: r.username || '', + subject: r.subject, category: r.category, status: r.status, priority: r.priority, created: Number(r.created), updated: Number(r.updated), + lastMemberAt: Number(r.last_member_at || 0), lastAdminAt: Number(r.last_admin_at || 0), adminUnread: !!r.admin_unread, memberUnread: !!r.member_unread }) : null; +const mRow = r => ({ id: r.id, ticketId: r.ticket_id, author: r.author, body: r.body || '', internal: !!r.internal, attachments: (() => { try { return JSON.parse(r.attachments || '[]'); } catch (e) { return []; } })(), + created: Number(r.created), emailMessageId: r.email_message_id || null, via: r.via || 'web' }); +const COLS = { platform: 'platform', source: 'source', email: 'email', name: 'name', username: 'username', subject: 'subject', category: 'category', status: 'status', priority: 'priority', + created: 'created', updated: 'updated', lastMemberAt: 'last_member_at', lastAdminAt: 'last_admin_at', adminUnread: 'admin_unread', memberUnread: 'member_unread' }; +const D = { + async insertTicket(t) { + const r = await db.q('INSERT INTO tickets (ref,platform,source,email,name,username,subject,category,status,priority,created,updated,last_member_at,last_admin_at,admin_unread,member_unread) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', + ['pending-' + crypto.randomBytes(5).toString('hex'), t.platform, t.source, t.email, t.name || null, t.username || null, t.subject, t.category, t.status, t.priority, t.created, t.updated, t.lastMemberAt || null, t.lastAdminAt || null, t.adminUnread ? 1 : 0, t.memberUnread ? 1 : 0]); + await db.q('UPDATE tickets SET ref=? WHERE id=?', [refOf(r.insertId, t.platform), r.insertId]); + return r.insertId; + }, + async updateTicket(id, f) { + const sets = [], vals = []; + for (const [k, v] of Object.entries(f)) if (COLS[k]) { sets.push(COLS[k] + '=?'); vals.push(typeof v === 'boolean' ? (v ? 1 : 0) : v); } + if (sets.length) await db.q('UPDATE tickets SET ' + sets.join(',') + ' WHERE id=?', vals.concat([Number(id)])); + }, + async getTicket(id) { return tRow((await db.q('SELECT * FROM tickets WHERE id=?', [Number(id)]))[0]); }, + async list(f) { + const w = [], v = []; + if (f.email) { w.push('email=?'); v.push(f.email); } + if (f.status) { w.push('status=?'); v.push(f.status); } + if (f.platform) { w.push('platform=?'); v.push(f.platform); } + if (f.category) { w.push('category=?'); v.push(f.category); } + if (f.q) { w.push('(ref LIKE ? OR email LIKE ? OR name LIKE ? OR username LIKE ? OR subject LIKE ?)'); const l = '%' + f.q + '%'; v.push(l, l, l, l, l); } + return (await db.q('SELECT * FROM tickets' + (w.length ? ' WHERE ' + w.join(' AND ') : '') + ' ORDER BY updated DESC LIMIT ?', v.concat([f.limit || 200]))).map(tRow); + }, + async insertMessage(m) { + const r = await db.q('INSERT INTO ticket_messages (ticket_id,author,body,internal,attachments,created,email_message_id,via) VALUES (?,?,?,?,?,?,?,?)', + [m.ticketId, m.author, m.body, m.internal ? 1 : 0, m.attachments && m.attachments.length ? JSON.stringify(m.attachments) : null, m.created, m.emailMessageId || null, m.via || 'web']); + return r.insertId; + }, + async messages(ticketId, internal) { return (await db.q('SELECT * FROM ticket_messages WHERE ticket_id=?' + (internal ? '' : ' AND internal=0') + ' ORDER BY id ASC', [Number(ticketId)])).map(mRow); }, + async byMessageId(mids) { if (!mids.length) return 0; const r = await db.q('SELECT ticket_id FROM ticket_messages WHERE email_message_id IN (?) LIMIT 1', [mids]); return r.length ? r[0].ticket_id : 0; }, + async counts() { + const out = { open: 0, waiting_on_member: 0, closed: 0, unread: 0 }; + for (const r of await db.q('SELECT status, COUNT(*) n, SUM(admin_unread) u FROM tickets GROUP BY status')) { out[r.status] = Number(r.n); out.unread += Number(r.u || 0); } + return out; + }, + async memberUnread(email) { return Number((await db.q('SELECT COUNT(*) n FROM tickets WHERE email=? AND member_unread=1', [email]))[0].n); } +}; +const impl = () => db.enabled() ? D : J; + +// deps: { mailer, messages, accounts, telegram(text) -> Promise, adminEmail } +function init(opts) { DATA_DIR = opts.dataDir; deps = opts; } + +// ---- notifications, throttled: the first event in a window goes out at once, the rest of the +// window's events are batched into one send at its end, so a burst of replies is one ping ---- +const windows = new Map(); +function throttled(key, ms, item, flush) { + const now = Date.now(); let w = windows.get(key); + if (!w || (now >= w.until && !w.timer)) { + windows.set(key, { until: now + ms, pending: [], timer: null }); + if (windows.size > 2000) for (const [k, v] of windows) if (v.until < now && !v.timer) windows.delete(k); + return void Promise.resolve().then(() => flush([item])).catch(e => console.error('support notify', e.message)); + } + w.pending.push(item); + if (!w.timer) { + w.timer = setTimeout(() => { + const items = w.pending.splice(0); w.timer = null; w.until = Date.now() + ms; + if (items.length) Promise.resolve().then(() => flush(items)).catch(e => console.error('support notify', e.message)); + }, Math.max(0, w.until - now)); + if (w.timer.unref) w.timer.unref(); + } +} +const newPings = { hour: 0, n: 0, skipped: 0 }; // new-ticket pings: at most 20 an hour, the rest summed into the next one +const escH = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +const who = t => (t.name ? t.name + ' ' : '') + '<' + t.email + '>' + (t.username ? ' @' + t.username : ''); +const adminLink = t => SITE + '/admin#support?t=' + t.ref; +const firstLine = s => oneLine(String(s || '').split('\n').find(l => l.trim()) || '', 140); + +function pingAdmin(kind, t, m) { + const send = items => { + const last = items[items.length - 1]; + const head = kind === 'new' ? '\u{1F3AB} ' + t.ref + ' new ticket' : '\u{1F4AC} ' + t.ref + ' ' + (items.length > 1 ? items.length + ' member replies' : 'member reply'); + let extra = ''; + if (kind === 'new') { + const h = Math.floor(Date.now() / 3600000); + if (newPings.hour !== h) { newPings.hour = h; newPings.n = 0; } + if (++newPings.n > 20) { newPings.skipped++; return; } + if (newPings.skipped) { extra = '\n(+' + newPings.skipped + ' more new tickets earlier were not pinged)'; newPings.skipped = 0; } + } + const text = head + ' · ' + t.platform + ' · ' + escH(t.category) + '\n' + escH(who(t)) + '\n' + escH(t.subject) + '\n“' + escH(firstLine(last.body)) + '”\n' + adminLink(t) + extra; + if (deps.telegram) deps.telegram(text).catch(() => {}); + if (deps.adminEmail && deps.mailer && deps.mailer.hasKey()) { + const body = items.map(i => i.body).join('\n\n---\n\n'); + deps.mailer.send(deps.adminEmail, '[' + t.ref + '] ' + (kind === 'new' ? 'New ticket: ' : 'Reply: ') + t.subject, + (kind === 'new' ? 'New support ticket' : 'Member reply') + ' on ' + t.platform + ' (' + t.category + ')\nFrom: ' + who(t) + '\nSource: ' + t.source + '\n\n' + body + '\n\nAnswer it in the desk: ' + adminLink(t), null, { transactional: true }).catch(e => console.error('support admin mail', e.message)); + } + }; + if (kind === 'new') return send([m]); + throttled('admin:' + t.id, 10 * 60 * 1000, m, send); +} +function htmlMail(intro, blocks, link, linkLabel) { + return '
' + + '

' + escH(intro) + '

' + blocks.map(b => '
' + escH(b) + '
').join('') + + '

' + escH(linkLabel) + '

' + + '

InstantAdPay support. Reply on the page above, or email support@instantadpay.com and keep the ticket number in the subject.

'; +} +function confirmRequester(t, m) { + if (!deps.mailer || !deps.mailer.hasKey()) return; + const link = linkFor(t); + const text = 'Hi' + (t.name ? ' ' + t.name : '') + ',\n\nWe got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.\n\n' + + 'Subject: ' + t.subject + '\n\n' + m.body + '\n\nView the ticket or add more detail here (no sign-in needed):\n' + link + '\n\nInstantAdPay support'; + deps.mailer.send(t.email, '[' + t.ref + '] ' + t.subject, text, htmlMail('We got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.', [m.body], link, 'View your ticket'), { transactional: true }) + .catch(e => console.error('support confirm mail', e.message)); +} +function notifyRequester(t, m) { + throttled('member:' + t.id, 2 * 60 * 1000, m, async items => { + const cur = (await impl().getTicket(t.id)) || t; + const link = linkFor(cur); + const bodies = items.map(i => i.body); + if (deps.mailer && deps.mailer.hasKey()) { + const text = 'Hi' + (cur.name ? ' ' + cur.name : '') + ',\n\nMarty replied to your support ticket ' + cur.ref + ':\n\n' + bodies.join('\n\n---\n\n') + + '\n\nRead the whole thread and reply here:\n' + link + '\n\nInstantAdPay support'; + deps.mailer.send(cur.email, '[' + cur.ref + '] ' + cur.subject, text, htmlMail('Marty replied to your support ticket ' + cur.ref + ':', bodies, link, 'Read and reply'), { transactional: true }) + .catch(e => console.error('support reply mail', e.message)); + } + // members also get it in their on-site inbox, as a notice: it never pops the sign-in modal + try { + const acct = deps.accounts && await deps.accounts.byEmail(cur.email); + if (acct && deps.messages) await deps.messages.deliver(1, deps.adminEmail || 'house@instantadpay.com', [cur.email], 'Support replied: [' + cur.ref + '] ' + cur.subject.slice(0, 110), + '

Marty replied to your support ticket ' + escH(cur.ref) + '.

' + escH(bodies[bodies.length - 1].slice(0, 600)) + '

Open it in Help

', 'notice'); + } catch (e) { console.error('support notice', e.message); } + }); +} + +// ---- the desk ---- +function validate(o) { + const subject = oneLine(o.subject, 140), body = clean(o.body, 5000); + if (subject.length < 3) return { error: 'Add a short subject.' }; + if (body.length < 5) return { error: 'Tell us a little more in the message.' }; + return { subject, body }; +} +// create a ticket and its first message. o: { platform, source, email, name, username, subject, category, body, +// attachments, priority, emailMessageId, via, confirm (default true except source 'email'), notify (default true) } +async function create(o) { + const email = lc(o.email); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return { error: 'That email address does not look right.' }; + const v = validate(o); if (v.error) return v; + const now = Date.now(); + const t = { platform: PLATFORMS.includes(o.platform) ? o.platform : 'iap', source: SOURCES.includes(o.source) ? o.source : 'form', email, + name: oneLine(o.name, 80), username: oneLine(o.username, 30), subject: v.subject, category: CATEGORIES.includes(o.category) ? o.category : 'Other', + status: 'open', priority: PRIORITIES.includes(o.priority) ? o.priority : 'normal', created: now, updated: now, lastMemberAt: now, lastAdminAt: 0, adminUnread: true, memberUnread: false }; + const id = await impl().insertTicket(t); + const m = { ticketId: id, author: 'member', body: v.body, internal: false, attachments: atts(o.attachments), created: now, emailMessageId: o.emailMessageId ? String(o.emailMessageId).slice(0, 250) : null, via: o.via || (t.source === 'email' ? 'email' : 'web') }; + m.id = await impl().insertMessage(m); + const ticket = await impl().getTicket(id); + if (o.notify !== false) pingAdmin('new', ticket, m); + if (o.confirm !== undefined ? o.confirm : t.source !== 'email') confirmRequester(ticket, m); + return { ok: true, ticket, message: m, token: tokenFor(ticket), link: linkFor(ticket) }; +} +// add a message. o: { author 'member'|'admin'|'system', body, internal, attachments, status (admin: status after sending), +// emailMessageId, via }. A member reply reopens a closed or waiting ticket; an admin reply defaults to waiting_on_member. +async function addMessage(ticketId, o) { + const t = await impl().getTicket(ticketId); + if (!t) return { error: 'Ticket not found.' }; + const author = ['member', 'admin', 'system'].includes(o.author) ? o.author : 'member'; + const body = clean(o.body, 5000); + if (body.length < 1) return { error: 'Write a message first.' }; + const internal = author === 'admin' && !!o.internal; + const now = Date.now(); + const m = { ticketId: t.id, author, body, internal, attachments: atts(o.attachments), created: now, emailMessageId: o.emailMessageId ? String(o.emailMessageId).slice(0, 250) : null, via: o.via || 'web' }; + m.id = await impl().insertMessage(m); + const f = { updated: now }; + if (author === 'member') Object.assign(f, { lastMemberAt: now, adminUnread: true, status: 'open' }); + if (author === 'admin' && !internal) Object.assign(f, { lastAdminAt: now, memberUnread: true, status: STATUSES.includes(o.status) ? o.status : 'waiting_on_member' }); + if (author === 'admin' && internal && STATUSES.includes(o.status)) f.status = o.status; + await impl().updateTicket(t.id, f); + const cur = await impl().getTicket(t.id); + if (author === 'member' && o.notify !== false) pingAdmin('reply', cur, m); + if (author === 'admin' && !internal && o.notify !== false) notifyRequester(cur, m); + return { ok: true, ticket: cur, message: m }; +} +async function setFields(ticketId, f) { + const t = await impl().getTicket(ticketId); if (!t) return { error: 'Ticket not found.' }; + const up = {}; + if (STATUSES.includes(f.status)) up.status = f.status; + if (PRIORITIES.includes(f.priority)) up.priority = f.priority; + if (CATEGORIES.includes(f.category)) up.category = f.category; + if (PLATFORMS.includes(f.platform)) up.platform = f.platform; + if (!Object.keys(up).length) return { error: 'Nothing to change.' }; + up.updated = Date.now(); + await impl().updateTicket(t.id, up); + return { ok: true, ticket: await impl().getTicket(t.id) }; +} +const byRef = async ref => { const r = parseRef(ref); if (!r) return null; const t = await impl().getTicket(r.id); return t && t.ref === r.ref ? t : null; }; +async function byToken(tok) { + const m = TOKEN_RE.exec(String(tok || '')); if (!m) return null; + const t = await byRef(m[1]); if (!t) return null; + const want = sig(t); + return want.length === m[2].length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(m[2])) ? t : null; +} +const pubMsg = m => ({ id: m.id, author: m.author, body: m.body, attachments: m.attachments, created: m.created }); +const pubTicket = t => ({ ref: t.ref, platform: t.platform, subject: t.subject, category: t.category, status: t.status, created: t.created, updated: t.updated, unread: t.memberUnread }); +async function memberList(email) { return (await impl().list({ email: lc(email), limit: 100 })).map(pubTicket); } +async function memberUnread(email) { return impl().memberUnread(lc(email)); } +// the requester's view of one ticket (no internal notes); opening it clears their unread flag +async function memberView(t) { + if (t.memberUnread) await impl().updateTicket(t.id, { memberUnread: false }); + return { ticket: Object.assign(pubTicket(t), { unread: false, name: t.name }), messages: (await impl().messages(t.id, false)).map(pubMsg) }; +} +async function adminList(f) { + const q = { status: STATUSES.includes(f.status) ? f.status : '', platform: PLATFORMS.includes(f.platform) ? f.platform : '', category: CATEGORIES.includes(f.category) ? f.category : '', q: oneLine(f.q, 80), limit: 300 }; + return { tickets: await impl().list(q), counts: await impl().counts() }; +} +async function adminView(id) { + const t = await impl().getTicket(id); if (!t) return null; + if (t.adminUnread) await impl().updateTicket(t.id, { adminUnread: false }); + return { ticket: Object.assign(t, { adminUnread: false }), messages: await impl().messages(t.id, true), link: linkFor(t) }; +} +const counts = () => impl().counts(); + +// inbound mail (next step): thread a reply or open a ticket. Returns { ok, ticket, message, created }. +async function ingestEmail(e) { + const from = lc(e.from); + const mid = e.messageId ? String(e.messageId).trim().slice(0, 250) : null; + const refs = [e.inReplyTo].concat(String(e.references || '').split(/\s+/)).map(x => String(x || '').trim()).filter(Boolean); + let ticketId = refs.length ? await impl().byMessageId(refs) : 0; + if (!ticketId) { const r = parseRef(e.subject); if (r) { const t = await byRef(r.ref); if (t && t.email === from) ticketId = t.id; } } + const body = clean(e.text, 5000); + if (ticketId) { const r = await addMessage(ticketId, { author: 'member', body, emailMessageId: mid, via: 'email' }); return Object.assign(r, { created: false }); } + const r = await create({ platform: e.platform || 'iap', source: 'email', email: from, name: e.name, subject: oneLine(e.subject, 140) || '(no subject)', category: 'Other', body, emailMessageId: mid, via: 'email', confirm: !!e.confirm }); + return Object.assign(r, { created: true }); +} + +module.exports = { init, CATEGORIES, STATUSES, PRIORITIES, PLATFORMS, SOURCES, DEFAULT_TEMPLATES, refOf, parseRef, tokenFor, linkFor, + create, addMessage, setFields, byRef, byToken, memberList, memberUnread, memberView, adminList, adminView, counts, ingestEmail };