|
| 1 | +import { db, sql } from '@stacksjs/database' |
| 2 | + |
| 3 | +/** |
| 4 | + * Payment statistics response interface |
| 5 | + */ |
| 6 | +export interface PaymentStats { |
| 7 | + total_transactions: number |
| 8 | + total_revenue: number |
| 9 | + average_transaction: number |
| 10 | + successful_rate: number |
| 11 | + comparison: { |
| 12 | + transactions: { |
| 13 | + difference: number |
| 14 | + percentage: number |
| 15 | + is_increase: boolean |
| 16 | + } |
| 17 | + revenue: { |
| 18 | + difference: number |
| 19 | + percentage: number |
| 20 | + is_increase: boolean |
| 21 | + } |
| 22 | + average: { |
| 23 | + difference: number |
| 24 | + percentage: number |
| 25 | + is_increase: boolean |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Fetch payment statistics for a specific time period |
| 32 | + * |
| 33 | + * @param daysRange Number of days to look back (7, 30, 60, etc.) |
| 34 | + */ |
| 35 | +export async function fetchPaymentStats(daysRange: number = 30): Promise<PaymentStats> { |
| 36 | + const today = new Date() |
| 37 | + |
| 38 | + // Current period (last N days) |
| 39 | + const currentPeriodStart = new Date(today) |
| 40 | + currentPeriodStart.setDate(today.getDate() - daysRange) |
| 41 | + |
| 42 | + // Previous period (N days before the current period) |
| 43 | + const previousPeriodEnd = new Date(currentPeriodStart) |
| 44 | + previousPeriodEnd.setDate(previousPeriodEnd.getDate() - 1) |
| 45 | + |
| 46 | + const previousPeriodStart = new Date(previousPeriodEnd) |
| 47 | + previousPeriodStart.setDate(previousPeriodEnd.getDate() - daysRange) |
| 48 | + |
| 49 | + // Get current period stats for completed payments |
| 50 | + const currentStats = await db |
| 51 | + .selectFrom('payments') |
| 52 | + .select([ |
| 53 | + db.fn.count('id').as('transaction_count'), |
| 54 | + db.fn.sum('amount').as('total_revenue'), |
| 55 | + ]) |
| 56 | + .where('date', '>=', currentPeriodStart) |
| 57 | + .where('date', '<=', today) |
| 58 | + .where('status', '=', 'completed') |
| 59 | + .executeTakeFirst() |
| 60 | + |
| 61 | + // Get previous period stats for completed payments |
| 62 | + const previousStats = await db |
| 63 | + .selectFrom('payments') |
| 64 | + .select([ |
| 65 | + db.fn.count('id').as('transaction_count'), |
| 66 | + db.fn.sum('amount').as('total_revenue'), |
| 67 | + ]) |
| 68 | + .where('date', '>=', previousPeriodStart) |
| 69 | + .where('date', '<=', previousPeriodEnd) |
| 70 | + .where('status', '=', 'completed') |
| 71 | + .executeTakeFirst() |
| 72 | + |
| 73 | + // Get total transactions count (including non-completed ones) for calculating success rate |
| 74 | + const totalTransactions = await db |
| 75 | + .selectFrom('payments') |
| 76 | + .select(db.fn.count('id').as('count')) |
| 77 | + .where('date', '>=', currentPeriodStart) |
| 78 | + .where('date', '<=', today) |
| 79 | + .executeTakeFirst() |
| 80 | + |
| 81 | + // Calculate current period stats |
| 82 | + const currentTransactions = Number(currentStats?.transaction_count || 0) |
| 83 | + const currentRevenue = Number(currentStats?.total_revenue || 0) |
| 84 | + const currentAverage = currentTransactions > 0 ? currentRevenue / currentTransactions : 0 |
| 85 | + |
| 86 | + // Calculate previous period stats |
| 87 | + const previousTransactions = Number(previousStats?.transaction_count || 0) |
| 88 | + const previousRevenue = Number(previousStats?.total_revenue || 0) |
| 89 | + const previousAverage = previousTransactions > 0 ? previousRevenue / previousTransactions : 0 |
| 90 | + |
| 91 | + // Calculate differences |
| 92 | + const transactionDifference = currentTransactions - previousTransactions |
| 93 | + const revenueDifference = currentRevenue - previousRevenue |
| 94 | + const averageDifference = currentAverage - previousAverage |
| 95 | + |
| 96 | + // Calculate percentage changes |
| 97 | + const transactionPercentage = previousTransactions > 0 |
| 98 | + ? (transactionDifference / previousTransactions) * 100 |
| 99 | + : (currentTransactions > 0 ? 100 : 0) |
| 100 | + |
| 101 | + const revenuePercentage = previousRevenue > 0 |
| 102 | + ? (revenueDifference / previousRevenue) * 100 |
| 103 | + : (currentRevenue > 0 ? 100 : 0) |
| 104 | + |
| 105 | + const averagePercentage = previousAverage > 0 |
| 106 | + ? (averageDifference / previousAverage) * 100 |
| 107 | + : (currentAverage > 0 ? 100 : 0) |
| 108 | + |
| 109 | + // Calculate success rate |
| 110 | + const allTransactions = Number(totalTransactions?.count || 0) |
| 111 | + const successRate = allTransactions > 0 |
| 112 | + ? (currentTransactions / allTransactions) * 100 |
| 113 | + : 0 |
| 114 | + |
| 115 | + return { |
| 116 | + total_transactions: currentTransactions, |
| 117 | + total_revenue: currentRevenue, |
| 118 | + average_transaction: currentAverage, |
| 119 | + successful_rate: successRate, |
| 120 | + comparison: { |
| 121 | + transactions: { |
| 122 | + difference: transactionDifference, |
| 123 | + percentage: Math.abs(transactionPercentage), |
| 124 | + is_increase: transactionDifference >= 0, |
| 125 | + }, |
| 126 | + revenue: { |
| 127 | + difference: revenueDifference, |
| 128 | + percentage: Math.abs(revenuePercentage), |
| 129 | + is_increase: revenueDifference >= 0, |
| 130 | + }, |
| 131 | + average: { |
| 132 | + difference: averageDifference, |
| 133 | + percentage: Math.abs(averagePercentage), |
| 134 | + is_increase: averageDifference >= 0, |
| 135 | + }, |
| 136 | + }, |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +/** |
| 141 | + * Fetch payment statistics by payment method |
| 142 | + * |
| 143 | + * @param daysRange Number of days to look back |
| 144 | + */ |
| 145 | +export async function fetchPaymentStatsByMethod(daysRange: number = 30): Promise<Record<string, { |
| 146 | + count: number |
| 147 | + revenue: number |
| 148 | + percentage_of_total: number |
| 149 | +}>> { |
| 150 | + const today = new Date() |
| 151 | + const startDate = new Date(today) |
| 152 | + startDate.setDate(today.getDate() - daysRange) |
| 153 | + |
| 154 | + // Get total stats for the period |
| 155 | + const totalStats = await db |
| 156 | + .selectFrom('payments') |
| 157 | + .select([ |
| 158 | + db.fn.count('id').as('total_count'), |
| 159 | + db.fn.sum('amount').as('total_revenue'), |
| 160 | + ]) |
| 161 | + .where('date', '>=', startDate) |
| 162 | + .where('date', '<=', today) |
| 163 | + .where('status', '=', 'completed') |
| 164 | + .executeTakeFirst() |
| 165 | + |
| 166 | + const totalCount = Number(totalStats?.total_count || 0) |
| 167 | + const totalRevenue = Number(totalStats?.total_revenue || 0) |
| 168 | + |
| 169 | + // Get stats grouped by payment method |
| 170 | + const methodStats = await db |
| 171 | + .selectFrom('payments') |
| 172 | + .select([ |
| 173 | + 'method', |
| 174 | + db.fn.count('id').as('count'), |
| 175 | + db.fn.sum('amount').as('revenue'), |
| 176 | + ]) |
| 177 | + .where('date', '>=', startDate) |
| 178 | + .where('date', '<=', today) |
| 179 | + .where('status', '=', 'completed') |
| 180 | + .groupBy('method') |
| 181 | + .execute() |
| 182 | + |
| 183 | + // Format the results |
| 184 | + const result: Record<string, { |
| 185 | + count: number |
| 186 | + revenue: number |
| 187 | + percentage_of_total: number |
| 188 | + }> = {} |
| 189 | + |
| 190 | + methodStats.forEach((item) => { |
| 191 | + const count = Number(item.count || 0) |
| 192 | + const revenue = Number(item.revenue || 0) |
| 193 | + const percentageOfTotal = totalCount > 0 ? (count / totalCount) * 100 : 0 |
| 194 | + |
| 195 | + result[item.method] = { |
| 196 | + count, |
| 197 | + revenue, |
| 198 | + percentage_of_total: percentageOfTotal, |
| 199 | + } |
| 200 | + }) |
| 201 | + |
| 202 | + return result |
| 203 | +} |
| 204 | + |
| 205 | +/** |
| 206 | + * Fetch monthly payment trends for the last 12 months |
| 207 | + */ |
| 208 | +export async function fetchMonthlyPaymentTrends(): Promise<Array<{ |
| 209 | + month: string |
| 210 | + year: number |
| 211 | + transactions: number |
| 212 | + revenue: number |
| 213 | + average: number |
| 214 | +}>> { |
| 215 | + // Calculate date 12 months ago |
| 216 | + const today = new Date() |
| 217 | + const twelveMonthsAgo = new Date(today) |
| 218 | + twelveMonthsAgo.setMonth(today.getMonth() - 11) |
| 219 | + |
| 220 | + // Set to first day of that month |
| 221 | + twelveMonthsAgo.setDate(1) |
| 222 | + |
| 223 | + // Use the query builder with expressions instead of raw SQL |
| 224 | + const monthlyData = await db |
| 225 | + .selectFrom('payments') |
| 226 | + .select([ |
| 227 | + sql`EXTRACT(YEAR FROM date)`.as('year'), |
| 228 | + sql`EXTRACT(MONTH FROM date)`.as('month'), |
| 229 | + db.fn.count('id').as('transactions'), |
| 230 | + db.fn.sum('amount').as('revenue'), |
| 231 | + ]) |
| 232 | + .where('date', '>=', twelveMonthsAgo) |
| 233 | + .where('status', '=', 'completed') |
| 234 | + .groupBy(sql`year`) |
| 235 | + .groupBy(sql`month`) |
| 236 | + .orderBy('year', 'asc') |
| 237 | + .orderBy('month', 'asc') |
| 238 | + .execute() |
| 239 | + |
| 240 | + // Format the results |
| 241 | + return monthlyData.map((item) => { |
| 242 | + const transactions = Number(item.transactions || 0) |
| 243 | + const revenue = Number(item.revenue || 0) |
| 244 | + const average = transactions > 0 ? revenue / transactions : 0 |
| 245 | + |
| 246 | + // Format month name |
| 247 | + const monthDate = new Date(Number(item.year), Number(item.month) - 1, 1) |
| 248 | + const monthName = monthDate.toLocaleString('default', { month: 'short' }) |
| 249 | + |
| 250 | + return { |
| 251 | + month: monthName, |
| 252 | + year: Number(item.year), |
| 253 | + transactions, |
| 254 | + revenue, |
| 255 | + average, |
| 256 | + } |
| 257 | + }) |
| 258 | +} |
0 commit comments