Skip to content
4 changes: 2 additions & 2 deletions dashboard/admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@
try{await api("/api/admin/merchants/"+encodeURIComponent(id)+"/reviews",{method:"POST",body:JSON.stringify({review_type:$("reviewType").value,status:$("reviewStatus").value,evidence_ref:$("reviewEvidence").value.trim(),notes:$("reviewNotes").value.trim()})});$("reviewNotes").value="";await loadMerchantReviews();await loadAudit();}
catch(e){$("merchantReviewError").textContent=e.message}finally{button.disabled=false}
}
async function load(){ $("appError").textContent="";try{const [data,refundData]=await Promise.all([api("/api/admin/merchants?status="+status),api("/api/admin/refunds?status="+refundStatus)]);const rows=data.merchants||[];$("count").textContent=rows.length+" records";$("merchants").innerHTML=rows.length?rows.map(m=>'<article class="merchant"><div><strong>'+esc(m.business_name)+'</strong> <span class="pill">'+esc(m.status)+'</span> '+(m.limited_access?'<span class="pill">LIMITED ACCESS</span>':'')+'<div class="muted">'+esc(m.email||"No email")+' · '+esc(m.upi_id||"No UPI ID")+'</div><small class="muted">ID: '+esc(m.id)+' · Created: '+esc(m.created_at)+' · Active keys: '+esc(m.active_key_count)+'</small></div><div class="actions">'+(status==="pending"?'<button class="btn primary" data-action="approve" data-id="'+esc(m.id)+'">Approve + issue key</button>':status==="active"?'<button class="btn danger" data-action="suspend" data-id="'+esc(m.id)+'">Suspend</button>':'<button class="btn primary" data-action="reactivate" data-id="'+esc(m.id)+'">Reactivate</button>')+'<button class="btn" data-limited-action="'+(m.limited_access?'revoke':'grant')+'" data-id="'+esc(m.id)+'">'+(m.limited_access?'Revoke limited access':'Grant limited access')+'</button></div></article>').join(""):'<p class="muted">No '+status+' merchants.</p>';$("merchants").querySelectorAll("[data-action]").forEach(b=>b.addEventListener("click",()=>change(b)));$("merchants").querySelectorAll("[data-limited-action]").forEach(b=>b.addEventListener("click",()=>changeLimitedAccess(b)));const refunds=refundData.refunds||[];$("refunds").innerHTML=refunds.length?refunds.map(r=>'<article class="merchant"><div><strong>'+esc(r.business_name)+' · '+(r.amount_minor/100).toFixed(2)+' '+esc(r.currency)+'</strong><div class="muted">'+esc(r.reason)+'</div><small class="muted">Transaction '+esc(r.transaction_id)+' · '+esc(r.created_at)+'</small><div class="pill">'+esc(r.status)+'</div></div><div class="actions">'+(r.status==="requested"?'<button class="btn primary" data-refund-action="approve" data-id="'+esc(r.id)+'">Approve (await provider)</button><button class="btn danger" data-refund-action="reject" data-id="'+esc(r.id)+'">Reject</button>':'—')+'</div></article>').join(""):'<p class="muted">No '+refundStatus.replaceAll("_"," ")+' refunds.</p>';$("refunds").querySelectorAll("[data-refund-action]").forEach(b=>b.addEventListener("click",()=>decideRefund(b)));}catch(e){$("appError").textContent=e.message}}
async function load(){ $("appError").textContent="";try{const [data,refundData]=await Promise.all([api("/api/admin/merchants?status="+status),api("/api/admin/refunds?status="+refundStatus)]);const rows=data.merchants||[];$("count").textContent=rows.length+" records";$("merchants").innerHTML=rows.length?rows.map(m=>'<article class="merchant"><div><strong>'+esc(m.business_name)+'</strong> <span class="pill">'+(m.archived_pending?'archived · pending':esc(m.status))+'</span> '+(m.limited_access?'<span class="pill">LIMITED ACCESS</span>':'')+'<div class="muted">'+esc(m.email||"No email")+' · '+esc(m.upi_id||"No UPI ID")+'</div><small class="muted">ID: '+esc(m.id)+' · Created: '+esc(m.created_at)+' · Active keys: '+esc(m.active_key_count)+'</small></div><div class="actions">'+(status==="pending"?'<button class="btn primary" data-action="approve" data-id="'+esc(m.id)+'">Approve + issue key</button><button class="btn danger" data-action="archive-pending" data-id="'+esc(m.id)+'">Archive pending</button>':status==="active"?'<button class="btn danger" data-action="suspend" data-id="'+esc(m.id)+'">Suspend</button>':(m.archived_pending?'<span class="muted">History preserved · archived</span>':'<button class="btn primary" data-action="reactivate" data-id="'+esc(m.id)+'">Reactivate</button>'))+(m.archived_pending?'':'<button class="btn" data-limited-action="'+(m.limited_access?'revoke':'grant')+'" data-id="'+esc(m.id)+'">'+(m.limited_access?'Revoke limited access':'Grant limited access')+'</button>')+'</div></article>').join(""):'<p class="muted">No '+status+' merchants.</p>';$("merchants").querySelectorAll("[data-action]").forEach(b=>b.addEventListener("click",()=>change(b)));$("merchants").querySelectorAll("[data-limited-action]").forEach(b=>b.addEventListener("click",()=>changeLimitedAccess(b)));const refunds=refundData.refunds||[];$("refunds").innerHTML=refunds.length?refunds.map(r=>'<article class="merchant"><div><strong>'+esc(r.business_name)+' · '+(r.amount_minor/100).toFixed(2)+' '+esc(r.currency)+'</strong><div class="muted">'+esc(r.reason)+'</div><small class="muted">Transaction '+esc(r.transaction_id)+' · '+esc(r.created_at)+'</small><div class="pill">'+esc(r.status)+'</div></div><div class="actions">'+(r.status==="requested"?'<button class="btn primary" data-refund-action="approve" data-id="'+esc(r.id)+'">Approve (await provider)</button><button class="btn danger" data-refund-action="reject" data-id="'+esc(r.id)+'">Reject</button>':'—')+'</div></article>').join(""):'<p class="muted">No '+refundStatus.replaceAll("_"," ")+' refunds.</p>';$("refunds").querySelectorAll("[data-refund-action]").forEach(b=>b.addEventListener("click",()=>decideRefund(b)));}catch(e){$("appError").textContent=e.message}}
async function changeLimitedAccess(button){
const action=button.dataset.limitedAction;
const reason=prompt(action==="grant"?"Reason for granting limited dashboard access (no live payment approval):":"Reason for revoking limited dashboard access:");
Expand All @@ -539,7 +539,7 @@
catch(e){$("appError").textContent=e.message;button.disabled=false}
}
async function decideRefund(b){const action=b.dataset.refundAction;const reason=prompt(action==="approve"?"Approval note (optional):":"Reason for rejecting this refund:");if(action==="reject"&&!reason?.trim())return;b.disabled=true;try{const result=await api("/api/admin/refunds/"+b.dataset.id+"/"+action,{method:"POST",body:JSON.stringify({reason:reason||""})});alert(result.status==="approved_waiting_provider"?"Approved. No money has moved; wait for authorised partner settlement.":"Refund request rejected.");await load()}catch(e){$("appError").textContent=e.message;b.disabled=false}}
async function change(b){const action=b.dataset.action;if(!confirm(action==="approve"?"Approve this merchant and issue a new API key? Verify KYC and business ownership first.":action+" this merchant?"))return;b.disabled=true;try{const result=await api("/api/admin/merchants/"+b.dataset.id+"/"+action,{method:"POST"});if(result.api_key){$("issuedKey").textContent=result.api_key;$("keyNotice").classList.remove("hidden")}await load()}catch(e){$("appError").textContent=e.message;b.disabled=false}}
async function change(b){const action=b.dataset.action;let body;let message=action==="approve"?"Approve this merchant and issue a new API key? Verify KYC and business ownership first.":action==="archive-pending"?"Archive this pending merchant? This preserves its gateway application and audit history and does not delete data.":action+" this merchant?";if(action==="archive-pending"){const reason=prompt("Why is this pending merchant a duplicate or no longer needed? (minimum 10 characters)");if(reason===null)return;if(reason.trim().length<10){alert("Enter an archive reason of at least 10 characters.");return}body={reason:reason.trim()}}if(!confirm(message))return;b.disabled=true;try{const result=await api("/api/admin/merchants/"+b.dataset.id+"/"+action,{method:"POST",...(body?{body:JSON.stringify(body)}:{})});if(result.api_key){$("issuedKey").textContent=result.api_key;$("keyNotice").classList.remove("hidden")}if(result.archived_pending)alert(result.note);await load();await loadAudit()}catch(e){$("appError").textContent=e.message;b.disabled=false}}
$("googleAdminSignIn").addEventListener("click",beginAdminGoogleSignIn);
$("adminSecretForm").addEventListener("submit",submitAdminSecret);
$("disconnect").addEventListener("click",async()=>{try{await Promise.all([fetch("/api/auth/sign-out",{method:"POST",credentials:"same-origin"}),fetch("/api/admin/key-logout",{method:"POST",credentials:"same-origin"})])}finally{$("app").classList.add("hidden");document.querySelector(".admin-shell")?.classList.remove("admin-authenticated");$("login").classList.remove("hidden");$("disconnect").classList.add("hidden");$("keyNotice").classList.add("hidden");$("issuedKey").textContent=""}});
Expand Down
20 changes: 19 additions & 1 deletion worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -984,7 +984,7 @@ export default {
const status = url.searchParams.get("status") || "pending";
if (!["pending", "active", "suspended"].includes(status)) return json({ error: "Invalid merchant status" }, 400, origin);
const rows = await env.DB.prepare(
"SELECT m.id,m.business_name,m.email,m.upi_id,m.currency,m.status,m.created_at,(SELECT COUNT(*) FROM api_keys k WHERE k.merchant_id=m.id AND k.revoked_at IS NULL) AS active_key_count,EXISTS(SELECT 1 FROM merchant_limited_access a WHERE a.merchant_id=m.id AND a.revoked_at IS NULL) AS limited_access FROM merchants m WHERE m.status=? ORDER BY m.created_at DESC LIMIT 100"
"SELECT m.id,m.business_name,m.email,m.upi_id,m.currency,m.status,m.created_at,(SELECT COUNT(*) FROM api_keys k WHERE k.merchant_id=m.id AND k.revoked_at IS NULL) AS active_key_count,EXISTS(SELECT 1 FROM merchant_limited_access a WHERE a.merchant_id=m.id AND a.revoked_at IS NULL) AS limited_access,EXISTS(SELECT 1 FROM audit_logs al WHERE al.merchant_id=m.id AND al.action='merchant.pending_archived') AS archived_pending FROM merchants m WHERE m.status=? ORDER BY m.created_at DESC LIMIT 100"
).bind(status).all();
return json({ merchants: rows.results || [] }, 200, origin);
}
Expand Down Expand Up @@ -1012,6 +1012,24 @@ export default {
.bind(makeId(),merchant.id,adminAuth.email,id,JSON.stringify({review_type:reviewType,status:reviewStatus})).run();
return json({id,merchant_id:merchant.id,review_type:reviewType,status:reviewStatus},201,origin);
}
const archiveMatch = url.pathname.match(/^\/api\/admin\/merchants\/([0-9a-f-]{36})\/archive-pending$/i);
if (request.method === "POST" && archiveMatch) {
const merchantId = archiveMatch[1];
const body = await request.json().catch(() => ({}));
const reason = String(body.reason || "").trim().slice(0, 1000);
if (reason.length < 10) return json({error:"An archive reason of at least 10 characters is required"},400,origin);
const merchant = await env.DB.prepare("SELECT id,status FROM merchants WHERE id=?").bind(merchantId).first();
if (!merchant) return json({error:"Merchant not found"},404,origin);
if (merchant.status !== "pending") return json({error:"Only pending merchants can be archived by this action"},409,origin);
const active = await env.DB.prepare("SELECT EXISTS(SELECT 1 FROM merchant_limited_access WHERE merchant_id=? AND revoked_at IS NULL) AS limited_access,EXISTS(SELECT 1 FROM api_keys WHERE merchant_id=? AND revoked_at IS NULL) AS active_keys,EXISTS(SELECT 1 FROM transactions WHERE merchant_id=?) AS transactions,EXISTS(SELECT 1 FROM payment_links WHERE merchant_id=?) AS payment_links,EXISTS(SELECT 1 FROM checkout_sessions WHERE merchant_id=?) AS checkout_sessions,EXISTS(SELECT 1 FROM merchant_provider_connections WHERE merchant_id=?) AS provider_connections").bind(merchantId,merchantId,merchantId,merchantId,merchantId,merchantId).first();
if (active?.limited_access || active?.active_keys || active?.transactions || active?.payment_links || active?.checkout_sessions || active?.provider_connections) return json({error:"This merchant has active access or payment assets. Revoke/review those through their dedicated workflow before archiving."},409,origin);
const archiveResults = await env.DB.batch([
env.DB.prepare("UPDATE merchants SET status='suspended' WHERE id=? AND status='pending'").bind(merchantId),
env.DB.prepare("INSERT INTO audit_logs (id,merchant_id,actor,action,resource_type,resource_id,metadata_json) SELECT ?,?,?,'merchant.pending_archived','merchant',?,? WHERE changes()=1").bind(makeId(),merchantId,adminAuth.email,merchantId,JSON.stringify({reason,previous_status:"pending",preserved_history:true}))
]);
if (!archiveResults[0]?.meta?.changes || !archiveResults[1]?.meta?.changes) return json({error:"Merchant status changed; refresh the queue and retry"},409,origin);
return json({merchant_id:merchantId,status:"suspended",archived_pending:true,preserved_history:true,note:"Pending merchant archived; linked application and audit history were preserved."},200,origin);
}
const match = url.pathname.match(/^\/api\/admin\/merchants\/([0-9a-f-]{36})\/(approve|suspend|reactivate)$/i);
if (request.method === "POST" && match) {
const [, merchantId, action] = match;
Expand Down
46 changes: 46 additions & 0 deletions worker/test/admin-pending-archive.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";

const worker = await readFile(new URL("../src/index.js", import.meta.url), "utf8");
const admin = await readFile(new URL("../../dashboard/admin.html", import.meta.url), "utf8");

test("pending merchant archive is an authenticated admin-only route", () => {
const route = worker.indexOf('const archiveMatch = url.pathname.match');
const auth = worker.lastIndexOf("authenticateAdmin(request, env)", route);
assert.ok(route > 0, "archive route exists");
assert.ok(auth >= 0, "archive route is inside the admin-authenticated route block");
assert.match(worker.slice(route, route + 2400), /status !== "pending"/);
assert.match(worker.slice(route, route + 2400), /reason\.length < 10/);
});

test("pending merchant archive fails closed when live access or payment assets exist", () => {
const route = worker.slice(worker.indexOf('const archiveMatch = url.pathname.match'), worker.indexOf('const match = url.pathname.match', worker.indexOf('const archiveMatch = url.pathname.match')));
for (const table of ["merchant_limited_access", "api_keys", "transactions", "payment_links", "checkout_sessions", "merchant_provider_connections"]) {
assert.ok(route.includes(table), "archive gate checks " + table);
}
assert.match(route, /UPDATE merchants SET status='suspended' WHERE id=\? AND status='pending'/);
assert.match(route, /merchant\.pending_archived/);
assert.match(route, /preserved_history:true/);
assert.match(route, /env\.DB\.batch\(\[/);
assert.match(route, /WHERE changes\(\)=1/);
assert.match(route, /adminAuth\.email/);
});

test("admin dashboard exposes archive action only in pending queue and preserves archived history", () => {
assert.match(admin, /data-action="archive-pending"/);
assert.match(admin, /archived_pending\?'archived · pending'/);
assert.match(admin, /History preserved · archived/);
assert.match(admin, /gateway application and audit history/);
});

test("archive route matcher is valid JavaScript regex for the exact API path", () => {
assert.match(worker, /url\.pathname\.match\(\/\^\\\/api\\\/admin\\\/merchants\\/);
});

test("archive mutation and audit entry are executed in one ordered D1 batch", () => {
const route = worker.slice(worker.indexOf('const archiveMatch = url.pathname.match'), worker.indexOf('const match = url.pathname.match', worker.indexOf('const archiveMatch = url.pathname.match')));
assert.ok(route.indexOf('env.DB.batch([') < route.indexOf('UPDATE merchants SET status='));
assert.ok(route.indexOf('UPDATE merchants SET status=') < route.indexOf('INSERT INTO audit_logs'));
assert.match(route, /archiveResults\[0\].*archiveResults\[1\]/s);
});
Loading