Subversion Repositories SmartDukaan

Rev

Rev 15598 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020;

import in.shop2020.model.v1.catalog.CatalogService;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.SnapdealItem;
import in.shop2020.model.v1.inventory.InventoryService;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.InventoryType;
import in.shop2020.model.v1.inventory.VendorItemPricing;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.inventory.WarehouseType;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderType;
import in.shop2020.model.v1.order.SnapdealOrder;
import in.shop2020.model.v1.order.SourceDetail;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.user.User;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.serving.services.SnapdealSessionCookie;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.PaymentClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.GmailUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
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 org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import utilities.SnapdealOrderUnit;
import utilities.VendorPendingOrderSkuDetail;
import utilities.VendorPendingProductOfferDisplayDTO;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

import com.google.gson.Gson;

public class SnapdealOrderCreator{
        private static DefaultHttpClient client = new DefaultHttpClient();
        private static Logger logger = LoggerFactory.getLogger(SnapdealOrderCreator.class);
        private static List<VendorPendingProductOfferDisplayDTO> pendingOrdersSkuList = new ArrayList<VendorPendingProductOfferDisplayDTO> ();
        private static final int SNAPDEAL_SOURCE_ID = 7;
        private static String transactionId;
        private static long paymentId;
        private static final int SNAPDEAL_GATEWAY_ID = 18;
        
        private static Map<String, String> headers = new HashMap<String, String>();
        
        static{
                headers.put("User-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
                headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                headers.put("Accept-Language", "en-US,en;q=0.8");
                headers.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
        }
        
        @SuppressWarnings("unchecked")
        public static void fetchOrders() throws Exception{
                List<SnapdealOrderUnit> snapdealOrderUnitsList = new ArrayList<SnapdealOrderUnit>();
                Map<String, SnapdealOrderUnit> snapdealOrderUnitListMap = new HashMap<String, SnapdealOrderUnit>();
                Map<String, Long> pendingSkuMap = new HashMap<String, Long>();
                SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
                String cookies = sdSessionCookie.getCookies();
                JSONObject cookieObject = new JSONObject(cookies);
                String pendingOrderSummaryUrl = "http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/pendingOrders/40?fulfillmentModelCode=ONESHIP";
                HttpGet get = new HttpGet(pendingOrderSummaryUrl);
                for(String key:headers.keySet())
                        get.addHeader(key, headers.get(key));
                get.addHeader("Cookie","AWSELB="+cookieObject.get("AWSELB")+";JSESSIONID="+cookieObject.get("JSESSIONID")+";");
                System.out.println(get.getAllHeaders().length);
                HttpResponse response = null;
                Gson gson = new Gson();
                BufferedReader rd= null;
                String line = "";
                try {
                        response = client.execute(get);
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                
                while((line=rd.readLine())!=null){
                        System.out.println(line);
                }
                
                get = new HttpGet("http://shipping.snapdeal.com/json/vendor/ONESHIP/product-shipment/pendingOrders/PFF/ALL/pending");
                for(String key:headers.keySet())
                        get.addHeader(key, headers.get(key));
                cookies = sdSessionCookie.getCookies();
                cookieObject = new JSONObject(cookies);
                get.addHeader("Cookie","AWSELB="+cookieObject.get("AWSELB")+";JSESSIONID="+cookieObject.get("JSESSIONID")+";");
                
                
                response = null;
                
                try {
                        response = client.execute(get);
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                
                
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                
                line = rd.readLine();
                System.out.println(line);
                
                
                JSONArray jsonArray = new JSONArray(line);
                for(int i=0; i<jsonArray.length(); i++){
                        VendorPendingOrderSkuDetail vendorPendingSku = (VendorPendingOrderSkuDetail)gson.fromJson(jsonArray.get(i).toString(),VendorPendingOrderSkuDetail.class);
                        pendingOrdersSkuList.add(vendorPendingSku.getVendorPendingProductOfferDisplayDTO());
                }
                
                for(VendorPendingProductOfferDisplayDTO vendorPendingSku : pendingOrdersSkuList){
                        pendingSkuMap.put(vendorPendingSku.getProductCode(), (long)vendorPendingSku.getPendingQuantity());
                }
                
                String productCodeToParse = "";
                String pendingQuantityToParse = "";
                
                for(String productCode : pendingSkuMap.keySet()){
                        productCodeToParse = productCodeToParse + productCode +",";
                        pendingQuantityToParse = pendingQuantityToParse + pendingSkuMap.get(productCode) + ",";
                }
                productCodeToParse = productCodeToParse.substring(0,productCodeToParse.length()-1);
                pendingQuantityToParse = pendingQuantityToParse.substring(0,pendingQuantityToParse.length()-1);
                
                productCodeToParse= URLEncoder.encode(productCodeToParse.toString(),"UTF-8"); 
                pendingQuantityToParse = URLEncoder.encode(pendingQuantityToParse.toString(),"UTF-8"); 
                
                get = new HttpGet("http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/pendingOrders/PFF/fetch?statusCode=PFF&packCategory=ALL&productCode="+productCodeToParse+"&maxPackagesToFetch="+pendingQuantityToParse+"&oneshipCenter=");
                for(String key:headers.keySet())
                        get.addHeader(key, headers.get(key));
                cookies = sdSessionCookie.getCookies();
                cookieObject = new JSONObject(cookies);
                get.addHeader("Cookie","AWSELB="+cookieObject.get("AWSELB")+";JSESSIONID="+cookieObject.get("JSESSIONID")+";");
                        
                response = null;
                
                try {
                        response = client.execute(get);
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                
                line = rd.readLine();
                String shipmentIdsToParse = "";
                JSONArray jsonArr = new JSONArray(line);
                for(int i=0; i<jsonArr.length(); i++){
                        JSONArray jsonSubArr = jsonArr.getJSONArray(i);
                        SnapdealOrderUnit snapdealOrderUnit = (SnapdealOrderUnit)gson.fromJson(jsonSubArr.get(0).toString(),SnapdealOrderUnit.class);
                        snapdealOrderUnitsList.add(snapdealOrderUnit);
                }
                
                for(SnapdealOrderUnit orderUnit : snapdealOrderUnitsList){
                        shipmentIdsToParse = shipmentIdsToParse + orderUnit.getSiId() + ",";
                        snapdealOrderUnitListMap.put(orderUnit.getSlpCode()+orderUnit.getSuborderCode(), orderUnit);
                }
                
                get = new HttpGet("http://shipping.snapdeal.com/vendor/ONESHIP/product-shipment/invoicedetails/VENDOR_READY?selectedShipments="+shipmentIdsToParse);
                for(String key:headers.keySet())
                        get.addHeader(key, headers.get(key));
                cookies = sdSessionCookie.getCookies();
                cookieObject = new JSONObject(cookies);
                get.addHeader("Cookie","AWSELB="+cookieObject.get("AWSELB")+";JSESSIONID="+cookieObject.get("JSESSIONID")+";");
                
                response = null;
                
                try {
                        response = client.execute(get);
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                
                CSVReader csvOrdersReader = new CSVReader(rd);
                String[] values;
                
                int i=1;

                CSVWriter writer = new CSVWriter(new FileWriter("/tmp/SnapdealOrders-"+System.currentTimeMillis()+".csv", true));
                while ((values = csvOrdersReader.readNext()) != null) {
                        writer.writeNext(values);
                        if(i==1){
                                if(values[3].equalsIgnoreCase("Reference Code") && values[4].equalsIgnoreCase("Suborder Id") 
                                                && values[5].equalsIgnoreCase("SKU Code") && values[9].equalsIgnoreCase("Customer Name")
                                                && values[13].equalsIgnoreCase("PIN Code") && values[14].equalsIgnoreCase("Selling Price Per Item")){
                                        System.out.println("Format Ok");
                                }
                                i++;
                                continue;
                        }
                        SnapdealOrderUnit orderUnit = snapdealOrderUnitListMap.get(values[3]+values[4]);
                        orderUnit.setCustomerName(values[9]);
                        orderUnit.setShippingPincode(values[13]);
                        if(!orderUnit.getSkuCode().equalsIgnoreCase(values[5])){
                                orderUnit.setSkuCode(values[5]);
                        }
                        if(orderUnit.getPrice()!=Integer.parseInt(values[14])){
                                orderUnit.setPrice(Integer.parseInt(values[14]));
                        }
                        snapdealOrderUnitListMap.put(values[3]+values[4], orderUnit);
                        i++;
                }
                writer.close();
                
                snapdealOrderUnitsList.removeAll(snapdealOrderUnitsList);
                snapdealOrderUnitsList.addAll(snapdealOrderUnitListMap.values());
                
                for(SnapdealOrderUnit orderUnit : snapdealOrderUnitsList){
                        System.out.print(orderUnit.getSuborderCode()+" "+ orderUnit.getSlpCode()+" "+orderUnit.getCustomerName() +" "+ orderUnit.getShippingPincode()+" ");
                        System.out.println(orderUnit.getOrderCreatedDateString() +" "+ new Date(orderUnit.getProductSoldDate())+" "+ orderUnit.getProductName());
                }
                processSnapdealOrders(snapdealOrderUnitsList);
        }
        public static void main(String[] args) {
                try {
                        //handleLogin();
                        fetchOrders();
                } catch (ClientProtocolException e2) {
                        System.out.println("Handle login failed");
                        e2.printStackTrace();
                } catch (IOException e2) {
                        System.out.println("Handle login failed");
                        e2.printStackTrace();
                } catch (IllegalStateException e) {
                        e.printStackTrace();
                } catch (JSONException e) {
                        e.printStackTrace();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
        
        public static void processSnapdealOrders(List<SnapdealOrderUnit> snapdealOrderUnitsList){
                SourceDetail sourceDetail = null;
                User user = null;
                TransactionClient tsc = null;
                try {
                        tsc = new TransactionClient();
                        sourceDetail = tsc.getClient().getSourceDetail(SNAPDEAL_SOURCE_ID);
                } catch (Exception e) {
                        logger.error("Unable to establish connection to the transaction service while getting Snapdeal Source Detail ", e);
                }
                try {   
                        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
                        user = userClient.getUserByEmail(sourceDetail.getEmail());
                } catch (Exception e) {
                        logger.error("Unable to establish connection to the User service ", e);
                }
                int duplicate_orders = 0;
                int new_orders = 0;
                int processed_orders = 0;
                StringBuffer sb = new StringBuffer();
                LineItem lineItem = null;
                CatalogService.Client catalogClient = null;
                SnapdealItem snapdealItem = null;
                double SellingPrice = 0;
                long sku;
                String subOrderId;
                Client transaction_client = null;
                try {
                        transaction_client = tsc.getClient();
                } catch (Exception e2) {
                        e2.printStackTrace();
                }
                
                for(SnapdealOrderUnit snapdealOrderUnit : snapdealOrderUnitsList){
                        subOrderId = snapdealOrderUnit.getSuborderCode();
                        
                        boolean flag = false;
                        try {
                                if(!transaction_client.isAlive()){
                                        transaction_client = tsc.getClient();
                                }
                        } catch (TException e1) {
                                e1.printStackTrace();
                        }
                        
                        try {
                                flag = transaction_client.snapdealOrderExists(subOrderId.trim(), snapdealOrderUnit.getSlpCode().trim());
                        } catch (TException e2) {
                                try {
                                        flag = new TransactionClient().getClient().snapdealOrderExists(subOrderId.trim(), snapdealOrderUnit.getSlpCode().trim());
                                } catch (TTransportException e) {
                                        logger.error("Problem with Transaction service " + subOrderId);
                                        e.printStackTrace();
                                        continue;
                                } catch (TException e) {
                                        logger.error("Problem with Transaction service " + subOrderId);
                                        e.printStackTrace();
                                        continue;

                                }
                        }
                        
                        if(flag) {
                                logger.error("Snapdeal suborder id exists " + subOrderId);
                                duplicate_orders++;
                                continue;
                        }
                        new_orders++;
                        
                        Transaction txn = new Transaction();
                        txn.setShoppingCartid(user.getActiveCartId());
                        txn.setCustomer_id(user.getUserId());
                        System.out.println("User Id is " + user.getUserId());
                        txn.setCreatedOn(new Date().getTime());
                        txn.setTransactionStatus(TransactionStatus.INIT);
                        txn.setStatusDescription("Order for Snapdeal ");
                        
                        List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
                        try {
                                flag = true;
                                while(flag){
                                        try{
                                                catalogClient =  new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                                                snapdealItem = catalogClient.getSnapdealItembySkuAtSnapdeal(snapdealOrderUnit.getSkuCode());
                                                flag=false;
                                        }
                                        catch (TException e) {
                                        }
                                }
                                if(snapdealItem.getItem_id()!=0){
                                        sku = snapdealItem.getItem_id();
                                }
                                else{
                                        sb.append(subOrderId +" "+"SKU not found "+"\n");
                                        continue;
                                }
                                if(snapdealItem.getExceptionPrice()!=0 && snapdealItem.getItem_id()!=0 && (snapdealOrderUnit.getPrice() <  snapdealItem.getExceptionPrice())){
                                        SellingPrice = snapdealItem.getExceptionPrice();
                                }
                                else{
                                        SellingPrice = snapdealOrderUnit.getPrice();
                                }
                                try{
                                        lineItem = createLineItem(sku,SellingPrice);
                                }
                                catch (TException e) {
                                        logger.error("Unable to create order for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
                                        e.printStackTrace();
                                        sb.append(snapdealOrderUnit.getSuborderCode() + " " + "Exception while creating lineitem" + "\n");
                                        continue;
                                }
                                if(lineItem == null){
                                        sb.append(snapdealOrderUnit.getSuborderCode() +" "+"SKU not found "+"\n");
                                        continue;
                                }
                                lineItem.setExtra_info("SubOrderId = " + snapdealOrderUnit.getSuborderCode() + " ReferenceCode = " + snapdealOrderUnit.getSlpCode());
                        } catch (CatalogServiceException e) {
                                logger.error("Unable to create order for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
                                e.printStackTrace();
                                sb.append(snapdealOrderUnit.getSuborderCode() + " " + "Problem with catalog service" + "\n");
                                continue;
                        }
                        
                        in.shop2020.model.v1.order.Order t_order = new in.shop2020.model.v1.order.Order();
                        t_order.setCustomer_id(user.getUserId());
                        t_order.setCustomer_email(sourceDetail.getEmail());
                        t_order.setCustomer_name(snapdealOrderUnit.getCustomerName());
                        t_order.setCustomer_address1("");
                        t_order.setCustomer_address2("");
                        t_order.setCustomer_city(snapdealOrderUnit.getShippingCity());
                        t_order.setCustomer_mobilenumber("+91-9999999999");
                        t_order.setCustomer_state(snapdealOrderUnit.getShippingState());
                        t_order.setCustomer_pincode(snapdealOrderUnit.getShippingPincode());
                        t_order.setTotal_amount(SellingPrice);            
                        t_order.setTotal_weight(lineItem.getTotal_weight());
                        t_order.setLineitems(Collections.singletonList(lineItem));            
                        t_order.setStatus(OrderStatus.PAYMENT_PENDING);
                        t_order.setStatusDescription("Payment Pending");
                        t_order.setCreated_timestamp(new Date().getTime());
                        t_order.setOrderType(OrderType.B2C);
                        t_order.setCod(false);
                        System.out.println("t order created");
                        Date snapdealTxnDate = new Date(snapdealOrderUnit.getProductSoldDate());
                        
                        try {
                                Date shipDate = new Date(snapdealTxnDate.getTime()+172800000l);
                                Calendar time = Calendar.getInstance();
                                t_order.setPromised_shipping_time(shipDate.getTime());
                                t_order.setExpected_shipping_time(shipDate.getTime());
                                time.add(Calendar.DAY_OF_MONTH, 4);
                                t_order.setPromised_delivery_time(time.getTimeInMillis());
                                t_order.setExpected_delivery_time(time.getTimeInMillis());
                                System.out.println("Dates set in transaction");
                        } catch(Exception e) {  
                                logger.error("Error in updating Shipping or Delivery Time for suborderid  " + snapdealOrderUnit.getSuborderCode());
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not update delivery time" + " " + "\n");
                                continue;
                        }
                        InventoryService.Client inventoryClient = null;
                        Warehouse fulfillmentWarehouse= null;
                        try {
                                inventoryClient = new InventoryClient().getClient();
                                if(snapdealItem.getItem_id()!=0 && snapdealItem.getWarehouseId()!=0) {
                                        fulfillmentWarehouse = inventoryClient.getWarehouse(snapdealItem.getWarehouseId());
                                } else {
                                        List<Long> itemAvailability = inventoryClient.getItemAvailabilityAtLocation(sku, 1, -1);
                                        fulfillmentWarehouse = inventoryClient.getWarehouse(itemAvailability.get(0));
                                        if(fulfillmentWarehouse.getStateId()!=0){
                                                fulfillmentWarehouse = inventoryClient.getWarehouse(7);
                                        }
                                }
                                t_order.setFulfilmentWarehouseId(fulfillmentWarehouse.getId());
                                long billingWarehouseId = 0;
                                if(fulfillmentWarehouse.getBillingWarehouseId()== 0) {
                                        inventoryClient = new InventoryClient().getClient();
                                        List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, fulfillmentWarehouse.getVendor().getId(), 0, 0);
                                        for(Warehouse warehouse : warehouses) {
                                                if(warehouse.getBillingWarehouseId()!=0) {
                                                        billingWarehouseId = warehouse.getBillingWarehouseId();
                                                        break;
                                                }
                                        }
                                }else {
                                        billingWarehouseId = fulfillmentWarehouse.getBillingWarehouseId();
                                }

                                //logger.info("Billing warehouse id for suborderid  " + snapdealOrderUnit.getSuborderCode() + " is " + fulfillmentWarehouse.getBillingWarehouseId());
                                t_order.setWarehouse_id(billingWarehouseId);
                                VendorItemPricing vendorItemPricing = new VendorItemPricing();
                                if(fulfillmentWarehouse.getId()==7) {
                                        Item item = new CatalogClient().getClient().getItem(lineItem.getItem_id());
                                        vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), item.getPreferredVendor());
                                } else {
                                        vendorItemPricing = inventoryClient.getItemPricing(lineItem.getItem_id(), fulfillmentWarehouse.getVendor().getId());
                                }

                                t_order.getLineitems().get(0).setTransfer_price(vendorItemPricing.getTransferPrice());
                                t_order.getLineitems().get(0).setNlc(vendorItemPricing.getNlc());
                        } catch (InventoryServiceException e) {
                                logger.error("Error connecting inventory service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Inventory Service Exception" + " " + "\n");
                                continue;
                        } catch (TTransportException e) {
                                logger.error("Transport Exception with Inventory Service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Transport Exception with Inventory Service" + " " + "\n");
                                continue;
                        } catch (TException e) {
                                logger.error("Exception with Inventory Service for suborderid  " + snapdealOrderUnit.getSuborderCode() , e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Exception in Inventory Service" + " " + "\n");
                                continue;
                        } catch (CatalogServiceException e) {
                                logger.error("Exception with Catalog Service for suborderid  " + snapdealOrderUnit.getSuborderCode() + " while getting item " + lineItem.getItem_id(), e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Exception in Catalog Service" + " " + "\n");
                                continue;
                        }
                        t_order.setLogistics_provider_id(44);
                        t_order.setTotal_amount(SellingPrice);
                        t_order.setOrderType(OrderType.B2C);
                        t_order.setSource(SNAPDEAL_SOURCE_ID);
                        t_order.setOrderType(OrderType.B2C);
                        orderlist.add(t_order);
                        txn.setOrders(orderlist);
                        String referenceCode = snapdealOrderUnit.getSlpCode();
                        String productName = snapdealOrderUnit.getProductName();
                        try {
                                transactionId =  String.valueOf(transaction_client.createTransaction(txn));
                        } catch (TransactionServiceException e) {
                                logger.error(snapdealOrderUnit.getSuborderCode() + " Could not create transaction " , e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create transaction" +"\n");
                                continue;
                        } catch (TException e) {
                                logger.error("Problem with transaction service while creating transaction", e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Transaction Service Exception could not create transaction" +"\n");
                                continue;
                        }
                        try{
                                paymentId = createPayment(user, (new Long(subOrderId)).toString(),lineItem.getTotal_price());
                        }
                        catch (NumberFormatException e) {
                                logger.error("Could not create payment",e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment");
                                e.printStackTrace();
                                continue;
                        } catch (PaymentException e) {
                                logger.error("Could not create payment payment exception",e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment Payment exception");
                                e.printStackTrace();
                                continue;
                        } catch (TException e) {
                                logger.error("Could not create payment thrift exception",e);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create payment Thrift exception");
                                e.printStackTrace();
                                continue;
                        }
                        Transaction transaction = null;
                        try {
                                transaction = transaction_client.getTransaction(Long.parseLong(transactionId));
                        } catch (NumberFormatException e) {
                                logger.error("Problem parsing transaction id " + transactionId);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Problem parsing transaction id "+ transactionId +"\n");
                                e.printStackTrace();
                                continue;
                        } catch (TransactionServiceException e) {
                                logger.error("Problem getting transaction from service transaction id " + transactionId);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Problem getting transaction id "+ transactionId +"\n");
                                e.printStackTrace();
                                continue;
                        } catch (TException e) {
                                logger.error("Problem with transaction service while getting transaction id " + transactionId);
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
                                e.printStackTrace();
                                continue;
                        }
                        in.shop2020.model.v1.order.Order snapdealorder = transaction.getOrders().get(0);
                        try {
                                inventoryClient.reserveItemInWarehouse(lineItem.getItem_id(), fulfillmentWarehouse.getId(), 1, 
                                                snapdealorder.getId(), snapdealorder.getCreated_timestamp(), snapdealorder.getPromised_shipping_time(), snapdealorder.getLineitems().get(0).getQuantity());
                        } catch (InventoryServiceException e1) {
                                logger.error("Problem while reserving item in inventory service" + snapdealorder.getId());
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not reserve inventory for sku "+ sku +"\n");
                                continue;
                        } catch (TException e1) {
                                logger.error("Problem with inventory service" + snapdealorder.getId());
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
                                continue;
                        }
                        SnapdealOrder snapdealOrder = new SnapdealOrder();
                        snapdealOrder.setOrderId(snapdealorder.getId());
                        System.out.println("Sub Order Id... "+snapdealOrderUnit.getSuborderCode());
                        snapdealOrder.setSubOrderId(snapdealOrderUnit.getSuborderCode());
                        snapdealOrder.setReferenceCode(referenceCode);
                        snapdealOrder.setProductName(productName);
                        snapdealOrder.setSnapdealTxnDate(snapdealTxnDate.getTime());
                        snapdealOrder.setListingPrice(snapdealOrderUnit.getPrice());
                        snapdealOrder.setMaxNlc(snapdealItem.getMaxNlc());
                        try {
                                transaction_client.createSnapdealOrder(snapdealOrder);
                                new PaymentClient().getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.SUCCESS, null, null);

                        } catch (TException e) {
                                logger.error("Could not create Snapdeal Order");
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not create snapdeal order"+"\n");
                        } catch (PaymentException e) {
                                logger.error("Could not update payment for Snapdeal Order");
                                sb.append(snapdealOrderUnit.getSuborderCode() + " Could not update payment for snapdeal order"+"\n");
                        }
                        processed_orders++;
                }
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                Calendar cal=GregorianCalendar.getInstance();
                String emailFromAddress = "adwords@shop2020.in";
                String password = "adwords_shop2020";
                GmailUtils mailer = new GmailUtils();
                //String sendTo[] = new String[]{"manish.sharma@shop2020.in"};
                String sendTo[] = new String[]{ "sandeep.sachdeva@shop2020.in", "manish.sharma@shop2020.in", "rajneesh.arora@shop2020.in",
                                "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
                                "yukti.jain@shop2020.in","yatin.singh@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","anikendra.das@shop2020.in"};
                try {
                        if(new_orders==processed_orders && new_orders > 0){
                                String emailSubjectTxt = "Snapdeal Orders Created Successfully "+sdf.format(cal.getTime());
                                String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
                                "Orders Already Existing : " + duplicate_orders + "\n" +
                                "Processed Orders : " + processed_orders + "\n" +
                                "Failed Orders : " + (new_orders - processed_orders);
                                mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                        }
                        else if(new_orders > 0){
                                String emailSubjectTxt = "Snapdeal Orders Failed while creation "+sdf.format(cal.getTime());
                                String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
                                "Orders Already Existing : " + duplicate_orders + "\n" +
                                "Processed Orders : " + processed_orders + "\n" +
                                "Failed Orders : " + (new_orders - processed_orders) + "\n"+ "\n" +
                                sb.toString();
                                mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                        }
                        else{
                                String emailSubjectTxt = "No new Snapdeal Orders " + sdf.format(cal.getTime());
                                String text = "Total Orders Received : " + ( new_orders + duplicate_orders ) + "\n" + 
                                "Orders Already Existing : " + duplicate_orders + "\n" +
                                "Processed Orders : " + processed_orders + "\n" +
                                "Failed Orders : " + (new_orders - processed_orders) + "\n"+ "\n" +
                                sb.toString();
                                mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                        }
                }
                catch (Exception e) {
                        e.printStackTrace();
                }
        }
        
        public static long createPayment(User user, String subOrderId, double amount) throws NumberFormatException, PaymentException, TException {
                in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
                return client.createPayment(user.getUserId(), amount, SNAPDEAL_GATEWAY_ID, Long.valueOf(transactionId), false);

        }   

        public static LineItem createLineItem(long itemId, double amount) throws CatalogServiceException, TException {
                LineItem lineItem = new LineItem();
                CatalogService.Client catalogClient = new CatalogClient().getClient();
                Item item = catalogClient.getItem(itemId);
                if(item.getId()==0){
                        //in case item id is incorrect..
                        return null;
                }

                lineItem.setProductGroup(item.getProductGroup());
                lineItem.setBrand(item.getBrand());
                lineItem.setModel_number(item.getModelNumber());
                lineItem.setModel_name(item.getModelName());
                lineItem.setExtra_info(item.getFeatureDescription());
                lineItem.setQuantity(1);
                lineItem.setItem_id(item.getId());
                lineItem.setUnit_weight(item.getWeight());
                lineItem.setTotal_weight(item.getWeight());
                lineItem.setUnit_price(amount);
                lineItem.setTotal_price(amount);

                if (item.getColor() == null || "NA".equals(item.getColor())) {
                        lineItem.setColor("");
                } else {
                        lineItem.setColor(item.getColor());
                }
                return lineItem;
        }
}