All files / source/productionOrders import.js

100% Statements 134/134
100% Branches 64/64
100% Functions 6/6
100% Lines 134/134

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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453                                14x 14x 14x 14x   14x 1x 1x 1x   13x       13x 1x 1x 1x       12x 1x 1x 1x                 14x 11x 1x 1x 1x 10x       1x 1x 1x           11x 1x 1x 1x   10x       10x 1x 1x 1x             9x 6x 6x       6x 1x 1x 1x           1x       5x         5x 1x 1x 1x           1x         9x           9x 1x 1x 1x               9x 1x 1x 1x         8x             8x 1x 1x 1x                       14x               14x   14x 14x 14x 14x 12x                   2x     2x           2x           2x                               2x             2x 1x 1x                   1x                 14x       11x 11x 11x   11x 1x 1x 1x   10x       10x 1x 1x 1x             11x 1x 1x 1x 10x       1x 1x 1x           11x 1x 1x 1x   10x       10x 1x 1x 1x                 11x 1x 1x 1x   10x     10x 2x 2x 2x       11x 2x                                         2x 1x 1x 1x                 11x               11x   11x 11x 11x 11x 10x                       1x                                           1x                                                               11x            
/* eslint-disable no-restricted-syntax */
import Sequelize, { Op } from 'sequelize';
import moment from 'moment-timezone';
import { t } from '../../helpers/i18n';
import { sequelize } from '../../../config/database';
import ProductionOrderInformation from './information';
import ProductionOrderCreate from './create';
import ProductionOrderReserveCreate from '../productionOrderReserve/create';
import BranchInformation from '../branches/information';
import DepositInformation from '../deposits/information';
import ProductBranchesInformation from '../productBranches/information';
import StockBalanceInformation from '../stock/information';
import StockMovement from '../stock/movement';
import ProductInformation from '../products/information';
 
async function ValidProductionOrder(productionOrder) {
  let isValid = true;
  let code = '';
  let message = '';
  let existBranch = {};
 
  if (!productionOrder.branchCode) {
    isValid = false;
    code = 9000;
    message = t('BEE1285' /* Código da filial deve ser informado */);
  } else {
    existBranch = await BranchInformation.getBranch({
      code: productionOrder.branchCode,
    });
 
    if (!existBranch) {
      isValid = false;
      code = 9001;
      message = t(
        'BEE1307',
        { 0: productionOrder.branchCode } /* Código da filial %{0} inválido */
      );
    } else if (!existBranch.factoryDeposit) {
      isValid = false;
      code = 9002;
      message = t(
        'BEE2966',
        {
          0: productionOrder.branchCode,
        } /* A Filial %{0} não possui o cadastro de depósito Fábrica! */
      );
    }
  }
 
  if (isValid) {
    if (!productionOrder.quantity) {
      isValid = false;
      code = 9003;
      message = t('BEE1331' /* Quantidade deve ser informada */);
    } else if (
      typeof productionOrder.quantity !== 'number' ||
      productionOrder.quantity <= 0
    ) {
      isValid = false;
      code = 9004;
      message = t(
        'BEE1146',
        { 0: productionOrder.quantity } /* Quantidade %{0} inválida ! */
      );
    }
 
    if (!productionOrder.productCode) {
      isValid = false;
      code = 9005;
      message = t('BEE2129' /* Produto não informado */);
    } else {
      const existProduct = await ProductInformation.getProduct({
        productCode: productionOrder.productCode,
      });
 
      if (!existProduct) {
        isValid = false;
        code = 9020;
        message = t(
          'BEE1321',
          {
            0: productionOrder.productCode,
          } /* Código do produto %{0} inválido */
        );
      } else {
        if (productionOrder.reserveProducts) {
          for (const reserveProduct of productionOrder.reserveProducts) {
            const existProductReserve = await ProductInformation.getProduct({
              productCode: reserveProduct.productCode,
            });
 
            if (!existProductReserve) {
              isValid = false;
              code = 9020;
              message = t(
                'BEE3274',
                {
                  0: reserveProduct.productCode,
                } /* Código de reserva do produto %{0} inválido */
              );
              break;
            }
 
            const productBranchReserve =
              await ProductBranchesInformation.getProductBranch({
                branchCode: productionOrder.branchCode,
                productCode: reserveProduct.productCode,
              });
 
            if (!productBranchReserve) {
              isValid = false;
              code = 9006;
              message = t(
                'BEE3275',
                {
                  0: `${productionOrder.branchCode} - ${reserveProduct.productCode}`,
                } /* Produto reservado da filial %{0} não encontrado */
              );
              break;
            }
          }
        }
 
        const productBranch = await ProductBranchesInformation.getProductBranch(
          {
            branchCode: productionOrder.branchCode,
            productCode: productionOrder.productCode,
          }
        );
        if (!productBranch) {
          isValid = false;
          code = 9006;
          message = t(
            'BEE1229',
            {
              0: `${productionOrder.branchCode} - ${productionOrder.productCode}`,
            } /* Produto filial %{0} não localizado */
          );
        }
 
        if (!productionOrder.code) {
          isValid = false;
          code = 9009;
          message = t(
            'BEE2924' /* O código da Ordem de Produção não informado! */
          );
        } else {
          const existProductionOrder =
            await ProductionOrderInformation.getProductionOrder({
              branchCode: productionOrder.branchCode,
              depositCode: existBranch.factoryDeposit,
              productCode: productionOrder.productCode,
              code: productionOrder.code,
            });
 
          if (existProductionOrder) {
            isValid = false;
            code = 9010;
            message = t(
              'BEE2814',
              {
                0: productionOrder.code,
              } /* Ordem de produção %{0} já existe! */
            );
          }
        }
      }
    }
  }
 
  return {
    isValid,
    code,
    message,
  };
}
 
async function importProductionOrders(productionOrders, userId) {
  const listProductionOrdersErrors = [];
 
  await sequelize.transaction(async (transaction) => {
    for (const productionOrder of productionOrders) {
      const valid = await ValidProductionOrder(productionOrder);
      if (!valid.isValid) {
        listProductionOrdersErrors.push({
          code: {
            branchCode: productionOrder.branchCode,
            customerCode: productionOrder.customerCode,
            orderNumber: productionOrder.orderNumber,
          },
          error: valid.code,
          message: valid.message,
        });
      } else {
        const branch = await BranchInformation.getBranch({
          code: productionOrder.branchCode,
        });
        const expirationDate = productionOrder.expirationDate
          ? moment(moment(productionOrder.expirationDate, 'DD/MM/YYYY'))
              .startOf('day')
              .format()
          : '';
 
        const expectedDate = productionOrder.expectedDate
          ? moment(moment(productionOrder.expectedDate, 'DD/MM/YYYY'))
              .startOf('day')
              .format()
          : '';
 
        const newProductionOrder = {
          branchCode: productionOrder.branchCode,
          depositCode: branch.factoryDeposit,
          code: productionOrder.code,
          productCode: productionOrder.productCode,
          quantity: productionOrder.quantity,
          quantityProduction: productionOrder.quantityProduction || 0,
          lotNumber: productionOrder.lotNumber,
          expirationDate,
          reference: productionOrder.reference,
          situation: productionOrder.situation,
          expectedDate,
          status: 1,
          createdUser: userId,
          updatedUser: userId,
        };
        const newProduction = await ProductionOrderCreate.createProductionOrder(
          newProductionOrder,
          {
            transaction,
          }
        );
 
        if (productionOrder.reserveProducts) {
          for (const reserveProduct of productionOrder.reserveProducts) {
            const newProductionOrderReserve = {
              productionOrderId: newProduction.id,
              productCode: reserveProduct.productCode,
              lineNumber: reserveProduct.lineNumber,
              quantity: reserveProduct.quantity,
              lotNumber: productionOrder.lotNumber,
              createdUser: userId,
              updatedUser: userId,
            };
 
            await ProductionOrderReserveCreate.createProductionOrderReserve(
              newProductionOrderReserve,
              { transaction }
            );
          }
        }
      }
    }
  });
  return { listProductionOrdersErrors };
}
 
async function ValidMovementStockKanban(productionOrder) {
  let isValid = true;
  let code = '';
  let message = '';
 
  if (!productionOrder.branchCode) {
    isValid = false;
    code = 9000;
    message = t('BEE1285' /* Código da filial deve ser informado */);
  } else {
    const existBranch = await BranchInformation.getBranch({
      code: productionOrder.branchCode,
    });
 
    if (!existBranch) {
      isValid = false;
      code = 9001;
      message = t(
        'BEE1307',
        { 0: productionOrder.branchCode } /* Código da filial %{0} inválido */
      );
    }
  }
 
  if (!productionOrder.quantity) {
    isValid = false;
    code = 9005;
    message = t('BEE1331' /* Quantidade deve ser informada */);
  } else if (
    typeof productionOrder.quantity !== 'number' ||
    productionOrder.quantity <= 0
  ) {
    isValid = false;
    code = 9006;
    message = t(
      'BEE1146',
      { 0: productionOrder.quantity } /* Quantidade %{0} inválida ! */
    );
  }
 
  if (!productionOrder.productCode) {
    isValid = false;
    code = 9007;
    message = t('BEE2129' /* Produto não informado */);
  } else {
    const productBranch = await ProductBranchesInformation.getProductBranch({
      branchCode: productionOrder.branchCode,
      productCode: productionOrder.productCode,
    });
    if (!productBranch) {
      isValid = false;
      code = 9008;
      message = t(
        'BEE1229',
        {
          0: `${productionOrder.branchCode} - ${productionOrder.productCode}`,
        } /* Produto filial %{0} não localizado */
      );
    }
  }
 
  if (!productionOrder.depositCode) {
    isValid = false;
    code = 9007;
    message = 'Deposito não informado';
  } else {
    const deposit = await DepositInformation.getDeposit({
      code: productionOrder.depositCode,
    });
    if (!deposit) {
      isValid = false;
      code = 9008;
      message = `Deposito ${productionOrder.depositCode} não localizado`;
    }
  }
 
  if (isValid) {
    const stock = await StockBalanceInformation.getStockBalanceKanban({
      branchCode: productionOrder.branchCode,
      productCode: productionOrder.productCode,
      depositCode: productionOrder.depositCode,
      [Op.and]: [
        Sequelize.where(
          Sequelize.col('StockBalance.flo_quantity'),
          '>=',
          Sequelize.where(
            Sequelize.where(
              Sequelize.col('StockBalance.flo_allocated'),
              '+',
              Sequelize.col('StockBalance.flo_reserved')
            ),
            '+',
            productionOrder.quantity
          )
        ),
      ],
    });
 
    if (!stock) {
      isValid = false;
      code = 9009;
      message = t(
        'BEE2872',
        {
          0: productionOrder.productCode,
        } /* Não foi localizado nenhum estoque Kanban para o produto %{0} ! */
      );
    }
  }
 
  return {
    isValid,
    code,
    message,
  };
}
 
async function importMovementStockKanban(productionOrders, userId) {
  const listMovementStockKanban = [];
 
  await sequelize.transaction(async (transaction) => {
    for (const productionOrder of productionOrders) {
      const valid = await ValidMovementStockKanban(productionOrder);
      if (!valid.isValid) {
        listMovementStockKanban.push({
          code: {
            branchCode: productionOrder.branchCode,
            customerCode: productionOrder.customerCode,
            orderNumber: productionOrder.orderNumber,
          },
          error: valid.code,
          message: valid.message,
        });
      } else {
        // Coleta os dados do endereço que possui estoque.
        const addressKanban =
          await StockBalanceInformation.getStockBalanceKanban({
            branchCode: productionOrder.branchCode,
            productCode: productionOrder.productCode,
            depositCode: productionOrder.depositCode,
            [Op.and]: [
              Sequelize.where(
                Sequelize.col('StockBalance.flo_quantity'),
                '>=',
                Sequelize.where(
                  Sequelize.where(
                    Sequelize.col('StockBalance.flo_allocated'),
                    '+',
                    Sequelize.col('StockBalance.flo_reserved')
                  ),
                  '+',
                  productionOrder.quantity
                )
              ),
            ],
          });
 
        // Cria o movimento da baixa do endereço
        await StockMovement.createMovement(
          {
            stockBalanceId: addressKanban.id,
            branchCode: addressKanban.branchCode,
            warehouseCode: addressKanban.warehouseCode,
            depositCode: addressKanban.depositCode,
            addressCode: addressKanban.addressCode,
            productCode: addressKanban.productCode,
            productLineNumber: 0,
            lotNumber: addressKanban.lotNumber,
            operation: 'REQ',
            type: 2,
            quantity: productionOrder.quantity,
            unitMeasure: addressKanban.product.unitMeasure,
            serie: '',
            orderNumber: productionOrder.orderCode,
            supplierCode: '',
            expirationDate: addressKanban.expirationDate,
            manufacturingDate: addressKanban.manufacturingDate,
            note: `${t('BEE2770' /* Ordem de Produção */)}: ${
              productionOrder.orderCode
            }`,
            baptismLabel: '',
            movementUser: userId,
            createdUser: userId,
            updatedUser: userId,
          },
          { transaction }
        );
      }
    }
  });
  return { listMovementStockKanban };
}
export default {
  importProductionOrders,
  importMovementStockKanban,
};