All files / src/modules/quick-rent quick-rent.service.ts

14% Statements 7/50
33.33% Branches 15/45
0% Functions 0/7
12.82% Lines 5/39

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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 10111x 11x 11x 11x                       11x                                                                                                                                                                          
import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
 
interface CreateQuickRentDto {
  city: string;
  specs: Record<string, any>;
  budgetMin?: number;
  budgetMax?: number;
  moveInDate?: Date;
  bidEndsAt: Date;
}
 
@Injectable()
export class QuickRentService {
  constructor(
    private readonly prisma: PrismaService,
    @InjectQueue('quick-rent:match') private readonly matchQ: Queue,
    @InjectQueue('quick-rent:end-bid-window') private readonly endQ: Queue,
    @InjectQueue('quick-rent:reminders') private readonly remindQ: Queue,
    @InjectQueue('notifications') private readonly notificationsQ: Queue,
  ) {}
 
  async createRequest(userId: number, dto: CreateQuickRentDto) {
    Iif (dto.bidEndsAt <= new Date()) throw new BadRequestException('bidEndsAt must be in the future');
    const req = await this.prisma.client.quickRentRequest.create({
      data: {
        userId,
        city: dto.city,
        specs: dto.specs as any,
        budgetMin: dto.budgetMin ?? null,
        budgetMax: dto.budgetMax ?? null,
        moveInDate: dto.moveInDate ?? null,
        bidEndsAt: dto.bidEndsAt,
      },
    });
    await this.matchQ.add('fanout', { requestId: req.id }, { jobId: `match:${req.id}` });
    await this.endQ.add('end', { requestId: req.id }, { delay: Math.max(0, dto.bidEndsAt.getTime() - Date.now()), jobId: `end:${req.id}` });
    await this.remindQ.add('remind', { requestId: req.id }, { delay: Math.max(0, dto.bidEndsAt.getTime() - Date.now() - 2 * 60_000), jobId: `remind:${req.id}` });
    return req;
  }
 
  async getRequestForOwner(id: number, ownerId: number) {
    const req = await this.prisma.client.quickRentRequest.findUnique({ where: { id } });
    Iif (!req) throw new NotFoundException('Request not found');
    Iif (req.userId !== ownerId) throw new ForbiddenException('Forbidden');
    return req;
  }
 
  getRequestPublic(id: number) {
    return this.prisma.client.quickRentRequest.findUnique({
      where: { id },
      select: { id: true, city: true, specs: true, budgetMin: true, budgetMax: true, bidEndsAt: true, status: true },
    });
  }
 
  async placeBid(requestId: number, user: any, amountCents: number) {
    Iif (amountCents <= 0) throw new BadRequestException('amountCents must be positive');
    const req = await this.prisma.client.quickRentRequest.findUnique({ where: { id: requestId } });
    Iif (!req) throw new NotFoundException('Request not found');
    Iif (req.status !== 'OPEN' || req.bidEndsAt <= new Date()) throw new ForbiddenException('Bidding closed');
    const bid = await this.prisma.client.quickRentBid.upsert({
      where: { id: 0 },
      update: {},
      create: {
        requestId,
        bidderId: user?.id ?? null,
        agencyId: user?.agencyId ?? null,
        amountCents,
      },
    } as any);
    return bid;
  }
 
  async closeEarly(requestId: number, ownerId: number) {
    const req = await this.prisma.client.quickRentRequest.findUnique({ where: { id: requestId } });
    Iif (!req) throw new NotFoundException('Request not found');
    Iif (req.userId !== ownerId) throw new ForbiddenException('Forbidden');
    await this.prisma.client.quickRentRequest.update({ where: { id: requestId }, data: { status: 'CLOSED' } });
    return { id: requestId, status: 'CLOSED' };
  }
 
  async disputeLeadAccess(id: number, user: any, body: { reason: string }) {
    const access = await this.prisma.client.quickRentLeadAccess.findUnique({ where: { id } });
    Iif (!access) throw new NotFoundException('Lead access not found');
    // Only bidder or agency member allowed (basic check)
    Iif (access.bidderId && access.bidderId !== user.id && user.role !== 'AGENCY_OWNER') {
      throw new ForbiddenException('Forbidden');
    }
    const updated = await this.prisma.client.quickRentLeadAccess.update({
      where: { id },
      data: { disputeStatus: 'OPEN', disputeReason: body.reason },
    });
    await this.notificationsQ.add('send', { type: 'QUICK_RENT_DISPUTE_OPENED', payload: { id, reason: body.reason } });
    return updated;
  }
}