All files / middlewares inboundCheckValidations.js

100% Statements 151/151
100% Branches 157/157
100% Functions 14/14
100% Lines 150/150

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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645                                            10x         10x   10x   10x     10x       10x 1x     9x 1x           8x             8x 3x 1x               2x         2x 1x                         6x 2x   2x       2x       1x                   5x       5x 2x                 2x 1x                                 3x   3x 1x     2x             2x           1x                             4x   4x 1x     3x             3x 1x         2x 1x           4x         4x 1x   3x             3x 1x               2x 1x   1x           7x         7x       7x       7x 1x         6x       2x         4x       2x         2x 1x           2x         2x   2x       2x 1x             5x     5x       5x 1x     4x   4x     4x         4x 5x   4x   4x 4x 7x         7x 1x       6x 1x         5x     2x   2x 1x                   6x     6x       6x       6x   6x           6x 5x         5x 1x                     4x 1x         3x         3x 1x                     2x 1x               4x     4x       4x 3x       3x         3x               2x                 2x   2x 2x   2x               1x                 4x 4x   4x   4x     4x       4x   3x         3x 3x 2x 2x 2x   2x         1x                                       6x     6x       6x 5x         5x   5x 4x 1x             3x                                 3x 1x       2x 1x                                   4x       4x 1x     3x   3x 1x           2x         2x 1x                                                      
/* eslint-disable no-restricted-syntax */
import moment from 'moment-timezone';
import { Op } from 'sequelize';
 
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
import InboundOrderProductLotsInformation from '../source/inboundOrderProductLots/information';
import InboundOrderProductInformation from '../source/inboundOrderProducts/information';
import BranchInformation from '../source/branches/information';
import InboundOrderProductStorageInformation from '../source/inboundOrderProductStorages/information';
import InboundCheckInformation from '../source/inboundOrders/inboundCheck';
import ProductBranchInformation from '../source/productBranches/information';
import StockBalanceInformation from '../source/stock/information';
import StorageAddressInformation from '../source/storageAddresses/information';
import UserInformation from '../source/users/information';
import TypeOrderInformation from '../source/typeOrders/information';
import InboundOrderProductPartial from '../source/inboundOrderProductPartial/information';
import BaptismsInformation from '../source/baptisms/information';
import { models } from '../../config/database';
 
async function validBaptismLabel(req) {
  const baptismLabel =
    req.body.baptismLabel ||
    req.query.baptismLabel ||
    req.body.baptism ||
    req.query.baptism;
 
  const { serialGroupId } = req.body;
 
  const { userId } = req;
 
  const user = await UserInformation.getUser({ id: userId });
 
  const automaticStorage =
    req.inboundOrderData && req.inboundOrderData.typeOrder
      ? req.inboundOrderData.typeOrder.automaticStorage
      : false;
 
  if (automaticStorage) {
    return;
  }
 
  if (!baptismLabel) {
    throw new APIError(
      '',
      t('BEE1201' /* Etiqueta de batismo deve ser informada */)
    );
  } else {
    const startStorage =
      await InboundOrderProductStorageInformation.getInboundOrderProductStorages(
        {
          branchCode: user.mainBranch,
          baptismLabel,
        }
      );
 
    if (serialGroupId) {
      if (startStorage && startStorage.length > 0) {
        throw new APIError(
          '',
          t(
            'BEE2575' /* Etiqueta Batismo já esta em processo de armazenamento! */
          )
        );
      } else {
        const inboundOrderPartial =
          await InboundOrderProductPartial.getInboundOrderProductPartial({
            branchCode: user.mainBranch,
            baptismLabel,
          });
 
        if (inboundOrderPartial) {
          throw new APIError(
            '',
            t(
              'BEE3271',
              {
                0: baptismLabel,
              } /* A UZ %{0} já foi utilizada em outra movimentação! Digite uma nova UZ. */
            )
          );
        }
      }
    }
 
    if (startStorage && startStorage.length > 0) {
      for (const productStorage of startStorage) {
        const inboundProduct =
          await InboundOrderProductInformation.getInboundOrderProduct({
            id: productStorage.inboundOrderProductId,
          });
 
        if (
          inboundProduct &&
          inboundProduct.inboundOrder.branchCode === user.mainBranch
        ) {
          throw new APIError(
            '',
            t(
              'BEE2575' /* Etiqueta Batismo já esta em processo de armazenamento! */
            )
          );
        }
      }
    }
 
    const { serialControlDeposit } = await BranchInformation.getBranch({
      code: user.mainBranch,
    });
 
    if (!serialControlDeposit) {
      const existUZ = await BaptismsInformation.getBaptism(
        {
          branchCode: user.mainBranch,
          code: baptismLabel,
          type: 1, // Entrada
        },
        { attributes: ['id'] }
      );
 
      if (!existUZ) {
        throw new APIError(
          '',
          t(
            'BEE3756',
            {
              0: baptismLabel,
              1: t('BEE201' /* Entrada */),
            } /* Etiqueta UZ %{0} do tipo %{1} não gerada. Por favor, verifique! */
          )
        );
      }
    }
  }
}
 
async function validProductInspection(req) {
  const inboundOrderProductId =
    req.body.inboundOrderProductId || req.query.inboundOrderProductId;
 
  if (!inboundOrderProductId) {
    throw new APIError('', t('BEE3510' /* Produto do documento inválido! */));
  } else {
    const existProduct =
      await InboundOrderProductInformation.getInboundOrderProduct(
        {
          id: inboundOrderProductId,
        },
        { userBranches: req.userBranches }
      );
 
    if (
      existProduct &&
      existProduct.inspection &&
      existProduct.inspected !== 1 &&
      existProduct.inspected !== 2
    ) {
      throw new APIError(
        '',
        t(
          'BEE4129',
          {
            0: existProduct.productCode,
          } /* O produto %{0} necessita de inspeção. */
        )
      );
    }
  }
}
 
async function validInboundOrderProductId(req) {
  const inboundOrderProductId =
    req.body.inboundOrderProductId || req.query.inboundOrderProductId;
 
  if (!inboundOrderProductId) {
    throw new APIError('', t('BEE3510' /* Produto do documento inválido! */));
  } else {
    const existProduct =
      await InboundOrderProductInformation.getInboundOrderProduct(
        {
          id: inboundOrderProductId,
        },
        { userBranches: req.userBranches }
      );
 
    if (!existProduct)
      throw new APIError(
        '',
        t('BEE3038' /* Produto do documento não localizado! */)
      );
 
    if (existProduct.status !== 1)
      throw new APIError('', t('BEE3039' /* Status do Produto inválido! */));
  }
}
 
async function validInboundOrderId(req) {
  const inboundOrderId =
    req.body.invoiceId ||
    req.query.invoiceId ||
    req.body.inboundOrderId ||
    req.query.inboundOrderId;
 
  if (!inboundOrderId) {
    throw new APIError('', t('BEE3040' /* Documento inválido! */));
  } else {
    const existInboundOrder = await InboundCheckInformation.getInboundOrder(
      {
        id: inboundOrderId,
      },
      { userBranches: req.userBranches }
    );
 
    if (!existInboundOrder)
      throw new APIError(
        '',
        t(
          'BEE1202',
          { 0: inboundOrderId } /* Documento de entrada %{0} não localizado */
        )
      );
 
    if (existInboundOrder.status > 4)
      throw new APIError('', t('BEE3041' /* Status do Documento inválido! */));
 
    req.inboundOrderData = existInboundOrder;
  }
}
 
async function validBranchDeposits(req) {
  const inboundOrderId =
    req.body.invoiceId ||
    req.query.invoiceId ||
    req.body.inboundOrderId ||
    req.query.inboundOrderId;
 
  const inboundOrder = await InboundCheckInformation.getInboundOrder({
    id: inboundOrderId,
  });
 
  const branchSettings = await BranchInformation.getBranchSettings({
    code: inboundOrder.branchCode,
  });
 
  if (!branchSettings)
    throw new APIError(
      '',
      t('BEE3042' /* Parâmetros da Filial não localizados! */)
    );
 
  if (
    branchSettings.inboundDeposit === null ||
    branchSettings.inboundDeposit === ''
  )
    throw new APIError(
      '',
      t('BEE3043' /* Depósito de Recebimento inválido! */)
    );
 
  if (
    branchSettings.divergenceDeposit === null ||
    branchSettings.divergenceDeposit === ''
  )
    throw new APIError(
      '',
      t('BEE3044' /* Depósito de Divergência inválido! */)
    );
 
  if (branchSettings.branchInInventory) {
    throw new APIError('', t('BEE3015' /* Filial em processo de Inventário */));
  }
}
 
async function validUserCheckOrder(req) {
  const inboundOrderId =
    req.body.invoiceId ||
    req.query.invoiceId ||
    req.body.inboundOrderId ||
    req.query.inboundOrderId;
 
  const { userId } = req;
 
  const inboundOrder = await InboundCheckInformation.getInboundOrder({
    id: inboundOrderId,
  });
 
  if (inboundOrder.checkOrderUser && inboundOrder.checkOrderUser !== userId)
    throw new APIError(
      '',
      t('BEE3045' /* Documento relacionado a outro usuário! */)
    );
}
 
async function validRangeAddress(req) {
  const { baptism, suggestedAddress } = req.body;
 
  const automaticStorage =
    req.inboundOrderData && req.inboundOrderData.typeOrder
      ? req.inboundOrderData.typeOrder.automaticStorage
      : false;
 
  if (automaticStorage) {
    return;
  }
 
  const { userId } = req;
 
  const user = await UserInformation.getUser({ id: userId });
 
  const baptismProducts =
    await InboundOrderProductInformation.getInboundOrderProducts({
      branchCode: user.mainBranch,
      baptismLabel: baptism,
    });
 
  const addressesCode = [
    ...new Set(baptismProducts.map((p) => p.suggestedAddress)),
  ];
  addressesCode.push(suggestedAddress);
 
  const ranges = [];
  for (const code of addressesCode) {
    const address = await StorageAddressInformation.getStorageAddress({
      code,
      branchCode: user.mainBranch,
    });
 
    if (!address)
      throw new APIError(
        '',
        t('BEE3046' /* Endereço Sugerido deve ser informado! */)
      );
    if (address.rangeCode === null)
      throw new APIError(
        '',
        t('BEE3047' /* Endereço sem faixa relacionada! */)
      );
 
    ranges.push(address.rangeCode);
  }
 
  const rangesCodes = [...new Set(ranges)];
 
  if (rangesCodes.length > 1) {
    throw new APIError(
      '',
      t(
        'BEE2576' /* O endereço informado é de um Range diferente do já usado na Etiqueta Batismo */
      )
    );
  }
}
 
async function validSharedAddress(req) {
  const { inboundOrderProductId, suggestedAddress } = req.body;
 
  const orderProduct =
    await InboundOrderProductInformation.getInboundOrderProduct({
      id: inboundOrderProductId,
    });
 
  const inboundOrder = await InboundCheckInformation.getInboundOrder({
    id: orderProduct.inboundOrderId,
  });
 
  const { branchCode } = inboundOrder;
 
  const stockBalance = await StockBalanceInformation.getStockBalance({
    addressCode: suggestedAddress,
    branchCode,
    quantity: { [Op.gt]: 0 },
  });
 
  if (stockBalance && stockBalance.productCode !== orderProduct.productCode) {
    const address = await StorageAddressInformation.getStorageAddress({
      code: suggestedAddress,
      branchCode,
    });
 
    if (!address)
      throw new APIError(
        '',
        t(
          'BEE3438',
          {
            0: branchCode,
            1: suggestedAddress,
          } /* Endereço não encontrado! (%{0} - %{1}) */
        )
      );
 
    if (!address.shareAddress)
      throw new APIError(
        '',
        t('BEE3048' /* Endereço não compartilha espaço */)
      );
 
    const productBranch = await ProductBranchInformation.getProductBranch({
      branchCode,
      productCode: orderProduct.productCode,
    });
 
    if (!productBranch)
      throw new APIError(
        '',
        t(
          'BEE3161',
          {
            0: branchCode,
            1: orderProduct.productCode,
          } /* Produto filial não localizado! (%{0} - %{1}) */
        )
      );
 
    if (!productBranch.shareAddress)
      throw new APIError(
        '',
        t('BEE3049' /* Produto não compartilha Endereço! */)
      );
  }
}
 
async function validQuantityProducts(req) {
  const { inboundOrderProductId, count } = req.body;
 
  const inboundOrderProduct =
    await InboundOrderProductInformation.getInboundOrderProduct({
      id: inboundOrderProductId,
    });
 
  if (inboundOrderProduct) {
    const branchInformation = await BranchInformation.getBranch({
      code: inboundOrderProduct.inboundOrder.branchCode,
    });
 
    const typeOrder = await TypeOrderInformation.getTypeOrder({
      branchCode: inboundOrderProduct.inboundOrder.branchCode,
      type: inboundOrderProduct.inboundOrder.orderType,
    });
 
    if (
      (typeOrder
        ? typeOrder.receiveLeftover
        : branchInformation && branchInformation.receiveLeftover) &&
      count >
        parseInt(inboundOrderProduct.quantity, 10) -
          parseInt(inboundOrderProduct.quantityCheck, 10)
    ) {
      throw new APIError(
        '',
        t('BEE1880' /* Quantidade conferida superior a Quantidade disponível */)
      );
    }
  }
}
 
async function validDateManufacture(req) {
  const { lots } = req.body;
 
  for (let index = 0; index < lots.length; index += 1) {
    const element = lots[index];
 
    if (
      element.mfgDate &&
      moment(element.mfgDate).isValid() &&
      moment(moment().subtract(1, 'days').format()).isBefore(
        moment(element.mfgDate).format(),
        'day'
      )
    ) {
      throw new APIError(
        '',
        t('BEE1981' /* A data de fabricação superior a data atual */)
      );
    }
  }
}
 
async function validBaptismExpiration(req) {
  const baptismLabel = req.body.baptism;
  const { lots, inboundOrderProductId } = req.body;
 
  const { userId } = req;
 
  const user = await UserInformation.getUser({ id: userId });
 
  const orderProduct =
    await InboundOrderProductInformation.getInboundOrderProduct({
      id: inboundOrderProductId,
    });
 
  if (lots && lots.length > 0) {
    const productLots =
      await InboundOrderProductLotsInformation.getInboundOrderProductLots({
        branchCode: user.mainBranch,
        baptismLabel,
      });
 
    for (const lot of lots) {
      if (productLots && productLots.length > 0) {
        for (const prdLot of productLots) {
          const pExpDate = moment(prdLot.expDate).format('L');
          const lExpDate = moment(lot.expDate).format('L');
 
          if (
            prdLot.inboundOrderProduct.productCode ===
              orderProduct.productCode &&
            pExpDate !== lExpDate
          ) {
            throw new APIError(
              '',
              t(
                'BEE2577',
                {
                  0: baptismLabel,
                  1: orderProduct.productCode,
                  2: pExpDate,
                  3: lExpDate,
                } /* Batismo %{0} já tem o Produto %{1} com a Data de Vencimento %{2} e não pode ser relacionado o mesmo Produto com outro vencimento (%{3}) */
              )
            );
          }
        }
      }
    }
  }
}
 
async function validStorageStage(req) {
  const { inboundOrderProductId, stage } = req.body;
 
  const inboundOrderProduct =
    await InboundOrderProductInformation.getInboundOrderProduct({
      id: inboundOrderProductId,
    });
 
  if (inboundOrderProduct) {
    const typeOrder = await TypeOrderInformation.getTypeOrder({
      branchCode: inboundOrderProduct.inboundOrder.branchCode,
      type: inboundOrderProduct.inboundOrder.orderType,
    });
 
    const isControlStage = typeOrder ? typeOrder.preStorageStage : false;
 
    if (isControlStage) {
      if (!stage) {
        throw new APIError(
          '',
          t('BEE3507', {
            0: t('BEE3495' /* Stage Pré-Armazenagem */),
          }) /* É necessário informar o endereço do tipo %{0}! */
        );
      } else {
        const stageAddress = await StorageAddressInformation.getStorageAddress(
          {
            code: stage,
            branchCode: inboundOrderProduct.inboundOrder.branchCode,
          },
          {
            include: [
              {
                model: models.StorageAddressType,
                as: 'addressType',
                required: true,
                attributes: ['status'],
              },
            ],
          }
        );
 
        if (!stageAddress) {
          throw new APIError(
            '',
            t('BEE3159', { 0: stage } /* Endereço não localizado! (%{0}) */)
          );
        } else if (stageAddress.addressType.status !== 8) {
          throw new APIError(
            '',
            t(
              'BEE3511',
              {
                0: stage,
                1: t('BEE3495' /* Stage Pré-Armazenagem */),
              } /* O endereço %{0} não pertence ao tipo %{1}! */
            )
          );
        }
      }
    }
  }
}
 
async function validSuggestAddress(req) {
  const automaticStorage =
    req.inboundOrderData && req.inboundOrderData.typeOrder
      ? req.inboundOrderData.typeOrder.automaticStorage
      : false;
 
  if (!automaticStorage) {
    return;
  }
 
  const { suggestedAddress } = req.body;
 
  if (!suggestedAddress) {
    throw new APIError(
      '',
      t('BEE1827' /* Endereço armazenamento deve ser informado! */)
    );
  }
 
  const address = await StorageAddressInformation.getStorageAddress({
    code: suggestedAddress,
    branchCode: req.inboundOrderData.branchCode,
  });
 
  if (!address)
    throw new APIError(
      '',
      t(
        'BEE3438',
        {
          0: req.inboundOrderData.branchCode,
          1: suggestedAddress,
        } /* Endereço não encontrado! (%{0} - %{1}) */
      )
    );
}
 
export default {
  validBaptismLabel,
  validInboundOrderProductId,
  validInboundOrderId,
  validBranchDeposits,
  validUserCheckOrder,
  validRangeAddress,
  validSharedAddress,
  validQuantityProducts,
  validDateManufacture,
  validBaptismExpiration,
  validStorageStage,
  validProductInspection,
  validSuggestAddress,
};