All files / services/totvs inboundOrders.js

78.04% Statements 32/41
58.49% Branches 31/53
100% Functions 1/1
78.04% Lines 32/41

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                                        3x 3x           2x     2x                         2x     2x 2x                     2x       2x 2x       2x       2x 2x   2x 2x                       2x 2x       2x                                                                   2x   2x           2x           1x 1x         1x                   1x               1x                             1x   1x   1x 1x         1x             1x                  
import moment from 'moment-timezone';
import { Op } from 'sequelize';
 
import isJson from '../../helpers/validators/totvs';
import RestService from './rest';
 
import InboundOrderProductInformation from '../../source/inboundOrderProducts/information';
import InboundOrderProductStorageUpdate from '../../source/inboundOrderProductStorages/update';
import InboundOrderInformation from '../../source/inboundOrders/information';
import DepositsInformation from '../../source/deposits/information';
import StockInformation from '../../source/stock/information';
 
import QueueCreate from '../../source/integrationQueue/create';
import QueueInformation from '../../source/integrationQueue/information';
import QueueUpdate from '../../source/integrationQueue/update';
 
import APIError from '../../helpers/error';
import { t } from '../../helpers/i18n';
 
async function sendInboundProductStorage(inboundProductStorage, userId) {
  let queueId = null;
  const existQueue = await QueueInformation.getIntegrationQueue({
    code: 'inboundProductStorage',
    tableId: inboundProductStorage.id,
    status: { [Op.ne]: 200 },
  });
 
  Iif (existQueue) {
    queueId = existQueue.id;
  } else {
    const newQueue = await QueueCreate.createIntegrationQueue({
      code: 'inboundProductStorage',
      tableId: inboundProductStorage ? inboundProductStorage.id : 0,
      branchCode: inboundProductStorage ? inboundProductStorage.branchCode : '',
      type: 1,
      body: '',
      response: '',
      message: '',
      status: 999,
      createdUser: userId,
      updatedUser: userId,
    });
 
    queueId = newQueue.id;
  }
 
  try {
    Iif (!inboundProductStorage) {
      const message = t('BEE3174' /* Produto armazenado deve ser informado */);
 
      await QueueUpdate.updateIntegrationQueue(queueId, {
        message,
        updatedUser: userId,
      });
 
      throw new APIError('', message);
    } else {
      const product =
        await InboundOrderProductInformation.getInboundOrderProduct({
          id: inboundProductStorage.inboundOrderProductId,
        });
 
      Eif (product) {
        const order = await InboundOrderInformation.getInboundOrder({
          id: product.inboundOrderId,
        });
 
        const stockBalance = await StockInformation.getStockBalance({
          id: inboundProductStorage.stockBalanceId,
        });
 
        Eif (order) {
          let depositCode = '';
 
          Eif (inboundProductStorage && inboundProductStorage.depositCode) {
            const deposit = await DepositsInformation.getDeposit(
              {
                code: inboundProductStorage.depositCode,
              },
              {
                attributes: ['code', 'codeErp'],
                include: [],
                raw: true,
                nest: true,
              }
            );
 
            Eif (deposit) {
              depositCode = deposit.codeErp || deposit.code;
            }
          }
 
          const json = {
            conferences: [
              {
                serie: order.serie || '',
                orderNumber: order.orderNumber,
                supplierCode: order.supplierCode,
                branchCode: order.branchCode,
                depositCode,
                lineNumber: product.lineNumber,
                productCode: product.productCode,
                quantityStorage: inboundProductStorage.quantityStorage || 0,
                quantityDamage: inboundProductStorage.quantityDamage || 0,
                quantityDivergence:
                  inboundProductStorage.quantityDivergence || 0,
                storages: [
                  {
                    depositCode,
                    quantityStorage: inboundProductStorage.quantityStorage || 0,
                    expirationDate:
                      (stockBalance &&
                        stockBalance.expirationDate &&
                        moment(stockBalance.expirationDate).format(
                          'DD/MM/YYYY'
                        )) ||
                      '',
                    lotNumber: stockBalance
                      ? stockBalance.lotNumber
                      : inboundProductStorage.lotNumber,
                  },
                ],
              },
            ],
          };
 
          const tableKey = `${order.supplierCode} | ${order.serie} | ${order.orderNumber} | ${product.lineNumber} | ${product.productCode}`;
 
          await QueueUpdate.updateIntegrationQueue(queueId, {
            body: JSON.stringify(json),
            tableKey,
            updatedUser: userId,
          });
 
          const result = await RestService.requestRest(
            order.branchCode,
            json,
            'inboundProductStorage'
          );
 
          Eif (isJson(result.data)) {
            Eif (
              result &&
              result.status === 200 &&
              result.data.retorno === 'Arquivo recebido com sucesso!'
            ) {
              await InboundOrderProductStorageUpdate.updateInboundOrderProductStorage(
                inboundProductStorage.id,
                {
                  integrated: true,
                  integratedAt: moment().format(),
                  updatedUser: userId,
                }
              );
            }
 
            await QueueUpdate.updateIntegrationQueue(queueId, {
              response: JSON.stringify(result.data),
              status: result.status,
              message: result.data.retorno || '',
              integratedAt: moment().format(),
              updatedUser: userId,
            });
 
            return result;
          }
 
          await QueueUpdate.updateIntegrationQueue(queueId, {
            response: 'Resposta Inválida',
            status: 998,
            message: 'Erro Integração',
            updatedUser: userId,
          });
 
          return false;
        }
      }
    }
  } catch (error) {
    const integrated = error.message.includes('já integrado');
 
    let status = 998;
 
    if (error.response) {
      status = error.response.status;
    } else Eif (integrated) {
      status = 200;
    }
 
    await QueueUpdate.updateIntegrationQueue(queueId, {
      response: error.response ? error.response.data : '',
      status,
      message: error.message,
      integratedAt: integrated ? moment().format() : null,
      updatedUser: userId,
    });
    return error;
  }
 
  return null;
}
 
export default {
  sendInboundProductStorage,
};