Welcome to Great Loan
Loans up to ₹2,50,000 with easy monthly EMI. Tap Apply for a Loan to get started.
Get a loan in minutes
Apply with just your NID card — amounts from ₹20,000 to ₹2,50,000, repaid over 6 to 36 months.
Lending & Banking Partners
Trusted Financial Partners
Profile
Your account, loan card, balance and all services.
All Services
Everything about your loan, in one place.
EMI Calculator
Choose an amount and tenure to see the monthly EMI, total interest and total payable.
| Loan Amount | 12 months / monthly | 24 months / monthly |
|---|
EMIs for 6, 18, 30 and 36 months are calculated at the same rate as the 12 / 24 month table above.
Apply for a Loan
Fill in the form with your ID card. Approval comes from the admin panel and the Telegram bot.
Your Plan Summary
Updates as you change the amount and tenure.
My Loans / Loan Status
Your applications, repayment schedule and statement — all in one page.
Repayment Schedule
Generated for disbursed loans.
Statement
All activity on your loans.
Inbox
Loan status updates, notifications and messages about your applications.
Welcome to Great Loan
Log in with your phone number to manage your loans.
Admin Panel
Users, loan applications, approvals, settings and the Telegram bot.
Admin Login
Sign in with an account that has the admin role on the server. Complete the “I am not a robot” check to continue.
Applications by Status
Live from the applications list.
Recent Applications
The latest five submissions.
Loan Applications
Verify the ID card and approve, cancel, disburse or close each application.
Registered Users
Accounts created from the register page, along with applicants.
| User | Phone | Applications | Joined | Actions |
|---|
Telegram Bot — Live Preview
This is exactly what the admin receives on Telegram for every new application. The Approve / Cancel buttons below work just like the bot's inline buttons.
Bot Settings
Create a bot with @BotFather, enter the token and the chat / group ID. The portal works normally even if Telegram is not configured.
How the approval flow works
Application submitted. The portal sends the applicant's full name, age, WhatsApp number, occupation, amount, tenure, purpose, detailed Reason / Details, ID card type and EMI to your Telegram chat.
Admin taps a button. The message has two inline buttons — Approve and Cancel.
The webhook updates the record. Telegram calls your webhook; the application status changes and the bot sends a confirmation message.
Site Settings
Everything on this site comes from these settings — nothing is fixed in the code. Edit any value, press Save Settings, and the change applies across the whole portal at once: header, home page, promo banner, EMI calculator, apply form, footer, inbox and admin. On the deployed site the same values are saved as one JSON row in the database settings table and served by GET /api/settings (see Backend & API).
Deploy on Cloudflare Pages
Project name great-loan — the site runs at great-loan.pages.dev. The portal is a static site, plus one Pages Function for the Telegram webhook.
Upload the site. Create a Pages project named great-loan and upload index.html together with manifest.webmanifest, sw.js, icon-192.png, icon-512.png and icon-maskable-512.png — all as separate files in the project root (or push them all to a Git repo). No build command is needed. The manifest, service worker and icons must be real files at the root: without them Chrome shows “This app cannot be installed”, and a service worker in a subfolder can never control the home page.
Add the webhook function. Create the file functions/api/telegram/webhook.js in the project with the code below.
Set the secrets. In Pages → Settings → Environment variables, add TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID. Connect the function to the database / KV where application statuses are stored.
Register the webhook. Open once in your browser: https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://great-loan.pages.dev/api/telegram/webhook
// functions/api/telegram/webhook.js — Cloudflare Pages Function
// Secrets (Pages → Settings → Environment variables):
// TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
// Replace updateApplicationStatus() with your DB / KV write.
async function tg(env, method, payload) {
return fetch(`https://api.telegram.org/bot${env.TELEGRAM_BOT_TOKEN}/${method}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload)
});
}
// Call this from your application-submit endpoint:
export async function notifyNewApplication(env, app) {
const text =
`New Loan Application ${app.id}\n` +
`Name: ${app.name} (age ${app.age})\nPhone / WhatsApp: ${app.whatsapp}\n` +
`Occupation: ${app.occupation}\n` +
`Amount: ₹${app.amount} · Tenure: ${app.tenure} months\n` +
`Purpose: ${app.purpose} · EMI: ₹${app.emi}/month\n` +
`Reason / Details: ${app.loanReason || app.reasonDetails || ''}\n` +
`ID Card: ${app.idType} (front + back photos submitted)`;
await tg(env, 'sendMessage', {
chat_id: env.TELEGRAM_CHAT_ID,
text,
reply_markup: { inline_keyboard: [[
{ text: '✓ Approve', callback_data: `approve:${app.id}` },
{ text: '✕ Cancel', callback_data: `cancel:${app.id}` }
]]}
});
}
export async function onRequestPost({ request, env }) {
const update = await request.json();
const cb = update.callback_query;
if (!cb) return new Response('ok');
if (String(cb.message.chat.id) !== String(env.TELEGRAM_CHAT_ID))
return new Response('forbidden', { status: 403 });
const [action, appId] = cb.data.split(':');
const status = action === 'approve' ? 'Approved' : 'Cancelled';
await updateApplicationStatus(env, appId, status); // ← your DB/KV
await tg(env, 'answerCallbackQuery', {
callback_query_id: cb.id, text: `${appId} marked ${status}`
});
await tg(env, 'editMessageText', {
chat_id: cb.message.chat.id, message_id: cb.message.message_id,
text: cb.message.text + `\n\nStatus: ${status}`
});
return new Response('ok');
}
Backend Architecture — Cloudflare Pages
Deploy guide — the live backend is not active in this static preview. The portal's screens are built against the API contract below and post every action to these endpoints; until the Pages Functions are deployed, no server answers and the same flows run in the browser session instead. Once the functions below are deployed next to this page, the same screens run on the live backend: server-side authentication with httpOnly session cookies, user / admin roles, and a D1 database for users, applications, status history, EMI schedules and payments. ID card photos go to an R2 bucket.
| Endpoint | Method | Access | What it does |
|---|---|---|---|
/api/auth/register | POST | Public | Create account — PBKDF2 password hash, session cookie issued |
/api/auth/login | POST | Public | Verify password, create a server session (7 days) |
/api/auth/logout | POST | User | Delete the session row and clear the cookie |
/api/auth/me | GET | User | Current user and role from the session cookie |
/api/loans | POST / GET | User | Submit an application (EMI + schedule generated server-side) / list my loans |
/api/admin/stats | GET | Admin | Totals by status and user count |
/api/admin/applications | GET | Admin | Search and filter all applications |
/api/admin/status | POST | Admin | Approve / Cancel / Disburse / Repaid + status history entry |
/api/admin/payment | POST | Admin | Record an EMI payment and mark the schedule row paid |
/api/admin/users | GET | Admin | All registered users with roles |
/api/settings | GET | Public | All site settings from the settings table — the page applies them on load, nothing is hardcoded |
/api/admin/settings | POST | Admin | Save site settings (name, tagline, theme color, texts, amounts, tenures, EMI table, contacts, notifications) |
/api/telegram/webhook | POST | Telegram | Approve / Cancel callbacks update D1 and confirm in chat |
/api/admin/login | POST | Public → Admin | Admin sign-in for /admin — verifies the Cloudflare Turnstile token with the secret key first, then the password, then issues an admin session |
1 · Database Schema (D1)
Users, sessions, applications, status history, EMI schedule and payments.
-- schema.sql — run once on your D1 database:
-- wrangler d1 execute great-loan-db --remote --file=schema.sql
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL, phone TEXT UNIQUE NOT NULL,
pass_hash TEXT NOT NULL, salt TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user', -- 'user' | 'admin'
card_number TEXT UNIQUE, -- generated once at registration from the user id; never changes
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY, user_id INTEGER NOT NULL,
expires_at INTEGER NOT NULL -- epoch ms, 7 days
);
CREATE TABLE IF NOT EXISTS applications (
id TEXT PRIMARY KEY, user_id INTEGER,
name TEXT, age INTEGER, whatsapp TEXT, occupation TEXT,
amount INTEGER, tenure INTEGER, purpose TEXT,
loan_reason TEXT DEFAULT '', -- applicant's detailed Reason / Details
id_type TEXT, id_front_key TEXT, id_back_key TEXT, -- R2 object keys
emi INTEGER, status TEXT DEFAULT 'Pending',
reason TEXT DEFAULT '', paid_emis INTEGER DEFAULT 0,
created_at TEXT, disbursed_on TEXT
);
CREATE TABLE IF NOT EXISTS status_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, status TEXT, note TEXT, at TEXT
);
CREATE TABLE IF NOT EXISTS emi_schedule (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, n INTEGER, due_date TEXT,
emi INTEGER, principal INTEGER, interest INTEGER,
balance INTEGER, paid INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app_id TEXT, n INTEGER, amount INTEGER, method TEXT, at TEXT
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY, value TEXT NOT NULL -- one JSON row, key = 'site'
);
-- The admin panel's Site Settings page reads / writes that JSON row:
-- SELECT value FROM settings WHERE key = 'site';
-- INSERT INTO settings (key, value) VALUES ('site', '{...}')
-- ON CONFLICT(key) DO UPDATE SET value = excluded.value;
-- Make your own account an admin after registering:
-- UPDATE users SET role = 'admin' WHERE phone = 'YOUR_PHONE';
-- Existing databases, add the card number column once:
-- ALTER TABLE users ADD COLUMN card_number TEXT UNIQUE;
2 · Project Config
Bindings for the D1 database and the R2 file bucket.
# wrangler.toml — place next to index.html, with a functions/ folder beside it name = "great-loan" pages_build_output_dir = "." compatibility_date = "2024-11-01" [[d1_databases]] binding = "DB" database_name = "great-loan-db" database_id = "<your-d1-database-id>" [[r2_buckets]] binding = "FILES" bucket_name = "great-loan-files" # Sessions live in D1 (sessions table). A KV namespace can replace them # later for faster reads; the API contract stays the same.
3 · Deploy Steps
Create the database. Cloudflare dashboard → Storage & Databases → D1 → Create great-loan-db, then run schema.sql in its console (or with Wrangler).
Create the file bucket. R2 → Create bucket great-loan-files for ID card photos.
Add the functions. Put this page and a functions/ folder (files below) in the Pages project great-loan, with the wrangler.toml bindings — or add the same D1 / R2 bindings in Pages → Settings → Functions.
Set the secrets. Pages → Settings → Environment variables: TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID.
Make yourself admin. Register normally, then run in the D1 console: UPDATE users SET role = 'admin' WHERE phone = 'your phone';
Register the Telegram webhook. Open once: https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://great-loan.pages.dev/api/telegram/webhook
4 · Shared Helpers — functions/api/_shared.js
JSON responses, PBKDF2 password hashing, session cookies, role guards.
// functions/api/_shared.js — helpers shared by every Pages Function
// Bindings (Pages project -> Settings -> Functions, or wrangler.toml):
// DB -> D1 database (users, sessions, applications, ...)
// FILES -> R2 bucket for ID card photos
export function json(data, status = 200, extra = {}) {
return new Response(JSON.stringify(data), {
status, headers: { 'content-type': 'application/json', ...extra }
});
}
async function pbkdf2(password, salt) {
const enc = new TextEncoder();
const key = await crypto.subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveBits']);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt: enc.encode(salt), iterations: 100000, hash: 'SHA-256' }, key, 256);
return [...new Uint8Array(bits)].map(b => b.toString(16).padStart(2, '0')).join('');
}
export async function hashPassword(password) {
const salt = crypto.randomUUID();
return { salt, hash: await pbkdf2(password, salt) };
}
export async function checkPassword(password, salt, expected) {
return (await pbkdf2(password, salt)) === expected;
}
export function sessionCookie(token) {
return 'gl_session=' + token + '; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=' + (7 * 24 * 3600);
}
export async function createSession(env, userId) {
const token = crypto.randomUUID() + crypto.randomUUID();
await env.DB.prepare('INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)')
.bind(token, userId, Date.now() + 7 * 24 * 3600 * 1000).run();
return token;
}
// One unique card number per user, built from the user id:
// '4001' + the id zero-padded to 6 digits (id 23 -> 4001000023).
// Generated once at registration and stored on the user row;
// logins never regenerate it, so an existing user's number never
// changes and every new user gets a different one.
export function cardNumberForId(id) {
return '4001' + String(id).padStart(6, '0');
}
export async function currentUser(request, env) {
const m = (request.headers.get('cookie') || '').match(/gl_session=([^;]+)/);
if (!m) return null;
return env.DB.prepare(
'SELECT u.id, u.name, u.phone, u.role, u.card_number FROM sessions s JOIN users u ON u.id = s.user_id ' +
'WHERE s.token = ? AND s.expires_at > ?').bind(m[1], Date.now()).first();
}
export async function requireUser(request, env) {
const user = await currentUser(request, env);
if (!user) throw json({ error: 'Login required' }, 401);
return user;
}
export async function requireAdmin(request, env) {
const user = await requireUser(request, env);
if (user.role !== 'admin') throw json({ error: 'Admin only' }, 403);
return user;
}
5 · Auth API — functions/api/auth/[[route]].js
Register, login, logout and /me — server-side sessions, roles user / admin.
// functions/api/auth/[[route]].js — one catch-all file for /api/auth/*
// POST /api/auth/register POST /api/auth/login
// POST /api/auth/logout GET /api/auth/me
import { json, hashPassword, checkPassword, createSession, sessionCookie, currentUser, cardNumberForId } from '../_shared.js';
export async function onRequest({ request, env, params }) {
const route = (params.route || []).join('/');
try {
if (route === 'register' && request.method === 'POST') {
const { name, phone, password } = await request.json();
if (!name || !phone || !password || password.length < 6)
return json({ error: 'Name, phone and a 6+ character password are required' }, 400);
const exists = await env.DB.prepare('SELECT id FROM users WHERE phone = ?').bind(phone).first();
if (exists) return json({ error: 'Phone already registered' }, 409);
const { salt, hash } = await hashPassword(password);
const r = await env.DB.prepare(
'INSERT INTO users (name, phone, pass_hash, salt, role, created_at) VALUES (?, ?, ?, ?, ?, ?)')
.bind(name, phone, hash, salt, 'user', new Date().toISOString()).run();
const uid = r.meta.last_row_id;
// New user -> a new unique card number, generated from the
// user id and stored on the row. It is never generated again.
const cardNumber = cardNumberForId(uid);
await env.DB.prepare('UPDATE users SET card_number = ? WHERE id = ?').bind(cardNumber, uid).run();
const token = await createSession(env, uid);
return json({ id: uid, name, phone, role: 'user', card_number: cardNumber }, 201,
{ 'set-cookie': sessionCookie(token) });
}
if (route === 'login' && request.method === 'POST') {
const { phone, password } = await request.json();
const u = await env.DB.prepare('SELECT * FROM users WHERE phone = ?').bind(phone).first();
if (!u || !(await checkPassword(password, u.salt, u.pass_hash)))
return json({ error: 'Wrong phone or password' }, 401);
// An existing user's stored card number is returned as-is —
// it never changes. Only a legacy row without one gets it
// generated (once, from the id) and saved here.
let cardNumber = u.card_number;
if (!cardNumber) {
cardNumber = cardNumberForId(u.id);
await env.DB.prepare('UPDATE users SET card_number = ? WHERE id = ?').bind(cardNumber, u.id).run();
}
const token = await createSession(env, u.id);
return json({ id: u.id, name: u.name, phone: u.phone, role: u.role, card_number: cardNumber }, 200,
{ 'set-cookie': sessionCookie(token) });
}
if (route === 'logout' && request.method === 'POST') {
const m = (request.headers.get('cookie') || '').match(/gl_session=([^;]+)/);
if (m) await env.DB.prepare('DELETE FROM sessions WHERE token = ?').bind(m[1]).run();
return json({ ok: true }, 200,
{ 'set-cookie': 'gl_session=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0' });
}
if (route === 'me' && request.method === 'GET') {
const user = await currentUser(request, env);
return user ? json(user) : json({ error: 'Not logged in' }, 401);
}
return json({ error: 'Not found' }, 404);
} catch (e) {
return e instanceof Response ? e : json({ error: 'Server error' }, 500);
}
}
6 · Loans API — functions/api/loans.js
Multipart FormData POST — all form fields plus both ID photos (id_front, id_back) in one request. The server parses the photos, forwards them to Telegram, generates the full EMI schedule in D1. No R2 pre-upload, no JSON body.
// functions/api/loans.js
// POST /api/loans (login required) — multipart FormData: new application + EMI schedule rows
// GET /api/loans (login required) — my applications
// ID photos: NO separate upload step and NO JSON body. The browser sends
// ONE multipart FormData POST to /api/loans with every form field plus
// the two photo files — id_front and id_back — in the same request.
// The server parses the photos with request.formData(), forwards them
// to Telegram with sendPhoto, and stores the returned Telegram
// file_ids (in id_front_key / id_back_key). Do NOT upload to R2 (FILES)
// first and do NOT send idFrontKey / idBackKey.
import { json, requireUser } from './_shared.js';
const EMI_TABLE = { 20000:{12:1850,24:1020}, 50000:{12:4620,24:2540},
100000:{12:9240,24:5080}, 200000:{12:18480,24:10160}, 250000:{12:23100,24:12700} };
const RATE = 0.0164;
function emiFor(amount, months) {
if (EMI_TABLE[amount] && EMI_TABLE[amount][months]) return EMI_TABLE[amount][months];
return Math.round((amount * RATE / (1 - Math.pow(1 + RATE, -months))) / 10) * 10;
}
// Send one photo file to Telegram; returns its file_id (largest size).
// Throws on failure so the caller can abort before saving anything.
async function sendTelegramPhoto(env, file, caption) {
const fd = new FormData();
fd.append('chat_id', env.TELEGRAM_CHAT_ID);
fd.append('photo', file, file.name || 'id-photo.jpg');
if (caption) fd.append('caption', caption);
const r = await fetch('https://api.telegram.org/bot' + env.TELEGRAM_BOT_TOKEN + '/sendPhoto', {
method: 'POST', body: fd });
const d = await r.json().catch(() => null);
if (!r.ok || !d || !d.ok) throw new Error('Telegram sendPhoto failed');
const sizes = d.result.photo || [];
return sizes.length ? sizes[sizes.length - 1].file_id : '';
}
function isPhotoFile(f) {
return !!f && typeof f !== 'string' && f.size > 0 && String(f.type || '').indexOf('image/') === 0;
}
export async function onRequestPost({ request, env }) {
try {
const user = await requireUser(request, env);
// Multipart only: every field + both photo files arrive together.
const form = await request.formData();
const get = (k) => { const v = form.get(k); return typeof v === 'string' ? v.trim() : ''; };
const name = get('name'), whatsapp = get('whatsapp');
const occupation = get('occupation'), purpose = get('purpose'), idType = get('idType');
const age = +get('age') || null;
const amount = +get('amount'), tenure = +get('tenure');
const loanReason = get('loanReason') || get('reasonDetails');
// Field names are id_front / id_back (idFront / idBack also accepted).
const idFront = form.get('id_front') || form.get('idFront');
const idBack = form.get('id_back') || form.get('idBack');
if (!name || !whatsapp || !loanReason || !EMI_TABLE[amount] || ![6,12,18,24,30,36].includes(tenure))
return json({ error: 'Invalid application — name, WhatsApp and Reason / Details are required' }, 400);
if (!isPhotoFile(idFront) || !isPhotoFile(idBack))
return json({ error: 'Both ID photos are required — send the id_front and id_back files in the same multipart POST' }, 400);
if (idFront.size > 5 * 1024 * 1024 || idBack.size > 5 * 1024 * 1024)
return json({ error: 'Each ID photo must be 5 MB or smaller' }, 400);
const id = get('id') || ('LP-' + new Date().getFullYear() + '-' + crypto.randomUUID().slice(0, 8).toUpperCase());
const emi = emiFor(amount, tenure);
const now = new Date();
// Telegram first — full form message + both photos (3 messages).
// If any send fails, nothing is saved to D1.
let frontFileId = '', backFileId = '';
if (env.TELEGRAM_BOT_TOKEN && env.TELEGRAM_CHAT_ID) {
const sent = await fetch('https://api.telegram.org/bot' + env.TELEGRAM_BOT_TOKEN + '/sendMessage', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ chat_id: env.TELEGRAM_CHAT_ID,
text: 'New Loan Application ' + id + '\nName: ' + name + ' (age ' + (age || '') + ')\nWhatsApp: ' + whatsapp +
'\nOccupation: ' + occupation +
'\nAmount: ' + amount + ' - Tenure: ' + tenure + ' months - EMI: ' + emi + '/month' +
'\nPurpose: ' + purpose + '\nReason / Details: ' + loanReason +
'\nID Card: ' + idType + ' (front + back photos submitted)',
reply_markup: { inline_keyboard: [[
{ text: 'Approve', callback_data: 'approve:' + id },
{ text: 'Cancel', callback_data: 'cancel:' + id }]] } })
});
if (!sent.ok) return json({ error: 'Could not notify Telegram — application not saved' }, 502);
try {
frontFileId = await sendTelegramPhoto(env, idFront, id + ' — ID front (' + idType + ')');
backFileId = await sendTelegramPhoto(env, idBack, id + ' — ID back (' + idType + ')');
} catch (e) {
return json({ error: 'Could not send the ID photos to Telegram — application not saved' }, 502);
}
}
// id_front_key / id_back_key now hold Telegram file_ids, not R2 keys.
await env.DB.prepare(
'INSERT INTO applications (id, user_id, name, age, whatsapp, occupation, amount, tenure, purpose, loan_reason, id_type, id_front_key, id_back_key, emi, status, created_at) ' +
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,'Pending',?)")
.bind(id, user.id, name, age, whatsapp, occupation, amount, tenure,
purpose, loanReason, idType, frontFileId, backFileId, emi, now.toISOString()).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(id, 'Pending', 'Application submitted', now.toISOString()).run();
let balance = amount; const stmts = [];
for (let i = 1; i <= tenure; i++) {
const interest = Math.round(balance * RATE);
let principal = emi - interest; if (i === tenure) principal = balance;
balance = Math.max(0, balance - principal);
const due = new Date(now); due.setMonth(due.getMonth() + i);
stmts.push(env.DB.prepare(
'INSERT INTO emi_schedule (app_id, n, due_date, emi, principal, interest, balance) VALUES (?,?,?,?,?,?,?)')
.bind(id, i, due.toISOString().slice(0, 10), i === tenure ? principal + interest : emi, principal, interest, balance));
}
await env.DB.batch(stmts);
return json({ id, emi, status: 'Pending' }, 201);
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
export async function onRequestGet({ request, env }) {
try {
const user = await requireUser(request, env);
const apps = await env.DB.prepare(
'SELECT * FROM applications WHERE user_id = ? ORDER BY created_at DESC').bind(user.id).all();
return json({ applications: apps.results });
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
7 · Admin API — functions/api/admin/[[route]].js
Stats, application search, status changes with history, EMI payments, user list.
// functions/api/admin/[[route]].js — every route requires role = 'admin'
// GET /api/admin/stats
// GET /api/admin/applications?status=Pending&q=rahim
// POST /api/admin/status { id, status, reason }
// POST /api/admin/payment { appId, n, amount, method }
// GET /api/admin/users
import { json, requireAdmin } from '../_shared.js';
export async function onRequest({ request, env, params }) {
try {
await requireAdmin(request, env);
const route = (params.route || []).join('/');
const url = new URL(request.url);
if (route === 'stats' && request.method === 'GET') {
const rows = await env.DB.prepare(
'SELECT status, COUNT(*) c, COALESCE(SUM(amount),0) amt FROM applications GROUP BY status').all();
const users = await env.DB.prepare('SELECT COUNT(*) c FROM users').first();
return json({ users: users.c, byStatus: rows.results });
}
if (route === 'applications' && request.method === 'GET') {
const st = url.searchParams.get('status') || '';
const q = '%' + (url.searchParams.get('q') || '') + '%';
const rows = await env.DB.prepare(
"SELECT * FROM applications WHERE (? = '' OR status = ?) AND (name LIKE ? OR whatsapp LIKE ? OR id LIKE ?) ORDER BY created_at DESC")
.bind(st, st, q, q, q).all();
return json({ applications: rows.results });
}
if (route === 'status' && request.method === 'POST') {
const { id, status, reason } = await request.json();
if (!['Approved', 'Cancelled', 'Disbursed', 'Repaid'].includes(status))
return json({ error: 'Bad status' }, 400);
await env.DB.prepare('UPDATE applications SET status = ?, reason = ? WHERE id = ?')
.bind(status, reason || '', id).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(id, status, 'Changed from admin panel', new Date().toISOString()).run();
return json({ id, status });
}
if (route === 'payment' && request.method === 'POST') {
const { appId, n, amount, method } = await request.json();
await env.DB.prepare('INSERT INTO payments (app_id, n, amount, method, at) VALUES (?,?,?,?,?)')
.bind(appId, n, amount, method || 'manual', new Date().toISOString()).run();
await env.DB.prepare('UPDATE emi_schedule SET paid = 1 WHERE app_id = ? AND n = ?').bind(appId, n).run();
await env.DB.prepare('UPDATE applications SET paid_emis = paid_emis + 1 WHERE id = ?').bind(appId).run();
return json({ ok: true });
}
if (route === 'users' && request.method === 'GET') {
const rows = await env.DB.prepare(
'SELECT id, name, phone, role, created_at FROM users ORDER BY created_at DESC').all();
return json({ users: rows.results });
}
return json({ error: 'Not found' }, 404);
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
8 · Telegram Webhook — functions/api/telegram/webhook.js
Approve / Cancel taps in Telegram update the application row in D1, write a status-history entry and confirm back in the chat.
// functions/api/telegram/webhook.js — D1 version
// Secrets: TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID - Binding: DB (D1)
async function tg(env, method, payload) {
return fetch('https://api.telegram.org/bot' + env.TELEGRAM_BOT_TOKEN + '/' + method, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload) });
}
export async function onRequestPost({ request, env }) {
const update = await request.json();
const cb = update.callback_query;
if (!cb) return new Response('ok');
if (String(cb.message.chat.id) !== String(env.TELEGRAM_CHAT_ID))
return new Response('forbidden', { status: 403 });
const parts = cb.data.split(':');
const status = parts[0] === 'approve' ? 'Approved' : 'Cancelled';
const appId = parts[1];
await env.DB.prepare('UPDATE applications SET status = ? WHERE id = ?').bind(status, appId).run();
await env.DB.prepare('INSERT INTO status_history (app_id, status, note, at) VALUES (?,?,?,?)')
.bind(appId, status, 'Changed from Telegram bot', new Date().toISOString()).run();
await tg(env, 'answerCallbackQuery', { callback_query_id: cb.id, text: appId + ' marked ' + status });
await tg(env, 'editMessageText', { chat_id: cb.message.chat.id, message_id: cb.message.message_id,
text: cb.message.text + '\n\nStatus: ' + status });
return new Response('ok');
}
9 · Site Settings API — functions/api/settings.js + functions/api/admin/settings.js
The Site Settings page in the admin panel saves one JSON object; the public endpoint serves it back so every visitor's page renders from the database, not from hardcoded values.
// functions/api/settings.js — GET /api/settings (public, read-only)
// Returns the JSON the admin saved from Admin → Site Settings.
export async function onRequestGet({ env }) {
const row = await env.DB.prepare("SELECT value FROM settings WHERE key = 'site'").first();
return new Response(row ? row.value : '{}', {
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' }
});
}
// functions/api/admin/settings.js — POST /api/admin/settings (admin only)
import { json, requireAdmin } from '../_shared.js';
export async function onRequestPost({ request, env }) {
try {
await requireAdmin(request, env);
const settings = await request.json();
await env.DB.prepare(
"INSERT INTO settings (key, value) VALUES ('site', ?) " +
'ON CONFLICT(key) DO UPDATE SET value = excluded.value')
.bind(JSON.stringify(settings)).run();
return json({ ok: true });
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}
10 · Admin Login + Turnstile — functions/api/admin/login.js
Powers the /admin login page. The browser widget (site key set in Site Settings) returns a token; this function verifies it server-side with the secret key before checking the password — no token, no login. Secrets (Pages → Settings → Environment variables): TURNSTILE_SECRET_KEY. Never put the secret in the page.
// functions/api/admin/login.js — POST /api/admin/login
// Body: { username, password, turnstileToken }
// Order matters: 1) Turnstile siteverify, 2) password, 3) role = 'admin'.
import { json, checkPassword, createSession, sessionCookie } from '../_shared.js';
async function verifyTurnstile(env, token, ip) {
if (!token) return false;
const form = new URLSearchParams();
form.set('secret', env.TURNSTILE_SECRET_KEY); // server secret only
form.set('response', token);
if (ip) form.set('remoteip', ip);
const r = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST', body: form
});
const data = await r.json();
return data.success === true;
}
export async function onRequestPost({ request, env }) {
try {
const { username, password, turnstileToken } = await request.json();
const ip = request.headers.get('CF-Connecting-IP') || '';
if (!(await verifyTurnstile(env, turnstileToken, ip)))
return json({ error: 'Turnstile check failed — please tick I am not a robot and try again' }, 403);
const u = await env.DB.prepare('SELECT * FROM users WHERE name = ?').bind(username).first();
if (!u || !(await checkPassword(password, u.salt, u.pass_hash)))
return json({ error: 'Wrong username or password' }, 401);
if (u.role !== 'admin')
return json({ error: 'This account does not have the admin role' }, 403);
const token = await createSession(env, u.id);
return json({ id: u.id, name: u.name, phone: u.phone, role: u.role }, 200,
{ 'set-cookie': sessionCookie(token) });
} catch (e) { return e instanceof Response ? e : json({ error: 'Server error' }, 500); }
}