All files / controllers waybills.js

100% Statements 50/50
95.83% Branches 23/24
100% Functions 3/3
100% Lines 50/50

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                            4x   4x 4x 4x   4x             3x 3x       3x 1x         3x 3x                   3x 3x     1x 1x     1x                   7x 7x             6x                     6x 1x       5x             5x       5x 5x                     5x   5x 3x 1x 2x 1x   2x 2x     5x                     5x               5x   5x     1x 1x         3x 3x   3x 3x         2x   2x 1x       1x           1x 1x     1x                  
/* eslint-disable no-restricted-syntax */
import moment from 'moment-timezone';
import { Op } from 'sequelize';
 
import translateWaybillsHelpers from '../helpers/status/translateWaybillsHelpers';
import Totvs from '../services/totvs';
import BranchesInformation from '../source/branches/information';
import DockControlInformation from '../source/dockControl/information';
import OutboundOrdersInformation from '../source/outboundOrders/information';
import OutboundOrderUpdate from '../source/outboundOrders/update';
import WaybillCreate from '../source/waybills/create';
import WaybillInformation from '../source/waybills/information';
 
async function getWaybillsByDate(req, res) {
  const { filterStartDate, filterEndDate } = req.query;
 
  try {
    const startDate = moment(filterStartDate).startOf('day').format();
    const endDate = moment(filterEndDate).endOf('day').format();
 
    const waybills = await WaybillInformation.getWaybills(
      {
        createdAt: { [Op.between]: [startDate, endDate] },
      },
      { userBranches: req.userBranches }
    );
 
    for (const iterator of waybills) {
      iterator.dataValues.carrierBusinessName =
        iterator.carrier && iterator.carrier.code
          ? `${iterator.carrier.code} - ${iterator.carrier.businessName}`
          : '';
      if (iterator.dataValues.status) {
        iterator.dataValues.statusName = translateWaybillsHelpers.waybillStatus(
          iterator.dataValues.status
        );
      }
 
      for (const element of iterator.waybillDocuments) {
        element.outboundOrder.dataValues.customerBusinessName =
          element.outboundOrder &&
          element.outboundOrder.customerCode &&
          element.outboundOrder.customer &&
          element.outboundOrder.customer.businessName
            ? `${element.outboundOrder.customerCode} - ${element.outboundOrder.customer.businessName}`
            : '';
      }
    }
 
    const result = { success: true, data: waybills };
    res.json(result);
  } catch (err) {
    // eslint-disable-next-line no-console
    console.log(err);
    const response = {
      success: false,
    };
    res.json(response);
  }
}
 
async function generateWaybill(
  dockControlId,
  userId,
  userMainBranch,
  transaction
) {
  try {
    const dockControl = await DockControlInformation.getDockControl(
      {
        id: dockControlId,
      },
      { transaction }
    );
 
    const newWaybill = await WaybillCreate.createWaybill(
      {
        branchCode: dockControl.branchCode,
        carrierCode: dockControl.carrierCode,
        dockControlId: dockControl.id,
        createdUser: userId,
        updatedUser: userId,
      },
      { transaction }
    );
 
    if (!newWaybill) {
      return null;
    }
 
    const outboundOrders =
      await OutboundOrdersInformation.getOutboundOrdersValidation(
        {
          dockControlId: dockControl.id,
        },
        { transaction }
      );
 
    const branches = await BranchesInformation.getBranch({
      code: userMainBranch,
    });
 
    for (const order of outboundOrders) {
      await WaybillCreate.createWaybillDocument(
        {
          outboundOrderId: order.id,
          waybillId: newWaybill.id,
          note: '',
          createdUser: userId,
          updatedUser: userId,
        },
        { transaction }
      );
 
      let orderStatus = 10; // Finalizado
 
      if (order.typeOrders) {
        if (order.typeOrders.consolidation) {
          orderStatus = 8; // Consolidação
        } else if (order.typeOrders.requestDeliveryConfirmation) {
          orderStatus = 14; // Pendente Retirada
        }
      } else Eif (branches.consolidation) {
        orderStatus = 8; // Consolidação
      }
 
      await OutboundOrderUpdate.updateOutboundOrder(
        order.id,
        {
          status: orderStatus,
          waybillId: newWaybill.id,
          updatedUser: userId,
        },
        { transaction }
      );
    }
 
    const waybill = await WaybillInformation.getWaybill(
      {
        id: newWaybill.id,
      },
      { transaction }
    );
 
    // Sincroniza Romaneio com ERP
    Totvs.syncWaybill(waybill, userId);
 
    return newWaybill;
  } catch (err) {
    // eslint-disable-next-line no-console
    console.log(err);
    return null;
  }
}
 
async function syncWaybillErp(req, res) {
  const { waybillId } = req.body;
  const { userId } = req;
 
  try {
    const waybill = await WaybillInformation.getWaybill({
      id: waybillId,
    });
 
    // Sincroniza Romaneio com ERP
    const result = await Totvs.syncWaybill(waybill, userId);
 
    if (result) {
      res.json({
        success: true,
      });
    } else {
      res.json({
        success: false,
      });
    }
  } catch (err) {
    // eslint-disable-next-line no-console
    console.log(err);
    const response = {
      success: false,
    };
    res.json(response);
  }
}
 
export default {
  getWaybillsByDate,
  generateWaybill,
  syncWaybillErp,
};