// Rayan admin panel. The page is public, but every read and write below is enforced on the server: // tables use RLS with public.is_admin() (the confirmed owner email for the JWT's user), the admin_* RPCs raise // 'admin only' for anyone else, and the AI assistant runs in the Edge Function rayan-admin, which verifies the JWT itself. import { supa, hasStoredSession, SUPA_URL, SUPA_KEY } from './auth.js'; import { applyTheme } from './extras.js'; applyTheme(); const $ = id => document.getElementById(id); const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const fa = n => String(n ?? 0).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]); const when = t => t ? new Date(t).toLocaleString('fa-IR', { dateStyle: 'short', timeStyle: 'short' }) : '—'; const sb = await supa(); const session = hasStoredSession() ? (await sb.auth.getSession()).data.session : null; async function adminFn(body) { const r = await fetch(SUPA_URL + '/functions/v1/rayan-admin', { method: 'POST', headers: { 'Content-Type': 'application/json', apikey: SUPA_KEY, Authorization: 'Bearer ' + session.access_token }, body: JSON.stringify(body) }); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || r.status); return j; } let ok = false; if (session) { const { data, error } = await sb.rpc('is_admin'); ok = !error && data === true; } if (!ok) { $('gate').innerHTML = session ? 'این حساب دسترسی مدیر ندارد (بررسی سمت سرور).' : 'برای ورود به پنل مدیریت ابتدا وارد شوید.'; } else { $('gate').hidden = true; $('admin').hidden = false; // ---------- overview ---------- const loadOv = async () => { const { data: o, error } = await sb.rpc('admin_overview'); if (error) { $('stats').textContent = error.message; return; } const cards = [['کاربران', o.users], ['کاربر جدید (۷ روز)', o.users_7d], ['فعال (۷ روز)', o.active_7d], ['گفت‌وگوها', o.conversations], ['پیام‌ها', o.messages], ['پیام‌های امروز', o.messages_today], ['سهم سرور امروز', o.quota_used_today], ['خطا (۲۴ ساعت)', o.errors_24h], ['👍', o.feedback_up], ['👎', o.feedback_down], ['نمونه‌های آموزشی', o.training_samples], ['انصراف از آموزش', o.train_opted_out], ['حافظه‌ی دانش', o.knowledge], ['عضو خبرنامه', o.marketing_opted_in], ['صف ایمیل (معلق)', o.email_queue_held]]; $('stats').innerHTML = cards.map(([k, v]) => `
${fa(v)}${k}
`).join(''); const { data: d } = await sb.rpc('admin_daily', { p_days: 14 }); const max = Math.max(1, ...(d || []).map(r => r.chat)); $('daily').innerHTML = 'روزگفت‌وگو (سرور)پیام ذخیره‌شدهکاربر جدیدتصویرپشتیبانآفلاینفایلسایت' + (d || []).map(r => `${r.day} ${fa(r.chat)}${fa(r.messages)}${fa(r.new_users)}${fa(r.image)}${fa(r.fallback)}${fa(r.offline)}${fa(r.file)}${fa(r.site)}`).join(''); }; // ---------- users ---------- const agentTool = async (tool, args) => { const r = await fetch(SUPA_URL + '/functions/v1/rayan-admin-agent', { method: 'POST', headers: { 'Content-Type': 'application/json', apikey: SUPA_KEY, Authorization: 'Bearer ' + session.access_token }, body: JSON.stringify({ action: 'tool', tool, args }) }); const j = await r.json().catch(() => ({})); if (!j.ok) throw new Error(j.result?.error || j.error || r.status); return j.result; }; const loadU = async () => { const [{ data, error }, { data: fl }] = await Promise.all([sb.rpc('admin_users', { p_q: $('uq').value.trim(), p_limit: 100, p_offset: 0 }), sb.from('user_flags').select('*')]); if (error) { $('ulist').innerHTML = `${esc(error.message)}`; return; } const F = Object.fromEntries((fl || []).map(f => [f.user_id, f])); $('ulist').innerHTML = 'ایمیلنامورود باعضویتآخرین ورودگفت‌وگوپیامآموزشخبرنامهوضعیتسهم اضافه' + data.map(u => { const f = F[u.id] || {}; const ex = f.extra_daily && (!f.extra_until || f.extra_until >= new Date().toISOString().slice(0, 10)) ? fa(f.extra_daily) + (f.extra_until ? ' تا ' + esc(f.extra_until) : '') : '—'; return `${esc(u.email)}${esc(u.display_name || '')}${esc(u.provider)}${when(u.created_at)}${when(u.last_sign_in_at)}${fa(u.conversations)}${fa(u.messages)}${u.train_opt_in ? '✓' : '—'}${u.marketing_opt_in ? '✓' : '—'}` + `${f.banned ? 'مسدود' : 'فعال'}${ex}${u.email === 'jalilitaymaz@gmail.com' ? '' : ` · `}`; }).join(''); for (const b of $('ulist').querySelectorAll('[data-ban]')) b.onclick = async () => { try { if (b.dataset.b === '1') await agentTool('unban_user', { user: b.dataset.ban }); else { const reason = prompt('دلیل مسدودسازی ' + b.dataset.ban + ' (اختیاری):'); if (reason === null) return; await agentTool('ban_user', { user: b.dataset.ban, reason }); } loadU(); } catch (e) { alert(e.message || e); } }; for (const b of $('ulist').querySelectorAll('[data-quota]')) b.onclick = async () => { const n = prompt('چند پیام اضافه در روز برای ' + b.dataset.quota + '؟ (۰ = حذف)'); if (n === null) return; const until = prompt('تا چه روزی؟ (YYYY-MM-DD، خالی = بدون پایان)') || ''; try { await agentTool('grant_quota', { user: b.dataset.quota, extra: +String(n).replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d)), until }); loadU(); } catch (e) { alert(e.message || e); } }; }; $('ugo').onclick = loadU; $('uq').onkeydown = e => { if (e.key === 'Enter') loadU(); }; $('uexport').onclick = () => { // v13: CSV export of the visible users table const rows = [...$('ulist').querySelectorAll('tr')].map(tr => [...tr.querySelectorAll('th,td')].map(td => '"' + td.innerText.replace(/"/g, '""').replace(/\n/g, ' ') + '"').join(',')); const blob = new Blob(['\ufeff' + rows.join('\n')], { type: 'text/csv;charset=utf-8' }); const url = URL.createObjectURL(blob); const a2 = document.createElement('a'); a2.href = url; a2.download = 'rayan-users.csv'; a2.click(); URL.revokeObjectURL(url); }; // ---------- errors ---------- const loadE = async () => { const { data, error } = await sb.from('app_errors').select('*').order('at', { ascending: false }).limit(100); $('elist').innerHTML = error ? `${esc(error.message)}` : (data.length ? 'زمانمنبعکدمدلجزئیات' + data.map(e => `${when(e.at)}${esc(e.source)}${esc(e.code)}${esc((e.model || '').replace(':free', ''))}${esc(e.detail)}`).join('') : 'خطایی ثبت نشده است.'); }; $('eclear').onclick = async () => { await sb.from('app_errors').delete().lt('at', new Date(Date.now() - 7 * 864e5).toISOString()); loadE(); }; // ---------- feedback ---------- const loadF = async () => { const { data, error } = await sb.rpc('admin_feedback', { p_limit: 60 }); if (error) { $('fbsum').textContent = error.message; return; } const up = data.filter(r => r.rating > 0).length; $('fbsum').textContent = `۶۰ بازخورد اخیر: 👍 ${fa(up)} · 👎 ${fa(data.length - up)} (فقط متن پاسخ رایان نمایش داده می‌شود، نه پرسش کاربر)`; $('fblist').innerHTML = 'زمانمدلپاسخ' + data.map(r => `${when(r.at)}${r.rating > 0 ? '👍' : '👎'}${esc((r.model || r.tier || '').replace(':free', ''))}${esc(r.answer || '')}`).join(''); }; // ---------- settings ---------- const loadS = async () => { const { data } = await sb.from('site_settings').select('*'); const v = Object.fromEntries((data || []).map(r => [r.key, r.value])); $('sDay').value = v.limit_day ?? ''; $('sMin').value = v.limit_minute ?? ''; $('sGlobal').value = v.limit_global ?? ''; $('sPrompt').value = typeof v.system_prompt === 'string' ? v.system_prompt : ''; if (!$('sDay').value) $('sDay').placeholder = 'پیش‌فرض ۳۰'; if (!$('sMin').value) $('sMin').placeholder = 'پیش‌فرض ۵'; if (!$('sGlobal').value) $('sGlobal').placeholder = 'پیش‌فرض ۴۵'; }; const saveKey = async (key, val) => val === null ? sb.from('site_settings').delete().eq('key', key) : sb.from('site_settings').upsert({ key, value: val, updated_at: new Date().toISOString() }); $('sSave').onclick = async () => { const num = id => { const x = $(id).value.trim(); return x === '' ? null : Math.max(0, Math.min(100000, Math.round(+x))); }; const p = $('sPrompt').value.trim(); const res = await Promise.all([saveKey('limit_day', num('sDay')), saveKey('limit_minute', num('sMin')), saveKey('limit_global', num('sGlobal')), saveKey('system_prompt', p.length > 20 ? p : null)]); const err = res.find(r => r.error); $('sMsg').textContent = err ? err.error.message : 'ذخیره شد ✓ (تا ۶۰ ثانیه دیگر روی سرور اعمال می‌شود)'; }; $('sDefault').onclick = async () => { try { const j = await adminFn({ action: 'default_prompt' }); $('sPrompt').value = j.prompt || ''; $('sMsg').textContent = 'دستور پیش‌فرض بارگذاری شد؛ برای اعمال تغییر، ذخیره کنید.'; } catch (e) { $('sMsg').textContent = String(e.message || e); } }; $('sReset').onclick = async () => { if (!confirm('دستور سیستمی و سقف‌ها به پیش‌فرض برگردند؟')) return; await Promise.all(['limit_day', 'limit_minute', 'limit_global', 'system_prompt'].map(k => saveKey(k, null))); loadS(); $('sMsg').textContent = 'به پیش‌فرض برگشت.'; }; // ---------- announcements + AI assistant ---------- const loadA = async () => { const { data } = await sb.from('announcements').select('*').order('created_at', { ascending: false }).limit(50); $('aList').innerHTML = 'متننوعوضعیت' + (data || []).filter(x => x.kind !== 'site_config').map(a => '' + esc(a.body_fa) + '' + esc(a.kind) + '' + (a.active ? 'فعال' : 'خاموش') + ' · ').join(''); for (const b of $('aList').querySelectorAll('[data-t]')) b.onclick = async () => { const a = data.find(x => x.id === b.dataset.t); await sb.from('announcements').update({ active: !a.active }).eq('id', a.id); loadA(); }; for (const b of $('aList').querySelectorAll('[data-d]')) b.onclick = async () => { if (confirm('حذف شود؟')) { await sb.from('announcements').delete().eq('id', b.dataset.d); loadA(); } }; }; $('aSave').onclick = async () => { const row = { body_fa: $('aFa').value.trim(), body_en: $('aEn').value.trim() || null, link_url: $('aLink').value.trim() || null, kind: $('aKind').value, active: $('aActive').checked }; const { error } = await sb.from('announcements').insert(row); if (error) alert(error.message); else { $('aFa').value = $('aEn').value = $('aLink').value = ''; loadA(); } }; $('aiGo').onclick = async () => { const brief = $('aiBrief').value.trim(); if (!brief) return; $('aiGo').disabled = true; $('aiMsg').textContent = 'در حال نوشتن…'; try { const j = await adminFn({ action: 'draft', brief }); $('aFa').value = j.fa; $('aEn').value = j.en; $('aKind').value = j.kind; $('aiMsg').textContent = 'پیش‌نویس در فرم پایین قرار گرفت؛ بررسی و سپس «افزودن اعلان» را بزنید.'; } catch (e) { $('aiMsg').textContent = 'ناموفق: ' + (e.message || e); } $('aiGo').disabled = false; }; // ---------- email campaigns (queue only; sending disabled) ---------- const loadC = async () => { const { data } = await sb.from('campaigns').select('*').order('created_at', { ascending: false }).limit(50); const { data: q } = await sb.from('email_queue').select('campaign_id').limit(10000); const held = id => (q || []).filter(x => x.campaign_id === id).length; $('cList').innerHTML = 'موضوعوضعیتدر صف (معلق)' + (data || []).map(c => '' + esc(c.subject) + '' + esc(c.status) + '' + fa(held(c.id)) + ' · ').join(''); for (const b of $('cList').querySelectorAll('[data-d]')) b.onclick = async () => { if (confirm('حذف شود؟')) { await sb.from('campaigns').delete().eq('id', b.dataset.d); loadC(); } }; for (const b of $('cList').querySelectorAll('[data-q]')) b.onclick = async () => { const { data: n, error } = await sb.rpc('admin_queue_campaign', { p_campaign: b.dataset.q }); alert(error ? error.message : `${fa(n)} گیرنده به صف اضافه شد. ارسال تا تنظیم سرویس ایمیل غیرفعال است.`); loadC(); }; }; $('cSave').onclick = async () => { const { error } = await sb.from('campaigns').insert({ subject: $('cSub').value.trim(), body: $('cBody').value.trim(), lang: $('cLang').value }); if (error) alert(error.message); else { $('cSub').value = $('cBody').value = ''; loadC(); } }; sb.rpc('campaign_audience_count').then(({ data }) => { $('aud').textContent = fa(data ?? '?'); }); loadOv(); loadU(); loadE(); loadF(); loadS(); loadA(); loadC(); // ---------- v13: email automation bots (run while the panel is open) ---------- const AU = 'rayan.automations.v1'; const auGet = () => { try { return JSON.parse(localStorage.getItem(AU) || 'null') || { welcome: true, changes: false, weekly: false, lastWelcomeAt: 0, lastWeeklyAt: 0, lastChangeAt: 0 }; } catch { return { welcome: true, changes: false, weekly: false, lastWelcomeAt: 0, lastWeeklyAt: 0, lastChangeAt: 0 }; } }; const auSet = o => localStorage.setItem(AU, JSON.stringify(o)); const auLog = m => { const el = $('auLog'); if (el) el.textContent = new Date().toLocaleString('fa-IR') + ' — ' + m + '\n' + el.textContent.slice(0, 1500); }; (() => { const x = auGet(); $('auWelcome').checked = x.welcome !== false; $('auChanges').checked = !!x.changes; $('auWeekly').checked = !!x.weekly; })(); $('auSave').onclick = () => { const x = auGet(); x.welcome = $('auWelcome').checked; x.changes = $('auChanges').checked; x.weekly = $('auWeekly').checked; auSet(x); $('auMsg').textContent = 'ذخیره شد ✓'; }; const queueCampaign = async (subject, body) => { const { data: c, error } = await sb.from('campaigns').insert({ subject, body, lang: 'fa' }).select('id').single(); if (error) throw error; const { data: n, error: e2 } = await sb.rpc('admin_queue_campaign', { p_campaign: c.id }); if (e2) throw e2; return n || 0; }; const auRun = async () => { const x = auGet(); try { if (x.welcome !== false) { const since = new Date(x.lastWelcomeAt || 0).toISOString(); const { data: users } = await sb.rpc('admin_users', { p_q: '', p_limit: 50, p_offset: 0 }); const fresh = (users || []).filter(u => u.created_at && u.created_at > since && u.marketing_opt_in); if (fresh.length) { const n = await queueCampaign('به رایان خوش آمدید 🌟', 'سلام،\n\nاز اینکه به رایان پیوستید خوشحالیم. رایان، دستیار فارسی شما برای نوشتن، ترجمه، کد و ساخت وب‌سایت است.\n\nهمین حالا شروع کنید: {{LINK}}\n\nبرای انصراف: {{UNSUB}}'); x.lastWelcomeAt = Date.now(); auSet(x); auLog(`🤖 خوشامدگویی: ${fresh.length} کاربر جدید → ${n} ایمیل در صف`); } } if (x.weekly) { const week = 7 * 24 * 3600 * 1000; if (Date.now() - (x.lastWeeklyAt || 0) > week) { const n = await queueCampaign('خبرنامه هفتگی رایان 📬', 'درود،\n\nتازه‌ترین خبرهای این هفته رایان:\n\n۱) ...\n۲) ...\n۳) ...\n\nمشاهده: {{LINK}}\n\nانصراف: {{UNSUB}}'); x.lastWeeklyAt = Date.now(); auSet(x); auLog(`🤖 خبرنامه هفتگی → ${n} ایمیل در صف`); } } } catch (e) { auLog('❌ خطا: ' + (e.message || e)); } }; setInterval(auRun, 10 * 60 * 1000); auRun(); // changes bot: when the site code/appearance is saved, notify subscribers document.addEventListener('rayan:siteChanged', async () => { const x = auGet(); if (!x.changes) return; try { const n = await queueCampaign('تازه‌سازی جدید در رایان ✨', 'سلام،\n\nتغییر تازه‌ای در رایان اعمال شد — همین حالا ببینید:\n\n{{LINK}}\n\nانصراف: {{UNSUB}}'); x.lastChangeAt = Date.now(); auSet(x); auLog(`🤖 اطلاع‌رسانی تغییرات → ${n} ایمیل در صف`); } catch (e) { auLog('❌ تغییرات: ' + (e.message || e)); } }); }