All files / platform/modules/staff/src/Controllers/Http SystemStaffScheduleController.js

100% Statements 65/65
100% Branches 6/6
100% Functions 6/6
100% Lines 65/65

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    1x   1x 1x 1x       14x                                   14x 14x 14x 14x 14x 14x                                                                                   5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x   5x         5x                         5x 5x                                                                             7x 7x   7x 7x       6x 6x 6x 1x     5x 5x 5x 5x 4x   5x 6x 6x 6x           6x           6x   6x 6x 1x     5x                           4x 4x 4x         4x   1x     3x                                                                         2x   2x             1x   1x 1x 1x   1x         1x 1x       1x  
'use strict';
 
const moment = require('moment-timezone');
 
const configs = use('Config').get('modules.staff.general');
const namespace = configs.namespace;
const CE = use('C2C/Exceptions');
 
class SystemStaffScheduleController {
  static get inject() {
    return [
      `${namespace}/Services/StaffService`,
      `${namespace}/Services/SalonService`,
      `${namespace}/Services/SystemService`,
      `${namespace}/Services/SettingService`,
      'C2C/Services/QueueService',
      `C2C/Services/SalonService`,
    ];
  }
 
  constructor(
    staffService,
    salonService,
    systemService,
    settingService,
    queueService,
    sharedSalonService,
  ) {
    this.staffService = staffService;
    this.salonService = salonService;
    this.systemService = systemService;
    this.settingService = settingService;
    this.queue = queueService;
    this.sharedSalonService = sharedSalonService;
  }
 
  /**
   * @swagger
   *
   * /api/v1/apps/{appId}/salons/{salonId}/staff/schedules:
   *   get:
   *     tags:
   *       - staff
   *     operationId: 'getStaffScheduleBySystem'
   *     summary: 'getStaffScheduleBySystem'
   *     description: 'get all schedule of staff by system'
   *     parameters:
   *       - $ref: '#/components/parameters/AppIdParam'
   *       - $ref: '#/components/parameters/SalonIdParam'
   *       - $ref: '#/components/parameters/PageParam'
   *       - $ref: '#/components/parameters/LimitParam'
   *       - $ref: '#/components/parameters/ActiveParam'
   *       - $ref: '#/components/parameters/SortParam'
   *       - $ref: '#/components/parameters/FromParam'
   *       - $ref: '#/components/parameters/ToParam'
   *       - $ref: '#/components/parameters/ConnectionStatusParam'
   *       - $ref: '#/components/parameters/TypeParam'
   *       - $ref: '#/components/parameters/IdsParam'
   *     responses:
   *       200:
   *         description: |-
   *           A pagination object contain array of schedules
   *         content:
   *           application/json; charset=utf-8:
   *             schema:
   *               $ref: '#/components/schemas/StaffSchedulePaginationResponse'
   *       401:
   *         $ref: '#/components/responses/Unauthorized'
   *       404:
   *         $ref: '#/components/responses/NotFound'
   *     deprecated: false
   *     security:
   *      - BasicAuth: []
   */
  async index({ request, params, response, transform }) {
    const page = request.input('page', 1);
    const limit = request.input('limit', 20);
    const sort = request.input('sort', 'createdAt desc');
    const active = request.input('active');
    const from = request.input('from');
    const to = request.input('to');
    const connectionStatus = request.input('connectionStatus');
    const type = request.input('type', 0);
    const ids = request.input('ids');
 
    const systemId = params.appId;
    const salonId = params.salonId;
 
    const [, salon] = await Promise.all([
      this.systemService.findOrFail(systemId),
      this.salonService.findOrFail(salonId, { systemId }),
    ]);
 
    const staffWithSchedule = await this.staffService.findByPageWithSchedule({
      userId: salon.operatorId,
      page: Number(page),
      limit: Number(limit),
      sort,
      active,
      from,
      to,
      connectionStatus,
      type,
      ids,
    });
 
    const data = await transform.paginate(staffWithSchedule, 'StaffScheduleTransformer');
    return response.success(data);
  }
 
  /**
   * @swagger
   *
   * /api/v1/apps/{appId}/staff/{staffId}/schedules:
   *   put:
   *     tags:
   *       - staff
   *     operationId: 'updateStaffScheduleBySystem'
   *     summary: 'updateStaffScheduleBySystem'
   *     parameters:
   *       - $ref: '#/components/parameters/AppIdParam'
   *       - $ref: '#/components/parameters/StaffIdParam'
   *     requestBody:
   *       content:
   *         application/json:
   *           schema:
   *             $ref: '#/components/schemas/StaffScheduleBody'
   *     responses:
   *       200:
   *         description: |-
   *           success
   *         content:
   *           application/json; charset=utf-8:
   *             schema:
   *               $ref: '#/components/schemas/ApiResponse'
   *       401:
   *         $ref: '#/components/responses/Unauthorized'
   *       404:
   *         $ref: '#/components/responses/NotFound'
   *       422:
   *         $ref: '#/components/responses/BadData'
   *     deprecated: false
   *     security:
   *      - BearerAuth: []
   */
  async update({ request, params, response }) {
    const { schedules } = request.all();
    const systemId = params.appId;
 
    const system = await this.systemService.findOrFail(systemId);
    const staff = await this.staffService.findOneOrFail({
      id: params.id,
    });
 
    const salon = await this.salonService.findOrFail(staff.salonId);
    const isLocked = await this.sharedSalonService.checkLockSchedule({ salon, staff });
    if (isLocked) {
      throw CE.ForbiddenException.raise('errors.scheduleLocked');
    }
 
    const timezone = salon.timezone;
    const applyingDateSetting = await this.systemService.getApplyingDateForStaffSchedule(system);
    const applyingDate = moment().tz(timezone).add(applyingDateSetting, 'days');
    if (applyingDateSetting > 0) {
      applyingDate.startOf('day');
    }
    const schedulesData = schedules.map((schedule) => {
      const startAtOfSchedule = moment(schedule.startAt).tz(timezone);
      const endAtOfSchedule = moment(schedule.endAt).tz(timezone);
      const startAt = applyingDate.clone().set({
        hours: startAtOfSchedule.hour(),
        minutes: startAtOfSchedule.minute(),
        seconds: startAtOfSchedule.second(),
        milliseconds: startAtOfSchedule.millisecond(),
      });
      const endAt = applyingDate.clone().set({
        hours: endAtOfSchedule.hour(),
        minutes: endAtOfSchedule.minute(),
        seconds: endAtOfSchedule.second(),
        milliseconds: endAtOfSchedule.millisecond(),
      });
      const weekOfYear = startAt.clone().week();
 
      const isGreaterTime = endAt.isSameOrAfter(startAt);
      if (!isGreaterTime) {
        throw CE.BadRequestException.raise('errors.invalidWorkingTime');
      }
 
      return {
        staffId: staff.id,
        salonId: salon.id,
        dayOfWeek: schedule.dayOfWeek,
        weekOfYear: weekOfYear,
        startAt: startAt.clone(),
        endAt: endAt.clone(),
        startSchedule: applyingDate,
        endSchedule: null,
        isRepeat: 1,
      };
    });
 
    // execute job to create new booking
    const Job = use(`${namespace}/Jobs/UpdateStaffSchedule`);
    try {
      const job = await this.queue.add(Job.key, {
        conditions: { staffId: staff.id, salonId: salon.id },
        schedulesData,
        timezone,
      });
      await job.finished();
    } catch ({ message }) {
      throw CE.BadRequestException.raise(message);
    }
 
    return response.success({});
  }
 
  /**
   * @swagger
   *
   * /api/v1/apps/{appId}/staff/{staffId}/schedules:
   *   get:
   *     tags:
   *       - staff
   *     operationId: 'getSystemCurrentScheduleByStaff'
   *     summary: 'getSystemCurrentScheduleByStaff'
   *     parameters:
   *       - $ref: '#/components/parameters/AppIdParam'
   *       - $ref: '#/components/parameters/StaffIdParam'
   *       - $ref: '#/components/parameters/DateParam'
   *     responses:
   *       200:
   *         description: |-
   *           success
   *         content:
   *           application/json; charset=utf-8:
   *             schema:
   *               $ref: '#/components/schemas/StaffCurrentScheduleResponse'
   *       401:
   *         $ref: '#/components/responses/Unauthorized'
   *       403:
   *         $ref: '#/components/responses/Forbidden'
   *       404:
   *         $ref: '#/components/responses/NotFound'
   *       422:
   *         $ref: '#/components/responses/BadData'
   *     deprecated: false
   *     security:
   *      - BasicAuth: []
   */
  async show({ request, params, response, transform, system }) {
    const systemId = params.appId;
 
    const [, staff] = await Promise.all([
      this.systemService.findOrFail(systemId),
      this.staffService.findOneOrFail({
        id: params.id,
      }),
    ]);
 
    const salon = await this.salonService.findOrFail(staff.salonId);
 
    const timezone = salon.timezone;
    let date = request.input('date', moment());
    date = moment(date).tz(timezone).startOf('day');
 
    const schedules = await this.staffService.findSchedulesOfAStaffOnADate({
      staffId: staff.id,
      date,
    });
 
    const data = await transform.collection(schedules, 'ScheduleTransformer');
    return response.success(data);
  }
}
 
module.exports = SystemStaffScheduleController;