|
| 1 | +const mongoose = require("mongoose"); |
| 2 | +const coursePaymentSchema = require("../schemas/coursePaymentModel"); |
| 3 | + |
| 4 | +const ALLOWED_STATUSES = new Set([ |
| 5 | + "successful", |
| 6 | + "pending", |
| 7 | + "failed", |
| 8 | +]); |
| 9 | + |
| 10 | +const ALLOWED_SORTS = new Set([ |
| 11 | + "newest", |
| 12 | + "oldest", |
| 13 | + "amount-asc", |
| 14 | + "amount-desc", |
| 15 | +]); |
| 16 | + |
| 17 | +const escapeRegex = (value = "") => |
| 18 | + value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 19 | + |
| 20 | +const parsePositiveInteger = (value, fallback, maximum) => { |
| 21 | + const parsed = Number.parseInt(value, 10); |
| 22 | + |
| 23 | + if (!Number.isFinite(parsed) || parsed < 1) { |
| 24 | + return fallback; |
| 25 | + } |
| 26 | + |
| 27 | + return Math.min(parsed, maximum); |
| 28 | +}; |
| 29 | + |
| 30 | +const parseDateBoundary = (value, endOfDay = false) => { |
| 31 | + if (!value) return null; |
| 32 | + |
| 33 | + const parsed = new Date(value); |
| 34 | + |
| 35 | + if (Number.isNaN(parsed.getTime())) { |
| 36 | + return null; |
| 37 | + } |
| 38 | + |
| 39 | + if (endOfDay && /^\d{4}-\d{2}-\d{2}$/.test(value)) { |
| 40 | + parsed.setHours(23, 59, 59, 999); |
| 41 | + } |
| 42 | + |
| 43 | + return parsed; |
| 44 | +}; |
| 45 | + |
| 46 | +const parseAmount = (value) => { |
| 47 | + if (typeof value === "number" && Number.isFinite(value)) { |
| 48 | + return value; |
| 49 | + } |
| 50 | + |
| 51 | + const parsed = Number.parseFloat( |
| 52 | + String(value || "").replace(/[^0-9.-]/g, ""), |
| 53 | + ); |
| 54 | + |
| 55 | + return Number.isFinite(parsed) ? parsed : 0; |
| 56 | +}; |
| 57 | + |
| 58 | +const normalizeStatus = (status) => { |
| 59 | + const normalized = String(status || "").trim().toLowerCase(); |
| 60 | + |
| 61 | + if ( |
| 62 | + ["success", "successful", "completed", "paid", "enrolled"].includes( |
| 63 | + normalized, |
| 64 | + ) |
| 65 | + ) { |
| 66 | + return "successful"; |
| 67 | + } |
| 68 | + |
| 69 | + if (["failed", "declined", "rejected", "cancelled"].includes(normalized)) { |
| 70 | + return "failed"; |
| 71 | + } |
| 72 | + |
| 73 | + return "pending"; |
| 74 | +}; |
| 75 | + |
| 76 | +const maskCardNumber = (cardNumber) => { |
| 77 | + const digits = String(cardNumber || "").replace(/\D/g, ""); |
| 78 | + |
| 79 | + if (digits.length < 4) { |
| 80 | + return null; |
| 81 | + } |
| 82 | + |
| 83 | + return `•••• •••• •••• ${digits.slice(-4)}`; |
| 84 | +}; |
| 85 | + |
| 86 | +const buildSanitizedPayment = (payment) => { |
| 87 | + const amount = parseAmount(payment.courseId?.C_price); |
| 88 | + const safeStatus = normalizeStatus(payment.status); |
| 89 | + |
| 90 | + return { |
| 91 | + id: String(payment._id), |
| 92 | + student: { |
| 93 | + id: payment.userId?._id ? String(payment.userId._id) : null, |
| 94 | + name: payment.userId?.name || null, |
| 95 | + email: payment.userId?.email || "Unknown", |
| 96 | + }, |
| 97 | + course: { |
| 98 | + id: payment.courseId?._id ? String(payment.courseId._id) : null, |
| 99 | + title: payment.courseId?.C_title || "Deleted or unavailable course", |
| 100 | + }, |
| 101 | + amount, |
| 102 | + currency: "INR", |
| 103 | + status: safeStatus, |
| 104 | + createdAt: payment.createdAt || null, |
| 105 | + updatedAt: payment.updatedAt || null, |
| 106 | + maskedCard: maskCardNumber(payment.cardDetails?.cardnumber), |
| 107 | + }; |
| 108 | +}; |
| 109 | + |
| 110 | +const getAdminPaymentsController = async (req, res) => { |
| 111 | + try { |
| 112 | + const page = parsePositiveInteger(req.query.page, 1, 100000); |
| 113 | + const limit = parsePositiveInteger(req.query.limit, 10, 50); |
| 114 | + const search = String(req.query.search || "").trim().slice(0, 120); |
| 115 | + const status = String(req.query.status || "").trim().toLowerCase(); |
| 116 | + const sort = String(req.query.sort || "newest").trim().toLowerCase(); |
| 117 | + |
| 118 | + if (status && !ALLOWED_STATUSES.has(status)) { |
| 119 | + return res.status(400).send({ |
| 120 | + success: false, |
| 121 | + message: "Invalid payment status filter.", |
| 122 | + }); |
| 123 | + } |
| 124 | + |
| 125 | + if (!ALLOWED_SORTS.has(sort)) { |
| 126 | + return res.status(400).send({ |
| 127 | + success: false, |
| 128 | + message: "Invalid payment sort option.", |
| 129 | + }); |
| 130 | + } |
| 131 | + |
| 132 | + const startDate = parseDateBoundary(req.query.startDate); |
| 133 | + const endDate = parseDateBoundary(req.query.endDate, true); |
| 134 | + |
| 135 | + if (req.query.startDate && !startDate) { |
| 136 | + return res.status(400).send({ |
| 137 | + success: false, |
| 138 | + message: "Invalid start date.", |
| 139 | + }); |
| 140 | + } |
| 141 | + |
| 142 | + if (req.query.endDate && !endDate) { |
| 143 | + return res.status(400).send({ |
| 144 | + success: false, |
| 145 | + message: "Invalid end date.", |
| 146 | + }); |
| 147 | + } |
| 148 | + |
| 149 | + if (startDate && endDate && startDate > endDate) { |
| 150 | + return res.status(400).send({ |
| 151 | + success: false, |
| 152 | + message: "Start date cannot be after end date.", |
| 153 | + }); |
| 154 | + } |
| 155 | + |
| 156 | + const match = {}; |
| 157 | + |
| 158 | + if (startDate || endDate) { |
| 159 | + match.createdAt = {}; |
| 160 | + if (startDate) match.createdAt.$gte = startDate; |
| 161 | + if (endDate) match.createdAt.$lte = endDate; |
| 162 | + } |
| 163 | + |
| 164 | + const records = await coursePaymentSchema |
| 165 | + .find(match) |
| 166 | + .select( |
| 167 | + "_id userId courseId status createdAt updatedAt +cardDetails.cardnumber", |
| 168 | + ) |
| 169 | + .populate("userId", "name email") |
| 170 | + .populate("courseId", "C_title C_price") |
| 171 | + .lean(); |
| 172 | + |
| 173 | + let sanitizedPayments = records.map(buildSanitizedPayment); |
| 174 | + |
| 175 | + if (search) { |
| 176 | + const safeSearch = escapeRegex(search); |
| 177 | + const searchPattern = new RegExp(safeSearch, "i"); |
| 178 | + |
| 179 | + sanitizedPayments = sanitizedPayments.filter((payment) => |
| 180 | + [ |
| 181 | + payment.id, |
| 182 | + payment.student.email, |
| 183 | + payment.student.name, |
| 184 | + payment.course.title, |
| 185 | + ].some((field) => searchPattern.test(String(field || ""))), |
| 186 | + ); |
| 187 | + } |
| 188 | + |
| 189 | + if (status) { |
| 190 | + sanitizedPayments = sanitizedPayments.filter( |
| 191 | + (payment) => payment.status === status, |
| 192 | + ); |
| 193 | + } |
| 194 | + |
| 195 | + const sorters = { |
| 196 | + newest: (a, b) => |
| 197 | + new Date(b.createdAt || 0) - new Date(a.createdAt || 0), |
| 198 | + oldest: (a, b) => |
| 199 | + new Date(a.createdAt || 0) - new Date(b.createdAt || 0), |
| 200 | + "amount-asc": (a, b) => a.amount - b.amount, |
| 201 | + "amount-desc": (a, b) => b.amount - a.amount, |
| 202 | + }; |
| 203 | + |
| 204 | + sanitizedPayments.sort(sorters[sort]); |
| 205 | + |
| 206 | + const summary = sanitizedPayments.reduce( |
| 207 | + (current, payment) => { |
| 208 | + current.totalTransactions += 1; |
| 209 | + current[payment.status] += 1; |
| 210 | + |
| 211 | + if (payment.status === "successful") { |
| 212 | + current.totalRevenue += payment.amount; |
| 213 | + } |
| 214 | + |
| 215 | + return current; |
| 216 | + }, |
| 217 | + { |
| 218 | + totalTransactions: 0, |
| 219 | + successful: 0, |
| 220 | + pending: 0, |
| 221 | + failed: 0, |
| 222 | + totalRevenue: 0, |
| 223 | + }, |
| 224 | + ); |
| 225 | + |
| 226 | + const totalItems = sanitizedPayments.length; |
| 227 | + const totalPages = Math.max(1, Math.ceil(totalItems / limit)); |
| 228 | + const safePage = Math.min(page, totalPages); |
| 229 | + const startIndex = (safePage - 1) * limit; |
| 230 | + const paginatedPayments = sanitizedPayments.slice( |
| 231 | + startIndex, |
| 232 | + startIndex + limit, |
| 233 | + ); |
| 234 | + |
| 235 | + return res.status(200).send({ |
| 236 | + success: true, |
| 237 | + data: paginatedPayments, |
| 238 | + summary, |
| 239 | + pagination: { |
| 240 | + page: safePage, |
| 241 | + limit, |
| 242 | + totalItems, |
| 243 | + totalPages, |
| 244 | + hasPreviousPage: safePage > 1, |
| 245 | + hasNextPage: safePage < totalPages, |
| 246 | + }, |
| 247 | + filters: { |
| 248 | + search, |
| 249 | + status, |
| 250 | + startDate: startDate?.toISOString() || null, |
| 251 | + endDate: endDate?.toISOString() || null, |
| 252 | + sort, |
| 253 | + }, |
| 254 | + }); |
| 255 | + } catch (error) { |
| 256 | + console.error("Unable to retrieve payment records:", error); |
| 257 | + |
| 258 | + return res.status(500).send({ |
| 259 | + success: false, |
| 260 | + message: "Unable to retrieve payment records.", |
| 261 | + }); |
| 262 | + } |
| 263 | +}; |
| 264 | + |
| 265 | +module.exports = { |
| 266 | + getAdminPaymentsController, |
| 267 | +}; |
0 commit comments