import { Injectable, Logger } from '@nestjs/common'; import { Cron, CronExpression } from '@nestjs/schedule'; import { IsNull, Not } from 'typeorm'; import { BidsService } from './bids.service'; import * as moment from 'moment'; import { isTimeReached, shouldResetTool, subtractMinutes, subtractSeconds, } from '@/ultils'; import { ConfigsService } from './configs.service'; import { DashboardService } from './dashboard.service'; import { Bid } from '../entities/bid.entity'; @Injectable() export class TasksService { private readonly logger = new Logger(TasksService.name); constructor( private readonly bidsService: BidsService, private readonly configsService: ConfigsService, private readonly dashboadService: DashboardService, ) {} // - Chạy kiểm tra và lấy thời gian close của product gần với hiện tại nhất // - Nếu thỏa điều kiện sẽ reset tool trước thời gian close 20 phút @Cron(CronExpression.EVERY_MINUTE) async handleResetTool() { const bids = await this.bidsService.bidsRepo.find({ where: { status: 'biding' }, select: ['close_time', 'created_at', 'start_bid_time', 'id', 'lot_id'], }); const lastResetTimeRaw = await this.configsService.getConfig('REFRESH_TOOL_TIME'); const lastResetTime = lastResetTimeRaw?.value ? new Date(lastResetTimeRaw.value) : null; const now = new Date(); const minutesReset = 20; console.log('===== Reset Tool Check ====='); console.log( 'Last reset time:', lastResetTime ? moment(lastResetTime).format('YYYY-MM-DD HH:mm:ss') : 'null', ); console.log('Current time:', moment(now).format('YYYY-MM-DD HH:mm:ss')); const result = shouldResetTool(bids, lastResetTime, now); if (result.shouldReset) { console.log('Should reset due to:', result.reason); if (result.bidId) { console.log('Related bid id:', result.bidId); if (result.closeTime) { const closeTimeDate = new Date(result.closeTime); const expectedReset = moment(closeTimeDate) .subtract(minutesReset, 'minutes') .format('YYYY-MM-DD HH:mm:ss'); console.log( `Expected reset time (close_time - ${minutesReset} minutes):`, expectedReset, ); } } await this.dashboadService.resetTool(); await this.configsService.setConfig( 'REFRESH_TOOL_TIME', now.toISOString(), 'string', ); console.log('Tool reset at:', moment(now).format('YYYY-MM-DD HH:mm:ss')); } else { console.log('No reset needed at this time'); } } // Reset lại server. // Nếu server quá lâu không được reset sẽ đẫn đến mất kết nối với imap (không nhận được mail) //Chạy vào 12 giờ đêm mỗi ngày @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) async handleResetServer() { const processName = 'auto-bid-server'; console.log('===== Reset Server Check ====='); await this.dashboadService.resetProcessByName(processName); console.log( `Reset server at: ${moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}`, ); } }