All files / middlewares inventoryValidations.js

100% Statements 258/258
100% Branches 252/252
100% Functions 29/29
100% Lines 254/254

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 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894                                      3x   3x 2x     3x 1x   2x             2x 1x               2x   2x 1x         5x 5x   5x         5x 1x       4x 1x       3x 1x       2x 1x               2x 2x   2x         2x 2x 1x                       7x 7x 6x                                 6x 1x       5x 1x 4x 1x 3x 1x             2x 1x               1x         2x   2x 1x               3x   3x 1x   2x     2x 1x                 3x   3x 1x   2x       2x       2x 1x           4x 4x 3x 1x   2x     2x         2x 1x                   5x     5x     5x       5x 2x 1x         1x             3x 2x     2x                 2x 1x           6x   6x 1x           5x         5x       1x       1x                           4x 4x 3x                 3x 1x                         3x 2x                                 2x 1x                               3x   3x         3x 1x         2x     2x 1x                 2x   2x 1x         2x   2x 1x         2x   2x 1x           6x   6x 5x     5x 5x 6x   6x 2x       2x 4x 1x       1x 3x 1x       1x       5x 3x       2x 1x   1x           16x   16x 1x   15x     15x 1x         14x 1x 13x 1x   12x         12x 1x               11x         11x 1x         10x 1x         9x       9x 9x 9x 1x                 8x 1x             7x 1x             6x 1x       5x 1x         4x 4x   4x 3x 2x   4x   2x         2x   1x   1x   1x         4x         1x                       2x       2x 1x         1x       2x   2x 1x       2x   2x 1x       7x   7x 6x       6x 5x 5x 1x           4x 1x       3x 1x       2x 1x             1x     1x         7x   7x 6x       6x 5x 5x 1x       4x 1x       3x 1x       2x 1x             1x     1x         2x   2x         2x 1x                   2x   2x         1x         3x   3x 1x   2x                                                         2x 1x                             10x   10x 9x         9x 1x       8x 7x 1x         6x       6x 1x   5x       5x 1x   4x 1x   3x 1x                 2x   2x 1x       2x   2x 1x         2x   2x 1x                                                                            
/* eslint-disable no-restricted-syntax */
import { Op } from 'sequelize';
 
import APIError from '../helpers/error';
import { t } from '../helpers/i18n';
import InventoryInformation from '../source/inventory/information';
import StockInformation from '../source/stock/information';
import StorageAddressesInformation from '../source/storageAddresses/information';
import BranchInformation from '../source/branches/information';
import UserInformation from '../source/users/information';
import ProductBranchesInformation from '../source/productBranches/information';
import ApprovalLevelInformation from '../source/approvalLevel/information';
import ApprovalLevelUserInformation from '../source/approvalLevelUser/information';
import ProductEanInformation from '../source/productEans/information';
import ProductInformation from '../source/products/information';
import { models } from '../../config/database';
import inventoryHelper from '../helpers/status/translateInventoryStatus';
 
async function validBranchCode(req) {
  let branchCode = req.body.branchCode || req.query.branchCode;
 
  if (branchCode && typeof branchCode === 'object') {
    branchCode = req.body.branchCode.value || req.query.branchCode.value;
  }
 
  if (!branchCode) {
    throw new APIError('', t('BEE1913' /* filial não localizada */));
  } else {
    const existBranch = await BranchInformation.getBranch(
      {
        code: branchCode,
      },
      { userBranches: req.userBranches }
    );
 
    if (!existBranch)
      throw new APIError(
        '',
        t('BEE1160', { 0: branchCode } /* Filial %{0} inválida ! */)
      );
  }
}
 
function validGrouperCode(req) {
  const grouperCode = req.body.grouperCode || req.query.grouperCode;
 
  if (!grouperCode) {
    throw new APIError('', t('BEE2121' /* Agrupador não localizada */));
  }
}
 
async function validInventorySheet(req) {
  const branchCode = req.body.branchCode || req.query.branchCode;
  const grouperCode = req.body.grouperCode || req.query.grouperCode;
 
  const inventoryData = await InventoryInformation.getInventory({
    branchCode,
    grouperCode,
  });
 
  if (!inventoryData) {
    throw new APIError(
      '',
      t('BEE2122' /* Não foi possível localizar o inventário */)
    );
  } else if (inventoryData && inventoryData.status === 5) {
    throw new APIError(
      '',
      t('BEE2123', { 0: grouperCode } /* O inventário %{0} já foi atualizado */)
    );
  } else if (inventoryData && inventoryData.status === 6) {
    throw new APIError(
      '',
      t('BEE2186', { 0: grouperCode } /* O inventário %{0} foi cancelado */)
    );
  } else if (inventoryData && inventoryData.status === 7) {
    throw new APIError(
      '',
      t('BEE2205', { 0: grouperCode } /* O inventário %{0} foi reprovado */)
    );
  }
}
 
async function validProductClientInventorySheet(req) {
  const branchCode = req.body.branchCode || req.query.branchCode;
  const grouperCode = req.body.grouperCode || req.query.grouperCode;
 
  const inventoryData = await InventoryInformation.getProductsBranchValidation({
    branchCode,
    grouperCode,
  });
 
  for (const sheets of inventoryData.sheets) {
    if (sheets.productCode && !sheets.productBranch.length) {
      throw new APIError(
        'INVALID_BRANCH_PRODUCT_CODE',
        t(
          'BEE1229',
          { 0: sheets.productCode } /* Produto filial %{0} não localizado */
        )
      );
    }
  }
}
 
async function validInventorySheetId(req) {
  const { inventorySheetId } = req.body;
  if (inventorySheetId) {
    const inventorySheet = await InventoryInformation.getInventorySheet(
      {
        id: inventorySheetId,
      },
      {
        attributes: ['status', 'firstCountStatus', 'sheetNumber'],
        include: [
          {
            required: true,
            model: models.Inventory,
            as: 'inventory',
            attributes: ['type'],
          },
        ],
      }
    );
 
    if (!inventorySheet) {
      throw new APIError(
        '',
        t('BEE2122' /* Não foi possível localizar o inventário */)
      );
    } else if (inventorySheet.status === 1) {
      throw new APIError('', t('BEE2124' /* Nenhuma contagem foi feita */));
    } else if (inventorySheet.firstCountStatus === 1) {
      throw new APIError('', t('BEE2124' /* Nenhuma contagem foi feita */));
    } else if (inventorySheet.status === 4) {
      throw new APIError(
        '',
        t(
          'BEE2125',
          { 0: inventorySheet.sheetNumber } /* A ficha %{0} já foi atualizada */
        )
      );
    } else if (inventorySheet.inventory.type === 3) {
      throw new APIError(
        '',
        t(
          'BEE3618' /* O inventário por etiqueta seriada não pode ser reaberto! */
        )
      );
    }
  } else {
    throw new APIError('NOT_FOUND_INVENTORY_SHEET_ID', '');
  }
}
 
async function validSheetType(req) {
  const { sheetType } = req.body;
 
  if (!sheetType) {
    throw new APIError(
      '',
      t('BEE2130' /* Tipo de ficha não foi selecionado */)
    );
  }
}
 
async function validInventoryId(req) {
  const inventoryId = req.body.inventoryId || req.query.inventoryId;
 
  if (!inventoryId) {
    throw new APIError('NOT_FOUND_INVENTORY_ID', '');
  } else {
    const inventory = await InventoryInformation.getInventory({
      id: inventoryId,
    });
    if (!inventory) {
      throw new APIError(
        '',
        t('BEE2122' /* Não foi possível localizar o inventário */)
      );
    }
  }
}
 
async function validAddressCode(req) {
  const { inventoryId, addressCode } = req.body;
 
  if (!addressCode) {
    throw new APIError('', t('BEE2128' /* Endereço não informado */));
  } else {
    const inventory = await InventoryInformation.getInventory({
      id: inventoryId,
    });
    const storageAddresses =
      await StorageAddressesInformation.getStorageAddress({
        branchCode: inventory.branchCode,
        code: addressCode,
      });
    if (!storageAddresses) {
      throw new APIError('', t('BEE1784' /* Endereço não localizado */));
    }
  }
}
 
async function validProductCode(req) {
  const { sheetType, inventoryId, addressCode, productCode } = req.body;
  if (sheetType === 2) {
    if (!productCode) {
      throw new APIError('', t('BEE2129' /* Produto não informado */));
    } else {
      const inventory = await InventoryInformation.getInventory({
        id: inventoryId,
      });
      const stockBalance = await StockInformation.getStockBalance({
        branchCode: inventory.branchCode,
        addressCode,
        productCode,
      });
      if (!stockBalance) {
        throw new APIError(
          '',
          t('BEE2133' /* Produto não localizado no estoque */)
        );
      }
    }
  }
}
 
async function validInventorySheetCreation(req) {
  const { sheetType, inventoryId, addressCode, productCode } = req.body;
 
  const query =
    sheetType === '1'
      ? { inventoryId, addressCode }
      : { inventoryId, addressCode, productCode: [productCode, ''] };
  const existInventorySheet = await InventoryInformation.getInventorySheet(
    query
  );
 
  if (existInventorySheet) {
    if (sheetType === '1') {
      throw new APIError(
        '',
        t('BEE2131' /* Já existe uma ficha com esse endereço cadastrado */)
      );
    } else {
      throw new APIError(
        '',
        t(
          'BEE2132' /* Já existe uma ficha com esse produto/endereço cadastrado */
        )
      );
    }
  } else if (sheetType === '2') {
    const inventory = await InventoryInformation.getInventory({
      id: inventoryId,
    });
    const stockBalance = await StockInformation.getStockBalance(
      {
        branchCode: inventory.branchCode,
        productCode,
        addressCode,
      },
      { include: [], attributes: ['id'] }
    );
 
    if (!stockBalance) {
      throw new APIError('', t('BEE3299' /* Estoque não encontrado */));
    }
  }
}
 
async function validCreateInventory(req) {
  const { branchCode, depositCode, grouperCode, sheetList, type } = req.body;
 
  if (!sheetList || sheetList.length === 0) {
    throw new APIError(
      '',
      t('BEE3058' /* Nenhum Produto/Endereço selecionado para inventariar! */)
    );
  }
 
  const existInventory = await InventoryInformation.getInventory({
    branchCode,
    grouperCode,
  });
 
  if (
    existInventory &&
    (existInventory.depositCode !== depositCode || existInventory.status > 2)
  ) {
    const inventoryStatus = inventoryHelper.inventoryStatus(
      existInventory.status,
      req.appLanguage
    );
    throw new APIError(
      '',
      t(
        'BEE3653',
        {
          0: grouperCode,
          1: existInventory.depositCode,
          2: inventoryStatus,
        } /* O Agrupador %{0} já existe! Depósito %{1}, Status: %{2} */,
        req.appLanguage
      )
    );
  }
 
  for (const sheet of sheetList) {
    if (sheet.productCode && existInventory) {
      const inventorySheet = await InventoryInformation.getAllInventorySheet({
        inventoryId: existInventory.id,
        branchCode,
        addressCode: sheet.addressCode,
        productCode: sheet.productCode,
        lotNumber: sheet.lotNumber,
        expirationDate: sheet.expirationDate,
      });
 
      if (inventorySheet && inventorySheet.length > 0) {
        throw new APIError(
          '',
          t(
            'BEE3064',
            {
              0: grouperCode,
            } /* Produto já possui ficha no Agrupador %{0}! */
          )
        );
      }
    }
 
    // Inventário por Etiqueta seriada
    if (type === '3') {
      const stock = await StockInformation.getStockBalance(
        {
          branchCode,
          addressCode: sheet.addressCode,
          [Op.or]: [
            {
              allocated: { [Op.gt]: 0 },
            },
            { reserved: { [Op.gt]: 0 } },
          ],
        },
        {
          attributes: ['addressCode'],
          include: [],
        }
      );
 
      if (stock) {
        throw new APIError(
          '',
          t(
            'BEE3616',
            {
              0: stock.addressCode,
            } /* O endereço %{0} possui quantidade alocada ou reservada! */,
            req.appLanguage
          )
        );
      }
    }
  }
}
 
async function validInventorySheetCounting(req) {
  const { grouperCode, branchCode } = req.body;
 
  const inventory = await InventoryInformation.getInventory({
    grouperCode,
    branchCode,
  });
 
  if (!inventory) {
    throw new APIError(
      '',
      t('BEE2140' /* Não foi possível localizar o inventario */)
    );
  } else {
    const inventorySheet = await InventoryInformation.getAllInventorySheet({
      inventoryId: inventory.id,
    });
    if (!inventorySheet) {
      throw new APIError(
        '',
        t('BEE2141' /* Não foi possível localizar as fichas do inventario */)
      );
    }
  }
}
 
async function validCheckedInventorySheetIds(req) {
  const { checkedInventorySheetIds } = req.body;
 
  if (!checkedInventorySheetIds.length) {
    throw new APIError('', t('BEE2142' /* Nenhum ficha selecionada */));
  }
}
 
async function validUserId(req) {
  const { userId } = req.body;
 
  if (!userId) {
    throw new APIError('', t('BEE2144' /* O usuário não foi selecionado */));
  }
}
 
async function validInventoryCount(req) {
  const { inventoryCount } = req.body;
 
  if (!inventoryCount) {
    throw new APIError('NOT_FOUND_INVENTORY_COUNT', '');
  }
}
 
async function validChangingCountingUser(req) {
  const { checkedInventorySheetIds, inventoryCount, userId, typeAction } =
    req.body;
 
  if (typeAction) {
    const inventorySheet = await InventoryInformation.getAllInventorySheet({
      id: checkedInventorySheetIds,
    });
    let error = false;
    for (let index = 0; index < inventorySheet.length; index += 1) {
      const element = inventorySheet[index];
 
      if (inventoryCount !== 1 && element.firstCountUser === userId) {
        checkedInventorySheetIds.splice(
          checkedInventorySheetIds.indexOf(`${element.id}`),
          1
        );
        error = true;
      } else if (inventoryCount !== 2 && element.secondCountUser === userId) {
        checkedInventorySheetIds.splice(
          checkedInventorySheetIds.indexOf(`${element.id}`),
          1
        );
        error = true;
      } else if (inventoryCount !== 3 && element.thirdCountUser === userId) {
        checkedInventorySheetIds.splice(
          checkedInventorySheetIds.indexOf(`${element.id}`),
          1
        );
        error = true;
      }
    }
 
    if (!checkedInventorySheetIds.length) {
      throw new APIError(
        '',
        t('BEE2146' /* Usuário esta responsável por outra contagem */)
      );
    } else if (error) {
      req.countValidation = true;
    } else {
      req.countValidation = false;
    }
  }
}
 
async function validFinalizeSheets(req) {
  const { inventoryId, inventorySheetIds } = req.body;
 
  if (!inventoryId) {
    throw new APIError('', t('BEE3065' /* Inventário deve ser informado */));
  } else {
    const inventory = await InventoryInformation.getInventory({
      id: inventoryId,
    });
    if (!inventory)
      throw new APIError(
        '',
        t('BEE2122' /* Não foi possível localizar o inventário */)
      );
 
    if (inventory.status === 6)
      throw new APIError('', t('BEE3066' /* Inventário cancelado! */));
    else if (inventory.status === 7)
      throw new APIError('', t('BEE3067' /* Inventário reprovado! */));
 
    const approvalLevel = await ApprovalLevelInformation.getApprovalLevel({
      branchCode: inventory.branchCode,
      inventoryType: inventory.type,
    });
 
    if (!approvalLevel)
      throw new APIError(
        '',
        t(
          'BEE3068' /* Altura de Aprovação não cadastrada para Filial / Tipo de Inventário! */
        )
      );
 
    const approvalLevelUser =
      await ApprovalLevelUserInformation.getApprovalLevelUser({
        approvalLevelId: approvalLevel.id,
        userId: req.userId,
      });
 
    if (!approvalLevelUser)
      throw new APIError(
        '',
        t('BEE3069' /* Usuário não possui Alçada de Aprovação cadastrada! */)
      );
 
    if (!inventorySheetIds || inventorySheetIds.length === 0) {
      throw new APIError(
        '',
        t('BEE3070' /* Nenhuma Ficha de Inventário selecionada! */)
      );
    } else {
      const sheets = await InventoryInformation.getAllInventorySheet({
        id: inventorySheetIds,
      });
 
      let differenceValue = 0;
      for (const sheet of sheets) {
        if (sheet.status < 3) {
          throw new APIError(
            '',
            t(
              'BEE3071',
              {
                0: sheet.sheetNumber,
              } /* Contagem da Ficha %{0} não está finalizada! */
            )
          );
        } else if (sheet.status === 3) {
          throw new APIError(
            '',
            t(
              'BEE3072',
              { 0: sheet.sheetNumber } /* Ficha %{0} não aprovada! */
            )
          );
        } else if (sheet.status === 5) {
          throw new APIError(
            '',
            t(
              'BEE3073',
              { 0: sheet.sheetNumber } /* Ficha %{0} já foi atualizada! */
            )
          );
        } else if (sheet.status === 6) {
          throw new APIError(
            '',
            t('BEE3074', { 0: sheet.sheetNumber } /* Ficha %{0} cancelada */)
          );
        } else if (sheet.status === 7) {
          throw new APIError(
            '',
            t('BEE3075', { 0: sheet.sheetNumber } /* Ficha %{0} reprovada */)
          );
        }
        let sheetDifferenceValue = 0;
        let countNumber = '';
 
        if (sheet.numberCounts === 1) countNumber = 'first';
        else if (sheet.numberCounts === 2) countNumber = 'second';
        else if (sheet.numberCounts === 3) countNumber = 'third';
 
        if (sheet.productCode) {
          const productBranches =
            await ProductBranchesInformation.getProductBranch({
              productCode: sheet.productCode,
              branchCode: sheet.branchCode,
            });
 
          if (productBranches) {
            const quantityCounted =
              parseFloat(sheet[`${countNumber}CountQuantity`]) -
              parseFloat(sheet[`${countNumber}CountBalance`]);
            sheetDifferenceValue =
              quantityCounted * parseFloat(productBranches.averageCost);
            differenceValue += sheetDifferenceValue;
          }
        }
      }
 
      if (
        Math.abs(differenceValue) > 0 &&
        (Math.abs(differenceValue) < approvalLevelUser.minimumValue ||
          Math.abs(differenceValue) > approvalLevelUser.maximumValue)
      ) {
        throw new APIError(
          '',
          t(
            'BEE3076' /* Valor da Diferença fora da Alçada de Aprovação do usuário! */
          )
        );
      }
    }
  }
}
 
async function validMainBranch(req) {
  const user = await UserInformation.getUser({
    id: req.userId,
  });
 
  if (!user.mainBranch)
    throw new APIError(
      'USER_MAIN_BRANCH',
      t('BEE3016' /* Usuário não possui Filial Principal parametrizada! */)
    );
 
  req.userMainBranch = user.mainBranch;
}
 
async function validCancelNote(req) {
  const { cancelNote } = req.body;
 
  if (!cancelNote)
    throw new APIError('', t('BEE1977' /* O campo motivo e obrigatório */));
}
 
async function validDisapprovedNote(req) {
  const { disapprovedNote } = req.body;
 
  if (!disapprovedNote)
    throw new APIError('', t('BEE1977' /* O campo motivo e obrigatório */));
}
 
async function validApproveSheets(req) {
  const { inventorySheetIds } = req.body;
 
  if (inventorySheetIds.length) {
    const inventorySheets = await InventoryInformation.getAllInventorySheet({
      id: inventorySheetIds,
    });
 
    if (inventorySheets) {
      for (const sheet of inventorySheets) {
        if (sheet.status < 3) {
          throw new APIError(
            '',
            t(
              'BEE3077' /* Não é possível liberar fichas com contagens pendentes! */
            )
          );
        } else if (sheet.status === 4 || sheet.status === 5) {
          throw new APIError(
            '',
            t('BEE3245' /* Não é possível liberar fichas atualizadas! */)
          );
        } else if (sheet.status === 6) {
          throw new APIError(
            '',
            t('BEE3246' /* Não é possível liberar fichas canceladas! */)
          );
        } else if (sheet.status === 7) {
          throw new APIError(
            '',
            t('BEE3247' /* Não é possível liberar fichas reprovadas! */)
          );
        }
      }
    } else {
      throw new APIError('', t('BEE2142' /* Nenhum ficha selecionada */));
    }
  } else {
    throw new APIError('', t('BEE2142' /* Nenhum ficha selecionada */));
  }
}
 
async function validCancelSheets(req) {
  const { inventorySheetIds } = req.body;
 
  if (inventorySheetIds.length) {
    const inventorySheets = await InventoryInformation.getAllInventorySheet({
      id: inventorySheetIds,
    });
 
    if (inventorySheets) {
      for (const sheet of inventorySheets) {
        if (sheet.status === 5) {
          throw new APIError(
            '',
            t('BEE3078' /* Não é possível cancelar fichas atualizadas! */)
          );
        } else if (sheet.status === 6) {
          throw new APIError(
            '',
            t('BEE3079' /* Não é possível cancelar fichas já canceladas! */)
          );
        } else if (sheet.status === 7) {
          throw new APIError(
            '',
            t('BEE3080' /* Não é possível cancelar fichas reprovadas! */)
          );
        } else if (sheet.inventory.type === 3 && sheet.status !== 1) {
          throw new APIError(
            '',
            t('BEE3619' /* Não é possível cancelar fichas que já iniciaram! */)
          );
        }
      }
    } else {
      throw new APIError('', t('BEE2142' /* Nenhum ficha selecionada */));
    }
  } else {
    throw new APIError('', t('BEE2142' /* Nenhum ficha selecionada */));
  }
}
 
async function validUpdateStatusInventory(req) {
  const { inventoryId } = req.body;
 
  const existInventorySheet = await InventoryInformation.getAllInventorySheet({
    inventoryId,
    status: 5,
  });
 
  if (existInventorySheet && existInventorySheet.length) {
    throw new APIError(
      '',
      t(
        'BEE2196' /* Esta ação não pode ser feita! Algumas fichas já foram atualizadas */
      )
    );
  }
}
 
async function validQuantityCounted(req) {
  const { quantityCounted, emptyAddress, finishAddress = false } = req.body;
 
  if (
    !emptyAddress &&
    !finishAddress &&
    (!quantityCounted || parseFloat(quantityCounted) < 0)
  ) {
    throw new APIError('', t('BEE1476' /* Quantidade Inválida! */));
  }
}
 
async function validSheetNumber(req) {
  const { inventoryId, sheetNumber } = req.body;
 
  if (!sheetNumber) {
    throw new APIError('', t('BEE3081' /* Ficha de Inventário Inválida! */));
  } else {
    const sheet = await InventoryInformation.getInventorySheet({
      inventoryId,
      sheetNumber,
      status: [1, 2], // PENDENTE OU EM CONTAGEM
      [Op.or]: [
        {
          [Op.and]: {
            firstCountUser: req.userId,
            firstCountStatus: 1,
            numberCounts: 0,
          },
        },
        {
          [Op.and]: {
            secondCountUser: req.userId,
            secondCountStatus: 1,
            numberCounts: 1,
          },
        },
        {
          [Op.and]: {
            thirdCountUser: req.userId,
            thirdCountStatus: 1,
            numberCounts: 2,
          },
        },
      ],
    });
 
    if (!sheet)
      throw new APIError(
        '',
        t('BEE2141' /* Não foi possível localizar as fichas do inventario */)
      );
  }
}
 
async function validAddProductEmptyAddress(req) {
  const {
    inventoryId,
    sheetNumber,
    emptyAddress,
    ean,
    lotNumber,
    expirationDate,
  } = req.body;
 
  if (!emptyAddress) {
    const sheet = await InventoryInformation.getInventorySheet({
      inventoryId,
      sheetNumber,
    });
 
    if (!sheet) {
      throw new APIError(
        '',
        t('BEE2141' /* Não foi possível localizar as fichas do inventario */)
      );
    } else if (sheet.numberCounts === 0 && sheet.stockBalanceId === 0) {
      if (!ean)
        throw new APIError(
          '',
          t('BEE3082' /* Produto/EAN deve ser informado! */)
        );
 
      const productEan = await ProductEanInformation.getProductEan({
        ean,
      });
 
      if (!productEan)
        throw new APIError('', t('BEE3083' /* EAN não localizado! */));
 
      const product = await ProductInformation.getProduct({
        productCode: productEan.productCode,
      });
 
      if (!product)
        throw new APIError('', t('BEE3005' /* Produto não localizado! */));
 
      if (product.stockControlType === 3 && (!lotNumber || lotNumber === ''))
        throw new APIError('', t('BEE3084' /* Lote não informado! */));
 
      if (product.controlExpirationDate && !expirationDate)
        throw new APIError(
          '',
          t('BEE2006' /* Data de validade não informada! */)
        );
    }
  }
}
 
function validDepositCode(req) {
  const depositCode = req.body.depositCode || req.query.depositCode;
 
  if (!depositCode)
    throw new APIError('', t('BEE1330' /* Depósito deve ser informado ! */));
}
 
function validCode(req) {
  const { code } = req.query;
 
  if (!code) {
    throw new APIError('', t('BEE2901' /* Código é obrigatório. */));
  }
}
 
function validSheetSerialGroupId(req) {
  const { sheetSerialGroupId } = req.body;
 
  if (!sheetSerialGroupId) {
    throw new APIError(
      '',
      t('BEE3445' /* Contagem de inventário não encontrada. */)
    );
  }
}
 
export default {
  validBranchCode,
  validGrouperCode,
  validInventorySheet,
  validInventorySheetId,
  validInventorySheetCreation,
  validSheetType,
  validInventoryId,
  validAddressCode,
  validProductCode,
  validCreateInventory,
  validInventorySheetCounting,
  validChangingCountingUser,
  validCheckedInventorySheetIds,
  validInventoryCount,
  validUserId,
  validMainBranch,
  validCancelNote,
  validUpdateStatusInventory,
  validQuantityCounted,
  validFinalizeSheets,
  validApproveSheets,
  validCancelSheets,
  validDisapprovedNote,
  validAddProductEmptyAddress,
  validSheetNumber,
  validProductClientInventorySheet,
  validDepositCode,
  validCode,
  validSheetSerialGroupId,
};