Fix auth headers on pricing/credit/invoice/coupon pages

- All 4 pages now send Bearer token from sessionStorage on every fetch
- Pricing: fixed endpoint from /api/admin/packages → /api/admin/tracecoin-packages;
  added search, role filter, status filter, and sort (name/price/coins)
- Coupon: added search by code/title and status filter; fixed refetch to use load()
- Invoice: refactored from createResource to onMount+signals for consistent auth
- Credit: authenticated balance, ledger, adjust, and reconcile fetch calls

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ashwin Kumar 2026-04-08 02:11:06 +02:00
parent 0ec64be905
commit 411827f837
4 changed files with 433 additions and 323 deletions

View file

@ -1,7 +1,22 @@
import { createResource, createSignal, Show, For } from 'solid-js'; import { createSignal, createMemo, onMount, Show, For } from 'solid-js';
const API = ''; const API = '';
function getToken(): string {
return typeof sessionStorage !== 'undefined'
? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
: '';
}
function authHeaders(): Record<string, string> {
const token = getToken();
return {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
const ROLE_OPTIONS = [ const ROLE_OPTIONS = [
'company', 'company',
'customer', 'customer',
@ -30,16 +45,6 @@ type Coupon = {
role_keys: string[]; role_keys: string[];
}; };
async function loadCoupons(): Promise<Coupon[]> {
try {
const res = await fetch(`${API}/api/admin/coupons`);
if (!res.ok) throw new Error('Failed to load');
const data = await res.json();
return Array.isArray(data) ? data : (data.coupons || []);
} catch {
return [];
}
}
const defaultForm = () => ({ const defaultForm = () => ({
id: '', id: '',
@ -53,13 +58,45 @@ const defaultForm = () => ({
}); });
export default function CouponPage() { export default function CouponPage() {
const [coupons, { refetch }] = createResource(loadCoupons); const [coupons, setCoupons] = createSignal<Coupon[]>([]);
const [loading, setLoading] = createSignal(true);
const [loadError, setLoadError] = createSignal('');
const [activeTab, setActiveTab] = createSignal<'list' | 'create'>('list'); const [activeTab, setActiveTab] = createSignal<'list' | 'create'>('list');
const [form, setForm] = createSignal(defaultForm()); const [form, setForm] = createSignal(defaultForm());
const [saving, setSaving] = createSignal(false); const [saving, setSaving] = createSignal(false);
const [toggling, setToggling] = createSignal(''); const [toggling, setToggling] = createSignal('');
const [formError, setFormError] = createSignal(''); const [formError, setFormError] = createSignal('');
// Filters
const [search, setSearch] = createSignal('');
const [statusFilter, setStatusFilter] = createSignal('all');
const load = async () => {
setLoading(true); setLoadError('');
try {
const res = await fetch(`${API}/api/admin/coupons`, { headers: authHeaders(), credentials: 'include' });
if (!res.ok) throw new Error(`Request failed (${res.status})`);
const data = await res.json();
setCoupons(Array.isArray(data) ? data : (data.coupons ?? []));
} catch (err: any) {
setLoadError(err.message || 'Could not load coupons.');
setCoupons([]);
} finally {
setLoading(false);
}
};
onMount(() => void load());
const filteredCoupons = createMemo(() => {
let r = coupons();
const q = search().toLowerCase();
if (q) r = r.filter((c) => c.code.toLowerCase().includes(q) || (c.title || '').toLowerCase().includes(q));
if (statusFilter() === 'active') r = r.filter((c) => c.is_active);
if (statusFilter() === 'inactive') r = r.filter((c) => !c.is_active);
return r;
});
const resetForm = () => { const resetForm = () => {
setForm(defaultForm()); setForm(defaultForm());
setFormError(''); setFormError('');
@ -108,12 +145,13 @@ export default function CouponPage() {
const method = f.id ? 'PATCH' : 'POST'; const method = f.id ? 'PATCH' : 'POST';
const res = await fetch(url, { const res = await fetch(url, {
method, method,
headers: { 'Content-Type': 'application/json' }, headers: authHeaders(),
credentials: 'include',
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
if (!res.ok) throw new Error('Failed to save coupon'); if (!res.ok) throw new Error('Failed to save coupon');
resetForm(); resetForm();
refetch(); await load();
setActiveTab('list'); setActiveTab('list');
} catch (err: unknown) { } catch (err: unknown) {
setFormError(err instanceof Error ? err.message : 'Failed to save'); setFormError(err instanceof Error ? err.message : 'Failed to save');
@ -127,11 +165,12 @@ export default function CouponPage() {
setToggling(coupon.id); setToggling(coupon.id);
const res = await fetch(`${API}/api/admin/coupons/${coupon.id}`, { const res = await fetch(`${API}/api/admin/coupons/${coupon.id}`, {
method: 'PATCH', method: 'PATCH',
headers: { 'Content-Type': 'application/json' }, headers: authHeaders(),
credentials: 'include',
body: JSON.stringify({ is_active: !coupon.is_active }), body: JSON.stringify({ is_active: !coupon.is_active }),
}); });
if (!res.ok) throw new Error('Failed to toggle'); if (!res.ok) throw new Error('Failed to toggle');
refetch(); await load();
} catch { } catch {
// ignore // ignore
} finally { } finally {
@ -166,6 +205,25 @@ export default function CouponPage() {
<div class="flex-1 p-6"> <div class="flex-1 p-6">
<Show when={activeTab() === 'list'}> <Show when={activeTab() === 'list'}>
<div style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap">
<input
type="text"
placeholder="Search by code or title..."
value={search()}
onInput={(e) => setSearch(e.currentTarget.value)}
class="rounded-lg border border-gray-200 px-3 py-2 text-sm"
style="min-width:200px;flex:1"
/>
<select value={statusFilter()} onChange={(e) => setStatusFilter(e.currentTarget.value)} class="rounded-lg border border-gray-200 px-3 py-2 text-sm">
<option value="all">All Status</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
<button type="button" class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={load}>Refresh</button>
</div>
<Show when={loadError()}>
<div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{loadError()}</div>
</Show>
<div class="table-card"> <div class="table-card">
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="data-table w-full text-sm"> <table class="data-table w-full text-sm">
@ -181,17 +239,14 @@ export default function CouponPage() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<Show when={coupons.loading}> <Show when={loading()}>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr> <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
</Show> </Show>
<Show when={!coupons.loading && coupons.error}> <Show when={!loading() && filteredCoupons().length === 0}>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
</Show>
<Show when={!coupons.loading && !coupons.error && coupons()?.length === 0}>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No coupons found.</td></tr> <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No coupons found.</td></tr>
</Show> </Show>
<Show when={!coupons.loading && !coupons.error && (coupons()?.length ?? 0) > 0}> <Show when={!loading() && filteredCoupons().length > 0}>
<For each={coupons()}> <For each={filteredCoupons()}>
{(item) => ( {(item) => (
<tr class="hover:bg-slate-50"> <tr class="hover:bg-slate-50">
<td class="font-semibold text-slate-900" style="font-family:monospace">{item.code}</td> <td class="font-semibold text-slate-900" style="font-family:monospace">{item.code}</td>
@ -223,6 +278,11 @@ export default function CouponPage() {
</tbody> </tbody>
</table> </table>
</div> </div>
<Show when={!loading()}>
<div style="padding:10px 16px;font-size:12px;color:#64748b;border-top:1px solid #f1f5f9">
{filteredCoupons().length} of {coupons().length} coupons
</div>
</Show>
</div> </div>
</Show> </Show>

View file

@ -1,7 +1,22 @@
import { createSignal, createResource, Show, For } from 'solid-js'; import { createSignal, Show, For } from 'solid-js';
const API = ''; const API = '';
function getToken(): string {
return typeof sessionStorage !== 'undefined'
? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
: '';
}
function authHeaders(): Record<string, string> {
const token = getToken();
return {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
type LedgerEntry = { type LedgerEntry = {
id: string; id: string;
transactionType: 'ADD' | 'DEDUCT'; transactionType: 'ADD' | 'DEDUCT';
@ -57,8 +72,8 @@ export default function CreditPage() {
setSearchedUserId(uid); setSearchedUserId(uid);
try { try {
const [balRes, ledRes] = await Promise.all([ const [balRes, ledRes] = await Promise.all([
fetch(`${API}/api/admin/credits/balance?userId=${encodeURIComponent(uid)}`), fetch(`${API}/api/admin/credits/balance?userId=${encodeURIComponent(uid)}`, { headers: authHeaders(), credentials: 'include' }),
fetch(`${API}/api/admin/credits/ledger?userId=${encodeURIComponent(uid)}`), fetch(`${API}/api/admin/credits/ledger?userId=${encodeURIComponent(uid)}`, { headers: authHeaders(), credentials: 'include' }),
]); ]);
if (!balRes.ok || !ledRes.ok) throw new Error('Failed to fetch'); if (!balRes.ok || !ledRes.ok) throw new Error('Failed to fetch');
const balData = await balRes.json(); const balData = await balRes.json();
@ -82,7 +97,8 @@ export default function CreditPage() {
try { try {
const res = await fetch(`${API}/api/admin/credits/adjust`, { const res = await fetch(`${API}/api/admin/credits/adjust`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: authHeaders(),
credentials: 'include',
body: JSON.stringify({ body: JSON.stringify({
user_id: adjUserId(), user_id: adjUserId(),
amount: adjAmount(), amount: adjAmount(),
@ -115,7 +131,8 @@ export default function CreditPage() {
setReconResults(null); setReconResults(null);
try { try {
const res = await fetch( const res = await fetch(
`${API}/api/admin/credits/reconcile?from=${encodeURIComponent(reconFrom())}&to=${encodeURIComponent(reconTo())}` `${API}/api/admin/credits/reconcile?from=${encodeURIComponent(reconFrom())}&to=${encodeURIComponent(reconTo())}`,
{ headers: authHeaders(), credentials: 'include' }
); );
if (!res.ok) throw new Error('Failed to reconcile'); if (!res.ok) throw new Error('Failed to reconcile');
const data = await res.json(); const data = await res.json();

View file

@ -1,25 +1,47 @@
import { createResource, createSignal, createMemo, Show } from 'solid-js'; import { createSignal, createMemo, onMount, Show } from 'solid-js';
const API = ''; const API = '';
async function loadInvoices(): Promise<any[]> { function getToken(): string {
try { return typeof sessionStorage !== 'undefined'
const res = await fetch(`${API}/api/admin/invoices`); ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
if (!res.ok) throw new Error('Failed to load'); : '';
const data = await res.json(); }
return Array.isArray(data) ? data : (data.invoices || []);
} catch { function authHeaders(): Record<string, string> {
return []; const token = getToken();
} return {
Accept: 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
} }
export default function InvoicePage() { export default function InvoicePage() {
const [invoices] = createResource(loadInvoices); const [invoices, setInvoices] = createSignal<any[]>([]);
const [loading, setLoading] = createSignal(true);
const [loadError, setLoadError] = createSignal('');
const [search, setSearch] = createSignal(''); const [search, setSearch] = createSignal('');
const load = async () => {
setLoading(true); setLoadError('');
try {
const res = await fetch(`${API}/api/admin/invoices`, { headers: authHeaders(), credentials: 'include' });
if (!res.ok) throw new Error(`Request failed (${res.status})`);
const data = await res.json();
setInvoices(Array.isArray(data) ? data : (data.invoices ?? []));
} catch (err: any) {
setLoadError(err.message || 'Could not load invoices.');
setInvoices([]);
} finally {
setLoading(false);
}
};
onMount(() => void load());
const filteredInvoices = createMemo(() => { const filteredInvoices = createMemo(() => {
const q = search().toLowerCase(); const q = search().toLowerCase();
const all = invoices() ?? []; const all = invoices();
if (!q) return all; if (!q) return all;
return all.filter((inv) => return all.filter((inv) =>
(inv.invoice_number || inv.id || '').toLowerCase().includes(q) || (inv.invoice_number || inv.id || '').toLowerCase().includes(q) ||
@ -64,16 +86,16 @@ export default function InvoicePage() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<Show when={invoices.loading}> <Show when={loading()}>
<tr><td colspan="8" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr> <tr><td colspan="8" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
</Show> </Show>
<Show when={!invoices.loading && invoices.error}> <Show when={!loading() && loadError()}>
<tr><td colspan="8" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr> <tr><td colspan="8" style="text-align:center;padding:32px;color:#b91c1c">{loadError()}</td></tr>
</Show> </Show>
<Show when={!invoices.loading && !invoices.error && filteredInvoices().length === 0}> <Show when={!loading() && !loadError() && filteredInvoices().length === 0}>
<tr><td colspan="8" style="text-align:center;padding:32px;color:#94a3b8">No records found.</td></tr> <tr><td colspan="8" style="text-align:center;padding:32px;color:#94a3b8">No records found.</td></tr>
</Show> </Show>
<Show when={!invoices.loading && !invoices.error && filteredInvoices().length > 0}> <Show when={!loading() && !loadError() && filteredInvoices().length > 0}>
{filteredInvoices().map((item) => ( {filteredInvoices().map((item) => (
<tr class="hover:bg-slate-50"> <tr class="hover:bg-slate-50">
<td class="font-semibold text-slate-900" style="font-family:monospace">{item.invoice_number || item.id}</td> <td class="font-semibold text-slate-900" style="font-family:monospace">{item.invoice_number || item.id}</td>

View file

@ -1,7 +1,22 @@
import { createResource, createSignal, Show, For } from 'solid-js'; import { createSignal, createMemo, onMount, Show, For } from 'solid-js';
const API = ''; const API = '';
function getToken(): string {
return typeof sessionStorage !== 'undefined'
? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
: '';
}
function authHeaders(): Record<string, string> {
const token = getToken();
return {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
}
type Package = { type Package = {
id: string; id: string;
name: string; name: string;
@ -13,47 +28,42 @@ type Package = {
}; };
const ROLES = [ const ROLES = [
'company', 'company', 'customer', 'job_seeker', 'photographer', 'video_editor',
'customer', 'graphic_designer', 'social_media_manager', 'fitness_trainer',
'job_seeker', 'catering_services', 'makeup_artist', 'tutor', 'developer', 'ugc_content_creator',
'photographer',
'video_editor',
'graphic_designer',
'social_media_manager',
'fitness_trainer',
'catering_services',
'makeup_artist',
'tutor',
'developer',
]; ];
async function loadPackages(): Promise<Package[]> { type SortMode = 'name_asc' | 'name_desc' | 'price_asc' | 'price_desc' | 'coins_asc' | 'coins_desc';
try {
const res = await fetch(`${API}/api/admin/packages`); const SORT_LABELS: Record<SortMode, string> = {
if (!res.ok) throw new Error('Failed to load'); name_asc: 'Name A→Z', name_desc: 'Name Z→A',
const data = await res.json(); price_asc: 'Price ↑', price_desc: 'Price ↓',
return Array.isArray(data) ? data : (data.packages || []); coins_asc: 'TraceCoins ↑', coins_desc: 'TraceCoins ↓',
} catch { };
return [];
}
}
export default function PricingPage() { export default function PricingPage() {
const [packages, { refetch }] = createResource(loadPackages); const [rows, setRows] = createSignal<Package[]>([]);
const [loading, setLoading] = createSignal(true);
const [loadError, setLoadError] = createSignal('');
const [view, setView] = createSignal<'packages' | 'create'>('packages'); const [view, setView] = createSignal<'packages' | 'create'>('packages');
// Inline edit state // Filters
const [search, setSearch] = createSignal('');
const [roleFilter, setRoleFilter] = createSignal('all');
const [statusFilter, setStatusFilter] = createSignal('all');
const [sortBy, setSortBy] = createSignal<SortMode>('name_asc');
const [sortOpen, setSortOpen] = createSignal(false);
// Inline edit
const [editingId, setEditingId] = createSignal(''); const [editingId, setEditingId] = createSignal('');
const [editName, setEditName] = createSignal(''); const [editName, setEditName] = createSignal('');
const [editTracecoins, setEditTracecoins] = createSignal(''); const [editTracecoins, setEditTracecoins] = createSignal('');
const [editPrice, setEditPrice] = createSignal(''); const [editPrice, setEditPrice] = createSignal('');
const [editSaving, setEditSaving] = createSignal(false); const [editSaving, setEditSaving] = createSignal(false);
const [editError, setEditError] = createSignal(''); const [editError, setEditError] = createSignal('');
// Toggle active state
const [togglingId, setTogglingId] = createSignal(''); const [togglingId, setTogglingId] = createSignal('');
// Create form state // Create form
const [cName, setCName] = createSignal(''); const [cName, setCName] = createSignal('');
const [cRole, setCRole] = createSignal(ROLES[0]); const [cRole, setCRole] = createSignal(ROLES[0]);
const [cTracecoins, setCTracecoins] = createSignal(''); const [cTracecoins, setCTracecoins] = createSignal('');
@ -62,299 +72,300 @@ export default function PricingPage() {
const [cSaving, setCsaving] = createSignal(false); const [cSaving, setCsaving] = createSignal(false);
const [cError, setCError] = createSignal(''); const [cError, setCError] = createSignal('');
const startEdit = (pkg: Package) => { const load = async () => {
setEditingId(pkg.id); setLoading(true);
setEditName(pkg.name); setLoadError('');
setEditTracecoins(String(pkg.tracecoin_amount)); try {
setEditPrice(String(pkg.price_inr)); const res = await fetch(`${API}/api/admin/tracecoin-packages`, {
setEditError(''); headers: authHeaders(),
credentials: 'include',
});
if (!res.ok) throw new Error(`Request failed (${res.status})`);
const data = await res.json();
setRows(Array.isArray(data) ? data : (data.packages ?? []));
} catch (err: any) {
setLoadError(err.message || 'Could not load packages.');
setRows([]);
} finally {
setLoading(false);
}
}; };
const cancelEdit = () => { onMount(() => void load());
setEditingId('');
const filteredRows = createMemo(() => {
let r = rows();
const q = search().toLowerCase();
if (q) r = r.filter((p) => p.name.toLowerCase().includes(q) || p.role.toLowerCase().includes(q));
if (roleFilter() !== 'all') r = r.filter((p) => p.role === roleFilter());
if (statusFilter() === 'active') r = r.filter((p) => p.is_active);
if (statusFilter() === 'inactive') r = r.filter((p) => !p.is_active);
const sorted = [...r];
const mode = sortBy();
sorted.sort((a, b) => {
if (mode === 'name_desc') return b.name.localeCompare(a.name);
if (mode === 'price_asc') return a.price_inr - b.price_inr;
if (mode === 'price_desc') return b.price_inr - a.price_inr;
if (mode === 'coins_asc') return a.tracecoin_amount - b.tracecoin_amount;
if (mode === 'coins_desc') return b.tracecoin_amount - a.tracecoin_amount;
return a.name.localeCompare(b.name);
});
return sorted;
});
const startEdit = (pkg: Package) => {
setEditingId(pkg.id); setEditName(pkg.name);
setEditTracecoins(String(pkg.tracecoin_amount)); setEditPrice(String(pkg.price_inr));
setEditError(''); setEditError('');
}; };
const cancelEdit = () => { setEditingId(''); setEditError(''); };
const saveEdit = async (id: string) => { const saveEdit = async (id: string) => {
try { try {
setEditSaving(true); setEditSaving(true); setEditError('');
setEditError('');
const res = await fetch(`${API}/api/admin/tracecoin-packages/${id}`, { const res = await fetch(`${API}/api/admin/tracecoin-packages/${id}`, {
method: 'PATCH', method: 'PATCH', headers: authHeaders(), credentials: 'include',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: editName(), tracecoin_amount: Number(editTracecoins()), price_inr: Number(editPrice()) }),
body: JSON.stringify({
name: editName(),
tracecoin_amount: Number(editTracecoins()),
price_inr: Number(editPrice()),
}),
}); });
if (!res.ok) throw new Error('Failed to save'); if (!res.ok) throw new Error('Failed to save');
setEditingId(''); setEditingId(''); await load();
refetch(); } catch (err: any) { setEditError(err.message || 'Failed to save'); }
} catch (err: any) { finally { setEditSaving(false); }
setEditError(err.message || 'Failed to save');
} finally {
setEditSaving(false);
}
}; };
const toggleActive = async (pkg: Package) => { const toggleActive = async (pkg: Package) => {
try { try {
setTogglingId(pkg.id); setTogglingId(pkg.id);
const res = await fetch(`${API}/api/admin/tracecoin-packages/${pkg.id}`, { await fetch(`${API}/api/admin/tracecoin-packages/${pkg.id}`, {
method: 'PATCH', method: 'PATCH', headers: authHeaders(), credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_active: !pkg.is_active }), body: JSON.stringify({ is_active: !pkg.is_active }),
}); });
if (!res.ok) throw new Error('Failed to update'); await load();
refetch(); } catch { /* ignore */ } finally { setTogglingId(''); }
} catch {
// ignore
} finally {
setTogglingId('');
}
}; };
const handleCreate = async (e: Event) => { const handleCreate = async (e: Event) => {
e.preventDefault(); e.preventDefault();
try { try {
setCsaving(true); setCsaving(true); setCError('');
setCError('');
const body: Record<string, any> = { const body: Record<string, any> = {
name: cName(), name: cName(), role: cRole(),
role: cRole(), tracecoin_amount: Number(cTracecoins()), price_inr: Number(cPrice()),
tracecoin_amount: Number(cTracecoins()),
price_inr: Number(cPrice()),
}; };
if (cBonus()) body.bonus_percentage = Number(cBonus()); if (cBonus()) body.bonus_percentage = Number(cBonus());
const res = await fetch(`${API}/api/admin/tracecoin-packages`, { const res = await fetch(`${API}/api/admin/tracecoin-packages`, {
method: 'POST', method: 'POST', headers: authHeaders(), credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body), body: JSON.stringify(body),
}); });
if (!res.ok) throw new Error('Failed to create package'); if (!res.ok) throw new Error('Failed to create package');
setCName(''); setCName(''); setCRole(ROLES[0]); setCTracecoins(''); setCPrice(''); setCBonus('');
setCRole(ROLES[0]); setView('packages'); await load();
setCTracecoins(''); } catch (err: any) { setCError(err.message || 'Failed to create'); }
setCPrice(''); finally { setCsaving(false); }
setCBonus('');
setView('packages');
refetch();
} catch (err: any) {
setCError(err.message || 'Failed to create');
} finally {
setCsaving(false);
}
}; };
return ( return (
<div class="flex flex-col -mx-6 -mt-6 min-h-full"> <div class="flex flex-col -mx-6 -mt-6 min-h-full">
<div class="bg-white border-b border-gray-200 px-6 py-4"> <div class="bg-white border-b border-gray-200 px-6 py-4">
<h1 class="text-xl font-semibold text-gray-900">Pricing Management</h1> <h1 class="text-xl font-semibold text-gray-900">Pricing Management</h1>
<p class="text-sm text-gray-500 mt-0.5">Create and manage TraceCoin packages</p> <p class="text-sm text-gray-500 mt-0.5">Create and manage TraceCoin packages</p>
</div> </div>
{/* Tabs */} {/* Tabs */}
<div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10"> <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
{(['packages', 'create'] as const).map((t) => (
<button <button
type="button" type="button"
class={view() === 'packages' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'} class={view() === t
onClick={() => setView('packages')} ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
: 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
onClick={() => setView(t)}
> >
Packages {t === 'packages' ? 'Packages' : 'Create Package'}
</button> </button>
<button ))}
type="button" </div>
class={view() === 'create' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
onClick={() => setView('create')}
>
Create Package
</button>
</div>
<div class="flex-1 p-6"> <div class="flex-1 p-6">
{/* Packages list tab */}
<Show when={view() === 'packages'}> {/* ── Packages list ── */}
<div class="table-card"> <Show when={view() === 'packages'}>
<div class="overflow-x-auto"> <div style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap">
<table class="data-table w-full text-sm"> <input
<thead> type="text"
<tr> placeholder="Search by name or role..."
<th>Name</th> value={search()}
<th>Role</th> onInput={(e) => setSearch(e.currentTarget.value)}
<th>TraceCoins</th> class="rounded-lg border border-gray-200 px-3 py-2 text-sm"
<th>Price ()</th> style="min-width:200px;flex:1"
<th>Bonus (%)</th> />
<th>Status</th> <select value={roleFilter()} onChange={(e) => setRoleFilter(e.currentTarget.value)} class="rounded-lg border border-gray-200 px-3 py-2 text-sm">
<th class="text-right">Actions</th> <option value="all">All Roles</option>
</tr> <For each={ROLES}>{(r) => <option value={r}>{r}</option>}</For>
</thead> </select>
<tbody> <select value={statusFilter()} onChange={(e) => setStatusFilter(e.currentTarget.value)} class="rounded-lg border border-gray-200 px-3 py-2 text-sm">
<Show when={packages.loading}> <option value="all">All Status</option>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr> <option value="active">Active</option>
</Show> <option value="inactive">Inactive</option>
<Show when={!packages.loading && packages.error}> </select>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr> <div style="position:relative">
</Show> <button
<Show when={!packages.loading && !packages.error && (packages()?.length ?? 0) === 0}> type="button"
<tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No packages found.</td></tr> class="inline-flex items-center gap-1 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
</Show> onClick={() => setSortOpen(!sortOpen())}
<Show when={!packages.loading && !packages.error && (packages()?.length ?? 0) > 0}> >
<For each={packages()}> Sort: {SORT_LABELS[sortBy()]}
{(pkg) => ( <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
<> </button>
<tr class="hover:bg-slate-50"> <Show when={sortOpen()}>
<td class="font-semibold text-slate-900">{pkg.name}</td> <div style="position:absolute;top:calc(100% + 4px);right:0;background:white;border:1px solid #e5e7eb;border-radius:10px;box-shadow:0 4px 16px rgba(0,0,0,.1);z-index:50;min-width:170px;padding:4px">
<td class="text-slate-500">{pkg.role}</td> <For each={Object.entries(SORT_LABELS) as [SortMode, string][]}>
<td class="text-slate-500">{pkg.tracecoin_amount}</td> {([key, label]) => (
<td class="text-slate-500">{(pkg.price_inr / 100).toFixed(2)}</td> <button
<td class="text-slate-500">{pkg.bonus_percentage != null ? `${pkg.bonus_percentage}%` : '—'}</td> type="button"
<td> onClick={() => { setSortBy(key); setSortOpen(false); }}
<span class={`inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600 ${pkg.is_active ? 'active' : ''}`}> style={`display:block;width:100%;text-align:left;padding:8px 12px;font-size:13px;border-radius:7px;border:none;cursor:pointer;background:${sortBy() === key ? '#fff7ed' : 'transparent'};color:${sortBy() === key ? '#c2410c' : '#374151'};font-weight:${sortBy() === key ? '600' : '400'}`}
{pkg.is_active ? 'Active' : 'Inactive'} >
</span> {label}
</td> </button>
<td> )}
<div class="flex items-center justify-end gap-1"> </For>
<button class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={() => startEdit(pkg)}>Edit</button> </div>
<button </Show>
class={pkg.is_active ? 'inline-flex items-center rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-100 transition-colors' : 'btn-primary'} </div>
disabled={togglingId() === pkg.id} <button type="button" class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={load}>
onClick={() => toggleActive(pkg)} Refresh
> </button>
{togglingId() === pkg.id ? '...' : pkg.is_active ? 'Disable' : 'Enable'} </div>
</button>
<Show when={loadError()}>
<div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{loadError()}</div>
</Show>
<div class="table-card">
<div class="overflow-x-auto">
<table class="data-table w-full text-sm">
<thead>
<tr>
<th>Name</th><th>Role</th><th>TraceCoins</th><th>Price ()</th><th>Bonus</th><th>Status</th><th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
<Show when={loading()}>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
</Show>
<Show when={!loading() && filteredRows().length === 0}>
<tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No packages found.</td></tr>
</Show>
<Show when={!loading() && filteredRows().length > 0}>
<For each={filteredRows()}>
{(pkg) => (
<>
<tr class="hover:bg-slate-50">
<td class="font-semibold text-slate-900">{pkg.name}</td>
<td><span style="display:inline-block;padding:2px 8px;border-radius:999px;font-size:11px;font-weight:600;background:#f1f5f9;color:#475569">{pkg.role}</span></td>
<td class="text-slate-700 font-medium">{pkg.tracecoin_amount}</td>
<td class="text-slate-700">{(pkg.price_inr / 100).toFixed(2)}</td>
<td class="text-slate-500">{pkg.bonus_percentage != null ? `${pkg.bonus_percentage}%` : '—'}</td>
<td>
<span style={`display:inline-flex;align-items:center;border-radius:9999px;border:1px solid ${pkg.is_active ? '#FFD8C2' : '#D1D5DB'};background:${pkg.is_active ? '#FFF1EB' : '#F3F4F6'};color:${pkg.is_active ? '#FF5E13' : '#4B5563'};padding:2px 10px;font-size:12px;font-weight:500`}>
<span style={`display:inline-block;width:6px;height:6px;border-radius:50%;background:${pkg.is_active ? '#FF5E13' : '#9CA3AF'};margin-right:5px`} />
{pkg.is_active ? 'Active' : 'Inactive'}
</span>
</td>
<td>
<div class="flex items-center justify-end gap-1">
<button class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={() => startEdit(pkg)}>Edit</button>
<button
class={pkg.is_active ? 'inline-flex items-center rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-100 transition-colors' : 'btn-primary'}
disabled={togglingId() === pkg.id}
onClick={() => toggleActive(pkg)}
>
{togglingId() === pkg.id ? '...' : pkg.is_active ? 'Disable' : 'Enable'}
</button>
</div>
</td>
</tr>
<Show when={editingId() === pkg.id}>
<tr>
<td colspan="7" style="background:#f8fafc;padding:16px">
<Show when={editError()}>
<div class="mb-3 rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700">{editError()}</div>
</Show>
<div style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end">
<div>
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Name</label>
<input type="text" value={editName()} onInput={(e) => setEditName(e.currentTarget.value)} style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:180px" />
</div>
<div>
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">TraceCoins</label>
<input type="number" value={editTracecoins()} onInput={(e) => setEditTracecoins(e.currentTarget.value)} style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px" />
</div>
<div>
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Price (paise)</label>
<input type="number" value={editPrice()} onInput={(e) => setEditPrice(e.currentTarget.value)} style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px" />
</div>
<div style="display:flex;gap:8px">
<button class="btn-primary" disabled={editSaving()} onClick={() => saveEdit(pkg.id)}>{editSaving() ? 'Saving...' : 'Save'}</button>
<button class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={cancelEdit}>Cancel</button>
</div>
</div> </div>
</td> </td>
</tr> </tr>
<Show when={editingId() === pkg.id}> </Show>
<tr> </>
<td colspan="7" style="background:#f8fafc;padding:16px"> )}
<Show when={editError()}> </For>
<div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-bottom:10px">{editError()}</div> </Show>
</Show> </tbody>
<div style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end"> </table>
<div class="field">
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Name</label>
<input
type="text"
value={editName()}
onInput={(e) => setEditName(e.currentTarget.value)}
style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:180px"
/>
</div>
<div class="field">
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">TraceCoins</label>
<input
type="number"
value={editTracecoins()}
onInput={(e) => setEditTracecoins(e.currentTarget.value)}
style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px"
/>
</div>
<div class="field">
<label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">Price (paise)</label>
<input
type="number"
value={editPrice()}
onInput={(e) => setEditPrice(e.currentTarget.value)}
style="padding:7px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;width:110px"
/>
</div>
<div style="display:flex;gap:8px">
<button class="btn-primary" disabled={editSaving()} onClick={() => saveEdit(pkg.id)}>
{editSaving() ? 'Saving...' : 'Save'}
</button>
<button class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors" onClick={cancelEdit}>Cancel</button>
</div>
</div>
</td>
</tr>
</Show>
</>
)}
</For>
</Show>
</tbody>
</table>
</div>
</div> </div>
</Show> <Show when={!loading()}>
<div style="padding:10px 16px;font-size:12px;color:#64748b;border-top:1px solid #f1f5f9">
{filteredRows().length} of {rows().length} packages
</div>
</Show>
</div>
</Show>
{/* ── Create Package ── */}
<Show when={view() === 'create'}>
<section class="rounded-xl border border-gray-200 bg-white shadow-sm p-6" style="max-width:480px">
<h2 style="margin:0 0 20px;font-size:16px;font-weight:700">New Package</h2>
<Show when={cError()}>
<div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{cError()}</div>
</Show>
<form onSubmit={handleCreate} style="display:flex;flex-direction:column;gap:14px">
<div>
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Name</label>
<input type="text" value={cName()} onInput={(e) => setCName(e.currentTarget.value)} required placeholder="e.g. Starter Pack" style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box" />
</div>
<div>
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Role</label>
<select value={cRole()} onChange={(e) => setCRole(e.currentTarget.value)} required style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box">
<For each={ROLES}>{(r) => <option value={r}>{r}</option>}</For>
</select>
</div>
<div>
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">TraceCoins</label>
<input type="number" value={cTracecoins()} onInput={(e) => setCTracecoins(e.currentTarget.value)} required min="1" placeholder="e.g. 100" style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box" />
</div>
<div>
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Price INR (paise e.g. 49900 = 499)</label>
<input type="number" value={cPrice()} onInput={(e) => setCPrice(e.currentTarget.value)} required min="1" placeholder="e.g. 49900" style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box" />
</div>
<div>
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Bonus % <span style="font-weight:400;color:#94a3b8">(optional)</span></label>
<input type="number" value={cBonus()} onInput={(e) => setCBonus(e.currentTarget.value)} min="0" placeholder="e.g. 10" style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box" />
</div>
<div>
<button class="btn-primary" type="submit" disabled={cSaving()}>{cSaving() ? 'Creating...' : 'Create Package'}</button>
</div>
</form>
</section>
</Show>
{/* Create Package tab */}
<Show when={view() === 'create'}>
<section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:480px">
<h2 style="margin:0 0 20px;font-size:16px;font-weight:700">New Package</h2>
<Show when={cError()}>
<div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-bottom:14px">{cError()}</div>
</Show>
<form onSubmit={handleCreate} style="display:flex;flex-direction:column;gap:14px">
<div class="field">
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Name</label>
<input
type="text"
value={cName()}
onInput={(e) => setCName(e.currentTarget.value)}
required
placeholder="e.g. Starter Pack"
style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
/>
</div>
<div class="field">
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Role</label>
<select
value={cRole()}
onChange={(e) => setCRole(e.currentTarget.value)}
required
style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
>
<For each={ROLES}>{(r) => <option value={r}>{r}</option>}</For>
</select>
</div>
<div class="field">
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">TraceCoins</label>
<input
type="number"
value={cTracecoins()}
onInput={(e) => setCTracecoins(e.currentTarget.value)}
required
min="1"
placeholder="e.g. 100"
style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
/>
</div>
<div class="field">
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Price INR (paise, e.g. 49900 = 499)</label>
<input
type="number"
value={cPrice()}
onInput={(e) => setCPrice(e.currentTarget.value)}
required
min="1"
placeholder="e.g. 49900"
style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
/>
</div>
<div class="field">
<label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Bonus Percentage (optional, e.g. 10 = 10% bonus coins)</label>
<input
type="number"
value={cBonus()}
onInput={(e) => setCBonus(e.currentTarget.value)}
min="0"
placeholder="e.g. 10"
style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px"
/>
</div>
<div>
<button class="btn-primary" type="submit" disabled={cSaving()}>
{cSaving() ? 'Creating...' : 'Create Package'}
</button>
</div>
</form>
</section>
</Show>
</div>
</div> </div>
</div>
); );
} }