All files / source/capacities create.js

100% Statements 109/109
100% Branches 73/73
100% Functions 3/3
100% Lines 109/109

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                          5x 5x                           3x   2x         24x 24x 24x 24x   24x 1x 1x 1x     23x         2x 2x 2x         24x 21x 1x 1x 1x   20x       20x 1x 1x 1x                   24x 19x 1x 1x 1x   18x       18x 1x 1x 1x                   24x 15x 1x 1x 1x     14x         14x 1x 1x 1x             13x           13x 1x 1x 1x           12x 1x 1x 1x       15x 1x 1x 1x     15x 10x         1x 1x 1x           15x 9x 1x 1x 1x         24x 5x           5x 1x 1x 1x       24x               23x   23x 22x   22x 14x           8x   8x 4x   4x       4x         4x 4x 4x 3x         1x           4x                                   4x 4x 3x   3x       3x             3x 3x 3x 2x         1x           3x                                   1x   1x       1x           1x         8x               23x                
/* eslint-disable no-restricted-syntax */
import moment from 'moment-timezone';
import { t } from '../../helpers/i18n';
 
import BranchInformation from '../branches/information';
import CapacityInformation from './information';
import AddressSizeInformation from '../storageAddressSizes/information';
import ProductInformation from '../products/information';
import ProductBranchesInformation from '../productBranches/information';
import APIError from '../../helpers/error';
import CapacityDao from '../../database/dao/capacity';
 
async function createCapacity(Capacity) {
  try {
    const newCapacity = await CapacityDao.createCapacity({
      productCode: Capacity.productCode,
      branchCode: Capacity.branchCode,
      description: Capacity.description,
      size: Capacity.size,
      maximumCapacity: Capacity.maximumCapacity,
      referencePointUnity: Capacity.referencePointUnity,
      referencePointPercentage: Capacity.referencePointPercentage,
      status: Capacity.status,
      createdUser: Capacity.createdUser,
      createdAt: moment().format(),
      updatedUser: Capacity.updatedUser,
      updatedAt: moment().format(),
    });
    return newCapacity;
  } catch (error) {
    throw new APIError('', error);
  }
}
 
async function validCapacity(capacity) {
  let isValid = true;
  let code = '';
  let message = '';
  let existSize = '';
 
  if (!capacity.action) {
    isValid = false;
    code = 9000;
    message = t(
      'BEE2695' /* Ação inválida! Os códigos aceitos são "C" = criar, "A" = Alterar e "D" = deletar */
    );
  } else if (
    capacity.action.toUpperCase() !== 'C' &&
    capacity.action.toUpperCase() !== 'D' &&
    capacity.action.toUpperCase() !== 'A'
  ) {
    isValid = false;
    code = 9001;
    message = t(
      'BEE2695' /* Ação inválida! Os códigos aceitos são "C" = criar, "A" = alterar e "D" = deletar */
    );
  }
 
  if (isValid) {
    if (!capacity.branchCode) {
      isValid = false;
      code = 9002;
      message = t('BEE1285' /* Código da filial deve ser informado */);
    } else {
      const existBranch = await BranchInformation.getBranch({
        code: capacity.branchCode,
      });
 
      if (!existBranch) {
        isValid = false;
        code = 9003;
        message = t(
          'BEE1347',
          {
            0: capacity.branchCode,
          } /* Filial código %{0} não encontrado */
        );
      }
    }
  }
 
  if (isValid) {
    if (!capacity.storageAddressSize) {
      isValid = false;
      code = 9004;
      message = t('BEE2690' /* Classificação de Endereço não informada! */);
    } else {
      existSize = await AddressSizeInformation.getStorageAddressSize({
        code: capacity.storageAddressSize,
      });
 
      if (!existSize) {
        isValid = false;
        code = 9005;
        message = t(
          'BEE1598',
          {
            0: capacity.storageAddressSize,
          } /* Classificação de Endereço %{0} não localizada */
        );
      }
    }
  }
 
  if (isValid && capacity.action.toUpperCase() !== 'D') {
    if (!capacity.productCode) {
      isValid = false;
      code = 9006;
      message = t('BEE1288' /* Código do produto deve ser informado ! */);
    } else {
      const existProductBranch =
        await ProductBranchesInformation.getProductBranch({
          branchCode: capacity.branchCode,
          productCode: capacity.productCode,
        });
 
      if (!existProductBranch) {
        isValid = false;
        code = 9007;
        message = t(
          'BEE1229',
          {
            0: `${capacity.productCode} - ${capacity.branchCode}`,
          } /* Produto filial %{0} não localizado */
        );
      } else {
        const existCapacity = await CapacityInformation.getCapacity({
          branchCode: capacity.branchCode,
          productCode: capacity.productCode,
          size: existSize.id,
        });
 
        if (capacity.action.toUpperCase() === 'C' && existCapacity) {
          isValid = false;
          code = 9008;
          message = t(
            'BEE2691',
            {
              0: capacity.productCode,
            } /* Já existe cadastrado uma capacidade para o produto %{0}. */
          );
        } else if (capacity.action.toUpperCase() === 'A' && !existCapacity) {
          isValid = false;
          code = 9009;
          message = t('BEE2707' /* Capacidade não encontrada! */);
        }
      }
    }
    if (!capacity.maximumCapacity || capacity.maximumCapacity === 0) {
      isValid = false;
      code = 9010;
      message = t('BEE2692' /* Capacidade Máxima precisa ser informada! */);
    }
 
    if (isValid) {
      if (
        (!capacity.referencePointUnity || capacity.referencePointUnity === 0) &&
        (!capacity.referencePointPercentage ||
          capacity.referencePointPercentage === 0)
      ) {
        isValid = false;
        code = 9011;
        message = t(
          'BEE2693' /* Ponto de Ressuprimento precisa ser informada! */
        );
      }
    }
 
    if (isValid) {
      if (!capacity.status) {
        isValid = false;
        code = 9012;
        message = t('BEE1198' /* Status deve ser informado! */);
      }
    }
  }
 
  if (isValid && capacity.action.toUpperCase() !== 'C') {
    const regCapacity = await CapacityInformation.getCapacity({
      branchCode: capacity.branchCode,
      productCode: capacity.productCode,
      size: existSize.id,
    });
 
    if (!regCapacity) {
      isValid = false;
      code = 9013;
      message = t('BEE2707' /* Capacidade não encontrada! */);
    }
  }
 
  return {
    isValid,
    code,
    message,
  };
}
 
async function createBulkImportCapacity(bulkImportCapacities, user) {
  const bulkImport = bulkImportCapacities || [];
 
  for (const storageCapacity of bulkImport) {
    const valid = await validCapacity(storageCapacity);
 
    if (!valid.isValid) {
      storageCapacity.error = {
        line: storageCapacity.line,
        error: valid.code,
        message: valid.message,
      };
    } else {
      let message = '';
 
      if (storageCapacity.action.toUpperCase() === 'C') {
        message = t('BEE2696' /* Capacidade criada com sucesso! */);
 
        const size = await AddressSizeInformation.getStorageAddressSize({
          code: storageCapacity.storageAddressSize,
        });
 
        const product = await ProductInformation.getProduct({
          productCode: storageCapacity.productCode,
        });
 
        let valuereferencePointPercentage =
          storageCapacity.referencePointPercentage;
        let valuereferencePointUnity = storageCapacity.referencePointUnity;
        if (storageCapacity.referencePointUnity) {
          valuereferencePointPercentage = Math.round(
            (storageCapacity.referencePointUnity * 100) /
              storageCapacity.maximumCapacity
          );
        } else {
          valuereferencePointUnity = Math.round(
            (storageCapacity.referencePointPercentage / 100) *
              storageCapacity.maximumCapacity
          );
        }
 
        const capacity = {
          productCode: storageCapacity.productCode,
          branchCode: storageCapacity.branchCode,
          description: product.name,
          size: size.id,
          maximumCapacity: storageCapacity.maximumCapacity,
          referencePointUnity: valuereferencePointUnity,
          referencePointPercentage:
            valuereferencePointPercentage === 0
              ? 1
              : valuereferencePointPercentage,
          status: storageCapacity.status,
          createdUser: user,
          createdAt: moment().format(),
          updatedUser: user,
          updatedAt: moment().format(),
        };
 
        await CapacityDao.createCapacity(capacity);
      } else if (storageCapacity.action.toUpperCase() === 'A') {
        message = t('BEE2697' /* Capacidade alterada com sucesso! */);
 
        const size = await AddressSizeInformation.getStorageAddressSize({
          code: storageCapacity.storageAddressSize,
        });
 
        const capacity = await CapacityInformation.getCapacity({
          branchCode: storageCapacity.branchCode,
          productCode: storageCapacity.productCode,
          size: size.id,
        });
 
        let valuereferencePointPercentage =
          storageCapacity.referencePointPercentage;
        let valuereferencePointUnity = storageCapacity.referencePointUnity;
        if (storageCapacity.referencePointUnity) {
          valuereferencePointPercentage = Math.round(
            (storageCapacity.referencePointUnity * 100) /
              storageCapacity.maximumCapacity
          );
        } else {
          valuereferencePointUnity = Math.round(
            (storageCapacity.referencePointPercentage / 100) *
              storageCapacity.maximumCapacity
          );
        }
 
        await CapacityDao.updateCapacity(
          {
            id: capacity.id,
          },
          {
            size: size.id,
            maximumCapacity: storageCapacity.maximumCapacity,
            referencePointUnity: valuereferencePointUnity,
            referencePointPercentage:
              valuereferencePointPercentage === 0
                ? 1
                : valuereferencePointPercentage,
            status: storageCapacity.status,
            updatedUser: user,
            updatedAt: moment().format(),
          }
        );
      } else {
        message = t('BEE2698' /* Capacidade excluída com sucesso! */);
 
        const size = await AddressSizeInformation.getStorageAddressSize({
          code: storageCapacity.storageAddressSize,
        });
 
        const capacity = await CapacityInformation.getCapacity({
          branchCode: storageCapacity.branchCode,
          productCode: storageCapacity.productCode,
          size: size.id,
        });
 
        await CapacityDao.deleteCapacity({
          id: capacity.id,
        });
      }
 
      storageCapacity.error = {
        line: storageCapacity.line,
        error: '',
        message,
      };
    }
  }
 
  return bulkImport;
}
 
export default {
  validCapacity,
  createCapacity,
  createBulkImportCapacity,
};