All files / src/modules/analytics analytics.processor.ts

100% Statements 18/18
75% Branches 3/4
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3712x   12x 12x           12x 1x 1x     1x 1x 1x 1x 1x   1x 1x 2x           2x                
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
 
interface DailyPayload { day: string }
 
@Processor('analytics:daily')
@Injectable()
export class AnalyticsDailyProcessor extends WorkerHost {
  private readonly logger = new Logger(AnalyticsDailyProcessor.name);
  constructor(private readonly prisma: PrismaService) { super(); }
 
  async process(job: Job<DailyPayload>): Promise<void> {
    const day = new Date(job.data.day);
    const start = new Date(day);
    start.setHours(0,0,0,0);
    const end = new Date(start);
    end.setDate(end.getDate() + 1);
 
    const agents = await this.prisma.client.user.findMany({ where: { role: { in: ['AGENT', 'AGENCY_OWNER', 'REALTOR_PRO'] } }, select: { id: true } });
    for (const a of agents) {
      const [published, archived, inquiries, leads] = await Promise.all([
        this.prisma.client.listing.count({ where: { userId: a.id, createdAt: { gte: start, lt: end } } }),
        this.prisma.client.listing.count({ where: { userId: a.id, status: 'ARCHIVED', updatedAt: { gte: start, lt: end } } }),
        this.prisma.client.listingInquiry.count({ where: { listing: { userId: a.id }, createdAt: { gte: start, lt: end } } } as any),
        this.prisma.client.lead.count({ where: { agentId: a.id, createdAt: { gte: start, lt: end } } } as any),
      ]);
      await this.prisma.client.dailyAgentStats.upsert({
        where: { agentId_day: { agentId: a.id, day: start } } as any,
        update: { listingsPublished: published, listingsArchived: archived, inquiriesReceived: inquiries, leadsCreated: leads },
        create: { agentId: a.id, day: start, listingsPublished: published, listingsArchived: archived, inquiriesReceived: inquiries, leadsCreated: leads },
      } as any);
    }
  }
}