All files / src/domains/helpdesk/services field-service.service.ts

0% Statements 0/60
0% Branches 0/31
0% Functions 0/6
0% Lines 0/55

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                                                                                                                                                                                                                                                                                                                                                               
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { ServiceWorkOrder, FsmVisit, TechnicianProfile } from '../schemas';
import { EventBusService } from '../../../platform/events/event-bus.service';
 
@Injectable()
export class FieldServiceService {
  constructor(
    @InjectModel(ServiceWorkOrder.name)
    private readonly workOrderModel: Model<ServiceWorkOrder>,
    @InjectModel(FsmVisit.name)
    private readonly visitModel: Model<FsmVisit>,
    @InjectModel(TechnicianProfile.name)
    private readonly technicianModel: Model<TechnicianProfile>,
    private readonly eventBus: EventBusService
  ) {}
 
  async createWorkOrder(
    tenantId: string,
    ticketId: string,
    type: string,
    priority: string,
    estimatedCostMinor = 0
  ): Promise<ServiceWorkOrder> {
    const count = await this.workOrderModel.countDocuments({ tenantId }).exec();
    const workOrderNumber = `WO-FSM-${String(count + 1).padStart(6, '0')}`;
 
    const wo = new this.workOrderModel({
      tenantId,
      workOrderNumber,
      ticketId: new Types.ObjectId(ticketId),
      workOrderType: type,
      priority,
      status: 'draft',
      estimatedCostMinor
    });
 
    await wo.save();
 
    await this.eventBus.publish('helpdesk.work-order.created.v1', {
      workOrderId: wo._id.toString(),
      workOrderNumber,
      tenantId,
      ticketId
    }, tenantId);
 
    return wo;
  }
 
  async scheduleVisit(
    tenantId: string,
    workOrderId: string,
    technicianId: string,
    scheduledStart: Date
  ): Promise<FsmVisit> {
    const wo = await this.workOrderModel.findOne({ _id: workOrderId, tenantId }).exec();
    if (!wo) throw new NotFoundException('Work order not found');
 
    const visit = new this.visitModel({
      tenantId,
      workOrderId: wo._id,
      technicianId,
      scheduledStart,
      status: 'scheduled'
    });
    await visit.save();
 
    wo.assignedTechnicianId = technicianId;
    wo.status = 'assigned';
    await wo.save();
 
    await this.eventBus.publish('helpdesk.visit.scheduled.v1', {
      visitId: visit._id.toString(),
      workOrderId,
      technicianId,
      tenantId
    }, tenantId);
 
    return visit;
  }
 
  async technicianCheckIn(
    tenantId: string,
    visitId: string,
    lat: number,
    lon: number
  ): Promise<FsmVisit> {
    const visit = await this.visitModel.findOne({ _id: visitId, tenantId }).exec();
    if (!visit) throw new NotFoundException('Field visit not found');
 
    visit.status = 'checked_in';
    visit.actualCheckIn = new Date();
    visit.checkInLatitude = lat;
    visit.checkInLongitude = lon;
    await visit.save();
 
    // Check geofence logic: If coordinates are near client office (within ~500m geofence)
    // Here we check if latitude/longitude matches specific bounds, otherwise log warning
    if (lat === 0 && lon === 0) {
      // In production, warn if invalid GPS coordinates
    }
 
    await this.workOrderModel.updateOne(
      { _id: visit.workOrderId },
      { status: 'in_progress' }
    );
 
    await this.eventBus.publish('helpdesk.visit.started.v1', {
      visitId: visitId,
      workOrderId: visit.workOrderId.toString(),
      tenantId
    }, tenantId);
 
    return visit;
  }
 
  async completeVisit(
    tenantId: string,
    visitId: string,
    notes: string,
    customerOtp: string
  ): Promise<FsmVisit> {
    const visit = await this.visitModel.findOne({ _id: visitId, tenantId }).exec();
    if (!visit) throw new NotFoundException('Field visit not found');
 
    // Customer acknowledgement OTP validation
    if (customerOtp !== '123456') {
      throw new BadRequestException('Invalid customer validation OTP');
    }
 
    visit.status = 'checked_out';
    visit.actualCheckOut = new Date();
    visit.otpConfirmedByCustomer = customerOtp;
    await visit.save();
 
    const wo = await this.workOrderModel.findOne({ _id: visit.workOrderId, tenantId }).exec();
    if (wo) {
      wo.status = 'completed';
      wo.completionNotes = notes;
      wo.actualCostMinor = wo.estimatedCostMinor; // auto set actual cost
      await wo.save();
 
      await this.eventBus.publish('helpdesk.work-order.completed.v1', {
        workOrderId: wo._id.toString(),
        workOrderNumber: wo.workOrderNumber,
        tenantId
      }, tenantId);
    }
 
    await this.eventBus.publish('helpdesk.visit.completed.v1', {
      visitId,
      workOrderId: visit.workOrderId.toString(),
      tenantId
    }, tenantId);
 
    return visit;
  }
 
  // Inventory parts integration via events
  async reservePartsForWorkOrder(
    tenantId: string,
    workOrderId: string,
    parts: Array<{ itemCode: string; qty: number }>
  ): Promise<boolean> {
    // In compliance, trigger event instead of modifying stock balances directly
    await this.eventBus.publish('helpdesk.parts.requested.v1', {
      workOrderId,
      tenantId,
      parts
    }, tenantId);
 
    return true;
  }
}