All files / middlewares serialGroupValidations.js

98.63% Statements 72/73
92.75% Branches 64/69
100% Functions 8/8
98.57% Lines 69/70

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                            5x   5x 2x               3x   3x 3x               3x 2x                 3x 1x           2x       2x   2x 2x               2x 1x           1x       14x   14x   14x 13x                                         13x 1x           12x       12x       12x 8x   12x 7x             7x   3x                                 3x       3x 1x         2x 2x   2x       1x             1x       1x   1x             1x     1x           1x 1x                                       5x             5x 1x               4x                 8x 1x       7x 3x       2x                   4x 3x                 3x               3x 2x 2x 2x         2x 1x                           4x         2x   2x         2x 1x                 1x                      
import { Op } from 'sequelize';
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
import { models, sequelize } from '../../config/database';
 
import InformationSerialGroups from '../source/serialGroup/information';
import InformationSerialLabel from '../source/serialLabel/information';
import InformationInboundOrders from '../source/inboundOrders/information';
import InformationInboundOrdersProducts from '../source/inboundOrderProducts/information';
import ProductionOrderInformation from '../source/productionOrders/information';
import OutboundOrderInformation from '../source/outboundOrders/information';
import OutboundOrderProductInformation from '../source/outboundOrderProducts/information';
 
async function validLabel(req) {
  const { label, code } = req.query;
 
  if (!label && !code) {
    throw new APIError(
      'BAD_REQUEST',
      t('BEE2982' /* Etiqueta não informada */)
    );
  }
}
 
async function validSerialGroupAndLabel(req) {
  const { label, code, depositCode } = req.query;
 
  const deposit = depositCode ? { depositCode } : {};
  let serial = await InformationSerialGroups.getSerialGroup(
    {
      code: label || code,
      ...deposit,
    },
    { userBranches: req.userBranches }
  );
 
  if (!serial) {
    serial = await InformationSerialLabel.getSerialLabel(
      {
        code: label || code,
        ...deposit,
      },
      { userBranches: req.userBranches }
    );
  }
 
  if (!serial) {
    throw new APIError(
      'BAD_REQUEST',
      t('BEE2857' /* Etiqueta não encontrada. */)
    );
  }
 
  req.serial = serial;
}
 
async function validSerialGroup(req) {
  const { code, depositCode } = req.query;
 
  const deposit = depositCode ? { depositCode } : {};
  const serial = await InformationSerialGroups.getSerialGroup(
    {
      code,
      ...deposit,
    },
    { userBranches: req.userBranches }
  );
 
  if (!serial) {
    throw new APIError(
      'BAD_REQUEST',
      t('BEE2857' /* Etiqueta não encontrada. */)
    );
  }
 
  req.serialGroup = serial;
}
 
async function validSerialGroupDocument(req) {
  const { code = '', type = '', inboundOrderId, uz } = req.query;
 
  let outboundOrder = null;
 
  if (inboundOrderId) {
    const inboundOrder = await InformationInboundOrders.getInboundOrder(
      { id: inboundOrderId },
      {
        attributes: ['id', 'accessKey'],
        include: [
          {
            required: true,
            model: models.TypeOrders,
            as: 'typeOrder',
            attributes: ['customerReturn'],
            where: {
              branchCode: {
                [Op.eq]: sequelize.col('InboundOrders.str_branch_code'),
              },
            },
          },
        ],
        order: [],
      }
    );
 
    if (!inboundOrder) {
      throw new APIError(
        'BAD_REQUEST',
        t('BEE3807' /* Documento de entrada inválido */)
      );
    }
 
    const isReturn = inboundOrder.typeOrder
      ? inboundOrder.typeOrder.customerReturn
      : false;
 
    const filterDates = {};
 
    let serial;
 
    if (type === 'check') filterDates.entranceCheckedAt = null;
    else if (type === 'store') filterDates.entranceStoredAt = null;
 
    if (isReturn) {
      serial = await InformationSerialLabel.getSerialLabel(
        {
          code,
        },
        { userBranches: req.userBranches }
      );
 
      if (type === 'check') {
        const inboundOrderProduct =
          await InformationInboundOrdersProducts.getInboundOrderProducts(
            {
              inboundOrderId,
            },
            {
              attributes: [
                'productCode',
                'quantity',
                'outboundOrderNumber',
                'outboundOrderSerie',
                'quantityCheck',
                'quantityStorage',
              ],
            }
          );
 
        const serialReturn =
          await InformationSerialLabel.getSerialLabelShipmentDocRelationship({
            code,
          });
 
        if (!serialReturn) {
          throw new APIError(
            'BAD_REQUEST',
            t('BEE2857' /* Etiqueta não encontrada. */)
          );
        } else {
          for (let i = 0; i < serialReturn.movement.length; i++) {
            const serialLabelMovement = serialReturn.movement[i];
 
            if (
              serial.depositCode !== serialLabelMovement.depositCode ||
              parseFloat(serial.quantity) > 0
            ) {
              throw new APIError(
                '',
                t('BEE3783' /* A etiqueta já foi conferida. */)
              );
            }
 
            const outboundOrderProduct =
              await OutboundOrderProductInformation.getOutboundOrderProduct({
                id: serialLabelMovement.outboundOrderProductId,
              });
 
            const isValid = inboundOrderProduct.find(
              (product) =>
                product.outboundOrderNumber ===
                  outboundOrderProduct.outboundOrder.invoiceNumber &&
                product.outboundOrderSerie ===
                  outboundOrderProduct.outboundOrder.invoiceSerie &&
                product.product.productCode === serialReturn.product.productCode
            );
 
            const { fractionalLabel } = serial.deposit;
 
            const validQuantity =
              fractionalLabel &&
              parseFloat(isValid.quantity) <
                parseFloat(serialLabelMovement.quantity)
                ? parseFloat(isValid.quantity)
                : parseFloat(serialLabelMovement.quantity);
 
            if (!isValid) {
              throw new APIError(
                '',
                t(
                  'BEE3808',
                  {
                    0: serialLabelMovement.outboundOrderNumber,
                  } /* A etiqueta não corresponde ao documento de saída %{0} referenciado na devolução. */
                )
              );
            } else E{
              serial = {
                ...serial.dataValues,
                quantity: validQuantity,
                isReturn,
              };
            }
          }
        }
      }
    } else {
      outboundOrder = await OutboundOrderInformation.getOutboundOrder(
        {
          accessKey: inboundOrder.accessKey,
        },
        { attributes: ['id', 'orderNumber', 'customerCode'] }
      );
 
      if (!outboundOrder) {
        throw new APIError(
          'BAD_REQUEST',
          t(
            'BEE3192' /* Documento de saída da Indústria não localizada! Verifique a chave de acesso do faturamento! */
          )
        );
      }
 
      serial = await InformationSerialGroups.getSerialGroup(
        {
          code,
          ...filterDates,
        },
        { userBranches: req.userBranches }
      );
    }
 
    if (!serial) {
      throw new APIError(
        'BAD_REQUEST',
        t('BEE2857' /* Etiqueta não encontrada. */)
      );
    } else if (!isReturn) {
      if (
        serial.orderNumber !== outboundOrder.orderNumber ||
        serial.supplierCode !== outboundOrder.customerCode
      ) {
        throw new APIError(
          'BAD_REQUEST',
          t(
            'BEE3193',
            {
              0: code,
            } /* A etiqueta %{0} não está prevista para este documento! */
          )
        );
      }
    } else if (type === 'store' && !!uz) {
      const query = {
        inboundOrderId,
        productCode: serial.productCode,
        [Op.and]: [
          sequelize.where(sequelize.col('productLots.int_baptism_label'), uz),
        ],
      };
 
      const InboundOrderProducts =
        await InformationInboundOrdersProducts.getInboundOrderProducts(
          {
            query,
          },
          {},
          true
        );
 
      if (InboundOrderProducts.length > 0) {
        const lotsFiltered = InboundOrderProducts.filter((product) => {
          return (
            product.productLots.filter((lot) => lot.serialGroupId === serial.id)
              .length > 0
          );
        });
 
        if (lotsFiltered.length <= 0) {
          throw new APIError(
            'BAD_REQUEST',
            t(
              'BEE3270',
              {
                0: code,
                1: uz,
              } /* A etiqueta %{0} não está prevista na UZ %{1}! */
            )
          );
        }
      }
    }
 
    req.serialGroup = serial;
  }
}
 
async function validationProductionOrder(req) {
  const { productionOrderCode } = req.body;
 
  const productionOrder = await ProductionOrderInformation.getProductionOrder({
    branchCode: req.userMainBranch,
    code: productionOrderCode,
  });
 
  if (!productionOrder) {
    throw new APIError(
      t(
        'BEE2782',
        {
          0: productionOrderCode,
        } /* Ordem de produção %{0} não encontrada!  */
      )
    );
  } else {
    req.productionOrder = productionOrder;
  }
}
 
export default {
  validLabel,
  validSerialGroup,
  validSerialGroupAndLabel,
  validSerialGroupDocument,
  validationProductionOrder,
};