diff --git a/src/modules/payments/cron/payments.cron.ts b/src/modules/payments/cron/payments.cron.ts new file mode 100644 index 0000000..e573b54 --- /dev/null +++ b/src/modules/payments/cron/payments.cron.ts @@ -0,0 +1,37 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Cron } from '@nestjs/schedule'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Payment } from '../entities/payment.entity'; +import { In, Repository } from 'typeorm'; +import { PaymentStatusEnum } from '../enumns/payment-status.enum'; +import { ProcessPaymentService } from '../services/process-payment.service'; + +@Injectable() +export class PaymentsCron { + private readonly logger = new Logger(PaymentsCron.name); + + constructor( + @InjectRepository(Payment) + private readonly paymentRepository: Repository, + private processPaymentService: ProcessPaymentService, + ) {} + + @Cron('*/10 * * * * *') + async handleCron() { + const payments = await this.paymentRepository.find({ + where: { + status: In([PaymentStatusEnum.RETRY, PaymentStatusEnum.PROCESSING]), + }, + }); + + this.logger.debug( + `Found ${payments.length} payments in processing or retry status`, + ); + + if (payments.length > 0) { + for (const payment of payments) { + await this.processPaymentService.execute(payment.id); + } + } + } +}