%PDF- %PDF-
| Direktori : /home2/rezakur1/api.rezakurnia.com/zh-router/src/ |
| Current File : //home2/rezakur1/api.rezakurnia.com/zh-router/src/topup.js |
import {pool,createTopupOrder,findTopupOrder,listTopupOrders,verifyTopupOrder,deleteTopupOrder,getWallet,getQrisSettings} from './db.js';
import {requireSession} from './auth.js';
import {config} from './config.js';
import {convertQRIS} from './qris-core.js';
const err=(reply,status,message,type='gateway_error')=>reply.code(status).send({error:{message,type}});
const AMOUNT_RE=/^\d+(\.\d{1,6})?$/;
const MIN_AMOUNT=10000;
const EXPIRY_SECONDS=24*3600;
function body(req){
const raw=req.body;
if(!raw)return {};
if(typeof raw==='object'&&!Buffer.isBuffer(raw))return raw;
try{return JSON.parse(raw.toString())}catch{return {}}
}
async function requireAdmin(req,reply){
if(await requireSession(req,reply)) return true;
if(!req.session.is_admin) { err(reply,403,'Admin access required','authorization_error'); return true; }
return false;
}
/** Normalisasi nominal payload QRIS: integer apa adanya; desimal dibulatkan ke atas. */
function qrisAmountString(n){
return Number.isInteger(n) ? String(n) : String(Math.ceil(n));
}
// POST /me/topup — buat order topup (QRIS dinamis dari gambar yang diupload admin)
export async function createTopup(req,reply){
if(await requireSession(req,reply))return;
const amount=body(req).amount;
if(typeof amount==='string'&&AMOUNT_RE.test(amount)){
const n=Number(amount);
if(Number.isFinite(n)&&n>=MIN_AMOUNT){
const order=await createTopupOrder(req.session.user_id,n);
if(order.status===409){
const p=order.pending;
return err(reply,409,`Masih ada pembayaran yang menunggu (Order #${p.id}) — selesaikan atau tunggu kedaluwarsa`);
}
const uniqueCode=order.unique_code;
const expectedTotal=n+uniqueCode;
// QRIS dinamis: konversi dari gambar statis yang dikonfigurasi admin.
const settings=await getQrisSettings();
if(settings&&Number(settings.is_active)&&settings.qris_string){
const payload=convertQRIS(settings.qris_string,{amount:qrisAmountString(expectedTotal)});
// Simpan payload ke order agar status/verifikasi bisa menampilkannya kembali.
await pool.execute('UPDATE topup_orders SET dynamic_payload=? WHERE id=?',[payload,order.id]);
return reply.code(201).send({
order:{id:order.id,amount:order.amount,unique_code:uniqueCode,status:order.status,expires_at:order.expires_at},
qr:{type:'dynamic',payload,amount_total:expectedTotal},
expires_in_seconds:EXPIRY_SECONDS
});
}
// Fallback (backward-compat): QRIS statis via env QRIS_IMAGE_URL.
return reply.code(201).send({
order:{id:order.id,amount:order.amount,unique_code:uniqueCode,status:order.status,expires_at:order.expires_at},
qr:{type:'image',url:config.qrisImageUrl||null,amount_total:expectedTotal},
expires_in_seconds:EXPIRY_SECONDS
});
}
}
return err(reply,400,`Amount must be at least ${MIN_AMOUNT} IDR`);
}
// GET /me/topup/:id — status order (dipakai polling UI)
export async function getTopup(req,reply){
if(await requireSession(req,reply))return;
const id=Number(req.params.id);
if(!Number.isInteger(id)||id<=0)return err(reply,400,'Invalid order id');
const order=await findTopupOrder(id,req.session.user_id);
if(!order)return err(reply,404,'Order not found');
if(order.status==='pending'&&new Date(order.expires_at)<new Date()){
await pool.execute("UPDATE topup_orders SET status='expired' WHERE id=? AND status='pending'",[id]);
order.status='expired';
}
reply.send({order:{id:order.id,amount:order.amount,unique_code:order.unique_code,status:order.status,expires_at:order.expires_at,paid_at:order.paid_at,note:order.note,dynamic_payload:order.dynamic_payload||null}});
}
// GET /me/topup — riwayat order user
export async function listMyTopups(req,reply){
if(await requireSession(req,reply))return;
reply.send({orders:await listTopupOrders({userId:req.session.user_id})});
}
// GET /me/wallet — saldo + riwayat transaksi
export async function getWalletHandler(req,reply){
if(await requireSession(req,reply))return;
reply.send(await getWallet(req.session.user_id));
}
// GET /admin/topup?status=&q= — daftar order semua user (admin)
export async function listAllTopups(req,reply){
if(await requireAdmin(req,reply))return;
const {status,q}=req.query;
if(status!==undefined&&!['pending','paid','expired','failed'].includes(String(status)))return err(reply,400,'Invalid status filter');
reply.send({orders:await listTopupOrders({status:status?String(status):undefined,q:String(q||'')})});
}
// DELETE /admin/topup/:id — admin hapus order yang BELUM terbayar (pending/failed)
export async function deleteTopup(req,reply){
if(await requireAdmin(req,reply))return;
const id=Number(req.params.id);
if(!Number.isInteger(id)||id<=0)return err(reply,400,'Invalid order id');
const r=await deleteTopupOrder({orderId:id});
if(!r.ok){
if(r.status===404)return err(reply,404,'Order not found');
if(r.status===409)return err(reply,409,'Order sudah terbayar — tidak bisa dihapus');
}
reply.send({ok:true});
}
// POST /admin/topup/:id/verify — admin tandai terbayar
export async function verifyTopup(req,reply){
if(await requireAdmin(req,reply))return;
const id=Number(req.params.id);
if(!Number.isInteger(id)||id<=0)return err(reply,400,'Invalid order id');
const note=typeof body(req).note==='string'?body(req).note.slice(0,255):null;
const r=await verifyTopupOrder({orderId:id,adminId:req.session.user_id,note});
if(!r.ok)return err(reply,409,`Order already settled (${r.status})`);
reply.send({ok:true});
}