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, ) {} @Cron(CronExpression.EVERY_MINUTE) async handleCron() { 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(); 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(20, 'minutes') .format('YYYY-MM-DD HH:mm:ss'); console.log( 'Expected reset time (close_time - 20 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'); } } }