Subversion Repositories SmartDukaan

Rev

Rev 22695 | Rev 22939 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.hotspot.dashbaord.server;

import in.shop2020.hotspot.dashbaord.server.OrderPromisedShippingComparator;
import in.shop2020.hotspot.dashbaord.shared.actions.Order;
import in.shop2020.hotspot.dashbaord.shared.actions.OrderAlert;
import in.shop2020.hotspot.dashbaord.shared.actions.OrderCategory;
import in.shop2020.hotspot.dashbaord.shared.actions.OrderType;
import in.shop2020.hotspot.dashbaord.shared.actions.ReturnOrder;
import in.shop2020.model.v1.inventory.InventoryService;
import in.shop2020.model.v1.inventory.InventoryType;
import in.shop2020.model.v1.inventory.WarehouseType;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.ItemType;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.hotspot.dashbaord.server.EhcacheWrapper;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.LogisticsClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.sf.ehcache.CacheManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is a facade to the Transaction service and should be used to
 * access all order specific data which requires some kind of transformation.
 * 
 * @author Chandranshu
 * 
 */
public class TransactionUtils {
        private static String courierDetailsPath = "/CourierDetailReports";
        private static Logger logger = LoggerFactory.getLogger(TransactionUtils.class);
        private static long ALL_GREEN = 1L;
        private static long GREEN_AND_PURPULE = 2L;
        private static long GREEN_AND_IN_RED_OR_WHITE = 3L;
        private static long ALL_RED = 4L;
        private static long ALL_PURPLE = 5L;
        private static long PURPLE_AND_IN_RED_OR_WHITE = 6L;
        private static long ALL_OTHERS = 7L;
        private static int categoryOrderCount = 0; 
        private static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
        private static SimpleDateFormat newSdf = new SimpleDateFormat("yyyy-MM-dd");
        private static NumberFormat formatter = new DecimalFormat("#0.000");
        private static NumberFormat rformatter = new DecimalFormat("#0.00");
        
        private static  Map<Long, in.shop2020.logistics.Provider> getProvidersMap() {
                if(providersMap==null){
                        try {
                                in.shop2020.logistics.LogisticsService.Client logisticsClient = new LogisticsClient().getClient();
                                List<in.shop2020.logistics.Provider> providers = logisticsClient.getAllProviders();
                                providersMap = new HashMap<Long, in.shop2020.logistics.Provider>();
                        
                                for(in.shop2020.logistics.Provider provider : providers){
                                        providersMap.put(provider.getId(), provider);
                                }
                        }catch (Exception e) {
                                e.printStackTrace();
                        }
                }
                return providersMap;
        }
        
        private static Map<Long, in.shop2020.logistics.Provider> providersMap = null;
        
        
        private static Map<Long, OrderCategory> categoryStrMap = new HashMap<Long, OrderCategory>();
        
        private static enum ColorCode {
                GREEN,
                PURPLE,
                RED,
                OTHER
        }
        
        static{
                categoryStrMap.put(ALL_GREEN, OrderCategory.READY);
                categoryStrMap.put(GREEN_AND_PURPULE, OrderCategory.READY);
                categoryStrMap.put(GREEN_AND_IN_RED_OR_WHITE, OrderCategory.REVIEW);
                categoryStrMap.put(ALL_RED, OrderCategory.REVIEW);
                categoryStrMap.put(ALL_PURPLE, OrderCategory.READY_LATER);
                categoryStrMap.put(PURPLE_AND_IN_RED_OR_WHITE, OrderCategory.REVIEW_LATER);
                categoryStrMap.put(ALL_OTHERS, OrderCategory.REVIEW_LATER);
        }
        
        
        /**
         * The human user is concerned only with a consolidated view of actionable
         * orders. Orders with different statuses in the database can be part of the
         * same consolidated view. This method uses a mapping of <i>type</i> to
         * <i>status</i> to get all such orders and return them as order beans.
         * 
         * @param type
         *            The type of orders to return.
         * @param offset
         *            Offset to start from
         * @param limit
         *            No. of orders to return
         * @param warehouseId
         *            The billing warehouse for which the orders should be queried.
         * @return A list of orders of the given type to be fulfilled from the given
         *         warehouse
         */
        public static List<Order> getOrders(OrderType type, long offset, long limit, long warehouseId, long source, OrderCategory orderCategory){
                List<OrderStatus> statuses = getStatuses(type);
                
                List<Order> orders = new ArrayList<Order>();
                try{
                        TransactionClient txnClient = new TransactionClient();
                        Client client = txnClient.getClient();
                        
                        List<in.shop2020.model.v1.order.Order> t_orders = new ArrayList<in.shop2020.model.v1.order.Order>();
                        if(type==OrderType.NEW || type==OrderType.ALL_PENDING || type ==OrderType.LOW_INVENTORY || type == OrderType.PO_RAISED
                                        || type == OrderType.REVERSAL_INITIATED || type == OrderType.NOT_AVAILABLE){
                                t_orders.addAll(client.getOrdersInBatchAsPromisedShipping(statuses, 0, 0, warehouseId, source));
                        }else{
                                if(orderCategory!=OrderCategory.NONE){
                                        statuses = getStatuses(OrderType.ALL_PENDING);
                                        t_orders.addAll(client.getOrdersInBatchAsPromisedShipping(statuses, 0, 0, warehouseId, source));
                                }else{
                                        t_orders.addAll(client.getOrdersInBatch(statuses, offset, limit, warehouseId, source));
                                }
                        }
                        
                        orders = getOrdersFromThirftOrders(t_orders, warehouseId);
                        /*for (in.shop2020.model.v1.order.Order t_order: t_orders){
                                Order o = getOrderFromThriftOrder(t_order);
                                orders.add(o);
                        }*/
                        if(type==OrderType.NEW || type==OrderType.ALL_PENDING || type ==OrderType.LOW_INVENTORY || type == OrderType.PO_RAISED
                                        || type == OrderType.REVERSAL_INITIATED || type == OrderType.NOT_AVAILABLE || type == OrderType.NOT_APPLICABLE){
                                Map<Long, List<Order>> transactionOrdersMap = new HashMap<Long, List<Order>>();
                                Map<Long, Map<String, Long>> transactionsColorMap = new HashMap<Long, Map<String, Long>>();
                                for(Order order : orders){
                                        if(transactionOrdersMap.containsKey(order.getTransactionId())){
                                                List<Order> txnOrders = transactionOrdersMap.get(order.getTransactionId());
                                                txnOrders.add(order);
                                                transactionOrdersMap.put(order.getTransactionId(), txnOrders);
                                        }else{
                                                List<Order> txnOrders = new ArrayList<Order>();
                                                txnOrders.add(order);
                                                transactionOrdersMap.put(order.getTransactionId(), txnOrders);
                                        }
                                        
                                        if(transactionsColorMap.containsKey(order.getTransactionId())){
                                                Map<String, Long> colorMap = transactionsColorMap.get(order.getTransactionId());
                                                //SHIPPING_TIME_EXCEEDED, DELIVERY_TIME_EXCEEDED, ORDER_NOT_CONNECTED_FOR_TOO_LONG, ORDER_NOT_CONNECTED
                                                if(order.getAlert()==OrderAlert.TODAY_SHIPPING_IN_STOCK){
                                                        if(colorMap.containsKey(ColorCode.GREEN.toString())){
                                                                colorMap.put(ColorCode.GREEN.toString(),colorMap.get(ColorCode.GREEN.toString())+1);
                                                        }else{
                                                                colorMap.put(ColorCode.GREEN.toString(),1L);
                                                        }
                                                }else if(order.getAlert()==OrderAlert.TODAY_SHIPPING_NOT_IN_STOCK){
                                                        if(colorMap.containsKey(ColorCode.RED.toString())){
                                                                colorMap.put(ColorCode.RED.toString(),colorMap.get(ColorCode.RED.toString())+1);
                                                        }else{
                                                                colorMap.put(ColorCode.RED.toString(),1L);
                                                        }
                                                }else if(order.getAlert()==OrderAlert.LATER_SHIPPING_IN_STOCK){
                                                        if(colorMap.containsKey(ColorCode.PURPLE.toString())){
                                                                colorMap.put(ColorCode.PURPLE.toString(),colorMap.get(ColorCode.PURPLE.toString())+1);
                                                        }else{
                                                                colorMap.put(ColorCode.PURPLE.toString(),1L);
                                                        }
                                                }else{
                                                        if(colorMap.containsKey(ColorCode.OTHER.toString())){
                                                                colorMap.put(ColorCode.OTHER.toString(),colorMap.get(ColorCode.OTHER.toString())+1);
                                                        }else{
                                                                colorMap.put(ColorCode.OTHER.toString(),1L);
                                                        }
                                                }
                                                transactionsColorMap.put(order.getTransactionId(), colorMap);
                                        }else{
                                                Map<String, Long> colorMap = new HashMap<String, Long>();
                                                if(order.getAlert()==OrderAlert.TODAY_SHIPPING_IN_STOCK){
                                                        colorMap.put(ColorCode.GREEN.toString(),1L);
                                                }else if(order.getAlert()==OrderAlert.TODAY_SHIPPING_NOT_IN_STOCK){
                                                        colorMap.put(ColorCode.RED.toString(),1L);
                                                }else if(order.getAlert()==OrderAlert.LATER_SHIPPING_IN_STOCK){
                                                        colorMap.put(ColorCode.PURPLE.toString(),1L);
                                                }else{
                                                        colorMap.put(ColorCode.OTHER.toString(),1L);
                                                }
                                                transactionsColorMap.put(order.getTransactionId(), colorMap);
                                        }
                                        
                                }
                                
                                Map<Long, List<Long>> orderCategoryMap = new HashMap<Long, List<Long>>();
                                
                                for(Entry<Long, Map<String, Long>> colorMapEntry : transactionsColorMap.entrySet()){
                                        Map<String, Long> colorMap = colorMapEntry.getValue();
                                        List<String> colorSet = new ArrayList<String>(colorMap.keySet());
                                        long colorMapSize = colorSet.size();
                                        if(colorMapSize==1){
                                                if(ColorCode.GREEN.toString().equalsIgnoreCase(colorSet.get(0))){
                                                        if(orderCategoryMap.containsKey(ALL_GREEN)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_GREEN);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_GREEN, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_GREEN, transactions);
                                                        }
                                                }else if(ColorCode.RED.toString().equalsIgnoreCase(colorSet.get(0))){
                                                        if(orderCategoryMap.containsKey(ALL_RED)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_RED);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_RED, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_RED, transactions);
                                                        }
                                                }else if(ColorCode.PURPLE.toString().equalsIgnoreCase(colorSet.get(0))){
                                                        if(orderCategoryMap.containsKey(ALL_PURPLE)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_PURPLE);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_PURPLE, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_PURPLE, transactions);
                                                        }
                                                }else{
                                                        if(orderCategoryMap.containsKey(ALL_OTHERS)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_OTHERS);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }
                                                }
                                        }else if(colorMapSize==2){
                                                if(colorSet.contains(ColorCode.GREEN.toString())){
                                                        if(colorSet.contains(ColorCode.PURPLE.toString())){
                                                                if(orderCategoryMap.containsKey(GREEN_AND_PURPULE)){
                                                                        List<Long> transactions = orderCategoryMap.get(GREEN_AND_PURPULE);
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_PURPULE, transactions);
                                                                }else{
                                                                        List<Long> transactions = new ArrayList<Long>();
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_PURPULE, transactions);
                                                                }
                                                        }else{
                                                                if(orderCategoryMap.containsKey(GREEN_AND_IN_RED_OR_WHITE)){
                                                                        List<Long> transactions = orderCategoryMap.get(GREEN_AND_IN_RED_OR_WHITE);
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_IN_RED_OR_WHITE, transactions);
                                                                }else{
                                                                        List<Long> transactions = new ArrayList<Long>();
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_IN_RED_OR_WHITE, transactions);
                                                                }
                                                        }
                                                }else if(colorSet.contains(ColorCode.PURPLE.toString())){
                                                        if(orderCategoryMap.containsKey(PURPLE_AND_IN_RED_OR_WHITE)){
                                                                List<Long> transactions = orderCategoryMap.get(PURPLE_AND_IN_RED_OR_WHITE);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(PURPLE_AND_IN_RED_OR_WHITE, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(PURPLE_AND_IN_RED_OR_WHITE, transactions);
                                                        }
                                                }else{
                                                        if(orderCategoryMap.containsKey(ALL_OTHERS)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_OTHERS);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }
                                                }
                                        }else{
                                                if(colorSet.contains(ColorCode.GREEN.toString())){
                                                        if(colorSet.contains(ColorCode.RED.toString()) || colorSet.contains(ColorCode.OTHER.toString())){
                                                                if(orderCategoryMap.containsKey(GREEN_AND_IN_RED_OR_WHITE)){
                                                                        List<Long> transactions = orderCategoryMap.get(GREEN_AND_IN_RED_OR_WHITE);
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_IN_RED_OR_WHITE, transactions);
                                                                }else{
                                                                        List<Long> transactions = new ArrayList<Long>();
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_IN_RED_OR_WHITE, transactions);
                                                                }
                                                        }else{
                                                                if(orderCategoryMap.containsKey(GREEN_AND_PURPULE)){
                                                                        List<Long> transactions = orderCategoryMap.get(GREEN_AND_PURPULE);
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_PURPULE, transactions);
                                                                }else{
                                                                        List<Long> transactions = new ArrayList<Long>();
                                                                        transactions.add(colorMapEntry.getKey());
                                                                        orderCategoryMap.put(GREEN_AND_PURPULE, transactions);
                                                                }
                                                        }
                                                }else if(colorSet.contains(ColorCode.PURPLE.toString())){
                                                        if(orderCategoryMap.containsKey(PURPLE_AND_IN_RED_OR_WHITE)){
                                                                List<Long> transactions = orderCategoryMap.get(PURPLE_AND_IN_RED_OR_WHITE);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(PURPLE_AND_IN_RED_OR_WHITE, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(PURPLE_AND_IN_RED_OR_WHITE, transactions);
                                                        }
                                                }else{
                                                        if(orderCategoryMap.containsKey(ALL_OTHERS)){
                                                                List<Long> transactions = orderCategoryMap.get(ALL_OTHERS);
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }else{
                                                                List<Long> transactions = new ArrayList<Long>();
                                                                transactions.add(colorMapEntry.getKey());
                                                                orderCategoryMap.put(ALL_OTHERS, transactions);
                                                        }
                                                }
                                        }
                                }
                                
                                List<Long> categoryList = new ArrayList<Long>(orderCategoryMap.keySet());
                                Collections.sort(categoryList);
                                
                                orders = new ArrayList<Order>();
                                if(orderCategory==OrderCategory.NONE){
                                        for(Long category:categoryList){
                                                List<Long> transactions = orderCategoryMap.get(category);
                                                for(Long transactionId: transactions){
                                                        List<Order> txnOrders = transactionOrdersMap.get(transactionId);
                                                        for(Order order: txnOrders){
                                                                order.setCategory(categoryStrMap.get(category));
                                                        }
                                                        Collections.sort(txnOrders,new OrderPromisedShippingComparator());
                                                        orders.addAll(txnOrders);
                                                }
                                        }
                                }else{
                                        for(Long category:categoryList){
                                                if(orderCategory==categoryStrMap.get(category)){
                                                        List<Long> transactions = orderCategoryMap.get(category);
                                                        for(Long transactionId: transactions){
                                                                List<Order> txnOrders = transactionOrdersMap.get(transactionId);
                                                                for(Order order: txnOrders){
                                                                        order.setCategory(categoryStrMap.get(category));
                                                                }
                                                                Collections.sort(txnOrders,new OrderPromisedShippingComparator());
                                                                orders.addAll(txnOrders);
                                                        }
                                                }else{
                                                        continue;
                                                }
                                        }
                                        categoryOrderCount = 0;
                                        categoryOrderCount = categoryOrderCount+orders.size();
                                }
                                
                        }
                        
                }catch(Exception e){
                        e.printStackTrace();
                }
                return orders;
        }

        /**
         * Wrapper around the method of same name in the transaction service. This
         * method uses a mapping of <i>type</i> to <i>status</i> to get the count of
         * all orders with a given status.
         * 
         * @param type
         *            The type of orders to return.
         * @param warehouseId
         *            The warehouse for which the orders should be queried.
         * @return The count of orders of the given type assigned to the given
         *         warehouse.
         */
        public static int getOrderCount(OrderType type, long warehouseId, long source, OrderCategory orderCategory){
                List<OrderStatus> statuses = getStatuses(type);
                
                int count = 0;
                try{
                        if(type==OrderType.NOT_APPLICABLE && orderCategory!=OrderCategory.NONE){
                                int orderCount = categoryOrderCount;
                                categoryOrderCount = 0;
                                return orderCount;
                        }
                        else{
                                TransactionClient txnClient = new TransactionClient();
                                Client client = txnClient.getClient();
                                count += client.getOrderCount(statuses, warehouseId, source);
                        }
                }catch(Exception e){
                        e.printStackTrace();
                }
                return count;
        }
        
        /**
         * Calls the same method of the transaction service and returns the status
         * returned. Catches all exceptions that are raised and returns false in
         * that case.
         * 
         * @param warehouseId
         *            The warehouse for which the orders should be marked as
         *            manifested.
         * @param providerId
         *            The provider for which the orders should be marked as
         *            manifested.
         * @param cod
         *             Whether cod orders have to be marked as manifested
         * @return True if everything goes fine, false otherwise.
         */
        public static Map<Long, Long> getBilledOrders(long warehouseId, String providerId, boolean cod){
                Map<Long, Long> orders = new HashMap<Long, Long>();
                try {
                        long provider_id = Long.parseLong(providerId);
                        TransactionClient client = new TransactionClient();
                        Client c = client.getClient();

                        List<in.shop2020.model.v1.order.Order> torders = c.getBilledOrdersForManifestGen(warehouseId, Long.valueOf(provider_id), cod);
                        for(in.shop2020.model.v1.order.Order torder: torders){
                                orders.put(torder.getId(), torder.getPickupStoreId());
                        }

                }catch(Exception e){
                        e.printStackTrace();
                }
                return orders;
        }
        
        public static boolean generateCourierDetailsFile(List<Long> orderIds, long providerId, long warehouseId, boolean isCod){
                Calendar date = new GregorianCalendar();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) +1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                
                String fileNameSuffix = "-" + warehouseId + "-"+ providerId + "-" + year + "-" + month + "-" + day;
                if(isCod){
                    fileNameSuffix = "cod" + fileNameSuffix ;
                }
                else{
                    fileNameSuffix = "prepaid" + fileNameSuffix;
                }
                
                try {
                        String fileName = courierDetailsPath + "/courier-details-" + fileNameSuffix + "-temp.xls";
                        FileOutputStream f = new FileOutputStream(fileName);
                        CourierDetailsGenerator courierDetailsGenerator = new CourierDetailsGenerator();
                        ByteArrayOutputStream baosXLS = courierDetailsGenerator.generateCourierDetails(orderIds, warehouseId, providerId, isCod);
                        baosXLS.writeTo(f);
                        f.close();
                } catch (FileNotFoundException e) {
                        logger.error("Unable to create the courier details file", e);
                } catch (IOException e) {
                        logger.error("Unable to create the courier details file", e);
                }
        
                CourierDetailsReportMerger merger = new CourierDetailsReportMerger();
                try {
                        Map<Long, String> warehouseIdFileNames = new HashMap<Long, String>();
                        String fName;
                        fName = courierDetailsPath + "/courier-details-" + fileNameSuffix + "-temp.xls";
                        if((new File(fName)).exists()){
                                warehouseIdFileNames.put(0L, fName);
                        }
                        fName = courierDetailsPath + "/courier-details-" + fileNameSuffix + ".xls";
                        if((new File(fName)).exists()){
                                warehouseIdFileNames.put(1L, fName);
                        }
                        ByteArrayOutputStream binXLS = merger.mergeCourierDetailsReports(warehouseIdFileNames);
                        FileOutputStream f = new FileOutputStream(courierDetailsPath + "/courier-details-" + fileNameSuffix + ".xls");
                        binXLS.writeTo(f);
                        f.close();
                        File tempFile = new File(courierDetailsPath + "/courier-details-" + fileNameSuffix + "-temp.xls");
                        if(tempFile.exists()){
                                tempFile.delete();
                        }
                } catch (FileNotFoundException e) {
                        logger.error("Error while creating the Courier Details report", e);
                } catch (IOException e) {
                        logger.error("IO error while writing the Courier Details report", e);
                }
                return true;
        }
        
        
        public static List<Order> getOrdersFromThirftOrders(List<in.shop2020.model.v1.order.Order> orders, Long billingWarehouseId){
                List<Order> ordersToReturn = new ArrayList<Order>();
                Map<Long, Warehouse> warehousesMap = CatalogUtils.getAllWarehousesForBillingWarehouse(0); 
                List<Long> itemIds = new ArrayList<Long>();
                Map<Long, List<in.shop2020.model.v1.order.Order>> txnOrdersMap = new HashMap<Long, List<in.shop2020.model.v1.order.Order>>();
                
                Date date = new Date(System.currentTimeMillis());
                for(in.shop2020.model.v1.order.Order t_order : orders){
                        if(!itemIds.contains(t_order.getLineitems().get(0).getItem_id())){
                                itemIds.add(t_order.getLineitems().get(0).getItem_id());
                        }
                        List<in.shop2020.model.v1.order.Order> txnOrders = null;
                        if(txnOrdersMap.containsKey(t_order.getTransactionId())){
                                txnOrders = txnOrdersMap.get(t_order.getTransactionId());                               
                        }else{
                                txnOrders = new ArrayList<in.shop2020.model.v1.order.Order>();
                        }
                        txnOrders.add(t_order);
                        txnOrdersMap.put(t_order.getTransactionId(), txnOrders);
                }
                try {
                        in.shop2020.model.v1.catalog.CatalogService.Client client = new CatalogClient().getClient();
                        Map<Long, Item> itemsMap = client.getItems(itemIds);

                        in.shop2020.model.v1.order.TransactionService.Client tClient = new TransactionClient().getClient();
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        for(in.shop2020.model.v1.order.Order t_order : orders){
                                LineItem lineItem = t_order.getLineitems().get(0);
                                String pickFromWarehouse = warehousesMap.get(t_order.getFulfilmentWarehouseId()).getDisplayName();
                                Item item = itemsMap.get(lineItem.getItem_id());
                                in.shop2020.logistics.Provider provider = getProvidersMap().get(t_order.getLogistics_provider_id());
                                Warehouse fulfillmentWarehouse = warehousesMap.get(t_order.getFulfilmentWarehouseId());
                                Map<Long, Map<String, String>> acceptTogetherOrdersMap = null;
                                Map<Long, Map<String, String>> billTogetherOrdersMap = null;
                                if(!t_order.isSetAccepted_timestamp()){
                                        acceptTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                                        Map<String, String> orderValuesMap = new HashMap<String, String>();
                                        orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                                        orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                                        orderValuesMap.put("Promised_Shipping", sdf.format(new Date(t_order.getPromised_shipping_time())));     
                                        orderValuesMap.put("Weight", formatter.format(lineItem.getUnit_weight()));   
                                        orderValuesMap.put("UnitPrice", rformatter.format(lineItem.getUnit_price()));
                                        orderValuesMap.put("PackQuantity", item.getPackQuantity()+"");
                                        orderValuesMap.put("WarehouseType", fulfillmentWarehouse.getWarehouseType().toString());
                                        acceptTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
                                        List<in.shop2020.model.v1.order.Order> taOrders = null;
                                        if(txnOrdersMap.containsKey(t_order.getTransactionId())){
                                                taOrders = txnOrdersMap.get(t_order.getTransactionId());
                                        }else{
                                                try{
                                                        taOrders = tClient.getOrdersForTransaction(t_order.getTransactionId(), t_order.getCustomer_id());
                                                }catch(Exception te){
                                                        tClient = new TransactionClient().getClient();
                                                        taOrders = tClient.getOrdersForTransaction(t_order.getTransactionId(), t_order.getCustomer_id());
                                                }
                                        }
                                        for(in.shop2020.model.v1.order.Order taOrder : taOrders){
                                                LineItem lineItem1 = taOrder.getLineitems().get(0);
                                                if(t_order.getId()==taOrder.getId()){
                                                        continue;
                                                }
                                                else if(taOrder.getSource()!=OrderSource.WEBSITE.getValue()){
                                                        continue;
                                                }else{
                                                        orderValuesMap = new HashMap<String, String>();
                                                        if(provider.isGroupShipmentAllowed() && !taOrder.isSetAccepted_timestamp() && t_order.getStatus()==taOrder.getStatus() 
                                                                        && taOrder.isLogisticsCod()==t_order.isLogisticsCod() && taOrder.getWarehouse_id() == t_order.getWarehouse_id() 
                                                                        && taOrder.getOrderType() == t_order.getOrderType() && taOrder.getPickupStoreId() == t_order.getPickupStoreId()){
                                                                orderValuesMap.put("ProductName", getItemDisplayName(lineItem1));
                                                                orderValuesMap.put("Quantity", lineItem1.getQuantity()+"");
                                                                if(warehousesMap.containsKey(taOrder.getFulfilmentWarehouseId())){
                                                                        fulfillmentWarehouse = warehousesMap.get(taOrder.getFulfilmentWarehouseId());
                                                                }else{
                                                                        try{
                                                                                fulfillmentWarehouse = inventoryClient.getWarehouse(taOrder.getFulfilmentWarehouseId());
                                                                                warehousesMap.put(fulfillmentWarehouse.getId(), fulfillmentWarehouse);
                                                                        }
                                                                        catch(Exception ie){
                                                                                ie.printStackTrace();
                                                                                inventoryClient = inventoryServiceClient.getClient();
                                                                                fulfillmentWarehouse = inventoryClient.getWarehouse(taOrder.getFulfilmentWarehouseId());
                                                                                warehousesMap.put(fulfillmentWarehouse.getId(), fulfillmentWarehouse);
                                                                        }
                                                                }
                                                                orderValuesMap.put("WarehouseType", fulfillmentWarehouse.getWarehouseType().toString());
                                                                orderValuesMap.put("Promised_Shipping", sdf.format(new Date(taOrder.getPromised_shipping_time())));
                                                                orderValuesMap.put("UnitPrice", rformatter.format(lineItem1.getUnit_price()));
                                                                orderValuesMap.put("Weight", formatter.format(lineItem1.getUnit_weight()));
                                                                if(itemsMap.containsKey(lineItem1.getItem_id())){
                                                                        Item orderItem = itemsMap.get(lineItem1.getItem_id());
                                                                        orderValuesMap.put("PackQuantity", orderItem.getPackQuantity()+"");
                                                                }else{
                                                                        try{
                                                                                Item orderItem = client.getItem(lineItem1.getItem_id());
                                                                                orderValuesMap.put("PackQuantity", orderItem.getPackQuantity()+"");
                                                                                itemsMap.put(orderItem.getId(), orderItem);
                                                                        }catch(Exception ce){
                                                                                ce.printStackTrace();
                                                                                client = new CatalogClient().getClient();
                                                                                Item orderItem = client.getItem(lineItem1.getItem_id());
                                                                                orderValuesMap.put("PackQuantity", orderItem.getPackQuantity()+"");
                                                                                itemsMap.put(orderItem.getId(), orderItem);
                                                                        }
                                                                }
                                                        }
                                                        if(orderValuesMap!=null && orderValuesMap.size()>0){
                                                acceptTogetherOrdersMap.put(taOrder.getId(), orderValuesMap);
                                        }
                                                }
                                        }
                                }
                                
                                if(t_order.isSetLogisticsTransactionId()){
                                        billTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                        Map<String, String> orderValuesMap = new HashMap<String, String>();
                            if(t_order.getStatus()==OrderStatus.ACCEPTED || t_order.getStatus()==OrderStatus.RTO_IN_TRANSIT ){
                                orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                                orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                                if(ItemType.SERIALIZED==item.getType()){
                                        orderValuesMap.put("IsSerialized", "true");
                                }else{
                                        orderValuesMap.put("IsSerialized", "false");
                                }
                                if(t_order.isSetFreebieItemId() && t_order.getFreebieItemId()!=0){
                                        orderValuesMap.put("IsFreebie", "true");
                                } else {
                                        orderValuesMap.put("IsFreebie", "false");
                                }
                                billTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
                                logger.info("order Values Map- "+ orderValuesMap);
                        }
                            
                            List<in.shop2020.model.v1.order.Order> taOrders = null;
                            try{
                                taOrders = tClient.getGroupOrdersByLogisticsTxnId(t_order.getLogisticsTransactionId());
                            }catch(Exception te){
                                tClient = new TransactionClient().getClient();
                                taOrders = tClient.getGroupOrdersByLogisticsTxnId(t_order.getLogisticsTransactionId());
                            }
                            
                            for(in.shop2020.model.v1.order.Order taOrder: taOrders){
                                if(taOrder.getStatus()==OrderStatus.ACCEPTED || taOrder.getStatus()==OrderStatus.RTO_IN_TRANSIT ){
                                        if(taOrder.getId()==t_order.getId()){
                                                continue;
                                        } else {
                                                orderValuesMap = new HashMap<String, String>();
                                                Item orderItem = null;
                                                if(itemsMap.containsKey(taOrder.getLineitems().get(0).getItem_id())){
                                                        orderItem = itemsMap.get(taOrder.getLineitems().get(0).getItem_id());
                                                }else{
                                                                        try{
                                                                                orderItem = client.getItem(taOrder.getLineitems().get(0).getItem_id());
                                                                                itemsMap.put(orderItem.getId(), orderItem);
                                                                        }catch(Exception ce){
                                                                                ce.printStackTrace();
                                                                                client = new CatalogClient().getClient();
                                                                                orderItem = client.getItem(taOrder.getLineitems().get(0).getItem_id());
                                                                                itemsMap.put(orderItem.getId(), orderItem);
                                                                        }
                                                                }
                                                
                                                orderValuesMap.put("ProductName", getProductName(orderItem));
                                        orderValuesMap.put("Quantity", taOrder.getLineitems().get(0).getQuantity()+"");
                                        if(ItemType.SERIALIZED==orderItem.getType()){
                                                orderValuesMap.put("IsSerialized", "true");
                                        }else{
                                                orderValuesMap.put("IsSerialized", "false");
                                        }
                                        if(taOrder.isSetFreebieItemId() && taOrder.getFreebieItemId()!=0){
                                                orderValuesMap.put("IsFreebie", "true");
                                        } else {
                                                orderValuesMap.put("IsFreebie", "false");
                                        }
                                        billTogetherOrdersMap.put(taOrder.getId(), orderValuesMap);
                                        }
                                }
                        }
                        
                                }else{
                        billTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                        Map<String, String> orderValuesMap = new HashMap<String, String>();
                        orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                        orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                        if(ItemType.SERIALIZED==item.getType()){
                                orderValuesMap.put("IsSerialized", "true");
                        }else{
                                orderValuesMap.put("IsSerialized", "false");
                        }
                        if(t_order.isSetFreebieItemId() && t_order.getFreebieItemId()!=0){
                                orderValuesMap.put("IsFreebie", "true");
                        } else {
                                orderValuesMap.put("IsFreebie", "false");
                        }
                        billTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
                    }
                                String delayReason = null;
                                if(t_order.getDelayReason() != null)
                                    delayReason = t_order.getDelayReason().name();
                                
                                String osource = OrderSource.findByValue((int)t_order.getSource()).toString();
                                
                                Order order = new Order(t_order.getId(),
                                                t_order.getCustomer_id(),
                                                t_order.getCustomer_name(),
                                                t_order.getCustomer_mobilenumber(),
                                                t_order.getCustomer_pincode(),
                                                t_order.getCustomer_address1(),
                                                t_order.getCustomer_address2(),
                                                t_order.getCustomer_city(),
                                                t_order.getCustomer_state(),
                                                t_order.getCustomer_email(),
                                                t_order.getCreated_timestamp(),
                                                t_order.getShipping_timestamp(),
                                                t_order.getVerification_timestamp(),
                                                t_order.getExpected_delivery_time(),
                                                t_order.getPromised_delivery_time(),
                                                t_order.getExpected_shipping_time(),
                                                t_order.getPromised_shipping_time(),
                                                t_order.getStatus().getValue(),
                                                t_order.getStatusDescription(),
                                                t_order.getOrderType().name(),
                                                lineItem.getItem_id(),
                                                lineItem.getProductGroup(),
                                                lineItem.getBrand(),
                                                lineItem.getModel_name(),
                                                lineItem.getModel_number(),
                                                lineItem.getColor(),
                                                lineItem.getExtra_info(),
                                                lineItem.getDealText(),
                                                lineItem.getQuantity(),
                                                t_order.getTotal_amount(),
                                                t_order.getTotal_weight(),
                                                t_order.getAirwaybill_no(),
                                                t_order.getBilled_by(),
                                                t_order.getInvoice_number(),
                                                t_order.getJacket_number(),
                                                lineItem.getItem_number(),
                                                lineItem.getSerial_number(),
                                                t_order.getBatchNo(),
                                                t_order.getSerialNo(),
                                                t_order.isDoaFlag(),
                                                t_order.getPickupRequestNo(),
                                                t_order.isLogisticsCod(),
                                                delayReason,
                                                pickFromWarehouse,
                                                ItemType.SERIALIZED.equals(item.getType()),
                                                item.isHasItemNo(),
                                                t_order.getFulfilmentWarehouseId(),
                                                t_order.getWarehouse_id(),
                                                t_order.getPickupStoreId(),
                                                t_order.getFreebieItemId(),
                                                osource, 
                                                new Long(t_order.getProductCondition().getValue()),
                                                t_order.getTransactionId());
                                if(acceptTogetherOrdersMap!=null && acceptTogetherOrdersMap.size()>0){
                                        order.setAcceptTogetherOrdersMap(acceptTogetherOrdersMap);
                                }
                                if(billTogetherOrdersMap!=null && billTogetherOrdersMap.size()>0){
                                        order.setBillTogetherOrdersMap(billTogetherOrdersMap);
                                }
                                if(t_order.isSetLogisticsTransactionId()){
                                        order.setLogisticsTransactionId(t_order.getLogisticsTransactionId());
                                }
                                
                                
                                long currentDateTime = 0;
                                long promisedShippingTime =0 ;
                                long currentTime = date.getTime();
                                try{
                                        currentDateTime = newSdf.parse(newSdf.format(date)).getTime();
                                        promisedShippingTime = newSdf.parse(newSdf.format(new Date(order.getPromisedShippingTime()))).getTime();
                                }catch(Exception e){
                                        logger.error("Error formatting date for order" + order.getOrderId());
                                        logger.error("Error formatting date " + date.getTime());
                                        logger.error("Error formatting date " + order.getPromisedShippingTime());
                                        e.printStackTrace();
                                }
                                if(promisedShippingTime >0 && (order.getStatus()==3 || order.getStatus()==5 || order.getStatus()==41 ||
                                                order.getStatus()==35 || order.getStatus()==36 || order.getStatus()==37)){
                                        if(promisedShippingTime <= currentDateTime){
                                                if(loadVirtualWarehouseDetails().contains(order.getFulfilmentWarehouseId())){
                                                        order.setAlert(OrderAlert.TODAY_SHIPPING_NOT_IN_STOCK);
                                                }else{
                                                        order.setAlert(OrderAlert.TODAY_SHIPPING_IN_STOCK);
                                                }
                                        }else{
                                                if(!loadVirtualWarehouseDetails().contains(order.getFulfilmentWarehouseId())){
                                                        order.setAlert(OrderAlert.LATER_SHIPPING_IN_STOCK);
                                                }
                                        }
                                }
                                
                                ordersToReturn.add(order);
                        }
                }
                catch (Exception e) {
                        e.printStackTrace();
                }

                return ordersToReturn;

        }
        
        
        /**
         * 
         * @param t_order
         *            A thrift order object with line items.
         * @return an Order bean which can be used for rendering on the client side.
         */
        public static Order getOrderFromThriftOrder(in.shop2020.model.v1.order.Order t_order) {
                LineItem lineItem = t_order.getLineitems().get(0);
                String pickFromWarehouse = null;
                Item item = null;
                String warehouseType = "";
                
            Map<Long, Map<String, String>> acceptTogetherOrdersMap = null;
            Map<Long, Map<String, String>> billTogetherOrdersMap = null;

        try {
            in.shop2020.model.v1.catalog.CatalogService.Client client = new CatalogClient().getClient();
            in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = new InventoryClient().getClient();
            item = client.getItem(lineItem.getItem_id());
            pickFromWarehouse = CatalogUtils.getWarehousesForBillingWarehouse(0)
                                    .get(t_order.getFulfilmentWarehouseId());

            if (pickFromWarehouse == null) {
                Warehouse warehouse = inventoryClient.getWarehouse(t_order.getFulfilmentWarehouseId());
                pickFromWarehouse = inventoryClient.getWarehouses(null, InventoryType.GOOD, warehouse.getVendor().getId(), t_order.getWarehouse_id(), 0).get(0).getDisplayName();
            }                                                                                   
            if(!t_order.isSetAccepted_timestamp()){
                acceptTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                Map<String, String> orderValuesMap = new HashMap<String, String>();
                orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                                orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                                if(!inventoryClient.isAlive()){
                                        inventoryClient = new InventoryClient().getClient();
                                }
                                Warehouse fulfillmentWarehouse = inventoryClient.getWarehouse(t_order.getFulfilmentWarehouseId());
                                warehouseType = fulfillmentWarehouse.getWarehouseType().toString();
                                orderValuesMap.put("WarehouseType", fulfillmentWarehouse.getWarehouseType().toString());
                                SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
                                orderValuesMap.put("Promised_Shipping", sdf.format(new Date(t_order.getPromised_shipping_time())));
                                NumberFormat formatter = new DecimalFormat("#0.000");     
                                orderValuesMap.put("Weight", formatter.format(t_order.getLineitems().get(0).getUnit_weight()));
                                formatter = new DecimalFormat("#0.00");   
                                orderValuesMap.put("UnitPrice", formatter.format(t_order.getLineitems().get(0).getUnit_price()));
                                orderValuesMap.put("PackQuantity", item.getPackQuantity()+"");
                                acceptTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
                List<in.shop2020.model.v1.order.Order> taOrders = new TransactionClient().getClient().getOrdersForTransaction(t_order.getTransactionId(), t_order.getCustomer_id());
                in.shop2020.logistics.Provider provider = new LogisticsClient().getClient().getProvider(t_order.getLogistics_provider_id());
                for(in.shop2020.model.v1.order.Order taOrder : taOrders){
                        LineItem lineItem1 = taOrder.getLineitems().get(0);
                        if(t_order.getId()==taOrder.getId()){
                                continue;
                        }
                        else if(taOrder.getSource()!=OrderSource.WEBSITE.getValue()){
                                continue;
                        }
                        else{
                                orderValuesMap = new HashMap<String, String>();
                                if(provider.isGroupShipmentAllowed() && !taOrder.isSetAccepted_timestamp() && t_order.getStatus()==taOrder.getStatus() 
                                                && taOrder.isLogisticsCod()==t_order.isLogisticsCod() && taOrder.getWarehouse_id() == t_order.getWarehouse_id() 
                                                && taOrder.getOrderType() == t_order.getOrderType() && taOrder.getPickupStoreId() == t_order.getPickupStoreId()){
                                        orderValuesMap.put("ProductName", getItemDisplayName(lineItem1));
                                        orderValuesMap.put("Quantity", lineItem1.getQuantity()+"");
                                        if(!inventoryClient.isAlive()){
                                                inventoryClient = new InventoryClient().getClient();
                                        }
                                        fulfillmentWarehouse = inventoryClient.getWarehouse(taOrder.getFulfilmentWarehouseId());
                                        orderValuesMap.put("WarehouseType", fulfillmentWarehouse.getWarehouseType().toString());
                                        orderValuesMap.put("Promised_Shipping", sdf.format(new Date(taOrder.getPromised_shipping_time())));
                                        orderValuesMap.put("UnitPrice", formatter.format(taOrder.getLineitems().get(0).getUnit_price()));
                                        formatter = new DecimalFormat("#0.000");   
                                        orderValuesMap.put("Weight", formatter.format(taOrder.getLineitems().get(0).getUnit_weight()));
                                        Item orderItem = client.getItem(taOrder.getLineitems().get(0).getItem_id());
                                        orderValuesMap.put("PackQuantity", orderItem.getPackQuantity()+"");
                                }
                                if(orderValuesMap!=null && orderValuesMap.size()>0){
                                        acceptTogetherOrdersMap.put(taOrder.getId(), orderValuesMap);
                                }
                        }
                }
            }
            
            if(t_order.isSetLogisticsTransactionId()){
                billTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                Map<String, String> orderValuesMap = new HashMap<String, String>();
                    if(t_order.getStatus()==OrderStatus.ACCEPTED || t_order.getStatus()==OrderStatus.RTO_IN_TRANSIT ){
                        orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                        orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                        if(ItemType.SERIALIZED==item.getType()){
                                orderValuesMap.put("IsSerialized", "true");
                        }else{
                                orderValuesMap.put("IsSerialized", "false");
                        }
                        if(t_order.isSetFreebieItemId() && t_order.getFreebieItemId()!=0){
                                orderValuesMap.put("IsFreebie", "true");
                        } else {
                                orderValuesMap.put("IsFreebie", "false");
                        }
                        billTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
                }
                Map<Long, Item> orderItemMap = new HashMap<Long, Item>();
                List<in.shop2020.model.v1.order.Order> taOrders = new TransactionClient().getClient().getGroupOrdersByLogisticsTxnId(t_order.getLogisticsTransactionId());
                for(in.shop2020.model.v1.order.Order ord1: taOrders){
                        if(ord1.getStatus()==OrderStatus.ACCEPTED || ord1.getStatus()==OrderStatus.RTO_IN_TRANSIT ){
                                if(ord1.getId()== t_order.getId()){
                                        orderItemMap.put(ord1.getId(), item);
                                } else {
                                        if(!client.isAlive()){
                                                client = new CatalogClient().getClient();
                                        }
                                        Item it = client.getItem(ord1.getLineitems().get(0).getItem_id());
                                        orderItemMap.put(ord1.getId(), it);
                                }
                        }
                }
                
                for(in.shop2020.model.v1.order.Order taOrder: taOrders){
                        if(taOrder.getStatus()==OrderStatus.ACCEPTED || taOrder.getStatus()==OrderStatus.RTO_IN_TRANSIT ){
                                if(taOrder.getId()==t_order.getId()){
                                        continue;
                                } else {
                                        orderValuesMap = new HashMap<String, String>();
                                        Item orderItem = orderItemMap.get(taOrder.getId());
                                        orderValuesMap.put("ProductName", getProductName(orderItem));
                                orderValuesMap.put("Quantity", taOrder.getLineitems().get(0).getQuantity()+"");
                                if(ItemType.SERIALIZED==orderItem.getType()){
                                        orderValuesMap.put("IsSerialized", "true");
                                }else{
                                        orderValuesMap.put("IsSerialized", "false");
                                }
                                if(taOrder.isSetFreebieItemId() && taOrder.getFreebieItemId()!=0){
                                        orderValuesMap.put("IsFreebie", "true");
                                } else {
                                        orderValuesMap.put("IsFreebie", "false");
                                }
                                billTogetherOrdersMap.put(taOrder.getId(), orderValuesMap);
                                }
                        }
                }
            }
            else{
                billTogetherOrdersMap = new HashMap<Long, Map<String, String>>();
                Map<String, String> orderValuesMap = new HashMap<String, String>();
                orderValuesMap.put("ProductName", getItemDisplayName(lineItem));
                orderValuesMap.put("Quantity", lineItem.getQuantity()+"");
                if(ItemType.SERIALIZED==item.getType()){
                        orderValuesMap.put("IsSerialized", "true");
                }else{
                        orderValuesMap.put("IsSerialized", "false");
                }
                if(t_order.isSetFreebieItemId() && t_order.getFreebieItemId()!=0){
                        orderValuesMap.put("IsFreebie", "true");
                } else {
                        orderValuesMap.put("IsFreebie", "false");
                }
                billTogetherOrdersMap.put(t_order.getId(), orderValuesMap);
            }
                }
        catch (Exception e) {
            logger.error("Error looking up warehouse: " + t_order.getVendorId(), e);
        }

                String delayReason = null;
                if(t_order.getDelayReason() != null)
                    delayReason = t_order.getDelayReason().name();
                
                String osource = OrderSource.findByValue((int)t_order.getSource()).toString();
                
                Order order = new Order(t_order.getId(),
                                t_order.getCustomer_id(),
                                t_order.getCustomer_name(),
                                t_order.getCustomer_mobilenumber(),
                                t_order.getCustomer_pincode(),
                                t_order.getCustomer_address1(),
                                t_order.getCustomer_address2(),
                                t_order.getCustomer_city(),
                                t_order.getCustomer_state(),
                                t_order.getCustomer_email(),
                                t_order.getCreated_timestamp(),
                                t_order.getShipping_timestamp(),
                                t_order.getVerification_timestamp(),
                                t_order.getExpected_delivery_time(),
                                t_order.getPromised_delivery_time(),
                                t_order.getExpected_shipping_time(),
                                t_order.getPromised_shipping_time(),
                                t_order.getStatus().getValue(),
                                t_order.getStatusDescription(),
                                t_order.getOrderType().name(),
                                lineItem.getItem_id(),
                                lineItem.getProductGroup(),
                                lineItem.getBrand(),
                                lineItem.getModel_name(),
                                lineItem.getModel_number(),
                                lineItem.getColor(),
                                lineItem.getExtra_info(),
                                lineItem.getDealText(),
                                lineItem.getQuantity(),
                                t_order.getTotal_amount(),
                                t_order.getTotal_weight(),
                                t_order.getAirwaybill_no(),
                                t_order.getBilled_by(),
                                t_order.getInvoice_number(),
                                t_order.getJacket_number(),
                                lineItem.getItem_number(),
                                lineItem.getSerial_number(),
                                t_order.getBatchNo(),
                                t_order.getSerialNo(),
                                t_order.isDoaFlag(),
                                t_order.getPickupRequestNo(),
                                t_order.isLogisticsCod(),
                                delayReason,
                                pickFromWarehouse,
                                ItemType.SERIALIZED.equals(item.getType()),
                                item.isHasItemNo(),
                                t_order.getFulfilmentWarehouseId(),
                                t_order.getWarehouse_id(),
                                t_order.getPickupStoreId(),
                                t_order.getFreebieItemId(),
                                osource, 
                                new Long(t_order.getProductCondition().getValue()),
                                t_order.getTransactionId());
                if(acceptTogetherOrdersMap!=null && acceptTogetherOrdersMap.size()>0){
                        order.setAcceptTogetherOrdersMap(acceptTogetherOrdersMap);
                }
                if(billTogetherOrdersMap!=null && billTogetherOrdersMap.size()>0){
                        order.setBillTogetherOrdersMap(billTogetherOrdersMap);
                }
                if(t_order.isSetLogisticsTransactionId()){
                        order.setLogisticsTransactionId(t_order.getLogisticsTransactionId());
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date(System.currentTimeMillis());
                long currentDateTime = 0;
                long promisedShippingTime =0 ;
                long currentTime = date.getTime();
                try{
                        currentDateTime = sdf.parse(sdf.format(date)).getTime();
                        promisedShippingTime = sdf.parse(sdf.format(new Date(order.getPromisedShippingTime()))).getTime();
                }catch(Exception e){
                        e.printStackTrace();
                }
                if(promisedShippingTime >0 && (order.getStatus()==3 || order.getStatus()==5 || order.getStatus()==41 ||
                                order.getStatus()==35 || order.getStatus()==36 || order.getStatus()==37)){
                        if(promisedShippingTime <= currentDateTime){
                                if(loadVirtualWarehouseDetails().contains(order.getFulfilmentWarehouseId())){
                                        order.setAlert(OrderAlert.TODAY_SHIPPING_NOT_IN_STOCK);
                                }else{
                                        order.setAlert(OrderAlert.TODAY_SHIPPING_IN_STOCK);
                                }
                        }else{
                                if(!loadVirtualWarehouseDetails().contains(order.getFulfilmentWarehouseId())){
                                        order.setAlert(OrderAlert.LATER_SHIPPING_IN_STOCK);
                                }
                        }
                }
                return order;
        }

        /**
         * Queries the transction server to get the list of all return orders that
         * have to be processed.
         * 
         * @return A list of all return orders to be processed.
         */
        public static List<ReturnOrder> getReturnOrders(long warehouseId){
                List<ReturnOrder> retOrders = new ArrayList<ReturnOrder>();
                try{
                        TransactionClient client = new TransactionClient();
                        Client c = client.getClient();
                        List<in.shop2020.model.v1.order.ReturnOrder> tRetOrders =  c.getReturnOrders(warehouseId, 0L, new Date().getTime());
                        for(in.shop2020.model.v1.order.ReturnOrder retOrder : tRetOrders){
                                retOrders.add(getReturnOrderFromThriftRO(retOrder));
                        }
                }catch(Exception e){
                        e.printStackTrace();
                }
                return retOrders;
        }
        
        public static ReturnOrder getReturnOrderFromThriftRO(in.shop2020.model.v1.order.ReturnOrder tRetOrder){
                ReturnOrder retOrder = new ReturnOrder(tRetOrder.getOrderId(),
                                tRetOrder.getWarehouseId(),
                                tRetOrder.getItemId(),
                                tRetOrder.getProductGroup(),
                                tRetOrder.getBrand(),
                                tRetOrder.getModelName(),
                                tRetOrder.getModelNumber(),
                                tRetOrder.getColor(),
                                tRetOrder.getInvoiceNumber(),
                                tRetOrder.getJacketNumber(),
                                tRetOrder.getTotalPrice(),
                                tRetOrder.getTransferPrice(),
                                false,
                                tRetOrder.getCreatedAt());
                return retOrder;
        }
        
        /**
         * This method maps a given type to a list of statuses.
         * 
         * @param type
         *            The type of orders to fetch.
         * @return The list of Thrift statuses associated with a particular order
         *         type.
         */
        public static List<OrderStatus> getStatuses(OrderType type) {
                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                
                switch (type) {
                case ACCEPTED:
                        statuses.add(OrderStatus.ACCEPTED);
                        break;

                case ALL_PENDING:
                        statuses.add(OrderStatus.SUBMITTED_FOR_PROCESSING);
                        statuses.add(OrderStatus.CAPTURE_IN_PROCESS);
                        statuses.add(OrderStatus.INVENTORY_LOW);
                        statuses.add(OrderStatus.LOW_INV_PO_RAISED);
                        statuses.add(OrderStatus.LOW_INV_REVERSAL_IN_PROCESS);
                        statuses.add(OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT);
                        break;

                case NEW:
                        statuses.add(OrderStatus.SUBMITTED_FOR_PROCESSING);
                        statuses.add(OrderStatus.CAPTURE_IN_PROCESS);
                        break;

                case BILLED:
                        statuses.add(OrderStatus.BILLED);
                        break;

                case LOW_INVENTORY:
                        statuses.add(OrderStatus.INVENTORY_LOW);
                        break;

                case PO_RAISED:
                        statuses.add(OrderStatus.LOW_INV_PO_RAISED);
                        break;
                        
                case REVERSAL_INITIATED:
                        statuses.add(OrderStatus.LOW_INV_REVERSAL_IN_PROCESS);
                        break;
                        
                case NOT_AVAILABLE:
                        statuses.add(OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT);
                        break;
                        
                case CANCEL_CONFIRMED:
                        statuses.add(OrderStatus.CANCEL_REQUEST_CONFIRMED);
                        break;
                        
                case DOA_REQUEST_AUTHORIZED:
                        statuses.add(OrderStatus.DOA_REQUEST_AUTHORIZED);
                        statuses.add(OrderStatus.DOA_PICKUP_REQUEST_RAISED);
                        break;

                case LOST_IN_TRANSIT:
                        statuses.add(OrderStatus.LOST_IN_TRANSIT);
                        break;
                        
                case DOA_LOST_IN_TRANSIT:
                        statuses.add(OrderStatus.DOA_LOST_IN_TRANSIT);
                        break;
                
                case DOA_RECEIVED_DAMAGED:
                        statuses.add(OrderStatus.DOA_RECEIVED_DAMAGED);
                        break;

                case RET_REQUEST_AUTHORIZED:
                        statuses.add(OrderStatus.RET_REQUEST_AUTHORIZED);
                        statuses.add(OrderStatus.RET_PICKUP_REQUEST_RAISED);
                        break;

                case RET_AWAITED:
                        statuses.add(OrderStatus.RET_RETURN_IN_TRANSIT);
                        statuses.add(OrderStatus.RET_PICKUP_CONFIRMED);
                        break;
                        
                case RET_RECEIVED_PRESTINE:
                        statuses.add(OrderStatus.RET_RECEIVED_PRESTINE);
                        statuses.add(OrderStatus.RET_PRODUCT_USABLE);
                        break;

                case RET_LOST_IN_TRANSIT:
                        statuses.add(OrderStatus.RET_LOST_IN_TRANSIT);
                        break;
                
                case RET_RECEIVED_DAMAGED:
                        statuses.add(OrderStatus.RET_RECEIVED_DAMAGED);
                        statuses.add(OrderStatus.RET_PRODUCT_UNUSABLE);
                        break;
                        
                case REJECTED:
                        statuses.add(OrderStatus.REJECTED);
                        break;
                
                case SHIPPED:
                        statuses.add(OrderStatus.SHIPPED_FROM_WH);
                        statuses.add(OrderStatus.SHIPPED_TO_LOGST);
                        statuses.add(OrderStatus.SHIPPED_TO_DESTINATION_CITY);
                        statuses.add(OrderStatus.REACHED_DESTINATION_CITY);
                        statuses.add(OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE);
                        break;

                case DELIVERED:
                        statuses.add(OrderStatus.DELIVERY_SUCCESS);
                        statuses.add(OrderStatus.DOA_PICKUP_REQUEST_RAISED);
                        break;
                
                case DOA_AWAITED:
                        statuses.add(OrderStatus.DOA_PICKUP_CONFIRMED);
                        statuses.add(OrderStatus.DOA_RETURN_IN_TRANSIT);
                        statuses.add(OrderStatus.DOA_RECEIVED_PRESTINE);
                        break;
                        
                case RTO_AWAITED:
                        statuses.add(OrderStatus.RTO_IN_TRANSIT);
                        break;
                        
        case RTO_RECEIVED_DAMAGED:
            statuses.add(OrderStatus.RTO_RECEIVED_DAMAGED);
            break;

        case DOA_RECEIVED_PRESTINE:
                        statuses.add(OrderStatus.DOA_CERT_VALID);
                        statuses.add(OrderStatus.DOA_CERT_INVALID);
                        break;
                        
                case RTO_RETURNED:
                        statuses.add(OrderStatus.RTO_RECEIVED_PRESTINE);
                        break;
                
                case RESHIPPED:
                        statuses.add(OrderStatus.RTO_RESHIPPED);
                        statuses.add(OrderStatus.DOA_INVALID_RESHIPPED);
                        statuses.add(OrderStatus.DOA_VALID_RESHIPPED);
                        break;
                        
                case REFUNDED:
                    statuses.add(OrderStatus.COD_VERIFICATION_FAILED);
                        statuses.add(OrderStatus.RTO_REFUNDED);
                        statuses.add(OrderStatus.DOA_INVALID_REFUNDED);
                        statuses.add(OrderStatus.DOA_VALID_REFUNDED);
                        statuses.add(OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);
                        break;
                
                case VERIFICATION_PENDING:
                    statuses.add(OrderStatus.COD_VERIFICATION_PENDING);
                    break;
                default:
                        break;
                }
                return statuses;
        }
        
        public static List<Long> getEligibleOrdersToBeAccepted(Order order){
                List<Long> orders = new ArrayList<Long>();
                try {
                        
                        TransactionClient client = new TransactionClient();
                        Client c = client.getClient();
                        
                        in.shop2020.model.v1.order.Order thriftOrder = c.getOrder(order.getOrderId());
                        long provider_id = thriftOrder.getLogistics_provider_id();
                        boolean cod = thriftOrder.isLogisticsCod();
                        
                        List<in.shop2020.model.v1.order.Order> torders = c.getOrdersForTransaction(thriftOrder.getTransactionId(), thriftOrder.getCustomer_id());
                        for(in.shop2020.model.v1.order.Order torder: torders){
                                if(torder.getLogistics_provider_id() == provider_id && torder.isLogisticsCod() == cod){
                                        orders.add(torder.getId());
                                }
                        }
                        
                }catch(Exception e){
                        e.printStackTrace();
                }
                return orders;
        }
        
        public static String getItemDisplayName(LineItem lineitem){
                StringBuffer itemName = new StringBuffer();
        if (lineitem.getBrand() != null)
            itemName.append(lineitem.getBrand() + " ");
        if (lineitem.getModel_name() != null)
            itemName.append(lineitem.getModel_name() + " ");
        if (lineitem.getModel_number() != null)
            itemName.append(lineitem.getModel_number() + " ");
        if (lineitem.getColor() != null
                && !lineitem.getColor().trim().equals("NA"))
            itemName.append("(" + lineitem.getColor() + ")");

        return itemName.toString();
        }
        
        public static String getProductName(in.shop2020.model.v1.catalog.Item item){
                StringBuffer itemName = new StringBuffer();
        if (item.getBrand() != null)
            itemName.append(item.getBrand() + " ");
        if (item.getModelName() != null)
            itemName.append(item.getModelName() + " ");
        if (item.getModelNumber() != null)
            itemName.append(item.getModelNumber() + " ");
        if (item.getColor() != null
                && !item.getColor().trim().equals("NA"))
            itemName.append("(" + item.getColor() + ")");

        return itemName.toString();
        }
        
        public static List<Long> loadVirtualWarehouseDetails(){
                EhcacheWrapper<String, List<Long>> virtualWhCache = new EhcacheWrapper<String, List<Long>>(
                                "VirtualWarehouses", CacheManager.create());
                
                List<Long> virtualWarehouseIds = virtualWhCache.get("virtual_warehouses");
                
                if(virtualWarehouseIds!=null && virtualWarehouseIds.size()>0){
                        return virtualWarehouseIds;
                }else{
                        logger.info("Virtual Warehouse Not Exists, creating them");
                        virtualWarehouseIds = new ArrayList<Long>();
                        try{
                                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = new InventoryClient().getClient();
                                List<Warehouse> allWarehouses = inventoryClient.getWarehouses(null, null, 0, 0, 0);
                                for(Warehouse wh:allWarehouses){
                                        if(wh.getWarehouseType()==WarehouseType.THIRD_PARTY){
                                                virtualWarehouseIds.add(wh.getId());
                                        }
                                }
                        }catch(Exception e){
                                e.printStackTrace();
                        }
                        virtualWhCache.put("virtual_warehouses", virtualWarehouseIds);
                }
                
                return virtualWarehouseIds;
        }
}