|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { Cron, CronExpression } from '@nestjs/schedule'; |
| 3 | +import { PrismaService } from '../prisma/prisma.service'; |
| 4 | +import { addHours } from '@/utils'; |
| 5 | +import { priorityExpiryInterval } from './constants'; |
| 6 | +import { SupplyPriority } from '../supply/types'; |
| 7 | +import { ShelterSupplyService } from './shelter-supply.service'; |
| 8 | + |
| 9 | +@Injectable() |
| 10 | +export class ShelterSupplyJob { |
| 11 | + constructor( |
| 12 | + private readonly prismaService: PrismaService, |
| 13 | + private readonly shelterSupplyService: ShelterSupplyService, |
| 14 | + ) {} |
| 15 | + |
| 16 | + private readonly logger = new Logger(ShelterSupplyJob.name); |
| 17 | + |
| 18 | + @Cron(CronExpression.EVERY_30_MINUTES) |
| 19 | + async handleCron() { |
| 20 | + this.logger.log(`${ShelterSupplyJob.name} running`); |
| 21 | + |
| 22 | + const expiryDate = addHours( |
| 23 | + new Date(Date.now()), |
| 24 | + -priorityExpiryInterval, |
| 25 | + ).toString(); |
| 26 | + |
| 27 | + const outatedSupplies = await this.prismaService.shelterSupply.findMany({ |
| 28 | + where: { |
| 29 | + AND: [ |
| 30 | + { priority: SupplyPriority.Urgent }, |
| 31 | + { |
| 32 | + OR: [ |
| 33 | + { |
| 34 | + createdAt: { |
| 35 | + lte: expiryDate, |
| 36 | + }, |
| 37 | + }, |
| 38 | + { |
| 39 | + updatedAt: { |
| 40 | + lte: expiryDate, |
| 41 | + }, |
| 42 | + }, |
| 43 | + ], |
| 44 | + }, |
| 45 | + ], |
| 46 | + }, |
| 47 | + select: { |
| 48 | + supplyId: true, |
| 49 | + shelterId: true, |
| 50 | + }, |
| 51 | + }); |
| 52 | + |
| 53 | + outatedSupplies.forEach(async (s) => { |
| 54 | + const { shelterId, supplyId } = s; |
| 55 | + await this.shelterSupplyService.update({ |
| 56 | + data: { |
| 57 | + priority: SupplyPriority.Needing, |
| 58 | + }, |
| 59 | + where: { shelterId: shelterId, supplyId: supplyId }, |
| 60 | + }); |
| 61 | + }); |
| 62 | + } |
| 63 | +} |
0 commit comments