All files / platform/modules/salon/src/Services SalonService.js

96% Statements 120/125
93.94% Branches 31/33
84.85% Functions 28/33
95.93% Lines 118/123

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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401    1x 1x 1x 1x   1x 1x 1x 1x           1x 1x 1x 1x       177x                                         177x 177x 177x 177x 177x 177x 177x                         3x                     3x                             2x         2x       31x 25x 25x 5x     20x       30x 30x 4x     26x       47x 8x         34x 16x     32x         32x 1x     31x               6x 8x 8x 8x 2x     6x             2x     4x               2x             2x 14x 10x                 2x   2x       6x 4x 4x 2x       2x       2x 2x       4x               2x     1x 1x       7x   7x                                       1x       2x       2x 2x 2x 1x   1x 1x 1x       2x 2x       3x       2x       2x 2x               2x 1x   1x       17x                 2x 2x 2x 1x       1x   1x               2x                 2x 2x     2x   2x                 1x 1x 1x       1x 1x   1x   1x             4x 4x   1x 1x         3x       3x 1x     2x 2x 2x     2x         2x                 1x  
'use strict';
 
const _ = require('lodash');
const Moment = require('moment-timezone');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
 
const Config = use('Config');
const CE = use('C2C/Exceptions');
const Event = use('Event');
const { CREATE_ACTION, UPDATE_ACTION } = Config.get('core.shared.constants');
const {
  SALON_STAFF_CONNECTED_THIRD_PARTY,
  SALON_STAFF_DISCONNECTED_THIRD_PARTY,
  SALON_CONNECTED_THIRD_PARTY,
  SALON_DISCONNECTED_THIRD_PARTY,
} = Config.get('modules.salon.constants');
const namespace = Config.get('modules.salon.general.namespace');
const connectionStatuses = Config.get('modules.staff.general.connectionStatuses');
const defaultDateObject = Config.get('core.shared.general.defaultDateObject');
 
class SalonService {
  static get inject() {
    return [
      'C2C/Repositories/SalonRepo',
      'C2C/Repositories/SalonScheduleRepo',
      'C2C/Repositories/SalonPhotoRepo',
      'C2C/Repositories/SalonPropertyRepo',
      `C2C/Repositories/SettingRepo`,
      `${namespace}/UseCases/CreateAuthAccount`,
      `${namespace}/UseCases/HandleAuthAccountCreatedError`,
      'C2C/Repositories/ThirdPartyStaffRepo',
    ];
  }
 
  constructor(
    salonRepo,
    salonScheduleRepo,
    salonPhotoRepo,
    salonPropertyRepo,
    settingRepo,
    createAuthAccountUseCase,
    handleAuthAccountCreatedErrorUseCase,
  ) {
    this.salonRepo = salonRepo;
    this.salonScheduleRepo = salonScheduleRepo;
    this.salonPhotoRepo = salonPhotoRepo;
    this.salonPropertyRepo = salonPropertyRepo;
    this.settingRepo = settingRepo;
    this._handleAuthAccountCreatedErrorUseCase = handleAuthAccountCreatedErrorUseCase;
    this._createAuthAccountUseCase = createAuthAccountUseCase;
  }
 
  async createWithAuth({
    email,
    phoneNumber,
    businessName,
    salonType,
    password,
    verified,
    systemId,
    listEmail,
  }) {
    let salon = await this.salonRepo.create({
      operatorEmail: email,
      operatorPhoneNumber: phoneNumber,
      businessName,
      salonType,
      verified: !!verified,
      systemId,
      listEmail,
      action: CREATE_ACTION,
    });
 
    const signUpResult = await this._createAuthAccountUseCase.execute({
      email: email,
      password: password,
      connection: Config.get('auth0.connection'),
      email_verified: !!verified,
      user_metadata: {
        phone_number: phoneNumber,
        business_name: businessName,
        verified: !!verified,
        logged_in: false,
        salon_id: salon.id,
        salon_type: salonType,
      },
    });
 
    salon = await this.salonRepo.update({
      conditions: { id: salon.id },
      payload: { operatorId: signUpResult.userId },
    });
 
    return salon;
  }
 
  async findOrFail(id, user) {
    this._canAcessSalon(id, user);
    const salon = await this.salonRepo.findOne({ id });
    if (!salon) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
 
    return salon;
  }
 
  async findByOrFail(conditions) {
    const salon = await this.salonRepo.findOne(conditions);
    if (!salon) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
 
    return salon;
  }
 
  _canAcessSalon(id, user) {
    if (_.get(user, 'userMetadata.salonId') !== id) {
      throw CE.ForbiddenException.raise('errors.salonForbidden');
    }
  }
 
  async update(conditions, payload, user) {
    if (user) {
      this._canAcessSalon(conditions.id, user);
    }
 
    const salon = await this.salonRepo.update({
      conditions: { ...conditions },
      payload: { ...payload, action: UPDATE_ACTION },
    });
 
    if (!salon) {
      throw CE.NotFoundException.raise('errors.salonUpdateNotFound');
    }
 
    return salon;
  }
 
  /**
   * @param {Object} conditions
   * @param {Array<{dayOfWeek: Integer, startAt: String, endAt: String}>} schedules
   */
  async updateSchedules(conditions, schedules) {
    schedules = schedules.map((value, index) => {
      const { salonId, dayOfWeek, startAt, endAt } = value;
      const isGreater = startAt.isSameOrBefore(endAt);
      if (!isGreater) {
        throw CE.BadRequestException.raise('errors.invalidWorkingTime');
      }
 
      if (
        this._checkOverlap({
          checkedSchedule: value,
          nextIndex: index + 1,
          schedules,
        })
      ) {
        throw CE.BadRequestException.raise('errors.invalidWorkingTime');
      }
 
      return {
        salonId: salonId,
        dayOfWeek,
        startAt: startAt,
        endAt: endAt,
      };
    });
 
    const defaultDate = moment().set({
      ...defaultDateObject,
      hour: 0,
      minute: 0,
      second: 0,
      millisecond: 0,
    });
    for (let i = 0; i <= 6; i++) {
      if (_.find(schedules, { dayOfWeek: i }) === undefined) {
        schedules.push({
          dayOfWeek: i,
          salonId: conditions.salonId,
          startAt: defaultDate.clone(),
          endAt: defaultDate.clone(),
        });
      }
    }
 
    await this.salonScheduleRepo.deleteMany({ ...conditions });
 
    return this.salonScheduleRepo.createMany(schedules);
  }
 
  _checkOverlap({ checkedSchedule, nextIndex, schedules }) {
    for (let i = nextIndex; i < schedules.length; i++) {
      const nextSchedule = schedules[i];
      if (checkedSchedule.dayOfWeek === nextSchedule.dayOfWeek) {
        const range1 = moment.range(
          moment(checkedSchedule.startAt, 'HH:mm'),
          moment(checkedSchedule.endAt, 'HH:mm'),
        );
        const range2 = moment.range(
          moment(nextSchedule.startAt, 'HH:mm'),
          moment(nextSchedule.endAt, 'HH:mm'),
        );
        Eif (range1.overlaps(range2)) {
          return true;
        }
      }
    }
    return false;
  }
 
  async loadRelated(salonInstance) {
    await salonInstance.loadMany(['schedules', 'photos', 'properties']);
  }
 
  async findSalonIncludeScheduleOrFail(salonId) {
    const salon = await this.salonRepo.findOrFail(salonId, {
      schedules: null,
    });
    salon.scheduleObjetcs = await salon.schedules().fetch();
    return salon;
  }
 
  async updatePhotos(conditions, photos) {
    await this.salonPhotoRepo.deleteMany({ ...conditions });
 
    return this.salonPhotoRepo.createMany(photos);
  }
 
  countPhotosForCleanUp() {
    return this.salonPhotoRepo.countPhotosForCleanUp();
  }
 
  getPhotosForCleanUp(limit) {
    return this.salonPhotoRepo.getPhotosForCleanUp(limit);
  }
 
  getPhotosByListUrls(urls) {
    return this.salonPhotoRepo.getPhotosByListUrls(urls);
  }
 
  forceDeletePhotos(urls) {
    return this.salonPhotoRepo.forceDelete(urls);
  }
 
  getAllProperties(conditions) {
    return this.salonPropertyRepo.find({ ...conditions }, 'order asc,createdAt asc');
  }
 
  updateProperties(salonInstance, propertyIds) {
    return this.salonRepo.sync(salonInstance, 'properties', propertyIds);
  }
 
  async setCancellationPolicy({ policyCode, salon }) {
    const settings = await this.settingRepo.getCancellationPolicy();
    const policy = _.find(settings, { name: policyCode });
    if (!policy) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
    salon.cancellationPolicy = policyCode;
    await salon.save();
    return policy;
  }
 
  async updateSurveyResult(salonInstance, surveyResults) {
    await salonInstance.surveyResults().delete();
    return salonInstance.surveyResults().createMany(surveyResults);
  }
 
  getSurveyResults(salonInstance) {
    return salonInstance.surveyResults().fetch();
  }
 
  async findWithTotalStaffOrFail(id, systemId) {
    const salon = await this.salonRepo
      .make()
      .where({ id, systemId })
      .withCount('staffs', (builder) => {
        builder.whereHas('connections', (child) => {
          child.where({
            systemId,
            salonId: id,
            status: connectionStatuses.approved,
          });
        });
      })
      .first();
    if (!salon) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
    return salon;
  }
 
  paginateWithTotalStaff(whereClause, page, limit, includes = {}) {
    return this.salonRepo.paginateWithTotalStaff(
      { ...whereClause, connectionStatus: connectionStatuses.approved },
      page,
      limit,
      includes,
    );
  }
 
  async setAcceptBookingTime({ system, minimum, maximum, salon }) {
    const minimumValues = _.get(system.settings, 'acceptBookingTime.minimumValues');
    const maximumValues = _.get(system.settings, 'acceptBookingTime.maximumValues');
    if (_.find(minimumValues, { value: minimum }) && _.find(maximumValues, { value: maximum })) {
      salon.acceptBookingTime = JSON.stringify({
        minimum,
        maximum,
      });
      await salon.save();
    } else {
      throw CE.NotFoundException.raise('errors.invalidParam');
    }
  }
 
  /**
   * @return {void}
   */
  async handleAuthAccountCreatedError(payload) {
    await this._handleAuthAccountCreatedErrorUseCase.execute(payload);
  }
 
  /**
   * Connect salon to third party
   *
   * @return {void}
   */
  async connectSalonToThirdParty(salon, thirdParty, token) {
    await salon.thirdParties().attach([thirdParty.id], (row) => {
      row.token = token;
    });
    // emit event connected
    Event.fire(SALON_CONNECTED_THIRD_PARTY, { salon, thirdParty, token });
    // to trigger sync data to target system
    await salon.save();
  }
 
  /**
   * Disconnect salon to third party
   *
   * @return {void}
   */
  async disconnectSalonToThirdParty(salon, thirdParty) {
    await salon.thirdParties().detach([thirdParty.id]);
    const staffsConnected = await salon.thirdPartyStaffs().fetch();
    Event.fire(SALON_STAFF_DISCONNECTED_THIRD_PARTY, {
      salon,
      staff: staffsConnected.rows,
    });
    await salon.thirdPartyStaffs().detach();
    await salon.thirdPartySourceStaffs().where({ thirdPartyId: thirdParty.id }).delete();
    // emit event disconnected
    Event.fire(SALON_DISCONNECTED_THIRD_PARTY, { salon, thirdParty });
    // to trigger sync data to target system
    await salon.save();
  }
 
  /**
   * @return {void}
   */
  async toggleThirdPartyStaffConnection({ salon, staff, thirdParty, thirdPartyStaff }, transform) {
    const existsConnection = await salon.thirdPartyStaffs().wherePivot('staffId', staff.id).first();
    if (existsConnection) {
      // remove connection
      await salon.thirdPartyStaffs().detach([staff.id]);
      Event.fire(SALON_STAFF_DISCONNECTED_THIRD_PARTY, {
        salon,
        staff,
      });
    } else {
      const existsConnectionBySourceId = await salon
        .thirdPartyStaffs()
        .wherePivot('sourceId', thirdPartyStaff.sourceId)
        .first();
      if (existsConnectionBySourceId) {
        throw CE.BadRequestException.raise('errors.alreadyExists');
      }
      // add connection if sourceId is not connected
      await salon.thirdPartyStaffs().attach([staff.id], (row) => {
        row.thirdPartyId = thirdParty.id;
        row.sourceId = thirdPartyStaff.sourceId;
      });
      // transform data
      const [salonTransformed, staffTransformed] = await Promise.all([
        transform.include('thirdParties').item(salon, 'SalonTransformer'),
        transform.include('thirdParties').item(staff, 'StaffTransformer'),
      ]);
      // emit event
      Event.fire(SALON_STAFF_CONNECTED_THIRD_PARTY, {
        salon: salonTransformed,
        staff: staffTransformed,
        token: _.get(salonTransformed, 'thirdParties[0].token'),
      });
    }
  }
}
 
module.exports = SalonService;