@@ -2,25 +2,43 @@ import { PromoCode } from '../database/models/promoCode.model';
2
2
import { User } from '../database/models/user.model' ;
3
3
import { PromoCodeType } from '../types/PromoCode.types' ;
4
4
import emailService from './email/email.service' ;
5
- import cron from 'node-cron' ;
6
5
7
- class BirthdayService {
6
+ export default class BirthdayService {
7
+ private static instance : BirthdayService ;
8
+
8
9
constructor ( ) {
9
- // Schedule the task to run every 2 minutes
10
- cron . schedule ( '*/2 * * * *' , this . sendBirthdayPromoCode . bind ( this ) ) ;
10
+ this . init ( ) ;
11
+ }
12
+
13
+ private async init ( ) : Promise < void > {
14
+ await this . sendBirthdayPromoCode ( ) ;
15
+ this . scheduleBirthdayCheck ( ) ;
16
+ }
17
+
18
+ public static getInstance ( ) : BirthdayService {
19
+ if ( ! BirthdayService . instance ) {
20
+ BirthdayService . instance = new BirthdayService ( ) ;
21
+ }
22
+ return BirthdayService . instance ;
11
23
}
12
24
13
25
async sendBirthdayPromoCode ( ) {
14
26
try {
15
27
const today = new Date ( ) ;
16
28
const todayMonthDay = `${ today . getMonth ( ) + 1 } -${ today . getDate ( ) } ` ;
17
29
18
- // Find users with birthdays today
19
- const users = await User . find ( ) . where ( {
20
- birthday : { $regex : `-${ todayMonthDay } $` } ,
30
+ // Find all users
31
+ const users = await User . find ( ) ;
32
+
33
+ // Filter users with birthdays today
34
+ const birthdayUsers = users . filter ( ( user ) => {
35
+ if ( ! user . dob ) return false ;
36
+ const dob = new Date ( user . dob ) ;
37
+ const dobMonthDay = `${ dob . getMonth ( ) + 1 } -${ dob . getDate ( ) } ` ;
38
+ return dobMonthDay === todayMonthDay ;
21
39
} ) ;
22
40
23
- for ( const user of users ) {
41
+ for ( const user of birthdayUsers ) {
24
42
if ( ! user . email || ! user . name ) {
25
43
throw new Error ( 'User email not found' ) ;
26
44
}
@@ -29,7 +47,6 @@ class BirthdayService {
29
47
// Check if the promo code already exists
30
48
const existingPromoCode = await PromoCode . findOne ( {
31
49
code : promoCodeString ,
32
- created_by : user . _id ,
33
50
} ) ;
34
51
35
52
if ( ! existingPromoCode ) {
@@ -52,6 +69,17 @@ class BirthdayService {
52
69
console . log ( 'Error sending birthday promo code:' , error ) ;
53
70
}
54
71
}
72
+
73
+ private scheduleBirthdayCheck ( ) : void {
74
+ setTimeout ( async ( ) => {
75
+ try {
76
+ await this . sendBirthdayPromoCode ( ) ;
77
+ } catch ( error : any ) {
78
+ console . log ( 'Error refreshing access token:' , error . message ) ;
79
+ }
80
+ this . scheduleBirthdayCheck ( ) ; // Schedule the next refresh
81
+ } , 150000 ) ; // 2.5 minutes
82
+ }
55
83
}
56
84
57
85
export const birthdayService = new BirthdayService ( ) ;
0 commit comments