Subversion Repositories SmartDukaan

Rev

Rev 34578 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.service.dtdc;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.common.util.Utils.Attachment;
import com.spice.profitmandi.common.web.client.RestClient;
import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.entity.transaction.WarehouseAddressMapping;
import com.spice.profitmandi.dao.entity.transaction.WarehouseAddressMaster;
import com.spice.profitmandi.dao.model.BilledOrderListModel;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.dao.repository.transaction.WarehouseAddressMappingRepository;
import com.spice.profitmandi.dao.repository.transaction.WarehouseAddressMasterRepository;
import com.spice.profitmandi.service.mail.MailOutboxService;
import com.spice.profitmandi.service.user.RetailerService;
import in.shop2020.model.v1.order.OrderStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

@Component
public class DTDCServiceImpl implements DTDCService {

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private WarehouseAddressMappingRepository warehouseAddressMappingRepository;

        @Autowired
        private WarehouseAddressMasterRepository warehouseAddressMasterRepository;

        @Autowired
        private OrderRepository orderRepository;

        @Autowired
        private RestClient restClient;

        @Autowired
        private JavaMailSender googleMailSender;

        @Autowired
        MailOutboxService mailOutboxService;

        @Value("#{'${prod}'=='true' ? 'NL3832' : 'NL3832'}")
        private String customerCode;

        @Value("#{'${prod}'=='true' ? '4b2a38cf831edcf397629f68684da6' : '8c0800cae8401d95570d7551be9bd7'}")
        private String apiKey;

        private static final Logger LOGGER = LogManager.getLogger(DTDCServiceImpl.class);

        @Override
        public List<BilledOrderListModel> getAirwayBillNo(Map<String, List<BilledOrderListModel>> airbillBilledOrderMap,
                        String emailId) throws Exception {

                List<BilledOrderListModel> billedOrderListModels = new ArrayList<>();

                Consignments consignments = new Consignments();
                List<Consignment> consignmentList = new ArrayList<>();

                List<String> consigneeIds = new ArrayList<>();
                for (Entry<String, List<BilledOrderListModel>> billedOrderEntry : airbillBilledOrderMap.entrySet()) {

                        List<BilledOrderListModel> billedOrders = billedOrderEntry.getValue();

                        double weight = billedOrders.get(0).getWeight();

                        List<String> invoiceNumbers = billedOrders.stream().map(x -> x.getInvoiceNumber())
                                        .collect(Collectors.toList());

                        List<Order> orders = orderRepository.selectByInvoiceNumbers(invoiceNumbers);

                        Double totalAmount = orders.stream().collect(Collectors.summingDouble(x -> x.getTotalAmount()));

                        for (Order order : orders) {
                                if (!order.getStatus().equals(OrderStatus.BILLED)) {

                                        throw new ProfitMandiBusinessException("Uploaded File", "",
                                                        "Order Number " + order.getId() + "  status is not billed");

                                }
                        }

                        consigneeIds.add(billedOrderEntry.getKey());
                        Order order = orders.get(0);

                        int warehouseId = order.getWarehouseId();

                        CustomRetailer customRetailer = retailerService.getFofoRetailer(order.getRetailerId());

                        WarehouseAddressMapping warehouseAddressMapping = warehouseAddressMappingRepository
                                        .selectByWarehouseId(warehouseId);

                        WarehouseAddressMaster warehouseAddressMaster = warehouseAddressMasterRepository
                                        .selectById(warehouseAddressMapping.getAddressId());

                        Consignment consignment = new Consignment();
                        consignment.setCustomerCode(customerCode);
                        consignment.setServiceTypeId("PRIORITY");
                        consignment.setCommodityId("2");
                        consignment.setDeclaredValue(totalAmount.intValue());
                        consignment.setConsignmentType("Forward");
                        consignment.setLoadType("NON-DOCUMENT");
                        consignment.setWeghtUnit("kg");
                        consignment.setWeight(weight);

                        OriginDetails origionDetail = new OriginDetails();
                        origionDetail.setPincode("201301");// warehouseAddressMaster.getPin());
                        origionDetail.setName(warehouseAddressMaster.getContactPerson());
                        origionDetail.setPhone(warehouseAddressMaster.getContacNumber());
                        origionDetail.setAddressLine1(warehouseAddressMaster.getAddress());

                        consignment.setOriginDetail(origionDetail);

                        DestinationDetails destinationDetail = new DestinationDetails();
                        destinationDetail.setName(customRetailer.getBusinessName());
                        destinationDetail.setAddressLine1(customRetailer.getAddress().getLine1());
                        destinationDetail.setAddressLine2(customRetailer.getAddress().getLine2());
                        destinationDetail.setPhone(customRetailer.getMobileNumber());
                        destinationDetail.setPincode(customRetailer.getAddress().getPinCode());
                        destinationDetail.setState(customRetailer.getAddress().getState());
                        destinationDetail.setCity(customRetailer.getAddress().getCity());

                        consignment.setDestinationDetail(destinationDetail);

                        List<PiecesDetail> piecesDetails = new ArrayList<>();

                        PiecesDetail pieceDetail = new PiecesDetail();
                        pieceDetail.setDeclaredValue(totalAmount);
                        pieceDetail.setWidth(1.0);

                        pieceDetail.setHeight(1.0);
                        pieceDetail.setLength(1.0);

                        piecesDetails.add(pieceDetail);

                        consignment.setPiecesDetails(piecesDetails);

                        consignmentList.add(consignment);

                }

                consignments.setConsignments(consignmentList);
                LOGGER.info("consignments" + consignments);

                Map<String, String> requestheaders = new HashMap<>();
                requestheaders.put("Content-Type", "application/json");
                requestheaders.put("api-key", apiKey);

                String response = restClient.postJson(
                                "https://demodashboardapi.shipsy.in/api/customer/integration/consignment/softdata", consignments,
                                requestheaders);

                LOGGER.info("response" + response);
                List<Attachment> attachments = new ArrayList<>();

                List<List<?>> rows = new ArrayList<>();

                JSONObject resp = new JSONObject(response);
                JSONArray referenceData = resp.getJSONArray("data");

                for (int j = 0; j < referenceData.length(); j++) {

                        String consigneeId = consigneeIds.get(j);

                        List<BilledOrderListModel> billedOrders = airbillBilledOrderMap.get(consigneeId);

                        JSONObject referenceDetail = referenceData.getJSONObject(j);

                        boolean success = referenceDetail.getBoolean("success");
                        String airWayBill = "Error";
                        if (success) {

                                airWayBill = referenceDetail.getString("reference_number");
                        }

                        for (BilledOrderListModel billedOrder : billedOrders) {

                                billedOrder.setAirwayBillNumber(airWayBill);
                                if (!airWayBill.equals("Error")) {

                                        rows.add(Arrays.asList(billedOrder.getInvoiceNumber(), billedOrder.getLogisticsProviderName(),
                                                        billedOrder.getAirwayBillNumber(), billedOrder.getWeight()));
                                } else {

                                        String message = referenceDetail.getString("message");

                                        LOGGER.info("message" + message);

                                        rows.add(Arrays.asList(billedOrder.getInvoiceNumber(), billedOrder.getLogisticsProviderName(),
                                                        billedOrder.getAirwayBillNumber(), billedOrder.getWeight(),
                                                        referenceDetail.getString("message")));
                                }

                        }

                        billedOrderListModels.addAll(billedOrders);

                }

                org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil
                                .getCSVByteStream(Arrays.asList("Invoice Number", "Provider", "AWB", "Weight", "Reason"), rows);

                Attachment xlsattachment = new Attachment("uploaded bluedart sheet", new ByteArrayResource(baos.toByteArray()));

                attachments.add(xlsattachment);

                Map<String, List<BilledOrderListModel>> awbOrderMap = billedOrderListModels.stream()
                                .collect(Collectors.groupingBy(x -> x.getAirwayBillNumber(), Collectors.toList()));

                for (Entry<String, List<BilledOrderListModel>> awbOrderEntry : awbOrderMap.entrySet()) {

                        if (!awbOrderEntry.getKey().equals("Error")) {
                                Map<String, String> referenceNumber = new HashMap<>();
                                referenceNumber.put("reference_number", awbOrderEntry.getKey());

                                String responseLabel = restClient.postJson(
                                                "https://demodashboardapi.shipsy.in/api/customer/integration/consignment/label/multipiece",
                                                referenceNumber, requestheaders);

                                JSONObject respLabel = new JSONObject(responseLabel);
                                JSONArray labelData = respLabel.getJSONArray("data");

                                for (int j = 0; j < labelData.length(); j++) {
                                        JSONObject referenceDetail = labelData.getJSONObject(j);

                                        String airWayBill = referenceDetail.getString("reference_number");

                                        String label = referenceDetail.getString("label");
                                        byte[] decodedString = Base64.getDecoder().decode(label.getBytes("UTF-8"));

                                        Attachment attachment = new Attachment("DTDC" + airWayBill + ".pdf",
                                                        new ByteArrayResource(decodedString));

                                        attachments.add(attachment);

                                }

                        }
                }

                mailOutboxService.queueMailWithAttachmentsViaGoogle(new String[] { "sdtech@smartdukaan.com" }, null,
                                "DTDC AWb", "PFA", "DTDCServiceImpl.getAirwayBillNo", attachments.toArray(new Utils.Attachment[attachments.size()]));

                LOGGER.info("billedOrderListModels" + billedOrderListModels);

                return billedOrderListModels;
        }

}