All files / visitor visitor.service.ts

95.29% Statements 81/85
75% Branches 54/72
85.71% Functions 12/14
94.93% Lines 75/79

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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 2701x 1x 1x 1x                     1x     1x     9x   9x   9x   9x   9x   9x   9x   9x   9x 9x         7x 7x 7x     7x         1x 1x               1x 1x                 1x                   1x       2x 2x           2x   1x           1x                   6x 6x   6x     6x 6x 5x 1x       4x 4x 1x   3x 3x 2x 1x       1x                   1x           1x       2x 2x           2x   1x           1x         1x 1x         1x           1x                                     2x 2x     2x 2x 1x       1x   1x               1x           1x         1x 1x             1x 1x                     1x 1x 1x 1x   1x                
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import {
  VisitorConfiguration,
  VisitorProfile,
  VisitorAppointment,
  VisitorCheckIn,
  VisitorGatePass,
  VisitorParkingSlot,
  VisitorParkingReservation,
  VisitorFacilityLocation,
  VisitorFacilityRoom
} from './schemas';
import { EventBusService } from '../../platform/events/event-bus.service';
 
@Injectable()
export class VisitorService {
  constructor(
    @InjectModel(VisitorConfiguration.name)
    private readonly configModel: Model<VisitorConfiguration>,
    @InjectModel(VisitorProfile.name)
    private readonly profileModel: Model<VisitorProfile>,
    @InjectModel(VisitorAppointment.name)
    private readonly appointmentModel: Model<VisitorAppointment>,
    @InjectModel(VisitorCheckIn.name)
    private readonly checkInModel: Model<VisitorCheckIn>,
    @InjectModel(VisitorGatePass.name)
    private readonly gatePassModel: Model<VisitorGatePass>,
    @InjectModel(VisitorParkingSlot.name)
    private readonly parkingSlotModel: Model<VisitorParkingSlot>,
    @InjectModel(VisitorParkingReservation.name)
    private readonly reservationModel: Model<VisitorParkingReservation>,
    @InjectModel(VisitorFacilityLocation.name)
    private readonly locationModel: Model<VisitorFacilityLocation>,
    @InjectModel(VisitorFacilityRoom.name)
    private readonly roomModel: Model<VisitorFacilityRoom>,
    private readonly eventBus: EventBusService
  ) {}
 
  // 1. Configuration
  async getConfiguration(tenantId: string): Promise<VisitorConfiguration> {
    const tenantObjId = new Types.ObjectId(tenantId);
    let config = await this.configModel.findOne({ tenantId: tenantObjId }).exec();
    Iif (!config) {
      config = await this.configModel.create({ tenantId: tenantObjId });
    }
    return config;
  }
 
  // 2. Profiles management
  async createProfile(tenantId: string, data: any): Promise<VisitorProfile> {
    const tenantObjId = new Types.ObjectId(tenantId);
    return this.profileModel.create({
      tenantId: tenantObjId,
      ...data
    });
  }
 
  // 3. Appointments & pre-approvals
  async createAppointment(tenantId: string, data: any): Promise<VisitorAppointment> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const appointment = await this.appointmentModel.create({
      tenantId: tenantObjId,
      visitorProfileId: new Types.ObjectId(data.visitorProfileId),
      hostEmployeeId: new Types.ObjectId(data.hostEmployeeId),
      appointmentDate: new Date(data.appointmentDate),
      purposeOfVisit: data.purposeOfVisit || '',
      status: 'pending'
    });
 
    await this.eventBus.publish(
      'visitor.invited.v1',
      {
        appointmentId: appointment._id.toString(),
        hostEmployeeId: data.hostEmployeeId,
        visitorProfileId: data.visitorProfileId
      },
      tenantId
    );
 
    return appointment;
  }
 
  async approveAppointment(tenantId: string, appointmentId: string): Promise<VisitorAppointment> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const app = await this.appointmentModel.findOneAndUpdate(
      { _id: new Types.ObjectId(appointmentId), tenantId: tenantObjId },
      { status: 'approved' },
      { new: true }
    ).exec();
 
    if (!app) throw new NotFoundException('Appointment not found');
 
    await this.eventBus.publish(
      'visitor.approved.v1',
      { appointmentId },
      tenantId
    );
 
    return app;
  }
 
  // 4. Check-in & approvals safety checks
  async checkInVisitor(
    tenantId: string,
    profileId: string,
    appointmentId?: string,
    ndaStorageKey?: string
  ): Promise<VisitorCheckIn> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const profObjId = new Types.ObjectId(profileId);
 
    const config = await this.getConfiguration(tenantId);
 
    // Watchlist check
    const profile = await this.profileModel.findOne({ _id: profObjId, tenantId: tenantObjId }).exec();
    if (!profile) throw new NotFoundException('Visitor profile not found');
    if (profile.isBlacklisted) {
      throw new BadRequestException(`Check-in blocked: visitor is blacklisted. Reason: ${profile.blacklistReason}`);
    }
 
    // Pre-approval check
    Eif (config.preApprovalRequired) {
      if (!appointmentId) {
        throw new BadRequestException('Check-in blocked: pre-approval is required but no appointment ID provided.');
      }
      const app = await this.appointmentModel.findOne({ _id: new Types.ObjectId(appointmentId), tenantId: tenantObjId }).exec();
      if (!app) throw new NotFoundException('Associated appointment invitation not found');
      if (app.status !== 'approved') {
        throw new BadRequestException(`Check-in blocked: appointment status is '${app.status}', expected 'approved'.`);
      }
    }
 
    const checkIn = await this.checkInModel.create({
      tenantId: tenantObjId,
      visitorProfileId: profObjId,
      appointmentId: appointmentId ? new Types.ObjectId(appointmentId) : undefined,
      checkInTime: new Date(),
      qrTokenKey: `qr_${tenantId}_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
      status: 'checked-in',
      ndaStorageKey
    });
 
    await this.eventBus.publish(
      'visitor.checkedin.v1',
      { checkInId: checkIn._id.toString(), qrTokenKey: checkIn.qrTokenKey },
      tenantId
    );
 
    return checkIn;
  }
 
  async checkOutVisitor(tenantId: string, checkInId: string): Promise<VisitorCheckIn> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const checkIn = await this.checkInModel.findOneAndUpdate(
      { _id: new Types.ObjectId(checkInId), tenantId: tenantObjId, status: 'checked-in' },
      { status: 'checked-out', checkOutTime: new Date() },
      { new: true }
    ).exec();
 
    if (!checkIn) throw new NotFoundException('Active check-in record not found');
 
    await this.eventBus.publish(
      'visitor.checkedout.v1',
      { checkInId },
      tenantId
    );
 
    return checkIn;
  }
 
  // 5. Gate Pass
  async createGatePass(tenantId: string, data: any): Promise<VisitorGatePass> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const pass = await this.gatePassModel.create({
      tenantId: tenantObjId,
      ...data
    });
 
    await this.eventBus.publish(
      'visitor.gatepass.created.v1',
      { gatePassId: pass._id.toString(), type: pass.gatePassType },
      tenantId
    );
 
    return pass;
  }
 
  // 6. Parking allotment & check
  async createParkingSlot(tenantId: string, data: any): Promise<VisitorParkingSlot> {
    const tenantObjId = new Types.ObjectId(tenantId);
    return this.parkingSlotModel.create({
      tenantId: tenantObjId,
      ...data
    });
  }
 
  async reserveParking(
    tenantId: string,
    reservationDate: string,
    vehicleType: string,
    registrationNumber: string,
    profileId?: string
  ): Promise<VisitorParkingReservation> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const resDate = new Date(reservationDate);
 
    // Look for available slots matching type
    const slots = await this.parkingSlotModel.find({ tenantId: tenantObjId, vehicleType, isAvailable: true }).exec();
    if (slots.length === 0) {
      throw new BadRequestException(`No parking slots available for vehicle type: ${vehicleType}`);
    }
 
    // Allocate first available slot
    const slot = slots[0];
 
    const reservation = await this.reservationModel.create({
      tenantId: tenantObjId,
      slotId: slot._id,
      visitorProfileId: profileId ? new Types.ObjectId(profileId) : undefined,
      reservationDate: resDate,
      vehicleRegistrationNumber: registrationNumber
    });
 
    await this.eventBus.publish(
      'visitor.parking.assigned.v1',
      { reservationId: reservation._id.toString(), slotNumber: slot.slotNumber },
      tenantId
    );
 
    return reservation;
  }
 
  // 7. Facility
  async createLocation(tenantId: string, data: any): Promise<VisitorFacilityLocation> {
    const tenantObjId = new Types.ObjectId(tenantId);
    return this.locationModel.create({
      tenantId: tenantObjId,
      ...data
    });
  }
 
  async createFacilityRoom(tenantId: string, data: any): Promise<VisitorFacilityRoom> {
    const tenantObjId = new Types.ObjectId(tenantId);
    return this.roomModel.create({
      tenantId: tenantObjId,
      locationId: new Types.ObjectId(data.locationId),
      roomName: data.roomName,
      roomType: data.roomType,
      associatedAssetIds: (data.associatedAssetIds || []).map((id: string) => new Types.ObjectId(id))
    });
  }
 
  // 8. Analytics
  async getAnalyticsMetrics(tenantId: string): Promise<any> {
    const tenantObjId = new Types.ObjectId(tenantId);
    const totalCheckins = await this.checkInModel.countDocuments({ tenantId: tenantObjId }).exec();
    const activeCheckins = await this.checkInModel.countDocuments({ tenantId: tenantObjId, status: 'checked-in' }).exec();
    const totalAppointments = await this.appointmentModel.countDocuments({ tenantId: tenantObjId }).exec();
 
    return {
      totalCheckins,
      activeCheckins,
      totalAppointments,
      occupancyRatePercentage: activeCheckins > 0 ? Math.round((activeCheckins / (totalCheckins || 1)) * 100) : 0
    };
  }
}