refactor: streamline user payment retrieval by utilizing a subquery for latest active payments
This commit is contained in:
parent
0be53d3251
commit
064576f48e
@ -569,19 +569,7 @@ export async function distributeCreditsToAllUsers() {
|
||||
|
||||
// Get all users with their current active payments/subscriptions in a single query
|
||||
// This uses a LEFT JOIN to get users and their latest active payment in one query
|
||||
const usersWithPayments = await db
|
||||
.select({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
priceId: payment.priceId,
|
||||
paymentStatus: payment.status,
|
||||
paymentCreatedAt: payment.createdAt,
|
||||
})
|
||||
.from(user)
|
||||
.leftJoin(
|
||||
// Subquery to get the latest active payment for each user
|
||||
db
|
||||
const latestPaymentQuery = db
|
||||
.select({
|
||||
userId: payment.userId,
|
||||
priceId: payment.priceId,
|
||||
@ -594,10 +582,23 @@ export async function distributeCreditsToAllUsers() {
|
||||
})
|
||||
.from(payment)
|
||||
.where(or(eq(payment.status, 'active'), eq(payment.status, 'trialing')))
|
||||
.as('latest_payment'),
|
||||
.as('latest_payment');
|
||||
|
||||
const usersWithPayments = await db
|
||||
.select({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
priceId: latestPaymentQuery.priceId,
|
||||
paymentStatus: latestPaymentQuery.status,
|
||||
paymentCreatedAt: latestPaymentQuery.createdAt,
|
||||
})
|
||||
.from(user)
|
||||
.leftJoin(
|
||||
latestPaymentQuery,
|
||||
and(
|
||||
eq(user.id, sql`latest_payment.user_id`),
|
||||
eq(sql`latest_payment.row_number`, 1)
|
||||
eq(user.id, latestPaymentQuery.userId),
|
||||
eq(latestPaymentQuery.rowNumber, 1)
|
||||
)
|
||||
)
|
||||
.where(or(isNull(user.banned), eq(user.banned, false)));
|
||||
|
Loading…
Reference in New Issue
Block a user