stremio / Backend /fastapi /templates /subscriptions_manage.html
DevDoCode
Replace Space code with weebzone/Telegram-Stremio (strip binaries)
36dde81
Raw History Blame Contribute Delete
38.1 kB
{% extends "base.html" %}
{% block title %}Subscription Management - Telegram Stremio{% endblock %}
{% block content %}
<style>
.subs-shell { display: flex; flex-direction: column; gap: 2rem; }
.section-panel, .stat-card, .mobile-user-card, .modal-glass { background: var(--card); border: 1px solid var(--border); }
.section-panel { border-radius: var(--radius); }
.empty-state { border-radius: var(--radius-sm); }
.section-title { color: var(--text); }
.section-muted, .text-soft { color: var(--text-sec); }
.glass-btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px !important; font-weight: 500 !important; transition: background-color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
.glass-btn:hover { background: var(--card-high); }
.glass-btn:active { transform: scale(.97); }
.glass-btn:disabled { opacity: .45; }
.glass-btn-primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
.glass-btn-primary:hover { background: var(--primary); filter: brightness(1.07); }
.glass-btn-success { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 35%, transparent); background: color-mix(in srgb, var(--ok) 10%, transparent); }
.glass-btn-warning { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
.glass-btn-danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
.glass-btn-purple, .glass-btn-gold { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 35%, transparent); background: color-mix(in srgb, var(--primary) 10%, transparent); }
.glass-input, .glass-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .7rem 1rem; outline: none; font-size: .9rem; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
.glass-input::placeholder { color: var(--text-sec); }
.glass-input:focus, .glass-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }
.stats-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.5rem; padding: 1.25rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
.stat-value { font-size: 1.5rem; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
.stat-label { margin-top: .2rem; font-size: .85rem; color: var(--text-sec); }
.table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
.subs-table { width: 100%; border-collapse: separate; border-spacing: 0; }
.subs-table thead th { background: var(--card); color: var(--text-sec); font-size: .72rem; font-weight: 500 !important; text-transform: uppercase; letter-spacing: .08em; border-bottom: 1px solid var(--border); }
.subs-table tbody tr { transition: background-color .15s var(--ease); }
.subs-table tbody tr:hover { background: var(--surface); }
.subs-table td { border-bottom: 1px solid var(--border); color: var(--text); vertical-align: top; }
.subs-table tbody tr:last-child td { border-bottom: none; }
.row-expired { background: color-mix(in srgb, var(--danger) 5%, transparent); }
.status-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
.status-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
.status-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
.status-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
.status-lifetime { background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); }
.status-gold { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
.action-chip { display: inline-flex; align-items: center; gap: .35rem; border-radius: 9999px; padding: .35rem .75rem; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); background: transparent; color: var(--text); transition: background-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
.action-chip:hover { background: var(--card-high); }
.action-chip:active { transform: scale(.96); }
.addon-box { padding: .7rem .8rem; border-radius: 12px; background: var(--bg); border: 1px solid var(--border); min-width: 0; overflow-wrap: anywhere; }
.usage-box { font-size: .75rem; line-height: 1.55; }
.mobile-user-card { padding: 1rem; border-radius: var(--radius-sm); min-width: 0; }
.mobile-user-card + .mobile-user-card { margin-top: .75rem; }
.mobile-grid { display: none; }
.pagination-shell { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.pagination-text { color: var(--text-sec); }
.pagination-shell .controls { display: flex; align-items: center; gap: .5rem; }
.pagination-btn { min-width: 88px; }
.modal-backdrop { background: var(--scrim); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }
.modal-glass { border-radius: var(--radius); padding: 1.4rem; width: min(100%, 30rem); max-height: calc(100dvh - 2rem); overflow-y: auto; box-shadow: var(--shadow-strong); }
.modal-field label { color: var(--text-sec); font-size: .78rem; font-weight: 500 !important; margin-bottom: .45rem; display: block; }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
@media (max-width: 1024px) { .subs-table th, .subs-table td { padding-left: 1rem; padding-right: 1rem; } }
@media (max-width: 767.98px) {
.desktop-table-wrap { display: none; }
.mobile-grid { display: block; }
.section-panel { padding: 1rem; }
.stats-row { padding: 1rem; gap: 1rem; }
.pagination-shell { flex-direction: column; align-items: stretch; }
.pagination-shell .controls { width: 100%; display: grid; grid-template-columns: 1fr auto 1fr; }
.pagination-btn { width: 100%; }
}
.plan-card { position: relative; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); transition: border-color .2s var(--ease), transform .25s var(--ease); min-width: 0; }
.plan-card:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); transform: translateY(-2px); }
.metric-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
.badge-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
.badge-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
</style>
<div class="subs-shell">
<!-- Hero -->
<header class="page-head" style="margin-bottom:0">
<div>
<h1 class="page-title">Plans</h1>
<p class="page-sub">Subscription plans and the users on them</p>
</div>
<div class="page-actions">
<button onclick="backfillNames()" class="glass-btn px-4 py-2 text-sm" title="Fetch real Telegram names for 'User <id>' entries"><i class="fa-solid fa-id-badge"></i> Sync names</button>
<button onclick="fetchSubscribers()" class="glass-btn px-4 py-2 text-sm"><i class="fa-solid fa-rotate-right"></i> Refresh</button>
<button onclick="openPlanModal()" class="glass-btn glass-btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> Add plan</button>
</div>
</header>
<!-- Plans -->
<section class="section-panel p-5">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
<div>
<h2 class="text-lg font-semibold section-title">Plans</h2>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-5" id="plans-container">
<div class="empty-state col-span-full text-center px-6 py-10 text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading plans...
</div>
</div>
</section>
<!-- Users -->
<section class="section-panel p-5">
<div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
<div>
<h2 class="text-lg font-semibold section-title">Subscribers</h2>
<p class="text-sm section-muted mt-1">Search, filter, paginate, and manage subscription access.</p>
</div>
<div class="w-full lg:w-auto grid grid-cols-1 sm:grid-cols-3 gap-3">
<input
id="sub-search"
type="text"
placeholder="Search by name, username or ID..."
class="glass-input"
oninput="subPage=1; renderSubPage()"
>
<select id="sub-filter" class="glass-select" onchange="subPage=1; renderSubPage()">
<option value="all">All Status</option>
<option value="active">Active</option>
<option value="expired">Expired</option>
</select>
<select id="sub-page-size" class="glass-select" onchange="subPage=1; renderSubPage()">
<option value="10">10 / page</option>
<option value="25">25 / page</option>
<option value="50">50 / page</option>
</select>
</div>
</div>
<!-- Desktop table -->
<div class="desktop-table-wrap table-shell">
<div class="overflow-x-auto no-scrollbar">
<table class="subs-table min-w-[780px] text-sm">
<thead>
<tr>
<th class="px-6 py-4 text-left font-semibold">User Details</th>
<th class="px-6 py-4 text-center font-semibold">Status</th>
<th class="px-6 py-4 text-center font-semibold">Expiry</th>
<th class="px-6 py-4 text-right font-semibold">Actions</th>
</tr>
</thead>
<tbody id="subscribers-tbody">
<tr>
<td colspan="4" class="px-6 py-8 text-center text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading...
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Mobile cards -->
<div id="subscribers-mobile" class="mobile-grid mt-1">
<div class="empty-state text-center px-4 py-8 text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading...
</div>
</div>
<!-- Pagination -->
<div class="pagination-shell mt-5" id="sub-pagination">
<div id="sub-page-info" class="pagination-text text-sm"></div>
<div class="controls">
<button id="sub-btn-prev" onclick="subChangePage(-1)"
class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
<i class="fa-solid fa-chevron-left text-xs"></i> Prev
</button>
<span id="sub-page-num" class="text-sm font-semibold text-center section-title px-2"></span>
<button id="sub-btn-next" onclick="subChangePage(1)"
class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
Next <i class="fa-solid fa-chevron-right text-xs"></i>
</button>
</div>
</div>
</section>
</div>
<!-- Plan Modal -->
<div id="plan-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title" id="plan-modal-title">Add New Plan</h3>
<p class="text-sm text-soft mt-1">Create or update a subscription plan.</p>
</div>
<button onclick="closePlanModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
<i class="fas fa-xmark"></i>
</button>
</div>
<form id="plan-form" onsubmit="submitPlanForm(event)" class="space-y-4">
<input type="hidden" id="plan-id">
<div class="modal-field">
<label for="plan-days">Duration (Days)</label>
<input type="number" id="plan-days" class="glass-input" required min="1">
</div>
<div class="modal-field">
<label for="plan-price">Price</label>
<input type="number" id="plan-price" class="glass-input" required min="0" step="0.01">
</div>
<div>
<label for="plan-currency">Currency</label>
<select id="plan-currency" class="glass-input">
<option value="INR">INR (₹)</option>
<option value="USD">USD ($)</option>
<option value="EUR">EUR (€)</option>
<option value="GBP">GBP (£)</option>
<option value="JPY">JPY (¥)</option>
<option value="AUD">AUD (A$)</option>
<option value="CAD">CAD (C$)</option>
<option value="SGD">SGD (S$)</option>
<option value="AED">AED (د.إ)</option>
<option value="BRL">BRL (R$)</option>
</select>
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
<button type="button" onclick="closePlanModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
Cancel
</button>
<button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">
Save Plan
</button>
</div>
</form>
</div>
</div>
<!-- User Action Modal -->
<div id="user-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
<div class="modal-glass">
<div class="flex items-start justify-between gap-4 mb-5">
<div>
<h3 class="text-xl font-semibold section-title" id="user-modal-title">Manage User</h3>
<div class="text-sm text-soft mt-1" id="user-modal-desc"></div>
</div>
<button onclick="closeUserModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
<i class="fas fa-xmark"></i>
</button>
</div>
<form id="user-form" onsubmit="submitUserForm(event)" class="space-y-4">
<input type="hidden" id="manage-user-id">
<input type="hidden" id="manage-action">
<div class="modal-field" id="days-input-group">
<label for="manage-days">Days to <span id="days-action-label"></span></label>
<input type="number" id="manage-days" class="glass-input" min="1" value="30">
</div>
<div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
<button type="button" onclick="closeUserModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
Cancel
</button>
<button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold" id="btn-user-save">
Confirm
</button>
</div>
</form>
</div>
</div>
<script>
let allUsers = [];
let subPage = 1;
function formatExpiry(expiryValue) {
if (!expiryValue) return 'N/A';
const d = new Date(expiryValue);
return d.toLocaleDateString('en-IN', {
timeZone: 'Asia/Kolkata',
day: '2-digit',
month: 'short',
year: 'numeric'
}) + ' ' + d.toLocaleTimeString('en-IN', {
timeZone: 'Asia/Kolkata',
hour: '2-digit',
minute: '2-digit'
});
}
function getUserDisplayName(u) {
let name = u.first_name || '';
if (u.username) name += (name ? ' ' : '') + `(@${u.username})`;
if (!name) name = `User ${u._id}`;
return name;
}
function getStatusBadge(status) {
return status === 'active'
? '<span class="metric-badge badge-active"><i class="fas fa-circle text-[8px]"></i> Active</span>'
: '<span class="metric-badge badge-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>';
}
function getAdminBadge(u) {
return u.is_admin
? '<span class="metric-badge" style="background: color-mix(in srgb, var(--warn) 16%, transparent); color: var(--warn);"><i class="fas fa-crown text-[8px]"></i> Owner</span>'
: '';
}
async function fetchPlans() {
const container = document.getElementById('plans-container');
container.innerHTML = `
<div class="empty-state col-span-full text-center px-6 py-10 text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading plans...
</div>
`;
try {
const res = await fetch('/api/admin/subscriptions/plans');
if (!res.ok) throw new Error('Failed to fetch plans');
const data = await res.json();
const plans = data.data || data.plans || [];
if (!plans.length) {
container.innerHTML = `
<div class="empty-state col-span-full text-center px-6 py-10 text-soft">
<i class="fas fa-box-open text-2xl mb-3"></i>
<div class="font-semibold mb-1">No plans found</div>
<div class="text-sm">Create your first subscription plan.</div>
</div>
`;
return;
}
container.innerHTML = plans.map(p => `
<div class="plan-card p-5">
<div class="plan-actions absolute right-4 top-4 flex gap-2">
<button onclick="openPlanModal('${p._id}', ${p.days}, ${p.price}, '${p.currency || 'INR'}')"
class="glass-btn rounded-full w-9 h-9 flex items-center justify-center" title="Edit plan">
<i class="fas fa-pen text-sm"></i>
</button>
<button onclick="deletePlan('${p._id}')"
class="glass-btn glass-btn-danger rounded-full w-9 h-9 flex items-center justify-center" title="Delete plan">
<i class="fas fa-trash text-sm"></i>
</button>
</div>
<div class="flex items-start gap-4">
<div class="w-14 h-14 rounded-2xl flex items-center justify-center shrink-0"
style="background: color-mix(in srgb, var(--primary) 16%, transparent); border: 1px solid color-mix(in srgb, var(--primary) 24%, transparent);">
<i class="fas fa-calendar-alt text-xl" style="color: var(--primary);"></i>
</div>
<div class="min-w-0">
<div class="text-sm font-semibold section-muted">${p.days} Days Plan</div>
<div class="mt-1 text-3xl font-semibold section-title tracking-tight">${currencySymbol(p.currency)}${p.price}</div>
<div class="text-xs text-soft mt-0.5">${(p.currency || 'INR').toUpperCase()}</div>
<div class="mt-3 inline-flex items-center gap-2 text-xs font-semibold rounded-full px-3 py-1"
style="background: color-mix(in srgb, var(--accent) 12%, transparent); color: var(--text-sec); border: 1px solid color-mix(in srgb, var(--accent) 20%, transparent);">
<i class="fas fa-bolt" style="color: var(--accent);"></i>
Premium Access
</div>
</div>
</div>
</div>
`).join('');
} catch (err) {
console.error(err);
container.innerHTML = `
<div class="empty-state col-span-full text-center px-6 py-10 text-soft">
<i class="fas fa-triangle-exclamation mr-2"></i> Failed to load plans.
</div>
`;
}
}
function currencySymbol(code) {
const map = {INR:'₹',USD:'$',EUR:'€',GBP:'£',JPY:'¥',AUD:'A$',CAD:'C$',SGD:'S$',AED:'د.إ',BRL:'R$'};
return map[(code || 'INR').toUpperCase()] || ((code || 'INR') + ' ');
}
function openPlanModal(id = '', days = '', price = '', currency = 'INR') {
document.getElementById('plan-id').value = id;
document.getElementById('plan-days').value = days;
document.getElementById('plan-price').value = price;
const cur = document.getElementById('plan-currency');
if (cur) cur.value = (currency || 'INR').toUpperCase();
document.getElementById('plan-modal-title').innerText = id ? 'Edit Plan' : 'Add New Plan';
const modal = document.getElementById('plan-modal');
modal.classList.remove('hidden');
modal.classList.add('flex');
document.body.classList.add('overflow-hidden');
}
function closePlanModal() {
const modal = document.getElementById('plan-modal');
modal.classList.add('hidden');
modal.classList.remove('flex');
document.body.classList.remove('overflow-hidden');
}
async function submitPlanForm(e) {
e.preventDefault();
const id = document.getElementById('plan-id').value;
const payload = {
days: parseInt(document.getElementById('plan-days').value),
price: parseFloat(document.getElementById('plan-price').value),
currency: (document.getElementById('plan-currency') || {}).value || 'INR'
};
try {
const res = await fetch(id ? `/api/admin/subscriptions/plans/${id}` : '/api/admin/subscriptions/plans', {
method: id ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!res.ok) throw new Error('Failed to save plan');
closePlanModal();
fetchPlans();
} catch (err) {
console.error(err);
showToast('Failed to save plan.', 'error', 'Save Failed');
}
}
async function deletePlan(id) {
if (!confirm('Delete this plan?')) return;
try {
const res = await fetch(`/api/admin/subscriptions/plans/${id}`, { method: 'DELETE' });
if (!res.ok) throw new Error('Failed');
fetchPlans();
} catch (err) {
console.error(err);
showToast('Failed to delete plan.', 'error', 'Delete Failed');
}
}
function getSubFiltered() {
const q = document.getElementById('sub-search').value.toLowerCase().trim();
const status = document.getElementById('sub-filter').value;
return allUsers.filter(u => {
const name = ((u.first_name || '') + ' ' + (u.username || '') + ' ' + (u._id || '')).toLowerCase();
const matchQ = !q || name.includes(q);
const matchStatus = status === 'all' || u.subscription_status === status;
return matchQ && matchStatus;
});
}
function renderDesktopRows(slice) {
const tbody = document.getElementById('subscribers-tbody');
if (!slice.length) {
tbody.innerHTML = `
<tr>
<td colspan="4" class="px-6 py-10 text-center text-soft">
No users match your search.
</td>
</tr>
`;
return;
}
tbody.innerHTML = slice.map(u => {
const expiry = formatExpiry(u.subscription_expiry);
const name = getUserDisplayName(u);
const safeName = name.replace(/'/g, "\\'");
const statusBadge = getStatusBadge(u.subscription_status);
return `
<tr>
<td class="px-6 py-4">
<div class="font-semibold section-title flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
<div class="text-xs text-soft mt-1">ID: ${u._id}</div>
</td>
<td class="px-6 py-4 text-center">${statusBadge}</td>
<td class="px-6 py-4 text-center text-sm section-title">${expiry}</td>
<td class="px-6 py-4">
<div class="flex justify-end gap-2 flex-wrap">
<button onclick="openUserModal(${u._id}, '${safeName}', 'extend')"
class="action-chip glass-btn-success">
Extend
</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'reduce')"
class="action-chip glass-btn-warning">
Reduce
</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'delete')"
class="action-chip glass-btn-danger">
Revoke
</button>
<button onclick="removeSubscriber(${u._id})"
class="action-chip glass-btn" title="Delete from list">
Remove
</button>
</div>
</td>
</tr>
`;
}).join('');
}
function renderMobileCards(slice) {
const mobileWrap = document.getElementById('subscribers-mobile');
if (!slice.length) {
mobileWrap.innerHTML = `
<div class="empty-state text-center px-4 py-8 text-soft">
No users match your search.
</div>
`;
return;
}
mobileWrap.innerHTML = slice.map(u => {
const expiry = formatExpiry(u.subscription_expiry);
const name = getUserDisplayName(u);
const safeName = name.replace(/'/g, "\\'");
const statusBadge = getStatusBadge(u.subscription_status);
return `
<div class="mobile-user-card">
<div class="flex items-start justify-between gap-3 mb-3">
<div class="min-w-0">
<div class="font-semibold section-title break-words flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
<div class="text-xs text-soft mt-1 break-all">ID: ${u._id}</div>
</div>
<div class="shrink-0">${statusBadge}</div>
</div>
<div class="grid grid-cols-1 gap-3 mb-4">
<div class="rounded-2xl px-4 py-3"
style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
<div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Expiry</div>
<div class="text-sm font-semibold section-title">${expiry}</div>
</div>
</div>
<div class="grid grid-cols-3 gap-2">
<button onclick="openUserModal(${u._id}, '${safeName}', 'extend')"
class="action-chip glass-btn-success w-full">
Extend
</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'reduce')"
class="action-chip glass-btn-warning w-full">
Reduce
</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'delete')"
class="action-chip glass-btn-danger w-full">
Revoke
</button>
</div>
<button onclick="removeSubscriber(${u._id})"
class="action-chip glass-btn w-full mt-2">
Remove from list
</button>
</div>
`;
}).join('');
}
function renderSubPage() {
const filtered = getSubFiltered();
const pageSize = parseInt(document.getElementById('sub-page-size').value);
const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
if (subPage > totalPages) subPage = totalPages;
const start = filtered.length ? (subPage - 1) * pageSize : 0;
const slice = filtered.slice(start, start + pageSize);
document.getElementById('sub-page-info').textContent =
filtered.length
? `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}`
: 'Showing 0 of 0';
document.getElementById('sub-page-num').textContent = `Page ${subPage} / ${totalPages}`;
const prevBtn = document.getElementById('sub-btn-prev');
const nextBtn = document.getElementById('sub-btn-next');
prevBtn.disabled = subPage <= 1;
nextBtn.disabled = subPage >= totalPages;
prevBtn.style.opacity = subPage <= 1 ? '0.45' : '1';
nextBtn.style.opacity = subPage >= totalPages ? '0.45' : '1';
renderDesktopRows(slice);
renderMobileCards(slice);
}
function subChangePage(dir) {
const filtered = getSubFiltered();
const pageSize = parseInt(document.getElementById('sub-page-size').value);
const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
subPage += dir;
if (subPage < 1) subPage = 1;
if (subPage > totalPages) subPage = totalPages;
renderSubPage();
}
async function fetchSubscribers() {
document.getElementById('subscribers-tbody').innerHTML = `
<tr>
<td colspan="4" class="px-6 py-8 text-center text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading...
</td>
</tr>
`;
document.getElementById('subscribers-mobile').innerHTML = `
<div class="empty-state text-center px-4 py-8 text-soft">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading...
</div>
`;
try {
const res = await fetch('/api/admin/subscriptions/users');
if (!res.ok) throw new Error('Failed to fetch users');
const data = await res.json();
allUsers = data.data || [];
subPage = 1;
renderSubPage();
} catch (err) {
console.error(err);
document.getElementById('subscribers-tbody').innerHTML = `
<tr>
<td colspan="4" class="px-6 py-8 text-center text-soft">
<i class="fas fa-triangle-exclamation mr-2"></i> Failed to load users.
</td>
</tr>
`;
document.getElementById('subscribers-mobile').innerHTML = `
<div class="empty-state text-center px-4 py-8 text-soft">
<i class="fas fa-triangle-exclamation mr-2"></i> Failed to load users.
</div>
`;
}
}
function openUserModal(userId, userName, action) {
document.getElementById('manage-user-id').value = userId;
document.getElementById('manage-action').value = action;
let title = '';
let desc = '';
let btnClasses = 'glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold';
let showDays = true;
if (action === 'extend') {
title = 'Extend Subscription';
desc = `Add extra days to <b>${userName}</b>'s subscription.`;
document.getElementById('days-action-label').innerText = 'add';
btnClasses = 'glass-btn glass-btn-success px-4 py-2 text-sm font-semibold';
} else if (action === 'reduce') {
title = 'Reduce Subscription';
desc = `Subtract days from <b>${userName}</b>'s subscription.`;
document.getElementById('days-action-label').innerText = 'subtract';
btnClasses = 'glass-btn glass-btn-warning px-4 py-2 text-sm font-semibold';
} else {
title = 'Revoke Subscription';
desc = `<b>Warning:</b> This will remove <b>${userName}</b>'s subscription access completely.`;
showDays = false;
btnClasses = 'glass-btn glass-btn-danger px-4 py-2 text-sm font-semibold';
}
document.getElementById('user-modal-title').innerText = title;
document.getElementById('user-modal-desc').innerHTML = desc;
document.getElementById('days-input-group').style.display = showDays ? 'block' : 'none';
document.getElementById('btn-user-save').className = btnClasses;
if (!showDays) {
document.getElementById('manage-days').value = 0;
document.getElementById('manage-days').removeAttribute('required');
} else {
document.getElementById('manage-days').setAttribute('required', 'required');
if (!document.getElementById('manage-days').value || document.getElementById('manage-days').value === '0') {
document.getElementById('manage-days').value = 30;
}
}
const modal = document.getElementById('user-modal');
modal.classList.remove('hidden');
modal.classList.add('flex');
document.body.classList.add('overflow-hidden');
}
function closeUserModal() {
const modal = document.getElementById('user-modal');
modal.classList.add('hidden');
modal.classList.remove('flex');
document.body.classList.remove('overflow-hidden');
}
async function submitUserForm(e) {
e.preventDefault();
const userId = document.getElementById('manage-user-id').value;
const action = document.getElementById('manage-action').value;
const days = document.getElementById('manage-days').value;
try {
const res = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, days: parseInt(days) || 0 })
});
if (!res.ok) throw new Error('Failed to update user');
closeUserModal();
showToast('Subscription updated successfully.', 'success', 'Updated');
fetchSubscribers();
} catch (err) {
console.error(err);
showToast('Failed to update user subscription.', 'error', 'Update Failed');
}
}
document.addEventListener('click', (e) => {
const planModal = document.getElementById('plan-modal');
const userModal = document.getElementById('user-modal');
if (e.target === planModal) closePlanModal();
if (e.target === userModal) closeUserModal();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closePlanModal();
closeUserModal();
}
});
async function removeSubscriber(userId) {
if (!confirm('Remove this user from the list? This deletes their subscription record (their token access is revoked).')) return;
try {
const res = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'remove', days: 0 })
});
if (!res.ok) throw new Error('Failed');
showToast('User removed.', 'success', 'Removed');
fetchSubscribers();
} catch (err) {
showToast('Failed to remove user.', 'error', 'Failed');
}
}
async function backfillNames() {
try {
const res = await fetch('/api/admin/subscriptions/backfill-names', { method: 'POST' });
const data = await res.json();
if (res.ok) { showToast(data.message || 'Names synced.', 'success', 'Synced'); fetchSubscribers(); }
else { showToast('Failed to sync names.', 'error', 'Failed'); }
} catch (err) {
showToast('Failed to sync names.', 'error', 'Failed');
}
}
document.addEventListener('DOMContentLoaded', () => {
fetchPlans();
fetchSubscribers();
});
</script>
{% endblock %}