11import { db , bills , transactions } from '@/db' ;
22import { RecurrenceService } from '@/lib/services/RecurrenceService' ;
3- import { eq , and , lte } from 'drizzle-orm' ;
3+ import { eq , and , lte , ne } from 'drizzle-orm' ;
44import { endOfDay } from 'date-fns' ;
55
66/**
@@ -33,7 +33,7 @@ export const AutoPayService = {
3333 *
3434 * Eligibility Criteria:
3535 * - isAutoPay = true
36- * - status = 'pending ' (not already paid/ overdue from manual action )
36+ * - status ! = 'paid ' (pending or overdue - handles backlog after checkDailyBills )
3737 * - dueDate <= end of today (due date has arrived or passed)
3838 * - isArchived = false
3939 *
@@ -48,14 +48,17 @@ export const AutoPayService = {
4848 async processAutoPay ( ) : Promise < AutoPayResult > {
4949 const today = endOfDay ( new Date ( ) ) ;
5050
51- // Query all pending auto-pay bills that are due today or earlier
51+ // Query all unpaid auto-pay bills that are due today or earlier
52+ // Uses ne(status, 'paid') instead of eq(status, 'pending') to handle backlog:
53+ // checkDailyBills() runs at 00:00 and may mark old bills as 'overdue'
54+ // before auto-pay runs at 00:05. We still want to process those.
5255 const eligibleBills = await db
5356 . select ( )
5457 . from ( bills )
5558 . where (
5659 and (
5760 eq ( bills . isAutoPay , true ) ,
58- eq ( bills . status , 'pending ' ) ,
61+ ne ( bills . status , 'paid ' ) ,
5962 lte ( bills . dueDate , today ) ,
6063 eq ( bills . isArchived , false )
6164 )
0 commit comments