afede88c4a
- GET /api/admin/content?type=&q=&from=&to=&flagged=1&page=&per=&fresh=1 (admin only, read-only): content.js normalizes rows from each module's own adminAll() (new one-pass accessors in pages, rotator, sources, zones, postbacks, audiences, messages.adminBroadcasts, videomaker.adminJobs) plus ads.adminList and accounts.listAll; owner shown as @username, email and member #; created in Central time; totals per type; busiest hosts in the current view - Flags: open member reports on an ad, dead or parked destinations, burned link domains, failing postbacks, admin-paused zones, home-page demo links. No deny list exists yet - Row actions only reuse existing moderation routes (campaign pause/resume, zone pause/resume); "Open member" jumps to the member card; page Preview works for drafts and is never counted (admin allowed on ?preview=1) - Uploads: /uploads files now recorded with their uploader in uploads-index.json; older files get the owner from whatever uses them (campaign creative, profile, wall offer) - Credits > Your purchases: buys made from linked positions are included, labelled "Position N" - Cache tags: admin.css 20261018a, admin.js 20261018b, credits-screen.js 20261018b Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
214 lines
12 KiB
JavaScript
214 lines
12 KiB
JavaScript
// Sponsor → downline messages: team comms delivered to members' on-site inbox
|
|
// (and by email). Distinct from solo ADS (which are paid and earn credits).
|
|
// Dual-mode: MySQL when DATABASE_URL is set, else a JSON file in the volume.
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const db = require('./db');
|
|
|
|
let DATA_DIR = null;
|
|
const J = {
|
|
db: null,
|
|
FILE: () => path.join(DATA_DIR, 'sponsor-messages.json'),
|
|
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { nextId: 1, items: [] }; } },
|
|
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} }
|
|
};
|
|
function init(opts) { DATA_DIR = opts.dataDir; }
|
|
const DAY = 86400000;
|
|
|
|
// has this sponsor already broadcast within the last 24h? (1/day cap)
|
|
async function lastBroadcastAt(fromEmail) {
|
|
const e = String(fromEmail || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const r = await db.q("SELECT MAX(sent) m FROM sponsor_messages WHERE from_email=? AND kind='broadcast'", [e]);
|
|
return r.length && r[0].m ? Number(r[0].m) : 0;
|
|
}
|
|
if (!J.db) J.load();
|
|
const mine = J.db.items.filter(i => i.fromEmail === e && (i.kind || 'broadcast') === 'broadcast').map(i => i.sent);
|
|
return mine.length ? Math.max(...mine) : 0;
|
|
}
|
|
// deliver one message to many recipients (already-resolved emails). Returns count.
|
|
// `kind` (ported from InstantAdPay 2026-10-15): 'broadcast' = a person wrote it (may pop the sign-in modal);
|
|
// 'alert' = system message where the member loses money by not acting (may pop); 'notice' = system message,
|
|
// nothing required: inbox only, never a modal (carry-over notices, Marty: quiet inbox, seen once they log in).
|
|
async function deliver(fromMember, fromEmail, recipients, subject, body, kind) {
|
|
const k = ['notice', 'alert'].includes(kind) ? kind : 'broadcast';
|
|
const now = Date.now();
|
|
let n = 0;
|
|
if (db.enabled()) {
|
|
for (const to of recipients) {
|
|
await db.q("INSERT INTO sponsor_messages (from_member,from_email,to_email,subject,body,sent,kind) VALUES (?,?,?,?,?,?,?)",
|
|
[fromMember || 0, fromEmail, to, subject, body, now, k]);
|
|
n++;
|
|
}
|
|
} else {
|
|
if (!J.db) J.load();
|
|
for (const to of recipients) {
|
|
J.db.items.push({ id: J.db.nextId++, kind: k, fromMember: fromMember || 0, fromEmail, toEmail: to, subject, body, sent: now, readTs: 0 });
|
|
n++;
|
|
}
|
|
J.save();
|
|
}
|
|
return n;
|
|
}
|
|
// every non-chat kind is inbox mail; only a human broadcast or a money-at-stake alert may pop the modal
|
|
const isBroadcast = i => (i.kind || 'broadcast') !== 'chat';
|
|
const popsModal = i => ['broadcast', 'alert'].includes(i.kind || 'broadcast');
|
|
const isChat = i => i.kind === 'chat';
|
|
async function inbox(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const rows = await db.q(`SELECT id, from_member, subject, body, sent, read_ts FROM sponsor_messages
|
|
WHERE to_email=? AND kind<>'chat' ORDER BY sent DESC LIMIT 100`, [e]);
|
|
return rows.map(r => ({ id: r.id, fromMember: r.from_member, subject: r.subject, body: r.body,
|
|
sent: Number(r.sent), read: !!r.read_ts }));
|
|
}
|
|
if (!J.db) J.load();
|
|
return J.db.items.filter(i => i.toEmail === e && isBroadcast(i)).sort((a, b) => b.sent - a.sent).slice(0, 100)
|
|
.map(i => ({ id: i.id, fromMember: i.fromMember, subject: i.subject, body: i.body, sent: i.sent, read: !!i.readTs }));
|
|
}
|
|
|
|
// ── two-way sponsor CHAT (kind='chat'), plain-text 1:1 threads ──
|
|
async function sendChat(fromMember, fromEmail, toEmail, body) {
|
|
const now = Date.now();
|
|
const from = String(fromEmail || '').toLowerCase(), to = String(toEmail || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const r = await db.q("INSERT INTO sponsor_messages (from_member,from_email,to_email,subject,body,sent,kind) VALUES (?,?,?,'',?,?,'chat')",
|
|
[fromMember || 0, from, to, body, now]);
|
|
return { id: r.insertId, sent: now };
|
|
}
|
|
if (!J.db) J.load();
|
|
const id = J.db.nextId++;
|
|
J.db.items.push({ id, kind: 'chat', fromMember: fromMember || 0, fromEmail: from, toEmail: to, subject: '', body, sent: now, readTs: 0 });
|
|
J.save();
|
|
return { id, sent: now };
|
|
}
|
|
// messages between two members (both directions), id > afterId, oldest→newest
|
|
// last message from one member to another, any kind (0 if never)
|
|
async function lastFrom(fromEmail, toEmail) {
|
|
const f = String(fromEmail || '').toLowerCase(), t = String(toEmail || '').toLowerCase();
|
|
if (db.enabled()) { const r = await db.q('SELECT MAX(sent) s FROM sponsor_messages WHERE from_email=? AND to_email=?', [f, t]); return Number((r[0] && r[0].s) || 0); }
|
|
if (!J.db) J.load();
|
|
return J.db.items.filter(i => i.fromEmail === f && i.toEmail === t).reduce((m, i) => Math.max(m, i.sent || 0), 0);
|
|
}
|
|
async function thread(aEmail, bEmail, afterId = 0, limit = 300) {
|
|
const a = String(aEmail || '').toLowerCase(), b = String(bEmail || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const rows = await db.q(`SELECT id, from_member, from_email, body, sent, read_ts FROM sponsor_messages
|
|
WHERE kind='chat' AND id>? AND ((from_email=? AND to_email=?) OR (from_email=? AND to_email=?))
|
|
ORDER BY id ASC LIMIT ?`, [Number(afterId) || 0, a, b, b, a, limit]);
|
|
return rows.map(r => ({ id: r.id, fromMember: r.from_member, fromEmail: r.from_email, body: r.body, sent: Number(r.sent), read: !!r.read_ts }));
|
|
}
|
|
if (!J.db) J.load();
|
|
return J.db.items.filter(i => isChat(i) && i.id > (Number(afterId) || 0)
|
|
&& ((i.fromEmail === a && i.toEmail === b) || (i.fromEmail === b && i.toEmail === a)))
|
|
.sort((x, y) => x.id - y.id).slice(0, limit)
|
|
.map(i => ({ id: i.id, fromMember: i.fromMember, fromEmail: i.fromEmail, body: i.body, sent: i.sent, read: !!i.readTs }));
|
|
}
|
|
// mark every chat message FROM other → email as read
|
|
async function markChatRead(email, otherEmail) {
|
|
const e = String(email || '').toLowerCase(), o = String(otherEmail || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
await db.q("UPDATE sponsor_messages SET read_ts=? WHERE kind='chat' AND to_email=? AND from_email=? AND read_ts IS NULL", [Date.now(), e, o]);
|
|
return { ok: true };
|
|
}
|
|
if (!J.db) J.load();
|
|
let touched = false;
|
|
for (const i of J.db.items) if (isChat(i) && i.toEmail === e && i.fromEmail === o && !i.readTs) { i.readTs = Date.now(); touched = true; }
|
|
if (touched) J.save();
|
|
return { ok: true };
|
|
}
|
|
async function chatUnread(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const r = await db.q("SELECT COUNT(*) n FROM sponsor_messages WHERE kind='chat' AND to_email=? AND read_ts IS NULL", [e]);
|
|
return r[0].n;
|
|
}
|
|
if (!J.db) J.load();
|
|
return J.db.items.filter(i => isChat(i) && i.toEmail === e && !i.readTs).length;
|
|
}
|
|
// one row per conversation partner: newest message + my unread count from them
|
|
async function threadList(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
let rows;
|
|
if (db.enabled()) {
|
|
rows = (await db.q(`SELECT from_email, to_email, body, sent, read_ts FROM sponsor_messages
|
|
WHERE kind='chat' AND (from_email=? OR to_email=?) ORDER BY sent DESC LIMIT 800`, [e, e]))
|
|
.map(r => ({ fromEmail: r.from_email, toEmail: r.to_email, body: r.body, sent: Number(r.sent), read: !!r.read_ts }));
|
|
} else {
|
|
if (!J.db) J.load();
|
|
rows = J.db.items.filter(i => isChat(i) && (i.fromEmail === e || i.toEmail === e))
|
|
.sort((a, b) => b.sent - a.sent)
|
|
.map(i => ({ fromEmail: i.fromEmail, toEmail: i.toEmail, body: i.body, sent: i.sent, read: !!i.readTs }));
|
|
}
|
|
const byOther = new Map();
|
|
for (const r of rows) {
|
|
const other = r.fromEmail === e ? r.toEmail : r.fromEmail;
|
|
if (!byOther.has(other)) byOther.set(other, { email: other, last: { body: r.body, sent: r.sent, fromMe: r.fromEmail === e }, unread: 0 });
|
|
if (r.toEmail === e && !r.read) byOther.get(other).unread++;
|
|
}
|
|
return [...byOther.values()];
|
|
}
|
|
async function unreadCount(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const r = await db.q("SELECT COUNT(*) n FROM sponsor_messages WHERE to_email=? AND kind<>'chat' AND read_ts IS NULL", [e]);
|
|
return r[0].n;
|
|
}
|
|
if (!J.db) J.load();
|
|
return J.db.items.filter(i => i.toEmail === e && isBroadcast(i) && !i.readTs).length;
|
|
}
|
|
// the newest unread BROADCAST (for the sign-in modal; chat never pops the modal)
|
|
async function newestUnread(email) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const rows = await db.q(`SELECT id, from_member, subject, body, sent FROM sponsor_messages
|
|
WHERE to_email=? AND kind IN ('broadcast','alert') AND read_ts IS NULL ORDER BY sent DESC LIMIT 1`, [e]);
|
|
if (!rows.length) return null;
|
|
const r = rows[0];
|
|
return { id: r.id, fromMember: r.from_member, subject: r.subject, body: r.body, sent: Number(r.sent) };
|
|
}
|
|
if (!J.db) J.load();
|
|
const u = J.db.items.filter(i => i.toEmail === e && popsModal(i) && !i.readTs).sort((a, b) => b.sent - a.sent)[0];
|
|
return u ? { id: u.id, fromMember: u.fromMember, subject: u.subject, body: u.body, sent: u.sent } : null;
|
|
}
|
|
async function markRead(email, id) {
|
|
const e = String(email || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
await db.q('UPDATE sponsor_messages SET read_ts=? WHERE id=? AND to_email=? AND read_ts IS NULL', [Date.now(), Number(id), e]);
|
|
return { ok: true };
|
|
}
|
|
if (!J.db) J.load();
|
|
const i = J.db.items.find(x => x.id === Number(id) && x.toEmail === e);
|
|
if (i && !i.readTs) { i.readTs = Date.now(); J.save(); }
|
|
return { ok: true };
|
|
}
|
|
|
|
// one-time reclassify: system notices stored as 'broadcast' before the kinds existed become quiet 'notice' (idempotent)
|
|
const CARRY_SUBJECTS = /(Your LinkSpin payouts are switched on|We set up your LinkSpin position|just joined LinkSpin under you|was placed under you on LinkSpin|You missed .* on LinkSpin|is ready to buy on LinkSpin|The seat for .* passed to)/;
|
|
async function reclassifyCarryNotices(fromEmail) {
|
|
const f = String(fromEmail || '').toLowerCase();
|
|
if (db.enabled()) {
|
|
const rows = await db.q("SELECT id, subject FROM sponsor_messages WHERE kind='broadcast' AND from_member=1 AND LOWER(from_email)=?", [f]);
|
|
let n = 0; for (const r of rows) if (CARRY_SUBJECTS.test(r.subject)) { await db.q("UPDATE sponsor_messages SET kind='notice' WHERE id=?", [r.id]); n++; }
|
|
return n;
|
|
}
|
|
if (!J.db) J.load(); let n = 0;
|
|
for (const i of J.db.items) if ((i.kind || 'broadcast') === 'broadcast' && Number(i.fromMember) === 1 && String(i.fromEmail || '').toLowerCase() === f && CARRY_SUBJECTS.test(i.subject || '')) { i.kind = 'notice'; n++; }
|
|
if (n) J.save();
|
|
return n;
|
|
}
|
|
// admin Member content (2026-10-18): the broadcasts members wrote, one row per send (deliver() stores one row per recipient).
|
|
// Human broadcasts only: system notices / alerts and the private 1:1 chats are left out.
|
|
async function adminBroadcasts(limit) {
|
|
const lim = Math.max(1, Math.min(5000, Number(limit) || 2000));
|
|
if (db.enabled()) {
|
|
const rows = await db.q("SELECT from_member, from_email, subject, MAX(body) body, sent, COUNT(*) n FROM sponsor_messages WHERE (kind='broadcast' OR kind IS NULL) GROUP BY from_member, from_email, subject, sent ORDER BY sent DESC LIMIT ?", [lim]);
|
|
return rows.map(r => ({ fromMember: Number(r.from_member) || 0, fromEmail: String(r.from_email || '').toLowerCase(), subject: r.subject || '', body: String(r.body || ''), sent: Number(r.sent) || 0, recipients: Number(r.n) || 0 }));
|
|
}
|
|
if (!J.db) J.load(); const g = new Map();
|
|
for (const i of J.db.items) { if ((i.kind || 'broadcast') !== 'broadcast') continue; const k = (i.fromEmail || '') + '\u0000' + (i.subject || '') + '\u0000' + i.sent; const o = g.get(k); if (o) o.recipients++; else g.set(k, { fromMember: Number(i.fromMember) || 0, fromEmail: String(i.fromEmail || '').toLowerCase(), subject: i.subject || '', body: String(i.body || ''), sent: i.sent || 0, recipients: 1 }); }
|
|
return Array.from(g.values()).sort((a, b) => b.sent - a.sent).slice(0, lim);
|
|
}
|
|
module.exports = { init, adminBroadcasts, lastFrom, lastBroadcastAt, deliver, inbox, unreadCount, newestUnread, markRead,
|
|
sendChat, thread, markChatRead, chatUnread, threadList, reclassifyCarryNotices };
|