All files / platform/modules/booking/src/Services BookingService.js

100% Statements 177/177
97.47% Branches 77/79
100% Functions 31/31
100% Lines 171/171

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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524    1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       129x                                                       129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x       18x   18x       152x 152x 152x   150x 148x 148x   144x       181x   310x 159x 159x 159x 440x 310x                         181x   159x 159x 159x     159x       174x   152x 152x   297x   297x             148x                                                                             152x 3x   149x 149x 147x   2x       299x 299x 299x 298x 298x     299x               299x       5x 5x 5x 2x           2x                       1x                   3x         3x                   14x 9x   5x 4x           4x                       2x                 1x     4x         11x 9x       6x               5x 5x   5x                         5x       2x     5x                               26x 26x 26x   26x     26x 8x 8x 18x 8x       26x   26x             26x       41x 9x   41x 41x 41x   26x             26x     2x 2x     1x 1x     8x 8x   4x 4x     41x 41x 7x         49x 49x 8x     41x       21x       2x 2x 1x     1x       1x 1x 1x 1x 1x 1x       1x 1x 1x       1x 1x       2x 2x 14x 14x 112x 16x             14x   2x       7x 6x       1x   5x 2x     4x                     32x 32x 116x 24x 24x             32x   32x 20x 20x         6x 6x 3x 3x 3x   3x 3x                   3x         6x       1x  
'use strict';
 
const _ = require('lodash');
const Moment = require('moment-timezone');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const CE = use('C2C/Exceptions');
const Config = use('Config');
const Logger = use('Logger');
const statuses = Config.get('modules.booking.general.statuses');
const notes = Config.get('modules.booking.general.notes');
const namespace = Config.get('modules.booking.general.namespace');
const TARGET_SYSTEM_STATUSES = Config.get('modules.booking.general.targetSystemStatuses');
 
class BookingService {
  static get inject() {
    return [
      'C2C/Repositories/BookingRepo',
      'C2C/Repositories/ServiceRepo',
      'C2C/Repositories/StaffRepo',
      'C2C/Repositories/CustomerRepo',
      'C2C/Repositories/OrderRepo',
      'C2C/Repositories/SalonScheduleRepo',
      'C2C/Repositories/SalonRepo',
      'C2C/Repositories/StaffScheduleRepo',
      'C2C/Repositories/SystemRepo',
      `${namespace}/Services/TargetSystemService`,
      `${namespace}/Services/OrderService`,
    ];
  }
 
  constructor(
    bookingRepo,
    serviceRepo,
    staffRepo,
    customerRepo,
    orderRepo,
    salonScheduleRepo,
    salonRepo,
    staffScheduleRepo,
    systemRepo,
    targetSystemService,
    orderService,
  ) {
    this.bookingRepo = bookingRepo;
    this.serviceRepo = serviceRepo;
    this.staffRepo = staffRepo;
    this.customerRepo = customerRepo;
    this.orderRepo = orderRepo;
    this.salonScheduleRepo = salonScheduleRepo;
    this.salonRepo = salonRepo;
    this.staffScheduleRepo = staffScheduleRepo;
    this.systemRepo = systemRepo;
    this.targetSystemService = targetSystemService;
    this._orderService = orderService;
  }
 
  async getOne(conditions) {
    const booking = await this.bookingRepo.findOne({ ...conditions });
 
    return booking;
  }
 
  async create({ services: servicesInfo, ...bookingInfo }) {
    const services = await this._getServices(servicesInfo);
    this._generateInfoByListService(bookingInfo, services);
    bookingInfo.status = this._getStatusToCreate(bookingInfo.status);
 
    const booking = await this.bookingRepo.create(bookingInfo);
    await booking.reload();
    await this._addOrdersToBooking(booking, services);
 
    return booking;
  }
 
  async _getServices(servicesInfo) {
    if (_.isEmpty(servicesInfo)) return [];
 
    const serviceIds = servicesInfo.map(({ serviceId }) => serviceId);
    const services = await this.serviceRepo.allBy({ id: ['IN', serviceIds] });
    const servicesData = services.toJSON();
    return servicesInfo.map((service) => {
      const serviceInfo = servicesData.find(({ id }) => service.serviceId === id) || service;
      return {
        serviceId: service.serviceId,
        staffId: service.staffId,
        startTime: moment(service.startTime),
        endTime: moment(service.startTime).add(_.get(serviceInfo, 'duration', 0), 'minutes'),
        duration: _.get(serviceInfo, 'duration', 0),
        price: _.get(serviceInfo, 'price', 0),
        serviceName: _.get(serviceInfo, 'name', ''),
      };
    });
  }
 
  _generateInfoByListService(bookingInfo, services) {
    if (_.isEmpty(services)) return;
 
    bookingInfo.startTime = bookingInfo.startTime || _.minBy(services, 'startTime').startTime;
    bookingInfo.totalDuration = bookingInfo.totalDuration || _.sumBy(services, 'duration');
    bookingInfo.endTime =
      bookingInfo.endTime ||
      bookingInfo.startTime.clone().add(bookingInfo.totalDuration, 'minutes');
    bookingInfo.totalPrice = bookingInfo.totalPrice || _.sumBy(services, 'price');
  }
 
  async _addOrdersToBooking(bookingInstance, services) {
    if (_.isEmpty(services)) return;
    // soft-deletes current order
    await bookingInstance.orders().delete();
    for (const service of services) {
      // always return a list of one staff if not empty
      const staffs = await this.getStaffAvailable(service);
      // add order
      await this._orderService.createOrder({
        ...service,
        bookingId: bookingInstance.id,
        staffId: staffs.first() && staffs.first().id,
      });
    }
    // hard-delete old orders
    await bookingInstance.ordersOnlyTrashed().delete({ force: true });
  }
 
  // _checkServicesTime(services) {
  //   const timeSegments = [];
  //   _.each(services, (service) => {
  //     timeSegments.push([
  //       moment(service.startTime),
  //       moment(service.startTime).add(service.duration, 'minutes'),
  //     ]);
  //   });
  //   if (this._checkOverlap(timeSegments)) {
  //     throw CE.BadRequestException.raise('Booking time overlap');
  //   }
  // }
 
  // _checkOverlap(timeSegments) {
  //   let ret = false;
  //   let i = 0;
  //   while (!ret && i < timeSegments.length - 1) {
  //     const seg1 = timeSegments[i];
  //     const seg2 = timeSegments[i + 1];
  //     const range1 = moment.range(
  //       moment(seg1[0], 'HH:mm'),
  //       moment(seg1[1], 'HH:mm'),
  //     );
  //     const range2 = moment.range(
  //       moment(seg2[0], 'HH:mm'),
  //       moment(seg2[1], 'HH:mm'),
  //     );
  //     if (range1.overlaps(range2)) {
  //       ret = true;
  //     }
  //     i++;
  //   }
  //   return ret;
  // }
 
  _getStatusToCreate(status) {
    if (!Number.isInteger(status)) {
      return statuses.new;
    }
    const checkResult = _.includes([statuses.new, statuses.arrived, statuses.started], status);
    if (checkResult) {
      return status;
    }
    throw CE.BadRequestException.raise('errors.invalidStatus');
  }
 
  async getStaffAvailable({ serviceId, startTime = moment(), staffId, userId }) {
    const start = moment(startTime);
    let end = moment(startTime);
    if (serviceId) {
      const service = await this.serviceRepo.findOrFail(serviceId);
      end = moment(startTime).add(service.duration, 'minutes');
    }
 
    const staff = await this.staffRepo.getByService({
      serviceId: serviceId,
      startTime: start,
      endTime: end,
      staffId,
      userId,
    });
 
    return staff;
  }
 
  async cancelBookingFromCB(booking, { timezone, reasonObject, ...data }) {
    const status = statuses.cancel;
    this._checkStatusToUpdate(status, booking.status);
    if (booking.systemId) {
      const system = await this.systemRepo.findOrFail(booking.systemId);
      const {
        targetSystemStatus,
        fee,
        extraInfo,
        charge,
      } = await this.sendBookingInfoToTargetSystem({
        system,
        bookingId: booking.id,
        data: {
          ...data,
          status,
          bookingId: booking.id,
          sourceId: booking.sourceId,
          reason: reasonObject.name,
          isCharged: reasonObject.isCharged,
        },
      });
      return this.handleCancelBookingFromTargetSystem(booking, {
        ...data,
        fee,
        targetSystemStatus,
        reason: reasonObject.name,
        extraInfo,
        charge,
      });
    } else {
      // apply cancellation policy
      const fee = await this.calulateFeeBaseOnCancellationPolicy({
        policy: booking.cancellationPolicy,
        date: booking.startTime,
        timezone,
      });
      return this.update(booking, {
        ...data,
        fee,
        status,
        reason: reasonObject.name,
      });
    }
  }
 
  async updateBookingFromCB(booking, { status, ...data }) {
    this._checkStatusToUpdate(status, booking.status);
    if (booking.systemId) {
      // just allow update status of booking which created from target system
      if (status && booking.status !== status) {
        const system = await this.systemRepo.findOrFail(booking.systemId);
        const {
          targetSystemStatus,
          finalPrice,
          additionalPrice,
          extraInfo,
        } = await this.sendBookingInfoToTargetSystem({
          system,
          bookingId: booking.id,
          data: {
            status,
            bookingId: booking.id,
            sourceId: booking.sourceId,
            finalPrice: data.finalPrice,
            changePriceReason: data.changePriceReason,
            extraInfo: data.extraInfo,
          },
        });
        return this.update(booking, {
          status,
          targetSystemStatus,
          finalPrice,
          additionalPrice,
          changePriceReason: data.changePriceReason,
          extraInfo,
        });
      }
      throw CE.BadRequestException.raise('errors.dontAllow');
    } else {
      // allow update more info of booking which created from CB
      return this.update(booking, { ...data, status });
    }
  }
 
  async updateBookingFromTargetSystem(booking, bookingInfo) {
    this._checkStatusToUpdate(bookingInfo.status, booking.status);
    return this.update(booking, bookingInfo);
  }
 
  async sendBookingInfoToTargetSystem({ system, bookingId, data }) {
    return this.targetSystemService.requestToUpdateBooking({
      systemId: system.id,
      bookingId: bookingId,
      body: { ...data },
    });
  }
 
  handleCancelBookingFromTargetSystem(booking, data) {
    this._checkStatusToUpdate(statuses.cancel, booking.status);
    const { fee, reason, extraReason, targetSystemStatus, charge } = data;
 
    const updateData = {
      status: statuses.cancel,
      fee,
      reason,
      extraReason,
      targetSystemStatus,
      charge,
    };
 
    // SB-629, NFB-1133
    // Cancels a booking in case: change date or import (re-sync) => unset sourceId to ignore sync canceled booking to CS.
    // CS side won't see CANCELED status, only see CHANGED status after NL makes a new booking with the same sourceId (NL bookingId) later.
    // Note: targetSystemStatus = PERMANENT_DELETED now only used for case import (re-sync). It will be wrong if it is used in case really delete that booking.
    if (
      targetSystemStatus === TARGET_SYSTEM_STATUSES.CHANGE_DATE_CANCEL ||
      targetSystemStatus === TARGET_SYSTEM_STATUSES.PERMANENT_DELETED
    ) {
      updateData.sourceId = null;
    }
 
    return this.update(booking, updateData);
  }
 
  async update(
    booking,
    {
      services: servicesInfo,
      fee,
      charge,
      targetSystemStatus,
      canPayment,
      changeDateReason,
      changePriceReason,
      ...bookingInfo
    },
  ) {
    const services = await this._getServices(servicesInfo);
    this._generateInfoByListService(bookingInfo, services);
    await this._addOrdersToBooking(booking, services, false);
 
    booking.merge(bookingInfo);
 
    // charge-fee
    if (Number(fee) >= 0) {
      booking.cancellationFee = Number(fee);
      booking.charge = charge || Math.round(booking.totalPrice * Number(fee));
    } else if (bookingInfo.status === statuses.done) {
      booking.charge = charge || booking.finalPrice;
    }
 
    // save booking
    await booking.save();
    // sync notes
    await this.syncNotes(booking, {
      targetSystemStatus,
      canPayment,
      changeDateReason,
      changePriceReason,
    });
 
    return booking;
  }
 
  _checkStatusToUpdate(newStatus, status) {
    if (!Number.isInteger(newStatus)) {
      newStatus = status;
    }
    let checkResult = false;
    let validStatuses = [];
    switch (status) {
      case statuses.new:
        validStatuses = [
          statuses.new,
          statuses.cancel,
          statuses.arrived,
          statuses.started,
          statuses.done,
        ];
        break;
 
      case statuses.arrived:
        validStatuses = [statuses.arrived, statuses.cancel, statuses.started, statuses.done];
        break;
 
      case statuses.started:
        validStatuses = [statuses.started, statuses.cancel, statuses.done];
        break;
 
      case statuses.cancel:
        validStatuses = [statuses.cancel];
        break;
      case statuses.done:
        validStatuses = [statuses.done, statuses.cancel];
        break;
    }
 
    checkResult = _.includes(validStatuses, newStatus);
    if (!checkResult) {
      throw CE.BadRequestException.raise('errors.invalidStatus');
    }
  }
 
  async getOneOrFail(conditions) {
    const booking = await this.bookingRepo.findOne({ ...conditions });
    if (!booking) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
 
    return booking;
  }
 
  getByPage(params, includes = {}) {
    return this.bookingRepo.getPages(params, includes);
  }
 
  async getDetails(conditions) {
    const booking = await this.bookingRepo.findOne({ ...conditions });
    if (!booking) {
      throw CE.NotFoundException.raise('errors.notFound');
    }
 
    return booking;
  }
 
  async getOutsideBookingsBySalon(params, includes = {}) {
    const salon = await this.salonRepo.findOrFail(params.salonId);
    params.timezone = salon.timezone;
    const result = await this.salonScheduleRepo.getDataBySalonId(params.salonId);
    params.schedules = this.groupSchedulesByDayOfWeek(result.toJSON(), params.timezone);
    params.startTime = moment();
    return this.bookingRepo.getBookingsOutRangeDate(params, includes);
  }
 
  async getOutsideBookingsByStaff(params, includes = {}) {
    const salon = await this.salonRepo.findOrFail(params.salonId);
    params.timezone = salon.timezone;
    const result = await this.staffScheduleRepo.find({
      staffId: params.staffId,
      endSchedule: ['NULL'],
    });
    params.schedules = this.groupSchedulesByDayOfWeek(result.toJSON(), params.timezone);
    return this.bookingRepo.getBookingsOutRangeDate(params, includes);
  }
 
  groupSchedulesByDayOfWeek(schedules, timezone) {
    const schedulesByDayOfWeek = [];
    for (let i = 0; i <= 6; i++) {
      const data = [];
      schedules.forEach((item) => {
        if (item.dayOfWeek === i) {
          data.push({
            dayOfWeek: item.dayOfWeek,
            startAt: moment(item.startAt),
            endAt: moment(item.endAt),
          });
        }
      });
      schedulesByDayOfWeek[i] = data;
    }
    return schedulesByDayOfWeek;
  }
 
  calulateFeeBaseOnCancellationPolicy({ policy, date, timezone }) {
    if (policy) {
      if (
        policy.before1Day &&
        moment(date).tz(timezone).subtract(1, 'days').isSame(moment().tz(timezone), 'day')
      ) {
        return policy.before1Day;
      }
      if (policy.onDay && moment(date).tz(timezone).isSame(moment().tz(timezone), 'day')) {
        return policy.onDay;
      }
    }
    return 0;
  }
 
  /**
   * sync booking notes
   *
   * @param {Booking} bookingInstance The booking instance
   * @param {Array<{[key]: String}>}
   */
  async syncNotes(bookingInstance, notesData) {
    // generate
    const bookingNotes = [];
    _.forEach({ ...notesData }, function (value, key) {
      if (value !== undefined) {
        const noteValue = _.get(notes, key);
        bookingNotes.push({
          type: noteValue.type,
          format: noteValue.format,
          value: JSON.stringify(value),
        });
      }
    });
    Logger.info(`BookingSerivce -> syncNotes generate: ${JSON.stringify({ bookingNotes })}`);
    // update
    if (bookingNotes.length) {
      await bookingInstance.notes().whereIn('type', _.map(bookingNotes, 'type')).delete();
      await bookingInstance.notes().createMany(bookingNotes);
    }
  }
 
  async updateBookingServices(booking, { status, services, changeDateReason }) {
    this._checkStatusToUpdate(status, booking.status);
    if (booking.systemId) {
      services = await this._getServices(services);
      const bookingInfo = {};
      this._generateInfoByListService(bookingInfo, services);
      // send request to target system handle
      const system = await this.systemRepo.findOrFail(booking.systemId);
      await this.targetSystemService.requestChangeBookingDate({
        systemId: system.id,
        bookingId: booking.id,
        body: {
          bookingDate: bookingInfo.startTime.toISOString(),
          changeDateReason: changeDateReason,
          sourceId: booking.sourceId,
        },
      });
    } else {
      await this.update(booking, { services, changeDateReason });
    }
  }
 
  updateMany(conditions, data) {
    return this.bookingRepo.update(conditions, data);
  }
}
 
module.exports = BookingService;