stremio / Backend /fastapi /templates /subscriptions_manage.html
Karan Adhikari
Revert "Revamp frontend templates and admin dashboard UI; improve admin JS ro…" (#38)
b8fe50f unverified
Raw History Blame
19.3 kB
{% extends "base.html" %}
{% block title %}Subscription Management - Telegram Stremio{% endblock %}
{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div class="mb-8 flex justify-between items-center">
<div>
<h1 class="text-3xl font-bold text-gray-900 dark:text-white">Subscription Management</h1>
<p class="mt-2 text-sm text-gray-600 dark:text-gray-400">Manage subscription plans and view or edit active
users.</p>
</div>
</div>
<!-- Subscription Plans Section -->
<div class="mb-10">
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200">Subscription Plans</h2>
<button onclick="openPlanModal()"
class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors shadow-sm flex items-center">
<i class="fas fa-plus mr-2"></i> Add Plan
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6" id="plans-container">
<div class="col-span-3 text-center text-gray-500 py-8">
<i class="fas fa-spinner fa-spin mr-2"></i> Loading plans...
</div>
</div>
</div>
<!-- User Subscriptions Section -->
<div class="mb-10">
<div class="flex items-center justify-between mb-3">
<h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200">User Subscriptions</h2>
<button onclick="fetchSubscribers()"
class="bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 px-4 py-2 rounded-md text-sm font-medium transition-colors shadow-sm flex items-center">
<i class="fas fa-sync-alt mr-2"></i> Refresh
</button>
</div>
<!-- Search & Filter bar -->
<div class="flex flex-wrap gap-3 mb-3 items-center">
<input id="sub-search" type="text" placeholder="🔍 Search by name, username or ID…"
class="flex-1 min-w-[200px] border border-gray-300 dark:border-gray-600 rounded-lg px-4 py-2 text-sm focus:outline-none focus:border-primary bg-white dark:bg-gray-800 text-text"
oninput="renderSubPage()">
<select id="sub-filter"
class="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm focus:outline-none bg-white dark:bg-gray-800 text-text"
onchange="renderSubPage()">
<option value="all">All Status</option>
<option value="active">🟢 Active</option>
<option value="expired">🔴 Expired</option>
</select>
<select id="sub-page-size"
class="border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 text-sm focus:outline-none bg-white dark:bg-gray-800 text-text"
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 class="theme-card border rounded-xl overflow-hidden shadow-sm">
<div class="overflow-x-auto">
<table class="w-full text-sm text-left">
<thead class="text-xs uppercase bg-gray-50 dark:bg-gray-800 dark:text-gray-300 border-b">
<tr>
<th class="px-6 py-4 font-semibold">User Details</th>
<th class="px-6 py-4 font-semibold text-center">Status</th>
<th class="px-6 py-4 font-semibold text-center">Expiry Date</th>
<th class="px-6 py-4 font-semibold text-right">Actions</th>
</tr>
</thead>
<tbody id="subscribers-tbody" class="divide-y divide-gray-100 dark:divide-gray-800">
<tr>
<td colspan="4" class="px-6 py-8 text-center text-gray-500"><i
class="fas fa-spinner fa-spin mr-2"></i> Loading...</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Pagination -->
<div class="flex items-center justify-between mt-3 text-sm text-text opacity-70" id="sub-pagination">
<span id="sub-page-info"></span>
<div class="flex gap-2">
<button id="sub-btn-prev" onclick="subChangePage(-1)"
class="px-3 py-1 rounded border border-gray-300 hover:bg-gray-100 transition">‹ Prev</button>
<span id="sub-page-num" class="px-3 py-1 font-semibold"></span>
<button id="sub-btn-next" onclick="subChangePage(1)"
class="px-3 py-1 rounded border border-gray-300 hover:bg-gray-100 transition">Next ›</button>
</div>
</div>
</div>
</div>
<!-- Plan Modal -->
<div id="plan-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
<div class="relative top-20 mx-auto p-5 border shadow-lg rounded-md theme-card sm:w-11/12 md:max-w-md">
<div class="mt-3 text-center">
<h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white mb-2" id="plan-modal-title">Add New
Plan</h3>
<div class="mt-2 text-left">
<form id="plan-form" onsubmit="submitPlanForm(event)">
<input type="hidden" id="plan-id">
<div class="mb-4">
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">Duration
(Days)</label>
<input type="number" id="plan-days"
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none dark:bg-gray-700 dark:text-white dark:border-gray-600"
required min="1">
</div>
<div class="mb-4">
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">Price (₹)</label>
<input type="number" id="plan-price"
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none dark:bg-gray-700 dark:text-white dark:border-gray-600"
required min="0" step="0.01">
</div>
<div class="flex justify-end gap-2 mt-6">
<button type="button" onclick="closePlanModal()"
class="bg-gray-300 hover:bg-gray-400 text-gray-800 px-4 py-2 rounded shadow">Cancel</button>
<button type="submit"
class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded shadow">Save Plan</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- User Action Modal -->
<div id="user-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
<div class="relative top-20 mx-auto p-5 border shadow-lg rounded-md theme-card sm:w-11/12 md:max-w-md">
<div class="mt-3 text-center">
<h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white mb-2" id="user-modal-title">Manage
User</h3>
<div class="text-sm text-gray-500 dark:text-gray-400 mb-4" id="user-modal-desc"></div>
<div class="mt-2 text-left">
<form id="user-form" onsubmit="submitUserForm(event)">
<input type="hidden" id="manage-user-id">
<input type="hidden" id="manage-action">
<div class="mb-4" id="days-input-group">
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2">Days to <span
id="days-action-label"></span></label>
<input type="number" id="manage-days"
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 focus:outline-none dark:bg-gray-700 dark:text-white dark:border-gray-600"
min="1" value="30">
</div>
<div class="flex justify-end gap-2 mt-6">
<button type="button" onclick="closeUserModal()"
class="bg-gray-300 hover:bg-gray-400 text-gray-800 px-4 py-2 rounded shadow">Cancel</button>
<button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded shadow"
id="btn-user-save">Confirm</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
// ---- Plans ----
async function fetchPlans() {
try {
const res = await fetch('/api/admin/subscriptions/plans');
const container = document.getElementById('plans-container');
if (res.ok) {
const data = await res.json();
const plans = data.data || data.plans || [];
if (!plans.length) {
container.innerHTML = '<div class="col-span-3 text-center text-gray-500 py-8">No plans found. Create one.</div>';
return;
}
container.innerHTML = plans.map(p => `
<div class="theme-card rounded-xl border p-6 shadow-sm relative group">
<div class="absolute right-4 top-4 hidden group-hover:flex gap-2">
<button onclick="openPlanModal('${p._id}', ${p.days}, ${p.price})" class="text-blue-500 hover:text-blue-700"><i class="fas fa-edit"></i></button>
<button onclick="deletePlan('${p._id}')" class="text-red-500 hover:text-red-700"><i class="fas fa-trash"></i></button>
</div>
<div class="flex items-center">
<div class="flex-shrink-0 bg-yellow-100 dark:bg-yellow-900/30 p-3 rounded-lg">
<i class="fas fa-calendar-alt text-xl text-yellow-600 dark:text-yellow-400"></i>
</div>
<div class="ml-4">
<h3 class="text-sm font-medium text-gray-500 dark:text-gray-400">${p.days} Days Plan</h3>
<p class="text-2xl font-bold text-gray-900 dark:text-white">₹${p.price}</p>
</div>
</div>
</div>`).join('');
}
} catch (err) { console.error(err); }
}
function openPlanModal(id = '', days = '', price = '') {
document.getElementById('plan-id').value = id;
document.getElementById('plan-days').value = days;
document.getElementById('plan-price').value = price;
document.getElementById('plan-modal-title').innerText = id ? 'Edit Plan' : 'Add New Plan';
document.getElementById('plan-modal').classList.remove('hidden');
}
function closePlanModal() { document.getElementById('plan-modal').classList.add('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) };
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) { closePlanModal(); fetchPlans(); } else alert('Failed to save plan.');
}
async function deletePlan(id) {
if (!confirm('Delete this plan?')) return;
const res = await fetch(`/api/admin/subscriptions/plans/${id}`, { method: 'DELETE' });
if (res.ok) fetchPlans(); else alert('Failed to delete.');
}
// ---- Subscribers with Search + Pagination ----
let allUsers = [];
let subPage = 1;
function getSubFiltered() {
const q = document.getElementById('sub-search').value.toLowerCase();
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 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 = (subPage - 1) * pageSize;
const slice = filtered.slice(start, start + pageSize);
document.getElementById('sub-page-info').textContent = `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}`;
document.getElementById('sub-page-num').textContent = `Page ${subPage} / ${totalPages}`;
document.getElementById('sub-btn-prev').disabled = subPage <= 1;
document.getElementById('sub-btn-next').disabled = subPage >= totalPages;
const tbody = document.getElementById('subscribers-tbody');
if (!slice.length) {
tbody.innerHTML = '<tr><td colspan="4" class="px-6 py-8 text-center text-gray-500">No users match your search.</td></tr>';
return;
}
tbody.innerHTML = slice.map(u => {
const statusColor = u.subscription_status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
let expiry = 'N/A';
if (u.subscription_expiry) {
const d = new Date(u.subscription_expiry);
expiry = 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' });
}
let name = u.first_name || '';
if (u.username) name += (name ? ' ' : '') + `(@${u.username})`;
if (!name) name = `User ${u._id}`;
const safeName = name.replace(/'/g, "\\'");
return `<tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
<td class="px-6 py-4">
<div class="font-medium text-gray-900 dark:text-gray-100">${name}</div>
<div class="text-xs text-gray-500">ID: ${u._id}</div>
</td>
<td class="px-6 py-4 text-center">
<span class="px-2 py-1 rounded ${statusColor} text-xs font-bold uppercase tracking-wider">${u.subscription_status}</span>
</td>
<td class="px-6 py-4 text-center text-sm">${expiry}</td>
<td class="px-6 py-4 text-right">
<div class="flex justify-end gap-2 flex-wrap">
<button onclick="openUserModal(${u._id}, '${safeName}', 'extend')"
class="bg-green-50 text-green-600 hover:bg-green-100 px-2 py-1 rounded text-xs font-medium border border-green-200">Extend</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'reduce')"
class="bg-yellow-50 text-yellow-600 hover:bg-yellow-100 px-2 py-1 rounded text-xs font-medium border border-yellow-200">Reduce</button>
<button onclick="openUserModal(${u._id}, '${safeName}', 'delete')"
class="bg-red-50 text-red-600 hover:bg-red-100 px-2 py-1 rounded text-xs font-medium border border-red-200">Revoke</button>
</div>
</td>
</tr>`;
}).join('');
}
function subChangePage(dir) { subPage += dir; renderSubPage(); }
async function fetchSubscribers() {
document.getElementById('subscribers-tbody').innerHTML =
'<tr><td colspan="4" class="px-6 py-8 text-center text-gray-500"><i class="fas fa-spinner fa-spin mr-2"></i> Loading...</td></tr>';
try {
const res = await fetch('/api/admin/subscriptions/users');
if (res.ok) {
const data = await res.json();
allUsers = data.data || [];
subPage = 1;
renderSubPage();
}
} catch (err) { console.error(err); }
}
function openUserModal(userId, userName, action) {
document.getElementById('manage-user-id').value = userId;
document.getElementById('manage-action').value = action;
let title = '', desc = '', btnColor = 'bg-blue-600 hover:bg-blue-700', showDays = true;
if (action === 'extend') {
title = 'Extend Subscription'; desc = `Add days to <b>${userName}</b>'s subscription.`;
document.getElementById('days-action-label').innerText = 'Add';
} else if (action === 'reduce') {
title = 'Reduce Subscription'; desc = `Remove days from <b>${userName}</b>'s subscription.`;
document.getElementById('days-action-label').innerText = 'Subtract'; btnColor = 'bg-yellow-600 hover:bg-yellow-700';
} else {
title = 'Revoke Subscription'; desc = `<b>Warning:</b> This will revoke <b>${userName}</b>'s subscription entirely.`;
showDays = false; btnColor = 'bg-red-600 hover:bg-red-700';
}
document.getElementById('user-modal-title').innerText = title;
document.getElementById('user-modal-desc').innerHTML = desc;
document.getElementById('days-input-group').className = showDays ? 'mb-4' : 'hidden';
document.getElementById('btn-user-save').className = `${btnColor} text-white px-4 py-2 rounded shadow`;
if (!showDays) { document.getElementById('manage-days').value = 0; document.getElementById('manage-days').removeAttribute('required'); }
else document.getElementById('manage-days').setAttribute('required', 'required');
document.getElementById('user-modal').classList.remove('hidden');
}
function closeUserModal() { document.getElementById('user-modal').classList.add('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;
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) { closeUserModal(); fetchSubscribers(); } else alert('Failed to update user.');
}
document.addEventListener('DOMContentLoaded', () => { fetchPlans(); fetchSubscribers(); });
</script>
{% endblock %}