%PDF- %PDF-
| Direktori : /home2/rezakur1/api.rezakurnia.com/zh-router/src/ |
| Current File : //home2/rezakur1/api.rezakurnia.com/zh-router/src/packages.js |
import {
listPackages,createPackage,updatePackage,setPackageActive,
listUserPackages,buyPackage,claimPackage,deletePackagePermanent,
} from './db.js';
import {requireSession} from './auth.js';
const err=(reply,status,message,type='gateway_error')=>reply.code(status).send({error:{message,type}});
const INT_RE=/^\d+$/;
const PRICE_RE=/^\d+(\.\d{1,6})?$/;
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;
}
/** Validasi input paket dari admin → {ok, value|error} */
function parsePackageInput(raw){
const name=typeof raw.name==='string'?raw.name.trim():'';
if(!name||name.length>100) return {ok:false,error:'Nama paket wajib diisi (maks 100 karakter)'};
const description=typeof raw.description==='string'?raw.description.trim().slice(0,255):null;
const normalizeQuota=v=>{
if(v===null||v===undefined||v==='') return null;
if(typeof v==='number'&&Number.isInteger(v)&&v>0) return v;
if(typeof v==='string'&&INT_RE.test(v)&&Number(v)>0) return Number(v);
return undefined; // invalid
};
const requestQuota=normalizeQuota(raw.request_quota);
const tokenQuota=normalizeQuota(raw.token_quota);
if(requestQuota===undefined) return {ok:false,error:'Kuota request tidak valid (angka positif, atau kosong untuk unlimited)'};
if(tokenQuota===undefined) return {ok:false,error:'Kuota token tidak valid (angka positif, atau kosong untuk unlimited)'};
const priceRaw=typeof raw.price==='string'?raw.price:String(raw.price??'');
if(!PRICE_RE.test(priceRaw)) return {ok:false,error:'Harga tidak valid'};
const price=Number(priceRaw);
if(!Number.isFinite(price)||price<0) return {ok:false,error:'Harga tidak valid'};
const numOr=(v,def=0)=>typeof v==='number'&&Number.isFinite(v)?v:(typeof v==='string'&&INT_RE.test(v)?Number(v):def);
const durationDays=numOr(raw.duration_days);
const durationHours=numOr(raw.duration_hours);
if(durationDays>3650||durationHours>8760) return {ok:false,error:'Durasi terlalu besar (maks 3650 hari / 8760 jam)'};
const okDur=(durationDays>0&&durationHours===0)||(durationHours>0&&durationDays===0);
if(!okDur) return {ok:false,error:'Isi durasi: hari (mis. 30) ATAU jam (mis. 48), tidak keduanya'};
const claimFree=raw.claim_free===1||raw.claim_free===true||raw.claim_free==='1';
const value={name,description,requestQuota,tokenQuota,durationDays,durationHours,claimFree};
if(claimFree){
// Paket klaim gratis: harga selalu 0 (dipaksa).
value.price=0;
}else{
value.price=price;
}
return {ok:true,value};
}
// GET /admin/packages — katalog lengkap (termasuk nonaktif)
export async function adminListPackages(req,reply){
if(await requireAdmin(req,reply))return;
reply.send({packages:await listPackages({includeInactive:true})});
}
// POST /admin/packages — buat paket
export async function adminCreatePackage(req,reply){
if(await requireAdmin(req,reply))return;
const parsed=parsePackageInput(body(req));
if(!parsed.ok)return err(reply,400,parsed.error);
const created=await createPackage(parsed.value);
const pkg=(await listPackages({includeInactive:true})).find(p=>p.id===created.id);
reply.code(201).send({package:pkg});
}
// PATCH /admin/packages/:id — ubah paket
export async function adminUpdatePackage(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 package id');
const parsed=parsePackageInput(body(req));
if(!parsed.ok)return err(reply,400,parsed.error);
const raw=body(req);
const isActive=raw.is_active===undefined?true:Boolean(raw.is_active);
const ok=await updatePackage({packageId:id,...parsed.value,isActive});
if(!ok)return err(reply,404,'Package not found');
const pkg=(await listPackages({includeInactive:true})).find(p=>p.id===id);
reply.send({package:pkg});
}
// DELETE /admin/packages/:id — nonaktifkan (soft delete)
export async function adminDeletePackage(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 package id');
const ok=await setPackageActive({packageId:id,active:false});
if(!ok)return err(reply,404,'Package not found');
reply.send({ok:true});
}
// DELETE /admin/packages/:id/permanent — hapus permanen (ditolak jika sudah dibeli)
export async function adminDeletePackagePermanent(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 package id');
const r=await deletePackagePermanent({packageId:id});
if(r.status===404)return err(reply,404,'Package not found');
if(r.status===409)return err(reply,409,'Paket sudah pernah dibeli user — nonaktifkan saja');
reply.send({ok:true});
}
// GET /me/packages — katalog aktif + paket aktif user + riwayat pembelian
export async function myPackages(req,reply){
if(await requireSession(req,reply))return;
const [catalog,active,purchases]=await Promise.all([
listPackages({includeInactive:false}),
listUserPackages({userId:req.session.user_id,status:'active'}),
listUserPackages({userId:req.session.user_id}),
]);
reply.send({catalog,active:active[0]||null,purchases});
}
// POST /me/packages/:id/buy — beli paket dari saldo wallet
export async function buyPackageHandler(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 package id');
const r=await buyPackage({userId:req.session.user_id,packageId:id});
if(!r.ok){
if(r.status===404)return err(reply,404,'Paket tidak ditemukan atau tidak tersedia');
if(r.status===409)return err(reply,409,'Kamu masih memiliki paket aktif — tunggu hingga masa berlakunya habis');
if(r.status===402)return err(reply,402,'Saldo wallet tidak cukup untuk membeli paket ini','insufficient_balance');
return err(reply,500,'Gagal membeli paket');
}
reply.code(201).send({
ok:true,
user_package:{id:r.user_package_id,status:r.status,expires_at:r.expires_at,package_name:r.package_name},
});
}
// POST /me/packages/:id/claim — klaim paket gratis (sekali per paket,
// syarat saldo wallet ≥ Rp10.000, tanpa potongan saldo)
export async function claimPackageHandler(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 package id');
const r=await claimPackage({userId:req.session.user_id,packageId:id});
if(!r.ok){
if(r.status===404)return err(reply,404,'Paket gratis tidak ditemukan atau tidak tersedia');
if(r.status===409&&r.reason==='already_claimed')return err(reply,409,'Kamu sudah pernah mengklaim paket ini — klaim hanya sekali per paket');
if(r.status===409)return err(reply,409,'Kamu masih memiliki paket aktif — tunggu hingga masa berlakunya habis');
if(r.status===402)return err(reply,402,'Saldo wallet minimal Rp10.000 untuk mengklaim paket ini','insufficient_balance');
return err(reply,500,'Gagal mengklaim paket');
}
reply.code(201).send({
ok:true,
user_package:{id:r.user_package_id,status:r.status,expires_at:r.expires_at,package_name:r.package_name},
});
}