All files / middlewares userTimeTrackingValidations.js

100% Statements 63/63
100% Branches 66/66
100% Functions 11/11
100% Lines 63/63

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                      2x   2x 1x                     3x   3x       3x 2x                     2x 2x             2x 1x                     5x 5x   5x 2x           3x 3x 1x           2x 2x 1x               2x           2x 1x               3x   3x       3x 1x                 2x 1x                     3x   3x 1x         2x       2x 1x                         4x   4x 3x 1x           2x         2x 1x                         4x   4x 3x 1x           2x       2x 1x                       4x   4x 1x     3x 1x         3x 3x                             3x   3x 2x         2x           2x       1x                                                      
import { parse, isAfter, isBefore, isValid, parseISO } from 'date-fns';
 
import { models } from '../../config/database';
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
import IndirectTaskInfo from '../source/indirectTasks/information';
import ProductionOrderInfo from '../source/productionOrders/information';
import UsersInfo from '../source/users/information';
import UserTimeTrackingInfo from '../source/userTimeTracking/information';
 
async function validUserTimeTrackingId(req) {
  const userTimeTrackingId = req.body.trackingId || req.query.trackingId;
 
  if (!userTimeTrackingId) {
    throw new APIError(
      '',
      t(
        'BEE4292',
        { 0: userTimeTrackingId } /* Apontamento %{0} não encontrado */
      )
    );
  }
}
 
async function validUserTimeTracking(req) {
  const userTimeTrackingId = req.body.trackingId || req.query.trackingId;
 
  const userTimeTracking = await UserTimeTrackingInfo.getUserTimeTracking({
    id: userTimeTrackingId,
  });
 
  if (!userTimeTracking) {
    throw new APIError(
      '',
      t(
        'BEE4292',
        { 0: userTimeTrackingId } /* Apontamento %{0} não encontrado */
      )
    );
  }
}
 
async function validUserWorkShift(req) {
  const { userId } = req;
  const user = await UsersInfo.getUser(
    { id: userId },
    {
      attributes: ['id', 'login', 'workShift'],
    }
  );
 
  if (!user.workShift || user.workShift === '') {
    throw new APIError(
      '',
      t(
        'BEE4293',
        { 0: user.login } /* O usuário %{0} não possui turno de trabalho */
      )
    );
  }
}
 
function validFilterDates(req) {
  const filterStartDate = req.query.filterStartDate || req.body.filterStartDate;
  const filterEndDate = req.query.filterEndDate || req.body.filterEndDate;
 
  if (!filterStartDate || !filterEndDate) {
    throw new APIError(
      'DATE_MISSING',
      t('BEE1212' /* Não foi informada a data inicial ou final */)
    );
  }
 
  const validStartDate = isValid(parseISO(filterStartDate));
  if (!validStartDate) {
    throw new APIError(
      'INVALID_START_DATE',
      t('BEE1213' /* A data inicial informada não é válida */)
    );
  }
 
  const validEndDate = isValid(parseISO(filterEndDate));
  if (!validEndDate) {
    throw new APIError(
      'INVALID_END_DATE',
      t('BEE1214' /* A data final informada não é válida */)
    );
  }
}
 
async function validOpenUserTimeTracking(req) {
  const openUserTimeTracking = await UserTimeTrackingInfo.getUserTimeTracking({
    branchCode: req.userMainBranch,
    userId: req.userId,
    status: 1,
  });
 
  if (openUserTimeTracking) {
    throw new APIError(
      '',
      t('BEE4294' /* O usuário possui apontamento em aberto */)
    );
  }
}
 
async function validUserTimeTrackingIsOpen(req) {
  const userTimeTrackingId = req.body.trackingId || req.query.trackingId;
 
  const userTimeTracking = await UserTimeTrackingInfo.getUserTimeTracking({
    id: userTimeTrackingId,
  });
 
  if (userTimeTracking && userTimeTracking.status === 2) {
    throw new APIError(
      '',
      t(
        'BEE4296',
        { 0: userTimeTrackingId } /* O apontamento %{0} já está finalizado */
      )
    );
  }
 
  if (userTimeTracking && userTimeTracking.status === 0) {
    throw new APIError(
      '',
      t(
        'BEE4297',
        { 0: userTimeTrackingId } /* O apontamento %{0} foi eliminado */
      )
    );
  }
}
 
async function validProductionOrder(req) {
  const { productionOrderId } = req.query;
 
  if (!productionOrderId) {
    throw new APIError(
      'PRODUCTION_ORDER_REQUIRED',
      t('BEE2924' /* O código da Ordem de Produção não informado! */)
    );
  } else {
    const existProductionOrder = await ProductionOrderInfo.getProductionOrder({
      id: productionOrderId,
    });
 
    if (!existProductionOrder) {
      throw new APIError(
        t(
          'BEE2782',
          {
            0: productionOrderId,
          } /* Ordem de produção %{0} não encontrada!  */
        )
      );
    }
  }
}
 
async function validProductionOrderCode(req) {
  const { productionOrderCode, type } = req.body;
 
  if (type === 'production') {
    if (!productionOrderCode) {
      throw new APIError(
        'PRODUCTION_ORDER_REQUIRED',
        t('BEE2924' /* O código da Ordem de Produção não informado! */)
      );
    }
 
    const existProductionOrder = await ProductionOrderInfo.getProductionOrder({
      branchCode: req.userMainBranch,
      code: productionOrderCode,
    });
 
    if (!existProductionOrder) {
      throw new APIError(
        t(
          'BEE2782',
          {
            0: productionOrderCode,
          } /* Ordem de produção %{0} não encontrada!  */
        )
      );
    }
  }
}
 
async function validIndirectTaskCode(req) {
  const { indirectTaskCode, type } = req.body;
 
  if (type === 'indirect') {
    if (!indirectTaskCode) {
      throw new APIError(
        '',
        t('BEE4303' /* Código da Tarefa Indireta não informado */)
      );
    }
 
    const existIndirectTask = await IndirectTaskInfo.getIndirectTask({
      code: indirectTaskCode,
    });
 
    if (!existIndirectTask) {
      throw new APIError(
        '',
        t(
          'BEE4302',
          { 0: indirectTaskCode } /* Tarefa Indireta %{0} não encontrada! */
        )
      );
    }
  }
}
 
function validType(req) {
  const type = req.body.type || req.query.type;
 
  if (!type) {
    throw new APIError('', t('BEE2810' /* Tipo deve ser informado ! */));
  }
 
  if (type !== 'production' && type !== 'indirect') {
    throw new APIError('', t('BEE2598' /* Tipo inválido */));
  }
}
 
async function validStartUserTimeTracking(req) {
  const { userId } = req;
  const user = await UsersInfo.getUser(
    { id: userId },
    {
      attributes: ['id', 'login', 'workShift'],
      include: [
        {
          required: false,
          model: models.WorkShift,
          as: 'workShiftUser',
          attributes: ['code', 'name', 'breakStartTime', 'breakEndTime'],
        },
      ],
    }
  );
 
  const startedAt = new Date();
 
  if (user.workShiftUser) {
    const breakStartTimeDate = parse(
      user.workShiftUser.breakStartTime,
      'HH:mm:ss',
      startedAt
    );
    const breakEndTimeDate = parse(
      user.workShiftUser.breakEndTime,
      'HH:mm:ss',
      startedAt
    );
 
    if (
      isAfter(startedAt, breakStartTimeDate) &&
      isBefore(startedAt, breakEndTimeDate)
    ) {
      throw new APIError(
        '',
        t(
          'BEE4344',
          {
            0: user.login,
            1: user.workShiftUser.name,
          } /* O usuário %{0} não pode iniciar o apontamento no intervalo do turno %{1}. */
        )
      );
    }
  }
}
 
export default {
  validUserWorkShift,
  validFilterDates,
  validType,
  validUserTimeTrackingId,
  validUserTimeTracking,
  validOpenUserTimeTracking,
  validUserTimeTrackingIsOpen,
  validProductionOrder,
  validProductionOrderCode,
  validIndirectTaskCode,
  validStartUserTimeTracking,
};