All files / middlewares serialLabelValidations.js

100% Statements 57/57
100% Branches 36/36
100% Functions 6/6
100% Lines 57/57

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                            6x   6x 1x     5x 5x       5x 1x             4x 1x                     3x       3x 1x                 2x         2x 1x                       9x   9x 49x     9x       6x   6x 6x 6x   6x 1x                   5x       5x 1x                 4x 1x                   3x         3x         3x       2x                   3x   3x       3x 1x               2x 1x                       3x   3x   3x       3x       2x       2x 1x                   4x   4x 1x     3x             3x 1x             2x       2x 1x           1x                      
/* eslint-disable no-restricted-syntax */
import { t } from '../helpers/i18n';
import APIError from '../helpers/error';
 
import BranchesInformation from '../source/branches/information';
import ProductBranchInformation from '../source/productBranches/information';
import DepositsInformation from '../source/deposits/information';
import ProductionOrderInformation from '../source/productionOrders/information';
import ProductEanInformation from '../source/productEans/information';
import SerialLabelsCtrl from '../controllers/serialLabels';
import InformationSerialLabel from '../source/serialLabel/information';
import SerialGroupInformation from '../source/serialGroup/information';
 
async function validationData(req) {
  const { serialLabels } = req.body;
 
  if (!serialLabels) {
    throw new APIError('NOT_FOUND', t('BEE1895' /* Dados não localizados */));
  }
 
  for (const serialLabel of serialLabels) {
    const branchCode = await BranchesInformation.getBranch({
      code: serialLabel.branchCode,
    });
 
    if (!branchCode) {
      throw new APIError(
        'NOT_FOUND_BRANCH',
        t(
          'BEE1170',
          { 0: serialLabel.branchCode } /* Filial %{0} não localizada */
        )
      );
    } else if (!branchCode.factoryDeposit) {
      throw new APIError(
        'NOT_DEPOSIT_FACTORY',
        t(
          'BEE2966',
          {
            0: serialLabel.branchCode,
          } /* A Filial %{0} não possui o cadastro de depósito Fábrica! */
        )
      );
    }
 
    const deposit = await DepositsInformation.getDeposit({
      code: serialLabel.depositCode,
    });
 
    if (!deposit) {
      throw new APIError(
        'NOT_FOUND_DEPOSIT',
        t(
          'BEE1193',
          { 0: serialLabel.depositCode } /* Deposito %{0} não localizada */
        )
      );
    }
 
    const product = await ProductBranchInformation.getProductBranch({
      branchCode: serialLabel.branchCode,
      productCode: serialLabel.productCode,
    });
 
    if (!product) {
      throw new APIError(
        'NOT_FOUND_PRODUCT',
        t(
          'BEE1233',
          { 0: serialLabel.productCode } /* Produto %{0} não localizado */
        )
      );
    }
  }
}
 
function lPad(str, length = 1, char = ' ') {
  let valueNew = String(str); // Garante que str seja uma string
 
  while (valueNew.length < length) {
    valueNew = char + valueNew; // Adiciona o caractere à esquerda da string
  }
 
  return valueNew;
}
 
async function validationCode(req) {
  const { quantityToPrint, productionOrderId } = req.body;
 
  const nextCode = (await SerialLabelsCtrl.nextCode()) - 1;
  const maxSizeCharacters = 8;
  const maxCode = Number(lPad('', maxSizeCharacters, '9'));
 
  if (nextCode + quantityToPrint > maxCode) {
    throw new APIError(
      t(
        'BEE2792',
        {
          0: maxCode - nextCode,
        } /* Quantidade disponível para impressão é %{0}. Operação cancelada. */
      )
    );
  }
 
  const productionOrder = await ProductionOrderInformation.getProductionOrder({
    id: productionOrderId,
  });
 
  if (!productionOrder) {
    throw new APIError(
      t(
        'BEE2782',
        {
          0: productionOrderId,
        } /* Ordem de produção %{0} não encontrada!  */
      )
    );
  } else {
    if (![1, 2, 3].includes(productionOrder.status)) {
      throw new APIError(
        t(
          'BEE2977',
          {
            0: productionOrder.code,
          } /* A ordem de produção %{0} não consta com o status ativo! */
        )
      );
    }
 
    const product = await ProductBranchInformation.getProductBranch({
      branchCode: productionOrder.branchCode,
      productCode: productionOrder.productCode,
    });
 
    const productEan = await ProductEanInformation.getProductEan({
      productCode: product.productCode,
      packageCode: product.packageCode,
    });
 
    if (
      productionOrder.quantity <
      quantityToPrint * (productEan ? productEan.factor : 1)
    ) {
      throw new APIError(
        t(
          'BEE2793' /* Não é possível imprimir uma quantidade maior que a OP! Operação cancelada. */
        )
      );
    }
  }
}
 
async function validationProductionOrder(req) {
  const { orderCode } = req.body;
 
  const productionOrder = await ProductionOrderInformation.getProductionOrder({
    code: orderCode,
  });
 
  if (!productionOrder) {
    throw new APIError(
      t(
        'BEE2782',
        {
          0: orderCode,
        } /* Ordem de produção %{0} não encontrada!  */
      )
    );
  } else if (![1, 2, 3].includes(productionOrder.status)) {
    throw new APIError(
      t(
        'BEE2977',
        {
          0: productionOrder.code,
        } /* A ordem de produção %{0} não consta com o status ativo! */
      )
    );
  }
}
 
async function validationSerialGroupLabel(req) {
  const { productionOrderId, expirationDate } = req.body;
 
  const expirationDateObj = new Date(expirationDate);
 
  const productionOrder = await ProductionOrderInformation.getProductionOrder({
    id: productionOrderId,
  });
 
  if (
    new Date(productionOrder.expirationDate).getTime() !==
    expirationDateObj.getTime()
  ) {
    const serialGroupData = await SerialGroupInformation.getSerialGroup({
      productionOrderId,
    });
 
    if (serialGroupData) {
      throw new APIError(
        t(
          'BEE4109' /* A alteração da data de validade não é permitida quando já há uma movimentação associada à etiqueta agrupadora. */
        )
      );
    }
  }
}
 
async function validLabelShipmentDocRelationship(req) {
  const { label } = req.query;
 
  if (!label) {
    throw new APIError('EMPTY_ENTRY');
  }
 
  const validSerialLabel = await InformationSerialLabel.getSerialLabel(
    {
      code: label,
    },
    { attributes: ['code'] }
  );
 
  if (!validSerialLabel) {
    throw new APIError(
      '',
      t('BEE3665' /* Informe apenas etiquetas seriadas. */)
    );
  }
 
  const serialLabel =
    await InformationSerialLabel.getSerialLabelShipmentDocRelationship({
      code: label,
    });
 
  if (!serialLabel) {
    throw new APIError(
      '',
      t('BEE3637' /* Etiqueta sem Relacionamento com Documento de Saída */)
    );
  }
 
  req.serialLabel = serialLabel;
}
 
export default {
  validLabelShipmentDocRelationship,
  validationData,
  validationCode,
  validationProductionOrder,
  validationSerialGroupLabel,
  lPad,
};