Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import in.shop2020.model.v1.catalog.Amazonlisted;
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.AmazonFbaSalesSnapshot;
import in.shop2020.model.v1.order.FlipkartOrder;
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.SourceDetail;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.user.User;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.support.utils.ReportsUtils;
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.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
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 javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.bytecode.opencsv.CSVReader;

import com.opensymphony.xwork2.ValidationAwareSupport;

public class FlipkartDashboardController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{
        private static Logger logger = LoggerFactory.getLogger(FlipkartDashboardController.class);
        private static final int FLIPKART_SOURCE_ID = 8;
        private static final int FLIPKART_GATEWAY_ID = 17;
        private static final int FLIPKART_LOGISTICS_ID = 19;
        private HttpServletRequest request;
        private HttpServletResponse response;
        private HttpSession session;
        private ServletContext context;
        private String url;
        private File file;
        private String errMsg;
        private String id;
        private long paymentId;
        private static String transactionId;
        public String uploadorders(){
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
                        return "authfail";
                }
                return "flipkart-upload-orders";
        }
        public String show() {
                logger.info("Before fetching role");
                logger.info(request.getSession().toString());
                logger.info(ReportsUtils.ROLE);
                logger.info(session.getAttribute(ReportsUtils.ROLE).toString());
                logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1]);
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
                        logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1]);
                        return "authfail";
                }

                if (StringUtils.equals(id, "flipkart-options")){
                        return "flipkart-options";
                }

                return "id";
        }
        public void uploadOrdersFile() throws IOException, CatalogServiceException, TException{
                File fileToCreate = new File("/tmp/", "Flipkart-Orders.csv");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                CSVReader orderfilereader = null;
                replacecommas(fileToCreate);
                try {
                        orderfilereader = new CSVReader(new FileReader("/tmp/formatted.csv"),'$');
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                logger.info("Before Processing orders ");
                String [] nextLine;
                StringBuffer sb = new StringBuffer();
                int orders_processed = 0;
                String order_string = "";
                try {
                        User user = null;
                        TransactionClient tsc = null;
                        SourceDetail sourceDetail = null;
                        logger.info("Before Fetching sourcedetail");
                        try {
                                tsc = new TransactionClient();
                                sourceDetail = tsc.getClient().getSourceDetail(FLIPKART_SOURCE_ID);
                                logger.info("Flipkart sourcedetail " + sourceDetail.getEmail() + " " + sourceDetail.getName());
                        } catch (Exception e) {
                                logger.error("Unable to establish connection to the transaction service while getting Flipkart Source Detail ", e);
                        }
                        try {   
                                in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
                                logger.info("Before Fetching User by Email");
                                user = userClient.getUserByEmail(sourceDetail.getEmail());
                                logger.info("User is " + user.getEmail());
                        } catch (Exception e) {
                                logger.error("Unable to establish connection to the User service ", e);
                        }
                        logger.info("Before iterating orders in file");
                        while ((nextLine = orderfilereader.readNext()) != null && nextLine.length!=0) {
                                logger.info("Order file entry  " + nextLine + " Length " + nextLine.length);
                                String orderId,subOrderId,create_date;
                                long sku;
                                logger.info("Processing order " + nextLine[3]+ " " + nextLine[4]);
                                if(nextLine[3].length()==0 || nextLine[4].length()==0 ){
                                        sb.append(" Could not parse order id " + nextLine[3]+ " " + nextLine[4] + "\n");
                                        logger.info("Processing order " + nextLine[3]+ " " + nextLine[4]);
                                        continue;
                                }
                                else{
                                        orderId = nextLine[3];
                                        subOrderId = nextLine[4];
                                }

                                if(nextLine[0].length()!=0){
                                        create_date = nextLine[0];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
                                        logger.info(orderId+" "+subOrderId + " Could not parse order date");
                                        continue;
                                }
                                if(nextLine[5].length()==0){
                                        sb.append(orderId+" "+subOrderId + " Could not parse sku" +"\n");
                                        logger.info(orderId+" "+subOrderId + " Could not parse sku");
                                        continue;
                                }
                                else{
                                        sku =  Long.parseLong(nextLine[5]);
                                        logger.info(orderId+" "+subOrderId + " Processing  sku " + sku);
                                }
                                if(nextLine[6].length()!=0 && nextLine[6].equalsIgnoreCase("Approved")){
                                        String status = nextLine[6];    
                                }
                                else{
                                        if(nextLine[6].length()==0){
                                                sb.append(orderId+" "+subOrderId + " Could not parse status" +"\n");
                                                logger.info(orderId+" "+subOrderId + " Could not parse status" +"\n");
                                        }
                                        else{
                                                sb.append(orderId+" "+subOrderId + " Order not Approved" +"\n");
                                                logger.info(orderId+" "+subOrderId + " Order not Approved" +"\n");
                                        }
                                        continue;
                                }
                                double unitSellingPrice,shippingPrice,octroiFee,emiFee;
                                if(nextLine[7].length()!=0 ){
                                        if(Double.parseDouble(nextLine[7]) > 0){
                                                unitSellingPrice =  Double.parseDouble(nextLine[7]);
                                        }
                                        else{
                                                sb.append(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
                                                logger.info(orderId+" "+subOrderId + " Unit Price set to 0 " +"\n");
                                                continue;
                                        }
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Unit Price not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Unit Price not set " +"\n");
                                        continue;
                                }
                                if(nextLine[8].length()!=0){
                                        shippingPrice  =  Double.parseDouble(nextLine[8]);
                                        if(shippingPrice!=0){
                                                sb.append(orderId+" "+subOrderId + " Shipping Fee :"+ shippingPrice +"\n");
                                                logger.info(orderId+" "+subOrderId + " Shipping Fee :"+ shippingPrice +"\n");
                                        }
                                }
                                else{
                                        shippingPrice=0;
                                }
                                if(nextLine[9].length()!=0){
                                        octroiFee =  Double.parseDouble(nextLine[9]);
                                        if(octroiFee >0){
                                                sb.append(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
                                                logger.info(orderId+" "+subOrderId + " OctroiFee :"+ octroiFee +"\n");
                                        }
                                }
                                else{
                                        octroiFee=0;
                                }
                                if(nextLine[10].length()!=0){
                                        emiFee =  Double.parseDouble(nextLine[10]);
                                        if(emiFee >0){
                                                sb.append(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
                                                logger.info(orderId+" "+subOrderId + " EMI :"+ emiFee +"\n");
                                        }
                                }
                                else{
                                        emiFee = 0;
                                }
                                int quantity;
                                if(nextLine[11].length()!=0){
                                        quantity = Integer.parseInt(nextLine[11]);
                                        if(quantity > 1){
                                                sb.append(orderId+" "+subOrderId + " Quantity > 1 " + quantity +"\n");
                                                logger.info(orderId+" "+subOrderId + " Quantity > 1 " + quantity +"\n");
                                        }
                                        else{
                                                if(quantity==0){
                                                        sb.append(orderId+" "+subOrderId + " Quantity not set " + quantity +"\n");
                                                        logger.info(orderId+" "+subOrderId + " Quantity not set " + quantity +"\n");
                                                        continue;
                                                }
                                        }
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Quantity not set " + "\n");
                                        logger.info(orderId+" "+subOrderId + " Quantity not set " + "\n");
                                        continue;
                                }
                                double totalsellingPrice; 
                                if(nextLine[12].length()!=0){
                                        totalsellingPrice= Double.parseDouble(nextLine[12]);
                                        if(totalsellingPrice==0){
                                                sb.append(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
                                                logger.info(orderId+" "+subOrderId + " Total Selling Price set to 0 " +"\n");
                                                continue;
                                        }
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Total Selling Price not set " +"\n");
                                        continue;
                                }

                                String shipToName,addressLine1,addressLine2,city,state,pincode,buyerName="unknown";
                                if(nextLine[17].length()>0){
                                        buyerName = nextLine[17];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Buyer Name not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Buyer Name not set " +"\n");
                                }
                                if(nextLine[18].length()>0){
                                        shipToName = nextLine[18];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Ship to Name not set " +"\n");
                                        continue;
                                }
                                if(buyerName.contains("unknown")){
                                        buyerName = shipToName;
                                }
                                if(nextLine[19].length()>0){
                                        addressLine1 = nextLine[19];
                                }
                                else{
                                        addressLine1 ="";
                                }
                                if(nextLine[20].length()>0){
                                        addressLine2 = nextLine[20];
                                }
                                else{
                                        addressLine2 ="";
                                }
                                if(nextLine[21].length()>0){
                                        city = nextLine[21];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " City not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " City not set " +"\n");
                                        continue;
                                }
                                if(nextLine[22].length()>0){
                                        state = nextLine[22];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " State not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " State not set " +"\n");
                                        continue;
                                }
                                if(nextLine[23].length()>0){
                                        pincode = nextLine[23];
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Pincode not set " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Pincode not set " +"\n");
                                        continue;
                                }
                                int sla; 
                                if(nextLine[23].length()>0){
                                        sla = Integer.parseInt(nextLine[24]);
                                }
                                else{
                                        sb.append(orderId+" "+subOrderId + " Ship to date not available " +"\n");
                                        logger.info(orderId+" "+subOrderId + " Ship to date not available " +"\n");
                                        continue;
                                }
                                //String shipByDate = nextLine[26];
                                Client transaction_client = null;
                                try {
                                        transaction_client = new TransactionClient().getClient();
                                        if(transaction_client.flipkartOrderExists(orderId,subOrderId)) {
                                                logger.error("Flipkart order exists " + "id : " + orderId + " suborder id : " + subOrderId);
                                                sb.append("Flipkart order exists " + orderId+" "+subOrderId+"\n");
                                                continue;
                                        }

                                } catch (TTransportException e1) {
                                        logger.error("Problem with Transaction service " , e1);
                                        e1.printStackTrace();
                                } catch (TException e) {
                                        logger.error("Problem.. thrift exception with Transaction service " , e);
                                        e.printStackTrace();
                                }
                                SimpleDateFormat istFormatter = new SimpleDateFormat("MMM dd, yyyy");
                                Date flipkartTxnDate = null;
                                try {
                                        create_date = create_date.replaceAll("\"","");
                                        flipkartTxnDate = istFormatter.parse(create_date);
                                } catch (ParseException e) {
                                        logger.error(orderId+" "+subOrderId + " Could not parse flipkart order date from file " , e);
                                        sb.append(orderId+" "+subOrderId + " Could not parse order date" +"\n");
                                        continue;
                                }
                                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 flipkart ");
                                List<in.shop2020.model.v1.order.Order> orderlist = new ArrayList<in.shop2020.model.v1.order.Order>();
                                double total_price=0;
                                InventoryService.Client inventoryClient = null;
                                Warehouse fulfillmentWarehouse= null;
                                boolean exit = false;
                                LineItem lineItem = null;
                                lineItem = createLineItem(sku,unitSellingPrice,quantity);
                                logger.info(orderId+" "+subOrderId + "sku and Price " + sku + " " + unitSellingPrice);
                                lineItem.setExtra_info("flipkartOrderId = " + orderId + " flipkartsubOrderId = " + subOrderId);
                                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(shipToName);
                                addressLine1 = addressLine1.replaceAll("\"",""); 
                                t_order.setCustomer_address1(addressLine1);
                                addressLine2 = addressLine2.replaceAll("\"","");
                                t_order.setCustomer_address2(addressLine2);
                                t_order.setCustomer_mobilenumber("+91-9999999999");
                                t_order.setCustomer_city(city);
                                t_order.setCustomer_state(state);
                                t_order.setCustomer_pincode(pincode);
                                t_order.setTotal_amount(unitSellingPrice*quantity);            
                                t_order.setTotal_weight(lineItem.getTotal_weight());
                                t_order.setLineitems(Collections.singletonList(lineItem));            
                                t_order.setStatus(OrderStatus.PAYMENT_PENDING);
                                t_order.setStatusDescription("In Process");
                                t_order.setCreated_timestamp(new Date().getTime());
                                t_order.setOrderType(OrderType.B2C);
                                t_order.setCod(false);
                                try {
                                        Date shipDate = new Date();
                                        shipDate.setTime( flipkartTxnDate.getTime() + sla*24*60*60*1000);
                                        Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(shipDate);
                                        if(calendar.get(Calendar.DAY_OF_WEEK)!=1){
                                                t_order.setPromised_shipping_time(shipDate.getTime());
                                                t_order.setExpected_shipping_time(shipDate.getTime());
                                        }
                                        else{
                                                t_order.setPromised_shipping_time(shipDate.getTime()+24*60*60*1000);
                                                t_order.setExpected_shipping_time(shipDate.getTime()+24*60*60*1000);
                                        }
                                        calendar = Calendar.getInstance();
                                        calendar.add(Calendar.DAY_OF_MONTH, 4);
                                        t_order.setPromised_delivery_time(calendar.getTimeInMillis());
                                        t_order.setExpected_delivery_time(calendar.getTimeInMillis());
                                } catch(Exception e) {  
                                        logger.error("Error in updating Shipping or Delivery Time for suborderid  " + subOrderId);
                                        sb.append(orderId + " "+ subOrderId  + " Could not update delivery time" + " " + "\n");
                                        exit = true;
                                        continue;
                                }
                                SnapdealItem snapdealItem = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient().getSnapdealItem(sku);
                                inventoryClient = new InventoryClient().getClient();
                                try {
                                        logger.info("Snapdeal Item id is " + snapdealItem.getItem_id());
                                        if(snapdealItem.getItem_id()!=0 && snapdealItem.getWarehouseId()!=0) {
                                                logger.info("SnapdealItem Warehouse Id " + snapdealItem.getWarehouseId());
                                                fulfillmentWarehouse = inventoryClient.getWarehouse(snapdealItem.getWarehouseId());
                                                logger.info("fulfillmentWarehouse is " + fulfillmentWarehouse.getId() + " " + fulfillmentWarehouse.getDisplayName() );

                                        } 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  " + order.getSuborderId() + " 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  " + orderId + " " + subOrderId , e);
                                        sb.append(orderId + " " + subOrderId+ " Inventory Service Exception" + " " + "\n");
                                        exit = true;
                                        continue;
                                } catch (TTransportException e) {
                                        logger.error("Transport Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
                                        sb.append(orderId + " " + subOrderId + " Transport Exception with Inventory Service" + " " + "\n");
                                        exit = true;
                                        continue;
                                } catch (TException e) {
                                        logger.error("Exception with Inventory Service for suborderid  " + orderId + " " + subOrderId , e);
                                        sb.append(orderId + " " + subOrderId + " Exception in Inventory Service" + " " + "\n");
                                        exit = true;
                                        continue;
                                } catch (CatalogServiceException e) {
                                        logger.error("Exception with Catalog Service for   " + orderId + " " + subOrderId + " while getting item " + lineItem.getItem_id(), e);
                                        sb.append(orderId + " " + subOrderId + " Exception in Catalog Service" + " " + "\n");
                                        exit = true;
                                        continue;
                                }
                                t_order.setLogistics_provider_id(FLIPKART_LOGISTICS_ID);
                                t_order.setAirwaybill_no("");
                                t_order.setTracking_id("");
                                t_order.setOrderType(OrderType.B2C);
                                t_order.setSource(FLIPKART_SOURCE_ID);
                                t_order.setOrderType(OrderType.B2C);
                                total_price = unitSellingPrice*quantity;
                                orderlist.add(t_order);
                                if(exit){
                                        continue;
                                }
                                txn.setOrders(orderlist);
                                try {
                                        transactionId =  String.valueOf(transaction_client.createTransaction(txn));
                                        logger.info("Transaction id is : " + transactionId);
                                } catch (TransactionServiceException e) {
                                        logger.error(orderId+" "+subOrderId + " Could not create transaction " , e);
                                        sb.append(orderId+" "+subOrderId + " Could not create transaction" +"\n");
                                        continue;
                                } catch (TException e) {
                                        sb.append(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
                                        logger.info(orderId+" "+subOrderId + " Transaction Service Exception could not create transaction" +"\n");
                                        continue;
                                }
                                try{
                                        logger.info("Creating payment for suborder id " + subOrderId);
                                        paymentId = createPayment(user,subOrderId,total_price);
                                }
                                catch (NumberFormatException e) {
                                        logger.error("Could not create payment",e);
                                        sb.append(orderId+" "+subOrderId + " Could not create payment");
                                        e.printStackTrace();
                                        continue;
                                } catch (PaymentException e) {
                                        logger.error("Could not create payment payment exception",e);
                                        sb.append(orderId+" "+subOrderId + " Could not create payment Payment exception");
                                        e.printStackTrace();
                                        continue;
                                } catch (TException e) {
                                        logger.error("Could not create payment thrift exception",e);
                                        sb.append(orderId+" "+subOrderId + " 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(orderId+" "+subOrderId  + " Problem parsing transaction id "+ transactionId +"\n");
                                        e.printStackTrace();
                                        continue;
                                } catch (TransactionServiceException e) {
                                        logger.error("Problem getting transaction from service transaction id " + transactionId);
                                        sb.append(orderId+" "+subOrderId  + " 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(orderId+" "+subOrderId + " Problem with transaction service while getting transaction id "+ transactionId +"\n");
                                        e.printStackTrace();
                                        continue;
                                }
                                List<in.shop2020.model.v1.order.Order> flipkartorders = transaction.getOrders();
                                for(in.shop2020.model.v1.order.Order flipkartorder:flipkartorders){
                                        try {
                                                List<in.shop2020.model.v1.order.Attribute> attributeList = new ArrayList<in.shop2020.model.v1.order.Attribute>();
                                                inventoryClient.reserveItemInWarehouse(flipkartorder.getLineitems().get(0).getItem_id(), fulfillmentWarehouse.getId(), 1, 
                                                                flipkartorder.getId(), flipkartorder.getCreated_timestamp(), flipkartorder.getPromised_shipping_time(), flipkartorder.getLineitems().get(0).getQuantity());
                                                FlipkartOrder flipkartOrder = new FlipkartOrder();
                                                flipkartOrder.setOrderId(flipkartorder.getId());
                                                flipkartOrder.setFlipkartOrderId(orderId);
                                                flipkartOrder.setFlipkartSubOrderId(subOrderId);
                                                flipkartOrder.setFlipkartTxnDate(flipkartTxnDate.getTime());
                                                flipkartOrder.setEmiFee(emiFee);
                                                flipkartOrder.setOctroiFee(octroiFee);
                                                flipkartOrder.setShippingPrice(shippingPrice);
                                                flipkartOrder.setMaxNlc(snapdealItem.getMaxNlc());
                                                in.shop2020.model.v1.order.Attribute attribute = new in.shop2020.model.v1.order.Attribute();
                                                attribute.setName("Buyer Name");
                                                attribute.setValue(buyerName);
                                                attributeList.add(attribute);
                                                try {
                                                        transaction_client.createFlipkartOrder(flipkartOrder);
                                                        transaction_client.setOrderAttributes(flipkartOrder.getOrderId(),attributeList);
                                                        logger.info("transaction id : " + Long.valueOf(transactionId) + " Payment id : " + paymentId);
                                                        new PaymentClient().getClient().updatePaymentDetails(paymentId, null, null, null, null, null, null, subOrderId, null, PaymentStatus.SUCCESS, null, null);
                                                        orders_processed++;
                                                } catch (TException e) {
                                                        logger.error("Could not create flipkart order");
                                                        sb.append(orderId+" "+subOrderId + " Could not create flipkart order"+"\n");
                                                        continue;
                                                }catch (PaymentException e) {
                                                        logger.error("Could not update flipkart order payment ",e);
                                                        sb.append(orderId+" "+subOrderId + " Could not update flipkart order payment"+"\n");
                                                        continue;
                                                }

                                        } catch (InventoryServiceException e1) {
                                                logger.error("Problem while reserving item in inventory service" + flipkartorder.getId());
                                                sb.append(orderId+" "+subOrderId + " Could not reserve inventory for sku "+ sku +"\n");
                                                continue;
                                        } catch (TException e1) {
                                                logger.error("Problem with inventory service" + flipkartorder.getId());
                                                sb.append(orderId+" "+subOrderId + " Problem with inventory service while reserving inventory for sku "+ sku +"\n");
                                                continue;
                                        }
                                }
                        }
                        response.setHeader("Content-Type", "text/javascript");

                        if(orders_processed==1){
                                order_string = "Order";
                        }
                        else{
                                order_string = "Orders";
                        }

                        ServletOutputStream sos;
                        try {
                                sos = response.getOutputStream();
                                if(sb.toString().equalsIgnoreCase("")){
                                        sos.write((orders_processed + " " + order_string + " Created").toString().getBytes());
                                }
                                else{
                                        sos.write((orders_processed +" " + order_string + " Created \n"+ sb.toString()).getBytes());
                                }
                                sos.flush();
                        } catch (IOException e) {
                                System.out.println("Unable to stream the manifest file");
                        }   

                }
                catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                Calendar cal=GregorianCalendar.getInstance();
                String emailFromAddress = "build@shop2020.in";
                String password = "cafe@nes";
                GmailUtils mailer = new GmailUtils();
                //String sendTo[] = new String[]{"vikram.raghav@shop2020.in"};
                String sendTo[] = new String[]{ "rajneesh.arora@shop2020.in", "himanshu.pandey@shop2020.in",
                                "khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
                                "yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};
                try {
                        logger.info("Before Sending Emails");

                        if(sb.toString().equalsIgnoreCase("")){
                                if(orders_processed!=0){
                                        String emailSubjectTxt = orders_processed + " Flipkart " + order_string + " created manually "+sdf.format(cal.getTime());
                                        mailer.sendSSLMessage(sendTo, emailSubjectTxt,"Orders Created Successfully (No Alerts)", emailFromAddress, password, new ArrayList<File>());
                                        logger.info("Sending Email Flipkart Orders Created Successfully (No Alerts)");
                                }
                                else{
                                        String emailSubjectTxt = "No new orders created manually "+sdf.format(cal.getTime());
                                        mailer.sendSSLMessage(sendTo, emailSubjectTxt,"No new orders created manually", emailFromAddress, password, new ArrayList<File>());
                                        logger.info("Sending Email Flipkart Orders Created Successfully (No Alerts)");
                                }
                        }
                        else{
                                if(orders_processed!=0){
                                        String emailSubjectTxt = orders_processed + " Flipkart " + order_string + " created manually (Check Alerts) "+sdf.format(cal.getTime());
                                        mailer.sendSSLMessage(sendTo, emailSubjectTxt,sb.toString(), emailFromAddress, password, new ArrayList<File>());
                                        logger.info("Sending Email Flipkart Orders Created Successfully (Check Alerts)");
                                }
                                else{
                                        String emailSubjectTxt = "No new Flipkart orders created manually "+sdf.format(cal.getTime());
                                        mailer.sendSSLMessage(sendTo, emailSubjectTxt,sb.toString(), emailFromAddress, password, new ArrayList<File>());
                                        logger.info("Sending Email Flipkart Orders Created Successfully (Check Alerts)");
                                }
                        }
                }
                catch (Exception e) {
                        e.printStackTrace();
                        logger.error("Exception ",e);
                }
        }

        public static Logger getLogger() {
                return logger;
        }
        public static void setLogger(Logger logger) {
                FlipkartDashboardController.logger = logger;
        }
        public HttpServletRequest getRequest() {
                return request;
        }
        public void setRequest(HttpServletRequest request) {
                this.request = request;
        }
        public HttpServletResponse getResponse() {
                return response;
        }
        public void setResponse(HttpServletResponse response) {
                this.response = response;
        }
        public HttpSession getSession() {
                return session;
        }
        public void setSession(HttpSession session) {
                this.session = session;
        }
        public ServletContext getContext() {
                return context;
        }
        public void setContext(ServletContext context) {
                this.context = context;
        }
        public String getUrl() {
                return url;
        }
        public void setUrl(String url) {
                this.url = url;
        }
        public File getFile() {
                return file;
        }
        public void setFile(File file) {
                this.file = file;
        }
        public String getErrMsg() {
                return errMsg;
        }
        public void setErrMsg(String errMsg) {
                this.errMsg = errMsg;
        }
        public String getId() {
                return id;
        }
        public void setId(String id) {
                this.id = id;
        }
        @Override
        public void setServletContext(ServletContext arg0) {
                // TODO Auto-generated method stub

        }
        @Override
        public void setServletResponse(HttpServletResponse response) {
                this.response = response;
        }
        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
                this.session = request.getSession();        

        }
        public static LineItem createLineItem(long itemId, double amount,int qty) 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(qty);
                lineItem.setItem_id(item.getId());
                lineItem.setUnit_weight(item.getWeight());
                lineItem.setTotal_weight(item.getWeight());
                lineItem.setUnit_price(amount);
                lineItem.setTotal_price(amount*qty);
                if (item.getColor() == null || "NA".equals(item.getColor())) {
                        lineItem.setColor("");
                } else {
                        lineItem.setColor(item.getColor());
                }
                return lineItem;
        }

        public static void replacecommas (File file) throws IOException {
                BufferedReader br = null;
                File tempFile = new File("/tmp/formatted.csv");
                FileWriter fw = new FileWriter(tempFile);
                String line;    
                br = new BufferedReader(new FileReader(file));
                boolean replace = false;
                char [] lineChars; 
                int counter=1;
                String completeorder = "";
                while ((line = br.readLine()) != null) {
                        if(counter!=1){
                                if(line.endsWith(",,,,,,")){
                                        completeorder = completeorder.concat(line);
                                        if(line.contains("Ordered On")){
                                                continue;
                                        }
                                        else{
                                                lineChars = completeorder.toCharArray();
                                                int count = 0;
                                                for(int i=0;i<lineChars.length;i++)  
                                                {
                                                        if(lineChars[i]=='"'){
                                                                count++;
                                                        }
                                                        if(count%2==1){
                                                                replace=false;
                                                        }
                                                        if(count%2==0){
                                                                replace=true;
                                                        }
                                                        if(replace && lineChars[i] == ','){
                                                                lineChars[i]='$';
                                                        }
                                                }
                                        }
                                        line = String.valueOf(lineChars);
                                        System.out.println(" Line and Length " + line + " " + line.length());
                                        fw.write(line+"\n");
                                        completeorder="";
                                }
                                else{
                                        line = line.replace("\n","");
                                        if(completeorder.equalsIgnoreCase("")){
                                                completeorder = line;
                                        }
                                        else{
                                                completeorder = completeorder.concat(line);;
                                        }
                                }
                        }
                        counter++;
                }               if (br != null)br.close();
                if (fw != null)fw.close();
        }               

        public static long createPayment(User user, String subOrderId, double amount) throws PaymentException, TException {
                in.shop2020.payments.PaymentService.Client client = new PaymentClient().getClient();
                logger.info("Creating payment for user id " + user.getUserId() + " Gateway id " + FLIPKART_GATEWAY_ID);
                logger.info("Long value of transaction id : " + Long.valueOf(transactionId));
                return client.createPayment(user.getUserId(), amount, FLIPKART_GATEWAY_ID, Long.valueOf(transactionId), false);
        }   


}