All files / source/inboundOrders import.js

82.12% Statements 193/235
68.92% Branches 122/177
72.72% Functions 8/11
82.32% Lines 191/232

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 895 896 897 898 899 900                                                  28x 28x 28x 28x 28x 28x   28x 1x 1x 1x   27x       27x 1x 1x 1x           27x 1x 1x 1x       28x 1x 1x 1x   27x       27x 1x 1x 1x                 28x 1x 1x 1x     28x 27x       27x 1x 1x 1x                 28x       28x                       28x 28x         28x 1x 1x 1x         27x 26x   27x 27x                                                               28x 20x             20x 3x 1x 1x 1x 2x 1x 1x 1x       17x 1x 1x 1x                       28x 8x 8x 8x   20x       20x           2x 2x 2x                 28x 1x 1x 1x     27x   27x 22x 22x 6x 6x 6x         22x 6x 6x 6x 6x           6x             6x 6x 6x 6x       22x 1x 1x 1x   21x       21x 1x 1x 1x             22x 1x 1x 1x 21x       2x 2x 2x           22x 1x 1x 1x   21x       21x 1x 1x 1x             22x 5x 5x 5x 5x     5x   5x 1x 1x 1x         5x 1x 1x 1x       4x       4x 1x 1x 1x             5x 1x 1x 1x       4x     5x 1x 1x 1x                 28x                           1x       1x                                             1x       3x 3x                                                                                 2x 2x                                                               2x       1x 1x 1x           1x 1x 1x                                                   1x         1x   1x             1x         1x   1x                   1x                                   1x                                                                                                                                                                                                                                                                                                                                                   28x   28x 28x   28x 27x                     1x                                           1x     1x         1x       1x                                                           1x             1x   1x   1x 1x         1x                 1x 1x                                         28x              
import moment from 'moment-timezone';
import { sequelize } from '../../../config/database';
import InboundOrderDao from '../../database/dao/inboundOrder';
import InboundOrderProductDao from '../../database/dao/inboundOrderProduct';
import { t } from '../../helpers/i18n';
 
import BranchInformation from '../branches/information';
import CarrierInformation from '../carriers/information';
import DepositInformation from '../deposits/information';
import InboundOrderProductDelete from '../inboundOrderProducts/delete';
import InboundOrderProductInformation from '../inboundOrderProducts/information';
import OrderTypeConfigSearch from '../orderTypeConfig/search';
import OutboundOrderInformation from '../outboundOrders/information';
import ProductInformation from '../products/information';
import StockDelete from '../stock/delete';
import StockMovement from '../stock/movement';
import SupplierInformation from '../suppliers/information';
import TypeOrderInformation from '../typeOrders/information';
import UnitMeasureInformation from '../unitsMeasure/information';
import InboundOrderInformation from './information';
import IntegrationQueueErp from '../integrationQueueErp/queue';
import CrossdockingDao from '../../database/dao/crossdocking';
import CustomerInformation from '../customers/information';
 
async function validInboundOrder(inboundOrder) {
  let isValid = true;
  let code = '';
  let message = '';
  let isReturn = false;
  let orderTypeValid = null;
  let isOrderTypeValid = false;
 
  if (!inboundOrder.branchCode) {
    isValid = false;
    code = 9000;
    message = t('BEE1285' /* Código da filial deve ser informada */);
  } else {
    const existBranch = await BranchInformation.getBranch({
      code: inboundOrder.branchCode,
    });
 
    if (!existBranch) {
      isValid = false;
      code = 9001;
      message = t(
        'BEE1307',
        { 0: inboundOrder.branchCode } /* Código da filial %{0} inválido */
      );
    }
 
    if (existBranch && existBranch.branchInInventory) {
      isValid = false;
      code = 9002;
      message = t('BEE3761' /* Filial em processo de inventário. */);
    }
  }
 
  if (!inboundOrder.supplierCode) {
    isValid = false;
    code = 9003;
    message = t('BEE1308' /* Código do fornecedor deve ser informado */);
  } else {
    const existSupplier = await SupplierInformation.getSupplier({
      code: inboundOrder.supplierCode,
    });
 
    if (!existSupplier) {
      isValid = false;
      code = 9004;
      message = t(
        'BEE1309',
        {
          0: inboundOrder.supplierCode,
        } /* Código do fornecedor %{0} inválido */
      );
    }
  }
 
  if (!inboundOrder.orderNumber) {
    isValid = false;
    code = 9005;
    message = t('BEE1310' /* Número do documento deve ser informado */);
  }
 
  if (inboundOrder.carrierCode || inboundOrder.carrierCode === '0') {
    const existCarrier = await CarrierInformation.getCarrier({
      code: inboundOrder.carrierCode,
    });
 
    if (!existCarrier) {
      isValid = false;
      code = 9007;
      message = t(
        'BEE1318',
        {
          0: inboundOrder.carrierCode,
        } /* Código da Transportadora %{0} inválido */
      );
    }
  }
 
  Iif (!inboundOrder.orderType && !inboundOrder.depositCode) {
    isValid = false;
    code = 9008;
    message = t('BEE1330' /* Depósito deve ser informado ! */);
  } else Iif (inboundOrder.depositCode) {
    const existDeposit = await DepositInformation.getDeposit({
      code: inboundOrder.depositCode,
    });
 
    if (!existDeposit) {
      isValid = false;
      code = 9009;
      message = t('BEE3318' /* Depósito inválido */);
    }
  }
 
  if (inboundOrder.orderType) {
    const typeOrder = await TypeOrderInformation.getTypeOrder({
      branchCode: inboundOrder.branchCode,
      type: inboundOrder.orderType,
    });
 
    if (!typeOrder) {
      isValid = false;
      code = 9010;
      message = t(
        'BEE1312',
        { 0: inboundOrder.orderType } /* Tipo do documento %{0} inválido */
      );
    } else {
      if (typeOrder.customerReturn) {
        isReturn = true;
      }
      isOrderTypeValid = true;
      orderTypeValid = inboundOrder.orderType;
    }
  } else E{
    // BUSCAR TIPO DE DOCUMENTO
    let stockGroupCode = null;
    if (inboundOrder.products && inboundOrder.products.length > 0) {
      const { productCode } = inboundOrder.products[0];
      const product = await ProductInformation.getProduct({
        productCode,
      });
      stockGroupCode =
        product && product.stockGroup ? product.stockGroup : null;
    }
 
    const orderTypeConfig = await OrderTypeConfigSearch.searchOrderTypeConfigs({
      branchCode: inboundOrder.branchCode,
      movementType: 1,
      depositCode: inboundOrder.depositCode,
      customerSupplierCode: inboundOrder.supplierCode,
      carrierCode: inboundOrder.carrierCode,
      stockGroupCode,
      cfop: inboundOrder.cfop,
    });
 
    if (orderTypeConfig) {
      orderTypeValid = orderTypeConfig.orderType;
      isOrderTypeValid = true;
    } else {
      isOrderTypeValid = false;
    }
  }
 
  if (isValid && isOrderTypeValid) {
    const existOrder = await InboundOrderInformation.getInboundOrderValidation({
      branchCode: inboundOrder.branchCode,
      supplierCode: inboundOrder.supplierCode,
      orderNumber: inboundOrder.orderNumber,
      orderType: orderTypeValid,
    });
 
    if (inboundOrder.canceled) {
      if (!existOrder) {
        isValid = false;
        code = 9011;
        message = t('BEE3758' /* Documento de entrada não encontrado. */);
      } else if (existOrder.status > 3 && existOrder.status < 9) {
        isValid = false;
        code = 9012;
        message = t(
          'BEE3759' /* A entrada do documento já foi iniciada ou processada totalmente. */
        );
      }
    } else if (existOrder && existOrder.status > 3 && existOrder.status < 9) {
      isValid = false;
      code = 9013;
      message = t(
        'BEE1316',
        {
          0: inboundOrder.branchCode,
          1: inboundOrder.supplierCode,
          2: inboundOrder.orderNumber,
          3: orderTypeValid,
        } /* Status do Documento de Entrada %{0} - %{1} - %{2} - %{3} não permite alteração */
      );
    }
  }
 
  if (!inboundOrder.accessKey || inboundOrder.accessKey === '') {
    isValid = false;
    code = 9014;
    message = t('BEE1313' /* Chave de Acesso deve ser informado */);
  } else {
    const existOrder = await InboundOrderInformation.getInboundOrderValidation({
      accessKey: inboundOrder.accessKey,
    });
 
    if (
      !inboundOrder.canceled &&
      existOrder &&
      existOrder.status > 3 &&
      existOrder.status < 9
    ) {
      isValid = false;
      code = 9015;
      message = t(
        'BEE3760',
        {
          0: inboundOrder.accessKey,
        } /* Chave de Acesso %{0} já cadastrada! */
      );
    }
  }
 
  if (!inboundOrder.products || inboundOrder.products.length === 0) {
    isValid = false;
    code = 9016;
    message = t('BEE1319' /* Produtos do documento devem ser informados */);
  } else {
    // Validar os produtos
    const { products } = inboundOrder;
 
    if (!inboundOrder.canceled) {
      for (const product of products) {
        if (!product.lineNumber) {
          isValid = false;
          code = 9017;
          message = t(
            'BEE1320' /* Número da linha no documento deve ser informada */
          );
        }
 
        if (isReturn && isValid) {
          Eif (!product.outboundOrderNumber) {
            isValid = false;
            code = 9018;
            message = t(
              'BEE3767' /* O número do documento de saída deve ser informado. */
            );
          }
 
          const existOutboundOrder =
            await OutboundOrderInformation.getOutboundOrder({
              branchCode: inboundOrder.branchCode,
              customerCode: inboundOrder.supplierCode,
              invoiceNumber: product.outboundOrderNumber,
              invoiceSerie: product.outboundOrderSerie,
            });
 
          Eif (!existOutboundOrder) {
            isValid = false;
            code = 9019;
            message = t('BEE3779' /* Documento de saída inválido. */);
          }
        }
 
        if (!product.productCode) {
          isValid = false;
          code = 9020;
          message = t('BEE1288' /* Código do produto deve ser informado */);
        } else {
          const existProduct = await ProductInformation.getProduct({
            productCode: product.productCode,
          });
 
          if (!existProduct) {
            isValid = false;
            code = 9021;
            message = t(
              'BEE1321',
              { 0: product.productCode } /* Código do produto %{0} inválido */
            );
          }
        }
 
        if (!product.quantity) {
          isValid = false;
          code = 9022;
          message = t('BEE1322' /* Quantidade prevista deve ser informada */);
        } else if (
          typeof product.quantity !== 'number' ||
          product.quantity <= 0
        ) {
          isValid = false;
          code = 9023;
          message = t(
            'BEE1323',
            { 0: product.quantity } /* Quantidade prevista %{0} inválida */
          );
        }
 
        if (!product.unitMeasure) {
          isValid = false;
          code = 9024;
          message = t('BEE1303' /* Unidade de medida deve ser informada */);
        } else {
          const existUnit = await UnitMeasureInformation.getUnitMeasure({
            code: product.unitMeasure,
          });
 
          if (!existUnit) {
            isValid = false;
            code = 9025;
            message = t(
              'BEE1211',
              { 0: product.unitMeasure } /* Unidade de medida %{0} inválida ! */
            );
          }
        }
 
        if (product.crossdocking) {
          const { crossdocking } = product;
          let crossdockingTotalQuantity = 0;
          for (let i = 0; i < crossdocking.length; i++) {
            const crossdockingProduct = crossdocking[i];
 
            const { customerCode, customerOrderCode, quantity } =
              crossdockingProduct;
 
            if (!customerOrderCode) {
              isValid = false;
              code = 9026;
              message = t(
                'BEE4349' /* O pedido do cliente para o crossdocking deve ser informado */
              );
            }
 
            if (!customerCode) {
              isValid = false;
              code = 9027;
              message = t(
                'BEE4350' /* O código do cliente para o crossdocking deve ser informado */
              );
            } else {
              const existCustomer = await CustomerInformation.getCustomer({
                code: customerCode,
              });
 
              if (!existCustomer) {
                isValid = false;
                code = 9028;
                message = t(
                  'BEE1187',
                  { 0: customerCode } /* Cliente %{0} não cadastrado */
                );
              }
            }
 
            if (!quantity) {
              isValid = false;
              code = 9029;
              message = t(
                'BEE4351' /* A quantidade para o crossdocking deve ser informada */
              );
            } else {
              crossdockingTotalQuantity += quantity;
            }
          }
          if (crossdockingTotalQuantity > product.quantity) {
            isValid = false;
            code = 9030;
            message = t(
              'BEE4352' /* A quantidade para o crossdocking deve ser menor ou igual à quantidade do produto da ordem */
            );
          }
        }
      }
    }
  }
 
  return {
    isValid,
    code,
    message,
    orderTypeValid,
    isOrderTypeValid,
  };
}
 
async function createInboundMovement(
  userId,
  inboundOrder,
  inboundOrderProduct
) {
  const branchInfo = await BranchInformation.getBranchSettings({
    code: inboundOrder.branchCode,
  });
 
  const newMovement = await StockMovement.createMovement({
    branchCode: inboundOrder.branchCode,
    warehouseCode: inboundOrder.branchCode,
    depositCode: branchInfo.preReceiptDeposit,
    addressCode: '',
    productCode: inboundOrderProduct.productCode,
    productLineNumber: inboundOrderProduct.lineNumber,
    lotNumber: '',
    operation: 'REC',
    type: 1,
    quantity: inboundOrderProduct.quantity,
    unitMeasure: inboundOrderProduct.unitMeasure,
    serie: inboundOrder.serie,
    orderNumber: inboundOrder.orderNumber,
    supplierCode: inboundOrder.supplierCode,
    expirationDate: null,
    manufacturingDate: null,
    baptismLabel: null,
    movementUser: userId,
    createdUser: userId,
    updatedUser: userId,
  });
 
  return newMovement;
}
 
async function createInboundOrder(inboundOrder) {
  return sequelize.transaction(async (transaction) => {
    const newInboundOrder = await InboundOrderDao.createInboundOrder(
      {
        branchCode: inboundOrder.branchCode,
        supplierCode: inboundOrder.supplierCode,
        orderNumber: inboundOrder.orderNumber,
        orderType: inboundOrder.orderType,
        serie: inboundOrder.serie,
        specie: inboundOrder.specie,
        accessKey: inboundOrder.accessKey,
        carrierCode: inboundOrder.carrierCode,
        licensePlate: inboundOrder.licensePlate,
        expectedVolumes: inboundOrder.expectedVolumes || 0,
        status: inboundOrder.status,
        preConferenceLabelPrinting: false,
        preConfLabelPrintAt: null,
        cfop: inboundOrder.cfop,
        deliveryDate:
          inboundOrder.deliveryDate &&
          moment(inboundOrder.deliveryDate, 'DD/MM/YYYY', true).format()
            ? moment(inboundOrder.deliveryDate, 'DD/MM/YYYY', true).format()
            : new Date(moment().format('MM/DD/YYYY')),
        postalCode: inboundOrder.postalCode,
        ibge: inboundOrder.ibge,
        street: inboundOrder.street,
        number: inboundOrder.number,
        complement: inboundOrder.complement,
        district: inboundOrder.district,
        city: inboundOrder.city,
        state: inboundOrder.state,
        country: inboundOrder.country,
        note: inboundOrder.note,
        createdUser: inboundOrder.createdUser,
        createdAt: moment().format(),
        updatedUser: inboundOrder.updatedUser,
        updatedAt: moment().format(),
      },
      {
        transaction,
      }
    );
 
    Eif (newInboundOrder) {
      const products = await inboundOrder.products.map((product) => ({
        inboundOrderId: newInboundOrder.id,
        outboundOrderNumber: product.outboundOrderNumber,
        outboundOrderSerie: product.outboundOrderSerie,
        branchCode: newInboundOrder.branchCode,
        lineNumber: product.lineNumber,
        productCode: product.productCode,
        supplierProductCode: product.supplierProductCode,
        quantity: product.quantity,
        deliveryDate:
          product.deliveryDate &&
          moment(product.deliveryDate, 'DD/MM/YYYY', true).format()
            ? moment(product.deliveryDate, 'DD/MM/YYYY', true).format()
            : new Date(moment().format('MM/DD/YYYY')),
        unitMeasure: product.unitMeasure,
        purchaseRequest: product.purchaseRequest,
        purchaseOrder: product.purchaseOrder,
        installment: product.installment,
        crossDockingOrder: product.crossDockingOrder,
        crossDockingQuantity: product.crossDockingQuantity,
        status: product.status ? product.status : 1,
        note: product.note,
        inspection: product.inspection ? product.inspection : 0,
        inspectionDetails: product.notes,
        crossdocking: product.crossdocking ? product.crossdocking : [],
        createdUser: inboundOrder.createdUser,
        createdAt: moment().format(),
        updatedUser: inboundOrder.updatedUser,
        updatedAt: moment().format(),
      }));
 
      const resultInboundOrderProducts =
        await InboundOrderProductDao.createInboundOrderProducts(products, {
          transaction,
        });
 
      Eif (resultInboundOrderProducts) {
        for (const [i, product] of products.entries()) {
          const inboundMovement = await createInboundMovement(
            inboundOrder.createdUser,
            inboundOrder,
            product
          );
 
          Eif (product.crossdocking && product.crossdocking.length > 0) {
            for (const crossDocking of product.crossdocking) {
              await CrossdockingDao.createCrossdocking(
                {
                  branchCode: inboundOrder.branchCode,
                  productCode: product.productCode,
                  inboundOrderId: newInboundOrder.id,
                  inboundOrderProductId: resultInboundOrderProducts[i].id,
                  customerOrderCode: crossDocking.customerOrderCode,
                  customerCode: crossDocking.customerCode,
                  quantity: crossDocking.quantity,
                  stockBalanceId: inboundMovement.stockBalanceId,
                  status: 1,
                  createdUser: inboundOrder.createdUser,
                  updatedUser: inboundOrder.updatedUser,
                  createdAt: moment().format(),
                  updatedAt: moment().format(),
                },
                {
                  transaction,
                }
              );
            }
          }
        }
      }
    }
 
    return newInboundOrder;
  });
}
 
async function cancelInboundOrder(existOrder, userId) {
  return sequelize.transaction(async (transaction) => {
    const inboundOrderProducts =
      await InboundOrderProductInformation.getInboundOrderProducts(
        {
          inboundOrderId: existOrder.id,
        },
        { transaction }
      );
 
    const branchInfo = await BranchInformation.getBranchSettings({
      code: existOrder.branchCode,
    });
 
    // Cancelar Produtos e Desfazer entrada no pre recebimento
    for (const inboundProduct of inboundOrderProducts) {
      // Desfaz entrada pre recebimento
      await StockDelete.deleteStockMovement(
        branchInfo.preReceiptDeposit,
        existOrder.orderNumber,
        inboundProduct.productCode,
        inboundProduct.lineNumber,
        [1],
        userId,
        transaction
      );
 
      await InboundOrderProductDao.updateInboundOrderProduct(
        {
          id: inboundProduct.id,
        },
        {
          status: 6,
          cancelProductUser: userId,
          cancelProductAt: moment().format(),
          updatedUser: userId,
          updatedAt: moment().format(),
        },
        {
          transaction,
        }
      );
    }
 
    // Cancelar Documento
    await InboundOrderDao.updateInboundOrder(
      {
        id: existOrder.id,
      },
      {
        canceled: true,
        cancelOrderUser: userId,
        cancelOrderAt: moment().format(),
        updatedUser: userId,
        updatedAt: moment().format(),
      },
      {
        transaction,
      }
    );
  });
}
 
async function updateInboundOrder(inboundOrder, existOrder) {
  return sequelize.transaction(async (transaction) => {
    const updInboundOrder = await InboundOrderDao.updateInboundOrder(
      {
        id: existOrder.id,
      },
      {
        carrierCode: inboundOrder.carrierCode,
        licensePlate: inboundOrder.licensePlate,
        expectedVolumes: inboundOrder.expectedVolumes,
        status: inboundOrder.status,
        preConferenceLabelPrinting: false,
        preConfLabelPrintAt: null,
        canceled: false,
        cancelOrderUser: null,
        cancelOrderAt: null,
        cancelNote: '',
        cfop: inboundOrder.cfop,
        deliveryDate:
          inboundOrder.deliveryDate &&
          moment(inboundOrder.deliveryDate, 'DD/MM/YYYY', true).format()
            ? moment(inboundOrder.deliveryDate, 'DD/MM/YYYY', true).format()
            : new Date(moment().format('MM/DD/YYYY')),
        postalCode: inboundOrder.postalCode,
        ibge: inboundOrder.ibge,
        street: inboundOrder.street,
        number: inboundOrder.number,
        complement: inboundOrder.complement,
        district: inboundOrder.district,
        city: inboundOrder.city,
        state: inboundOrder.state,
        country: inboundOrder.country,
        note: inboundOrder.note,
        updatedUser: inboundOrder.updatedUser,
        updatedAt: moment().format(),
      },
      {
        transaction,
      }
    );
 
    if (updInboundOrder) {
      const inboundOrderProducts =
        await InboundOrderProductInformation.getInboundOrderProducts({
          inboundOrderId: existOrder.id,
        });
 
      const branchInfo = await BranchInformation.getBranchSettings({
        code: inboundOrder.branchCode,
      });
 
      // Elimina os produtos da ordem para criar novamente
      for (const inboundProduct of inboundOrderProducts) {
        await InboundOrderProductDelete.deleteInboundOrderProduct(
          inboundProduct.id
        );
 
        // Desfaz entrada pre recebimento
        await StockDelete.deleteStockMovement(
          branchInfo.preReceiptDeposit,
          inboundOrder.orderNumber,
          inboundProduct.productCode,
          inboundProduct.lineNumber,
          [1],
          inboundOrder.updatedUser,
          transaction
        );
 
        await CrossdockingDao.deleteCrossdocking(
          {
            inboundOrderProductId: inboundProduct.id,
          },
          {
            transaction,
          }
        );
      }
 
      const products = await inboundOrder.products.map((product) => ({
        inboundOrderId: existOrder.id,
        branchCode: existOrder.branchCode,
        lineNumber: product.lineNumber,
        outboundOrderNumber: product.outboundOrderNumber,
        outboundOrderSerie: product.outboundOrderSerie,
        productCode: product.productCode,
        supplierProductCode: product.supplierProductCode,
        quantity: product.quantity,
        deliveryDate:
          product.deliveryDate &&
          moment(product.deliveryDate, 'DD/MM/YYYY', true).format()
            ? moment(product.deliveryDate, 'DD/MM/YYYY', true).format()
            : new Date(moment().format('MM/DD/YYYY')),
        unitMeasure: product.unitMeasure,
        purchaseRequest: product.purchaseRequest,
        purchaseOrder: product.purchaseOrder,
        installment: product.installment,
        crossDockingOrder: product.crossDockingOrder,
        crossDockingQuantity: product.crossDockingQuantity,
        note: product.note,
        crossdocking: product.crossdocking ? product.crossdocking : [],
        createdUser: inboundOrder.createdUser,
        createdAt: moment().format(),
        updatedUser: inboundOrder.updatedUser,
        updatedAt: moment().format(),
      }));
 
      const resultInboundOrderProducts =
        await InboundOrderProductDao.createInboundOrderProducts(products, {
          transaction,
        });
 
      if (resultInboundOrderProducts) {
        for (const [i, product] of products.entries()) {
          const inboundMovement = await createInboundMovement(
            inboundOrder.createdUser,
            inboundOrder,
            product
          );
 
          if (product.crossdocking && product.crossdocking.length > 0) {
            for (const crossDocking of product.crossdocking) {
              await CrossdockingDao.createCrossdocking(
                {
                  branchCode: inboundOrder.branchCode,
                  productCode: product.productCode,
                  inboundOrderId: existOrder.id,
                  inboundOrderProductId: resultInboundOrderProducts[i].id,
                  customerOrderCode: crossDocking.customerOrderCode,
                  customerCode: crossDocking.customerCode,
                  quantity: crossDocking.quantity,
                  stockBalanceId: inboundMovement.stockBalanceId,
                  status: 1,
                  createdUser: inboundOrder.createdUser,
                  updatedUser: inboundOrder.updatedUser,
                  createdAt: moment().format(),
                  updatedAt: moment().format(),
                },
                {
                  transaction,
                }
              );
            }
          }
        }
      }
    }
 
    return updInboundOrder;
  });
}
 
async function importInboundOrders(inboundOrders, userId) {
  const listInboundOrdersErrors = [];
 
  for (const inboundOrder of inboundOrders) {
    const valid = await validInboundOrder(inboundOrder);
 
    if (!valid.isValid) {
      listInboundOrdersErrors.push({
        code: {
          branchCode: inboundOrder.branchCode,
          supplierCode: inboundOrder.supplierCode,
          orderNumber: inboundOrder.orderNumber,
          orderType: inboundOrder.orderType || valid.orderTypeValid,
          serie: inboundOrder.serie,
        },
        error: valid.code,
        message: valid.message,
      });
    } else Iif (!valid.isOrderTypeValid || !valid.orderTypeValid) {
      const queueId = await IntegrationQueueErp.createIntegrationQueue(
        'inboundOrder',
        {
          ...inboundOrder,
          tableKey: `${inboundOrder.branchCode} | ${inboundOrder.supplierCode} | ${inboundOrder.orderNumber}`,
        },
        userId
      );
 
      if (queueId) {
        await IntegrationQueueErp.updateIntegrationQueue(
          queueId,
          {
            status: 998,
            message: t('BEE4133' /* Erro ao buscar tipo de documento */),
            body: JSON.stringify(inboundOrder),
          },
          userId
        );
      }
    } else {
      const branch = await BranchInformation.getBranch({
        code: inboundOrder.branchCode,
      });
      const typeOrder = await TypeOrderInformation.getTypeOrder({
        branchCode: inboundOrder.branchCode,
        type: valid.orderTypeValid,
      });
 
      const isCheckPlate = typeOrder
        ? typeOrder.inboundCheckPlate
        : branch.inboundCheckPlate;
 
      const newInboundOrder = {
        branchCode: inboundOrder.branchCode,
        supplierCode: inboundOrder.supplierCode,
        orderNumber: inboundOrder.orderNumber,
        orderType: typeOrder.type,
        serie: inboundOrder.serie,
        specie: inboundOrder.specie,
        accessKey: inboundOrder.accessKey,
        carrierCode: inboundOrder.carrierCode,
        licensePlate: inboundOrder.licensePlate,
        expectedVolumes: inboundOrder.expectedVolumes,
        status: isCheckPlate ? 1 : 3,
        cfop: inboundOrder.cfop,
        deliveryDate: inboundOrder.deliveryDate,
        postalCode: inboundOrder.postalCode,
        ibge: inboundOrder.ibge,
        street: inboundOrder.street,
        number: inboundOrder.number,
        complement: inboundOrder.complement,
        district: inboundOrder.district,
        city: inboundOrder.city,
        state: inboundOrder.state,
        country: inboundOrder.country,
        note: inboundOrder.note,
        products: inboundOrder.products,
        createdUser: userId,
        updatedUser: userId,
      };
 
      const existOrder =
        await InboundOrderInformation.getInboundOrderValidation({
          branchCode: inboundOrder.branchCode,
          supplierCode: inboundOrder.supplierCode,
          orderNumber: inboundOrder.orderNumber,
          orderType: typeOrder.type,
        });
 
      let inboundOrderCreated = null;
 
      Iif (!existOrder) {
        inboundOrderCreated = await createInboundOrder(newInboundOrder);
      } else if (inboundOrder.canceled) {
        await cancelInboundOrder(existOrder, userId);
      } else E{
        await updateInboundOrder(newInboundOrder, existOrder);
      }
 
      const queueId = await IntegrationQueueErp.createIntegrationQueue(
        'inboundOrder',
        {
          ...inboundOrder,
          tableKey: `${inboundOrder.branchCode} | ${inboundOrder.supplierCode} | ${inboundOrder.orderNumber}`,
        },
        userId
      );
 
      Eif (queueId) {
        await IntegrationQueueErp.updateIntegrationQueue(
          queueId,
          {
            tableKey: `${inboundOrder.branchCode} | ${inboundOrder.supplierCode} | ${inboundOrder.orderNumber} | ${typeOrder.type}`,
            tableId: existOrder ? existOrder.id : inboundOrderCreated.id,
            status: 200,
            message: t(
              'BEE3928',
              {
                0: inboundOrder.orderNumber,
              } /* Documento de entrada %{0} criado com sucesso */
            ),
            body: JSON.stringify(inboundOrder),
            integratedAt: moment().format(),
          },
          userId
        );
      }
    }
  }
 
  return { listInboundOrdersErrors };
}
 
export default {
  createInboundOrder,
  importInboundOrders,
};