All files / source/outboundOrders billingReturn.js

89.9% Statements 98/109
78.2% Branches 61/78
66.66% Functions 2/3
89.9% Lines 98/109

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                                22x 22x 22x   22x 1x 1x 1x 21x       1x 1x 1x           22x 1x 1x 1x   21x       21x 1x 1x 1x             22x 1x 1x 1x   21x       21x 1x 1x 1x             22x 1x 1x 1x   21x           21x 1x 1x 1x 20x 14x 1x 1x 1x         14x 1x 1x 1x     14x 1x 1x 1x     13x 1x 1x 1x     12x       1x 1x 1x             22x 21x       21x 1x 1x 1x               1x 1x 1x     22x 1x 1x 1x 21x       1x 1x 1x           22x               22x   22x 22x   22x 17x                     5x           5x 5x   5x 3x 1x 2x 1x   1x   2x       1x     5x                     5x       5x 3x                                                                                                                                                                                                             22x            
import moment from 'moment-timezone';
import { t } from '../../helpers/i18n';
import BranchInformation from '../branches/information';
import CarrierInformation from '../carriers/information';
import CustomerInformation from '../customers/information';
import OutboundOrderProductInformation from '../outboundOrderProducts/information';
import OutboundOrderProductUpdate from '../outboundOrderProducts/update';
import OutboundOrderInformation from './information';
import OutboundOrderUpdate from './update';
import SerialGroupInformation from '../serialGroup/information';
import SerialGroupUpdate from '../serialGroup/update';
import { sequelize } from '../../../config/database';
import StockMovement from '../stock/movement';
import OutboundConsolidationCtrl from '../../controllers/outboundConsolidation';
 
async function validBillingReturn(outboundOrder) {
  let isValid = true;
  let code = '';
  let message = '';
 
  if (!outboundOrder.status) {
    isValid = false;
    code = 9001;
    message = t('BEE1198' /* Status deve ser informado! */);
  } else if (
    outboundOrder.status !== 'OK' &&
    outboundOrder.status !== 'CANCELED'
  ) {
    isValid = false;
    code = 9002;
    message = t(
      'BEE1199',
      { 0: outboundOrder.status } /* Status %{0} inválido ! */
    );
  }
 
  if (!outboundOrder.branchCode) {
    isValid = false;
    code = 9003;
    message = t('BEE1285' /* Código da filial deve ser informado */);
  } else {
    const existBranch = await BranchInformation.getBranch({
      code: outboundOrder.branchCode,
    });
 
    if (!existBranch) {
      isValid = false;
      code = 9004;
      message = t(
        'BEE1307',
        { 0: outboundOrder.branchCode } /* Código da filial %{0} inválido */
      );
    }
  }
 
  if (!outboundOrder.customerCode) {
    isValid = false;
    code = 9005;
    message = t('BEE1299' /* Código do cliente deve ser informado */);
  } else {
    const existCustomer = await CustomerInformation.getCustomer({
      code: outboundOrder.customerCode,
    });
 
    if (!existCustomer) {
      isValid = false;
      code = 9006;
      message = t(
        'BEE1336',
        { 0: outboundOrder.customerCode } /* Código do cliente %{0} inválido */
      );
    }
  }
 
  if (!outboundOrder.orderNumber) {
    isValid = false;
    code = 9007;
    message = t('BEE1310' /* Número do documento deve ser informado */);
  } else {
    const existOrder = await OutboundOrderInformation.getOutboundOrder({
      branchCode: outboundOrder.branchCode,
      customerCode: outboundOrder.customerCode,
      orderNumber: outboundOrder.orderNumber,
    });
 
    if (!existOrder) {
      isValid = false;
      code = 9008;
      message = t('BEE1310' /* Número do documento deve ser informado */);
    } else if (isValid && outboundOrder.status === 'OK') {
      if (!outboundOrder.invoiceNumber) {
        isValid = false;
        code = 9009;
        message = t(
          'BEE4192' /* O número da Nota Fiscal deve ser informado. */
        );
      }
 
      if (!outboundOrder.accessKey) {
        isValid = false;
        code = 9010;
        message = t('BEE3168' /* Chave de Acesso deve ser informada! */);
      }
 
      if (existOrder.status === 12) {
        isValid = false;
        code = 9011;
        message = t(
          'BEE2602' /* Documento com status Cancelado não permite confirmação de faturamento */
        );
      } else if (existOrder.status === 13) {
        isValid = false;
        code = 9012;
        message = t(
          'BEE2603' /* Documento com status Devolvido não permite confirmação de faturamento */
        );
      } else if (
        existOrder.invoiceNumber &&
        existOrder.invoiceNumber.trim() !== ''
      ) {
        isValid = false;
        code = 9013;
        message = t(
          'BEE3932' /* Documento já faturado. Não é possível faturar novamente. */
        );
      }
    }
  }
 
  if (outboundOrder.carrierCode) {
    const existCarrier = await CarrierInformation.getCarrier({
      code: outboundOrder.carrierCode,
    });
 
    if (!existCarrier) {
      isValid = false;
      code = 9014;
      message = t(
        'BEE1318',
        {
          0: outboundOrder.carrierCode,
        } /* Código da Transportadora %{0} inválido */
      );
    }
  } else {
    isValid = false;
    code = 9017;
    message = t('BEE1317' /* Código da transportadora deve ser informado */);
  }
 
  if (!outboundOrder.deliveryType) {
    isValid = false;
    code = 9015;
    message = t('BEE1340' /* Tipo de entrega deve ser informado */);
  } else if (
    outboundOrder.deliveryType !== 'CIF' &&
    outboundOrder.deliveryType !== 'FOB'
  ) {
    isValid = false;
    code = 9016;
    message = t(
      'BEE1341',
      { 0: outboundOrder.deliveryType } /* Tipo de entrega %{0} inválido */
    );
  }
 
  return {
    isValid,
    code,
    message,
  };
}
 
async function importBillingReturn(outboundOrders, userId) {
  const listOutboundOrdersErrors = [];
 
  for (const outboundOrder of outboundOrders) {
    const valid = await validBillingReturn(outboundOrder);
 
    if (!valid.isValid) {
      listOutboundOrdersErrors.push({
        code: {
          branchCode: outboundOrder.branchCode,
          customerCode: outboundOrder.customerCode,
          orderNumber: outboundOrder.orderNumber,
        },
        error: valid.code,
        message: valid.message,
      });
    } else {
      const existOrder =
        await OutboundOrderInformation.getOutboundOrderValidation({
          branchCode: outboundOrder.branchCode,
          customerCode: outboundOrder.customerCode,
          orderNumber: outboundOrder.orderNumber,
        });
 
      if (outboundOrder.status === 'OK') {
        let { status } = existOrder;
 
        if (existOrder.typeOrders) {
          if (existOrder.typeOrders.dockControl) {
            status = 6; // Doca
          } else if (existOrder.typeOrders.requestDeliveryConfirmation) {
            status = 14; // Pendente Retirada
          } else {
            status = 10; // Finalizado
          }
        } else if (
          existOrder.orderType === 'CR' ||
          existOrder.orderType === 'LJ'
        ) {
          status = 10;
        }
 
        await OutboundOrderUpdate.updateOutboundOrder(existOrder.id, {
          status,
          carrierCode: outboundOrder.carrierCode,
          deliveryType: outboundOrder.deliveryType,
          invoiceNumber: outboundOrder.invoiceNumber,
          invoiceDate: moment().format(),
          invoiceSerie: outboundOrder.serie,
          accessKey: outboundOrder.accessKey,
          updatedUser: userId,
        });
 
        const isConsolidation = existOrder.typeOrders
          ? existOrder.typeOrders.consolidation
          : existOrder.branch.consolidation;
 
        if (isConsolidation) {
          await OutboundConsolidationCtrl.createOutboundConsolidation(
            existOrder.id,
            userId
          );
        }
      } else Eif (outboundOrder.status === 'CANCELED') {
        sequelize.transaction(async (transaction) => {
          await OutboundOrderUpdate.updateOutboundOrder(
            existOrder.id,
            {
              invoiceNumber: '',
              invoiceDate: null,
              invoiceSerie: '',
              accessKey: '',
              status: existOrder.status === 13 ? 13 : 12,
              updatedUser: userId,
            },
            { transaction }
          );
 
          const query = {
            orderNumber: outboundOrder.orderNumber,
            branchCode: outboundOrder.branchCode,
          };
 
          const getAllSerialGroups =
            await SerialGroupInformation.getAllSerialGroups(query, {
              transaction,
            });
 
          for (const serialGroup of getAllSerialGroups.rows) {
            const newMovement = await StockMovement.createMovement(
              {
                branchCode: serialGroup.branchCode,
                warehouseCode: serialGroup.branchCode || '',
                depositCode: serialGroup.depositCode,
                addressCode: 'PADRAO',
                productCode: serialGroup.productCode,
                lotNumber: serialGroup.lotNumber || '',
                operation: 'IND',
                type: 1,
                quantity: serialGroup.quantity,
                unitMeasure: serialGroup.product.unitMeasure || '',
                serie: '',
                orderNumber: serialGroup.code,
                supplierCode: '',
                expirationDate: serialGroup.expirationDate
                  ? moment(moment(serialGroup.expirationDate, 'DD/MM/YYYY'))
                      .startOf('day')
                      .format()
                  : '',
                manufacturingDate: null,
                note: t(
                  'BEE3323',
                  {
                    0: outboundOrder.id,
                  } /* Nota %{0} cancelada. Saldo restaurado. */
                ),
                serialGroupId: serialGroup.id,
                baptismLabel: '',
                movementUser: userId,
                createdUser: userId,
                updatedUser: userId,
              },
              { transaction }
            );
 
            await SerialGroupUpdate.updateSerialGroup(
              serialGroup.id,
              {
                orderNumber: null,
                updatedUser: userId,
                ...(newMovement.stockBalanceId !== serialGroup.stockBalanceId
                  ? { stockBalanceId: newMovement.stockBalanceId }
                  : {}),
              },
              { transaction }
            );
          }
 
          const outboundProducts =
            await OutboundOrderProductInformation.getOutboundOrderProducts(
              {
                outboundOrderId: existOrder.id,
              },
              { transaction }
            );
 
          for (const product of outboundProducts) {
            await OutboundOrderProductUpdate.updateOutboundOrderProduct(
              product.id,
              {
                status: existOrder.status === 13 ? 10 : 9,
                updatedUser: userId,
              },
              { transaction }
            );
          }
        });
      }
    }
  }
 
  return { listOutboundOrdersErrors };
}
 
export default {
  importBillingReturn,
};