Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import in.shop2020.config.ConfigException;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.CatalogServiceException;
import in.shop2020.model.v1.catalog.FlipkartItem;
import in.shop2020.model.v1.catalog.FlipkartItemDetails;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.MarketplaceItems;
import in.shop2020.model.v1.catalog.MarketplacePercentage;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.InventoryType;
import in.shop2020.model.v1.inventory.ItemInventory;
import in.shop2020.model.v1.inventory.OOSStatus;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.inventory.WarehouseType;
import in.shop2020.support.utils.ReportsUtils;
import in.shop2020.support.utils.UpdateFlipkartPricing;
import in.shop2020.support.utils.UpdateSDPricingUsingPanel;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.config.ConfigClient;
import in.shop2020.utils.GmailUtils;
import javax.mail.MessagingException;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
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.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ValidationAwareSupport;

@SuppressWarnings({"unused","deprecation"})

@InterceptorRefs({
        @InterceptorRef("defaultStack"),
        @InterceptorRef("login")
})

public class FlipkartListController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;


        private static Logger logger = LoggerFactory.getLogger(FlipkartListController.class);


        private HttpServletRequest request;
        private HttpServletResponse response;
        private HttpSession session;
        private ServletContext context;
        private String url;
        private String itemId;
        private String exceptionPrice;
        private String warehouseId;
        private File file;
        private String errMsg;
        private String next;
        private String id;
        private String searchText;
        private List<FlipkartItemDetails> flipkartItems;
        private long searchCount;
        private long totalCount;
        private String sellingPrice;
        private String transferPrice;
        private String webisteMrp;
        private String webisteSellingPrice;
        private String isListedOnFlipkart;
        private String commission;
        private String serviceTax;
        private String courierCost;
        private JSONObject itemObj;
        private String isSuppressInventoryFeed;
        private String isSuppressPriceFeed;
        private String maxNlc;
        private String fkItemCode;
        private String supc;
        private String held;
        private String lastUpdatedInventoryTimestamp;
        private String lastCheckedTimestamp;
        private String otherCost;
        private String isAutoIncrement;
        private String isAutoDecrement;
        private String isManualFavourite;
        private String isAutoFavourite;
        private String currentSp;
        private String currentTp;
        private String minPosSp;
        private String minPosTp;
        private String vat;
        private String comparsionResult;
        private String maxSp;
        private String nDaySale;
        private String fkSerialNumber;
        private static String live;

        public String getFkSerialNumber() {
                return fkSerialNumber;
        }

        public void setFkSerialNumber(String fkSerialNumber) {
                this.fkSerialNumber = fkSerialNumber;
        }

        public String getnDaySale() {
                return nDaySale;
        }

        public void setnDaySale(String nDaySale) {
                this.nDaySale = nDaySale;
        }

        private String avgSale;

        public String getAvgSale() {
                return avgSale;
        }

        public void setAvgSale(String avgSale) {
                this.avgSale = avgSale;
        }

        public String getMaxSp() {
                return maxSp;
        }

        public void setMaxSp(String maxSp) {
                this.maxSp = maxSp;
        }

        public String getComparsionResult() {
                return comparsionResult;
        }

        public void setComparsionResult(String comparsionResult) {
                this.comparsionResult = comparsionResult;
        }

        private Map<Integer, Long> holdInventoryMap;

        public String getVat() {
                return vat;
        }

        public void setVat(String vat) {
                this.vat = vat;
        }

        public String getOtherCost() {
                return otherCost;
        }

        public void setOtherCost(String otherCost) {
                this.otherCost = otherCost;
        }


        public String getCurrentSp() {
                return currentSp;
        }

        public void setCurrentSp(String currentSp) {
                this.currentSp = currentSp;
        }

        public String getCurrentTp() {
                return currentTp;
        }

        public void setCurrentTp(String currentTp) {
                this.currentTp = currentTp;
        }


        public String getLastCheckedTimestamp() {
                return lastCheckedTimestamp;
        }

        public String getLastUpdatedInventoryTimestamp() {
                return lastUpdatedInventoryTimestamp;
        }

        public void setLastUpdatedInventoryTimestamp(
                        String lastUpdatedInventoryTimestamp) {
                this.lastUpdatedInventoryTimestamp = lastUpdatedInventoryTimestamp;
        }

        public void setLastCheckedTimestamp(
                        String lastCheckedTimestamp) {
                this.lastCheckedTimestamp = lastCheckedTimestamp;
        }

        public String getIsAutoIncrement() {
                return isAutoIncrement;
        }

        public void setIsAutoIncrement(String isAutoIncrement) {
                this.isAutoIncrement = isAutoIncrement;
        }

        public String getIsAutoDecrement() {
                return isAutoDecrement;
        }

        public void setIsAutoDecrement(String isAutoDecrement) {
                this.isAutoDecrement = isAutoDecrement;
        }

        public String getIsManualFavourite() {
                return isManualFavourite;
        }

        public void setIsManualFavourite(String isManualFavourite) {
                this.isManualFavourite = isManualFavourite;
        }

        public String getIsAutoFavourite() {
                return isAutoFavourite;
        }

        public void setIsAutoFavourite(String isAutoFavourite) {
                this.isAutoFavourite = isAutoFavourite;
        }

        public String getMinPosSp() {
                return minPosSp;
        }

        public void setMinPosSp(String minPosSp) {
                this.minPosSp = minPosSp;
        }

        public String getMinPosTp() {
                return minPosTp;
        }

        public void setMinPosTp(String minPosTp) {
                this.minPosTp = minPosTp;
        }

        public String getHeld() {
                return held;
        }

        public void setHeld(String held) {
                this.held = held;
        }

        public String getSupc() {
                return supc;
        }

        public void setSupc(String supc) {
                this.supc = supc;
        }

        public String getFkItemCode() {
                return fkItemCode;
        }

        public void setFkItemCode(String fkItemCode) {
                this.fkItemCode = fkItemCode;
        }
        
        static{
                try {
                        live = ConfigClient.getClient().get("sync_price_on_marketplace");
                } catch (ConfigException e) {
                    logger.error("Unable to get parameter from the config service", e);
                    live = "false";
                }
        }

        public String index() {
                if (!ReportsUtils.canAccessReport((Long) session.getAttribute(ReportsUtils.ROLE),request.getServletPath())) {
                        return "authfail";
                }
                return "index";
        }

        public String edit() {
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
                        return "authfail";
                }
                return "edit";
        }

        public String fetchItems() throws TException {
                Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                if (searchText.length() == 0) {
                        flipkartItems = CatalogClient.getFlipkartItems(Long.valueOf(next), 10);
                        totalCount = CatalogClient.getCountForFlipkartItems();
                        setSearchCount(totalCount);
                } else {
                        List<String> subString = Arrays.asList(searchText.split(" "));
                        flipkartItems = CatalogClient.searchFlipkartItems(subString,Long.valueOf(next), 10);
                        totalCount = CatalogClient.getCountForFlipkartItems();
                        searchCount = CatalogClient.getFlipkartSearchResultCount(subString);
                }
                return "flipkart-item-table";
        }

        public FlipkartItemDetails fetchItemDetail() throws NumberFormatException, TException {
                Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                FlipkartItemDetails fkItemDetails = CatalogClient.getFlipkartItemDetails(Long.valueOf(id));
                lastUpdatedInventoryTimeStampForItem(fkItemDetails.getLastUpdatedInventoryTimestamp());
                return fkItemDetails;
        }

        public MarketplaceItems fetchMarketplaceDetail() throws NumberFormatException, TException {
                Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                MarketplaceItems mpItemDetails = CatalogClient.getMarketplacedetailsForItem(Long.valueOf(id), 8);
                lastCheckedTimeStampForItem(mpItemDetails.getLastCheckedTimestamp());
                return mpItemDetails;
        }

        public void lastUpdatedInventoryTimeStampForItem(long timestamp){
                setLastUpdatedInventoryTimestamp(new java.util.Date(timestamp).toLocaleString());
        }

        public void lastCheckedTimeStampForItem(long timestamp){
                setLastCheckedTimestamp(new java.util.Date(timestamp).toLocaleString());
        }

        public String uploadBulkSheet(){
                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-bulk-upload";
        }

        public String update() throws NumberFormatException, TException, InventoryServiceException, CatalogServiceException, JSONException{
                Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                //Client catalogClientProd = new CatalogClient().getClient();
                FlipkartItem flipkartItem = catalogClient.getFlipkartItem(Long.valueOf(itemId));
                Item item = catalogClient.getItem(Long.valueOf(itemId));
                MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
                if (mpCosting.getSource()==0){
                        throw new CatalogServiceException();
                }
                MarketplaceItems mpItem = catalogClient.getMarketplacedetailsForItem(Long.valueOf(itemId),8);
                boolean toUpdate =false;
                if (mpItem.getCurrentSp()!=Double.valueOf(sellingPrice) || flipkartItem.isIsListedOnFlipkart()!=Boolean.valueOf(isListedOnFlipkart) || flipkartItem.isSuppressPriceFeed()!=Boolean.valueOf(isSuppressPriceFeed)){
                        toUpdate=true;
                }
                mpItem.setEmiFee(mpCosting.getEmiFee());
                mpItem.setReturnProvision(mpCosting.getReturnProvision());
                mpItem.setClosingFee(mpCosting.getClosingFee());
                mpItem.setServiceTax(mpCosting.getServiceTax());
                mpItem.setCommission(mpCosting.getCommission());
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
                /*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
                        throw new InventoryServiceException();
                }*/
                flipkartItem.setWarehouseId(Long.valueOf(warehouseId));
                flipkartItem.setIsListedOnFlipkart(Boolean.valueOf(isListedOnFlipkart));
                flipkartItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
                flipkartItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
                flipkartItem.setExceptionPrice(Double.valueOf(exceptionPrice));
                flipkartItem.setCommissionValue(Double.valueOf(commission));
                flipkartItem.setServiceTaxValue(Double.valueOf(serviceTax));
                flipkartItem.setMaxNlc(Double.valueOf(maxNlc));
                flipkartItem.setSkuAtFlipkart(fkItemCode);
                flipkartItem.setFlipkartSerialNumber(fkSerialNumber);
                MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
                //double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
                //t_mpItem.setVat(vat);
                flipkartItem.setUpdatedBy(getUserName());
                flipkartItem.setMarketplaceItems(t_mpItem);

                if(!compareParameters(t_mpItem,flipkartItem,warehouse,item.getWeight())){
                        setComparsionResult("0");
                        return "flipkart-update-result";
                }
                else{
                        setComparsionResult("1");
                }
                Long timestamp = System.currentTimeMillis();
                if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
                        throw new CatalogServiceException();
                }

                if (t_mpItem.getCurrentSp()< t_mpItem.getMinimumPossibleSp()){
                        sendAlert(t_mpItem.getItemId(),t_mpItem.getCurrentSp(),t_mpItem.getMinimumPossibleSp());
                }
                logger.info("\nUpdate Method Item Id "+itemId+"\nSelling Price "+sellingPrice+"\nWarehouse Id "+warehouseId+"\nMax Nlc "+maxNlc+"\nUpdated By: "+session.getAttribute(ReportsUtils.USER_NAME).toString());
                if(toUpdate && Boolean.valueOf(live) && Boolean.valueOf(isListedOnFlipkart) && (!Boolean.valueOf(isSuppressPriceFeed))){
                        UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,timestamp);
                        updateFlipkartPricing.start();
                }
                return "flipkart-update-result";
        }
        
        public void updateForAutoPricing() throws NumberFormatException, CatalogServiceException, TException{
        logger.info("Calling Method to update price at flipkart for auto pricing");
        Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        Item item = catalogClient.getItem(Long.valueOf(itemId));
        UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,System.currentTimeMillis());
        updateFlipkartPricing.start();
    }



        public boolean compareParameters(MarketplaceItems mpItem, FlipkartItem flipkartItem, Warehouse warehouse,double weight) throws TException, JSONException, CatalogServiceException{
                double nlc =getNlcForWarehouse(flipkartItem.getWarehouseId(),flipkartItem.getItem_id());
                double vat = (mpItem.getCurrentSp()/(1+(mpItem.getVat()/100))-(nlc/(1+(mpItem.getVat()/100))))*(mpItem.getVat()/100);
                double inHouseCost = 15+vat+(mpItem.getReturnProvision()/100)*mpItem.getCurrentSp()+mpItem.getOtherCost();
                double lowest_possible_tp = nlc+inHouseCost;
                double our_tp =  mpItem.getCurrentSp()- mpItem.getCurrentSp()*(mpItem.getCommission()/100+mpItem.getEmiFee()/100)*(1+(mpItem.getServiceTax()/100))-(mpItem.getCourierCost()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100));
                double commission =  ((mpItem.getCommission()/100)*mpItem.getCurrentSp());
                double service_tax = (mpItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+mpItem.getCourierCost());
                double lowest_possible_sp = (nlc+(mpItem.getCourierCost()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat()/100))+(15+mpItem.getOtherCost())*(1+(mpItem.getVat())/100))/(1-(mpItem.getCommission()/100+mpItem.getEmiFee()/100)*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat())/100)-(mpItem.getReturnProvision()/100)*(1+(mpItem.getVat())/100));
                double vat_rate_prod = getVatRateForItem(warehouse,mpItem.getCurrentSp(),flipkartItem.getItem_id());
                JSONObject x = new JSONObject();
                x.put("NLC", nlc);
                x.put("VAT", vat);
                x.put("COURIER COST",getCourierCost(weight));
                x.put("LOWEST POS TP", lowest_possible_tp);
                x.put("TP", our_tp);
                x.put("COMMISSION", commission);
                x.put("SERVICE TAX", service_tax);
                x.put("LOWEST POS SP", lowest_possible_sp);
                x.put("VAT RATE",vat_rate_prod);
                logger.info("Flipkart Backend validation "+x.toString());
                boolean compare_result=true;

                if(!(getCourierCost(weight)==mpItem.getCourierCost())){
                        compare_result=false;
                }

                if(!(vat_rate_prod==mpItem.getVat())){
                        compare_result=false;
                }

                if(!(nlc==flipkartItem.getMaxNlc())){
                        compare_result=false;
                }
                if(!(lowest_possible_tp-mpItem.getMinimumPossibleTp()>-1 && lowest_possible_tp-mpItem.getMinimumPossibleTp()<1)){
                        compare_result=false;
                }
                if(!(our_tp-mpItem.getCurrentTp()>-1 && our_tp-mpItem.getCurrentTp()<1)){
                        compare_result=false;
                }
                if(!(commission-flipkartItem.getCommissionValue()>-1 && commission-flipkartItem.getCommissionValue()<1)){
                        compare_result=false;
                }
                if(!(service_tax-flipkartItem.getServiceTaxValue()>-1 && service_tax-flipkartItem.getServiceTaxValue()<1)){
                        compare_result=false;
                }
                if(!(lowest_possible_sp-mpItem.getMinimumPossibleSp()>-1 && lowest_possible_sp-mpItem.getMinimumPossibleSp()<1)){
                        compare_result=false;
                }
                return compare_result;

        }

        public double getVatRateForItem(Warehouse warehouse, double sellingPrice,long itemId) throws CatalogServiceException, TException{
                Client catalogClientProd = new CatalogClient().getClient();
                return catalogClientProd.getVatPercentageForItem(itemId, warehouse.getStateId(), sellingPrice);
        }

        public double getNlcForWarehouse(long warehouseId,long item_id) throws TException{
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                return inventoryClient.getNlcForWarehouse(warehouseId, item_id);
        }

        public double getCourierCost(double weight){
                double cCost = 40.0;
                int slabs = (int) ((weight+.05 - .001)/(.5));
                for(int i=0;i<slabs;i++){
                        cCost = cCost + 40;
                }
                return cCost;
        }

        public void getLastNDaySaleForItem(String itemId,String days) {
                try{
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        List<OOSStatus> oosStatuses = inventoryClient.getOosStatusesForXDaysForItem(Long.valueOf(itemId), 8, Integer.valueOf(days));
                        String lastNdaySale="";
                        double avgSale = 0.0;
                        long count = 0,sale = 0;
                        for(OOSStatus oosStatus : oosStatuses){
                                if(oosStatus.isIs_oos()){
                                        lastNdaySale += "X-";
                                }else{
                                        lastNdaySale += oosStatus.getNum_orders() + "-";
                                        sale = sale + oosStatus.getNum_orders();
                                        count+=1;
                                }
                        }
                        lastNdaySale = lastNdaySale.substring(0, lastNdaySale.length()-1);
                        lastNdaySale += "\n";
                        setnDaySale(lastNdaySale);
                        if (count!=0){
                                setAvgSale(String.valueOf(roundTwoDecimals(sale/(double)count)));
                        }
                        else{
                                setAvgSale("0");
                        }
                }
                catch (Exception e){
                        setAvgSale("0");
                        setnDaySale("Unable to fetch");
                        logger.error("Unable to get last n day sale",e);
                }

        }


        private MarketplaceItems updateMarketplaceItemDetails(MarketplaceItems mpItem){
                mpItem.setItemId(Long.valueOf(itemId));
                mpItem.setSource(8);
                mpItem.setVat(Double.valueOf(vat));
                mpItem.setCourierCost(Double.valueOf(courierCost));
                mpItem.setOtherCost(Double.valueOf(otherCost));
                mpItem.setCurrentSp(Double.valueOf(sellingPrice));
                mpItem.setCurrentTp(Double.valueOf(transferPrice));
                mpItem.setAutoDecrement(Boolean.valueOf(isAutoDecrement));
                mpItem.setAutoIncrement(Boolean.valueOf(isAutoIncrement));
                mpItem.setManualFavourite(Boolean.valueOf(isManualFavourite));
                mpItem.setMinimumPossibleSp(Double.valueOf(minPosSp));
                mpItem.setMinimumPossibleTp(Double.valueOf(minPosTp));
                mpItem.setMaximumSellingPrice(Double.valueOf(maxSp));
                return mpItem;
        }

        private void sendAlert(long itemId,double sp,double minSp){
                Item item;
                try{
                        Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                        item= catalogClient.getItem(itemId);
                }
                catch(Exception e){
                        e.printStackTrace();
                        return;
                }
                String emailSubjectTxt="Flipkart SP is set below Min Possible SP";
                String[] sendTo=new String[]{ "kshitij.sood@saholic.com","rajneesh.arora@saholic.com","rajveer.singh@saholic.com","vikram.raghav@saholic.com"};
                String text = "Item Details-\nItem Id: "+itemId+"\nProduct Name: "+item.getBrand()+" "+item.getModelName()+" "+item.getModelNumber()+" "+item.getColor()+"\nSellingPrice: "+sp+"\nMinPossibleSp: "+minSp+"\nUpdated By: "+session.getAttribute(ReportsUtils.USER_NAME).toString();
                logger.info(text);
                String emailFromAddress = "build@shop2020.in";
                String password = "cafe@nes";
                GmailUtils mailer = new GmailUtils();
                try {
                        mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
                }
                catch (Exception e) {
                        logger.info(e.toString());
                }
        }

        public String addNewItem() throws TException, NumberFormatException, InventoryServiceException, CatalogServiceException, JSONException{
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                Item item = catalogClient.getItem(Long.valueOf(itemId));
                //Client catalogClientProd = new CatalogClient().getClient();
                MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));

                if (mpCosting.getSource()==0){
                        throw new CatalogServiceException();
                }
                Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
                /*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
                        throw new InventoryServiceException();
                }*/
                FlipkartItem flipkartItem = new FlipkartItem();
                flipkartItem.setItem_id(Long.valueOf(itemId));
                flipkartItem.setWarehouseId(Long.valueOf(warehouseId));
                flipkartItem.setIsListedOnFlipkart(Boolean.valueOf(isListedOnFlipkart));
                flipkartItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
                flipkartItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
                flipkartItem.setExceptionPrice(Double.valueOf(exceptionPrice));
                flipkartItem.setCommissionValue(Double.valueOf(commission));
                flipkartItem.setServiceTaxValue(Double.valueOf(serviceTax));
                flipkartItem.setMaxNlc(Double.valueOf(maxNlc));
                flipkartItem.setSkuAtFlipkart(fkItemCode);
                flipkartItem.setFlipkartSerialNumber(fkSerialNumber);
                flipkartItem.setUpdatedBy(getUserName());

                MarketplaceItems mpItem = new MarketplaceItems();
                MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
                /*double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
                t_mpItem.setVat(vat);*/
                t_mpItem.setCommission(mpCosting.getCommission());
                t_mpItem.setServiceTax(mpCosting.getServiceTax());
                t_mpItem.setReturnProvision(mpCosting.getReturnProvision());
                t_mpItem.setEmiFee(mpCosting.getEmiFee());
                t_mpItem.setClosingFee(mpCosting.getClosingFee());
                if(!compareParameters(t_mpItem,flipkartItem,warehouse,item.getWeight())){
                        setComparsionResult("0");
                        return "flipkart-update-result";
                }
                else{
                        setComparsionResult("1");
                }
                flipkartItem.setMarketplaceItems(t_mpItem);
                Long timestamp = System.currentTimeMillis();
                boolean result = catalogClient.addOrUpdateFlipkartItem(flipkartItem);
                if(!result){
                        throw new CatalogServiceException();
                }
                if (t_mpItem.getCurrentSp()< t_mpItem.getMinimumPossibleSp()){
                        sendAlert(t_mpItem.getItemId(),t_mpItem.getCurrentSp(),t_mpItem.getMinimumPossibleSp());
                }
                if(Boolean.valueOf(isListedOnFlipkart) && Boolean.valueOf(live) && (!Boolean.valueOf(isSuppressPriceFeed))){
                        UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,timestamp);
                        updateFlipkartPricing.start();
                }
                return "flipkart-update-result";
        }


        public String getAddNewItemForm(){
                return "flipkart-add-item";
        }

        public String getItemDetailsInJson() throws NumberFormatException, CatalogServiceException, TException, JSONException, InventoryServiceException{
                Client catalogClientProd = new CatalogClient().getClient();
                Client catalogClient =new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                FlipkartItem flipkartItem = catalogClient.getFlipkartItem(Long.valueOf(itemId));
                MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
                if (flipkartItem.getItem_id()!=0){
                        throw new CatalogServiceException();
                }
                Item item = catalogClient.getItem(Long.valueOf(itemId));
                if (item.getId()==0){
                        throw new CatalogServiceException();
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
                /*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
                        throw new InventoryServiceException();
                }*/
                double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
                double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
                if (maxNLC==0){
                        throw new InventoryServiceException();
                }
                itemObj = new JSONObject();
                itemObj.put("ItemId", item.getId());
                itemObj.put("Brand", item.getBrand());
                itemObj.put("ModelName", item.getModelName());
                itemObj.put("ModelNumber", item.getModelNumber());
                itemObj.put("Color", item.getColor());
                itemObj.put("Weight", item.getWeight());
                itemObj.put("Risky", item.isRisky());
                itemObj.put("Status", item.getItemStatus());
                itemObj.put("MRP", item.getMrp());
                itemObj.put("SellingPrice", item.getSellingPrice());
                itemObj.put("MaxNlc", maxNLC);
                itemObj.put("VatRate", vat);
                itemObj.put("CommissionRate", mpCosting.getCommission());
                itemObj.put("ServiceTaxRate", mpCosting.getServiceTax());
                itemObj.put("ReturnProvision", mpCosting.getReturnProvision());
                itemObj.put("EmiFee", mpCosting.getEmiFee());
                itemObj.put("ClosingFee", mpCosting.getClosingFee());
                return "item-details-json";
        }

        public String ke$ha() throws NumberFormatException, TException, JSONException, InventoryServiceException, CatalogServiceException{
                Client catalogClientProd = new CatalogClient().getClient();
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
                //if (warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD){
                double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
                double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
                itemObj = new JSONObject();
                itemObj.put("ItemId", itemId);
                itemObj.put("WarehouseId", warehouseId);
                itemObj.put("MaxNlc", maxNLC);
                itemObj.put("VatRate", vat);
                /*}
                else{
                        itemObj = new JSONObject();
                        throw new InventoryServiceException();
                }*/
                return "item-details-json";
        }

        public ItemInventory getItemInventory(String itemId) throws NumberFormatException, InventoryServiceException, TException{
                try{
                        InventoryClient inventoryServiceClient = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                        in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(Long.valueOf(itemId));
                        return thriftItemInventory;
                }
                catch(Exception e){
                        logger.error("Unable to get inventory info for item",e);
                        return null;
                }
        }



        public Warehouse getWarehouse(String warehouseId,String itemId) throws NumberFormatException, TException, InventoryServiceException { 
                InventoryClient inventoryServiceClient = new InventoryClient();
                holdInventoryMap =inventoryServiceClient.getClient().getHeldInventoryMapForItem(Long.valueOf(itemId), Long.valueOf(warehouseId));
                return inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
        }

        public Map<Integer, Long> getHoldInventoryMapForItem(){
                return holdInventoryMap;
        }

        public void changeHeldForSource() throws NumberFormatException, TException, InventoryServiceException{
                InventoryClient inventoryServiceClient = new InventoryClient();
                Warehouse warehouse = inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
                if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
                        throw new InventoryServiceException();
                }
                inventoryServiceClient.getClient().addUpdateHoldInventory(Long.valueOf(itemId),Long.valueOf(warehouseId),Long.valueOf(held),8);
        }

        public void downloadFlipkartListings() throws IOException, TException{
                File file = new File("/tmp/flipkart-bulk-upload-template.xls");
                HSSFWorkbook hwb=new HSSFWorkbook();
                HSSFSheet sheet =  hwb.createSheet("Flipkart-Listings");
                HSSFRow rowhead=   sheet.createRow((short)0);
                rowhead.createCell((short) 0).setCellValue("ITEM-ID");
                rowhead.createCell((short) 1).setCellValue("CATEGORY CODE");
                rowhead.createCell((short) 2).setCellValue("PRODUCT");
                rowhead.createCell((short) 3).setCellValue("WAREHOUSE-ID");
                rowhead.createCell((short) 4).setCellValue("EXCEPTIONAL-PRICE");
                rowhead.createCell((short) 5).setCellValue("FLIPKART-LISTED");
                rowhead.createCell((short) 6).setCellValue("TRANSFER-PRICE");
                rowhead.createCell((short) 7).setCellValue("SELLING-PRICE");
                rowhead.createCell((short) 8).setCellValue("LOWEST POSSIBLE SP");
                rowhead.createCell((short) 9).setCellValue("LOWEST POSSIBLE TP");
                rowhead.createCell((short) 10).setCellValue("MARGIN");
                rowhead.createCell((short) 11).setCellValue("MARGING PERCENTAGE");
                rowhead.createCell((short) 12).setCellValue("OTHER COST");
                rowhead.createCell((short) 13).setCellValue("COURIER-COST");
                rowhead.createCell((short) 14).setCellValue("COMMISION PERCENTAGE");
                rowhead.createCell((short) 15).setCellValue("COMMISION VALUE");
                rowhead.createCell((short) 16).setCellValue("SERVICE TAX RATE");
                rowhead.createCell((short) 17).setCellValue("SERVICE-TAX VALUE");
                rowhead.createCell((short) 18).setCellValue("VAT PERCENTAGE");
                rowhead.createCell((short) 19).setCellValue("Suppress Inventory Feed");
                rowhead.createCell((short) 20).setCellValue("Suppress Price Feed");
                rowhead.createCell((short) 21).setCellValue("AUTO FAVOURITE");
                rowhead.createCell((short) 22).setCellValue("MANUAL FAVOURITE");
                rowhead.createCell((short) 23).setCellValue("AUTO INCREMENT");
                rowhead.createCell((short) 24).setCellValue("AUTO DECREMENT");
                rowhead.createCell((short) 25).setCellValue("Max NLC");
                rowhead.createCell((short) 26).setCellValue("SKU @ Flipkart");
                rowhead.createCell((short) 27).setCellValue("Flipkart Serial Number");
                Client catalogClient = null;
                List<FlipkartItemDetails> flipkartItems = null;
                try {
                        catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                        flipkartItems = catalogClient.getAllFkItems();
                } catch (Exception e) {
                        e.printStackTrace();
                }
                int iterator=1;
                Item item;
                MarketplaceItems marketplaceItem;
                for(FlipkartItemDetails fkItem:flipkartItems){
                        marketplaceItem = catalogClient.getMarketplacedetailsForItem(fkItem.getItem_id(), 8);
                        //MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, fkItem.getItem_id());
                        HSSFRow row = sheet.createRow((short)iterator);
                        row.createCell((short) 0).setCellValue(fkItem.getItem_id());
                        row.createCell((short) 1).setCellValue(fkItem.getCategory());
                        row.createCell((short) 2).setCellValue(getVaildName(fkItem.getBrand())+" "+getVaildName(fkItem.getModel_name())+" "+getVaildName(fkItem.getModel_number())+" "+getVaildName(fkItem.getColor()));
                        row.createCell((short) 3).setCellValue(fkItem.getWarehouseId());
                        row.createCell((short) 4).setCellValue(roundTwoDecimals(fkItem.getExceptionPrice()));
                        if(fkItem.isIsListedOnFlipkart()){
                                row.createCell((short) 5).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 5).setCellValue(0);
                        }
                        row.createCell((short) 6).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentTp()));
                        row.createCell((short) 7).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentSp()));
                        row.createCell((short) 8).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleSp()));
                        row.createCell((short) 9).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleTp()));
                        row.createCell((short) 10).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp()))));
                        row.createCell((short) 11).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp())/marketplaceItem.getMinimumPossibleSp())*100));
                        row.createCell((short) 12).setCellValue(roundTwoDecimals(marketplaceItem.getOtherCost()));
                        row.createCell((short) 13).setCellValue(marketplaceItem.getCourierCost());
                        row.createCell((short) 14).setCellValue(roundTwoDecimals(marketplaceItem.getCommission()));
                        row.createCell((short) 15).setCellValue(roundTwoDecimals(fkItem.getCommission()));
                        row.createCell((short) 16).setCellValue(roundTwoDecimals(marketplaceItem.getServiceTax()));
                        row.createCell((short) 17).setCellValue(roundTwoDecimals(fkItem.getServiceTax()));
                        row.createCell((short) 18).setCellValue(roundTwoDecimals(marketplaceItem.getVat()));
                        if(fkItem.isSuppressInventoryFeed()){
                                row.createCell((short) 19).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 19).setCellValue(0);
                        }
                        if(fkItem.isSuppressPriceFeed()){
                                row.createCell((short) 20).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 20).setCellValue(0);
                        }
                        if(marketplaceItem.isAutoFavourite()){
                                row.createCell((short) 21).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 21).setCellValue(0);
                        }
                        if(marketplaceItem.isManualFavourite()){
                                row.createCell((short) 22).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 22).setCellValue(0);
                        }
                        if(marketplaceItem.isAutoIncrement()){
                                row.createCell((short) 23).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 23).setCellValue(0);
                        }
                        if(marketplaceItem.isAutoDecrement()){
                                row.createCell((short) 24).setCellValue(1);
                        }
                        else{
                                row.createCell((short) 24).setCellValue(0);
                        }
                        row.createCell((short) 25).setCellValue(fkItem.getMaxNlc());
                        row.createCell((short) 26).setCellValue(fkItem.getSkuAtFlipkart());
                        row.createCell((short) 27).setCellValue(fkItem.getFlipkartSerialNumber());
                        iterator++;
                }

                FileOutputStream fileOut = null;
                try {
                        fileOut = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        hwb.write(fileOut);
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                try {
                        fileOut.close();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                byte[] buffer = new byte[(int)file.length()];
                InputStream input = null;
                try {
                        int totalBytesRead = 0;
                        input = new BufferedInputStream(new FileInputStream(file));
                        while(totalBytesRead < buffer.length){
                                int bytesRemaining = buffer.length - totalBytesRead;
                                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
                                if (bytesRead > 0){
                                        totalBytesRead = totalBytesRead + bytesRead;
                                }
                        }
                }
                finally {
                        input.close();
                        file.delete();
                }

                response.setHeader("Content-Disposition", "attachment; filename=\"Flipkart-Bulk-Listings.xls\"");
                response.setContentType("application/octet-stream");
                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        sos.write(buffer);
                        sos.flush();
                } catch (IOException e) {
                        System.out.println("Unable to stream the manifest file");
                }   


        }


        public void uploadflipkartBulkSheet() throws IOException, TException, NumberFormatException, InventoryServiceException, CatalogServiceException{
                File fileToCreate = new File("/tmp/", "flipkart-bulk-upload.xls");
                FileUtils.copyFile(this.file, fileToCreate);
                FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
                HSSFWorkbook workbook = new HSSFWorkbook(iFile);
                HSSFSheet sheet = workbook.getSheetAt(0);
                String updatedBy = getUserName();
                Client catalogClient=null;
                Client catalogClientProd=null;
                StringBuilder sb = new StringBuilder();
                try {
                        catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
                        catalogClientProd = new CatalogClient().getClient();
                } catch (TTransportException e) {
                        e.printStackTrace();
                }
                InventoryClient inventoryServiceClient = new InventoryClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();

                for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
                        if (sheet.getLastRowNum()-1>100){
                                sb.append("Number of items to update can't be greater than 100");
                                break;
                        }
                        FlipkartItem flipkartItem = null;
                        MarketplaceItems marketplaceItem = null;
                        MarketplacePercentage mpCosting = null;
                        Warehouse warehouse = null;
                        Item item = null;
                        Long sku;
                        boolean new_item = false;
                        if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
                                continue;
                        }
                        else {
                                sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
                                flipkartItem = catalogClient.getFlipkartItem(sku);
                                mpCosting = catalogClient.getCostingForMarketplace(8, sku);
                                marketplaceItem  = catalogClient.getMarketplacedetailsForItem(sku, 8);
                                marketplaceItem.setItemId(sku);
                                marketplaceItem.setSource(8);
                                marketplaceItem.setCommission(mpCosting.getCommission());
                                marketplaceItem.setServiceTax(mpCosting.getServiceTax());
                                marketplaceItem.setReturnProvision(mpCosting.getReturnProvision());
                                marketplaceItem.setEmiFee(mpCosting.getEmiFee());
                                marketplaceItem.setClosingFee(mpCosting.getClosingFee());

                                try {
                                        item = catalogClient.getItem(sku);
                                        if (item.getId()==0){
                                                sb.append(sku + " Item not valid"+"\n");
                                                continue;
                                        }
                                } catch (CatalogServiceException e) {
                                        sb.append(sku + " Item not valid"+"\n");
                                        continue;
                                }
                                if(flipkartItem.getItem_id()==0){
                                        new_item = true;
                                        flipkartItem = new FlipkartItem();
                                        flipkartItem.setItem_id(sku); 
                                }
                        }
                        
                        
                        if (checkEmptyString(sheet.getRow(iterator).getCell(1)) && new_item){
                                sb.append(sku + " New Listing - Warehouse Id not Present"+"\n");
                                continue;
                        }
                        
                        

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
                                /*Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
                                if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
                                        sb.append(sku + "Not acceptable warehouse"+"\n");
                                        continue;
                                }*/
                                long warehouseId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
                                double maxNLC = inventoryClient.getNlcForWarehouse(warehouseId, item.getId());
                                if (maxNLC==0){
                                        sb.append(sku + " Max Nlc can't be 0"+"\n");
                                        continue;
                                }
                                flipkartItem.setWarehouseId(warehouseId);
                                flipkartItem.setMaxNlc(maxNLC);
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
                                double exceptionPrice = sheet.getRow(iterator).getCell(2).getNumericCellValue();
                                flipkartItem.setExceptionPrice(exceptionPrice);
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
                                if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==1){
                                        flipkartItem.setIsListedOnFlipkart(true);
                                }
                                if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==0){
                                        flipkartItem.setIsListedOnFlipkart(false);
                                }
                        }

                        double transferPrice = 0,sellingPrice,commission,courierCost =40,serviceTax,otherCost;
                        if (checkEmptyString(sheet.getRow(iterator).getCell(4))&& new_item){
                                sb.append(sku + "New Item -  Selling Price cannot be empty"+"\n");
                                continue;
                        }
                        if (!checkEmptyString(sheet.getRow(iterator).getCell(4))){
                                sellingPrice = sheet.getRow(iterator).getCell(4).getNumericCellValue();
                                if(sellingPrice==0){
                                        sb.append(sku + " Selling Price cannot be zero"+"\n");
                                        continue;
                                }
                                marketplaceItem.setCurrentSp(sellingPrice);
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(5))){
                                otherCost = sheet.getRow(iterator).getCell(5).getNumericCellValue();
                                marketplaceItem.setOtherCost(otherCost);
                        }


                        if (!checkEmptyString(sheet.getRow(iterator).getCell(6))){
                                if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==1){
                                        flipkartItem.setSuppressPriceFeed(true);
                                }
                                if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
                                        flipkartItem.setSuppressPriceFeed(false);
                                }
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(7))){
                                if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==1){
                                        flipkartItem.setSuppressInventoryFeed(true);
                                }
                                if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==0){
                                        flipkartItem.setSuppressInventoryFeed(false);
                                }
                        }

                        if (checkEmptyString(sheet.getRow(iterator).getCell(8)) && new_item){
                                sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
                                continue;
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
                                sheet.getRow(iterator).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                                String flipkartItemCode = sheet.getRow(iterator).getCell(8).getStringCellValue();
                                if (flipkartItemCode.length()==0 && new_item){
                                        sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
                                        continue;
                                }
                                flipkartItem.setSkuAtFlipkart(flipkartItemCode);
                        }
                        
                        if (checkEmptyString(sheet.getRow(iterator).getCell(9)) && new_item){
                                sb.append(sku + " New Item -  Flipkart serial number cannot be empty"+"\n");
                                continue;
                        }

                        if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
                                sheet.getRow(iterator).getCell(9).setCellType(Cell.CELL_TYPE_STRING);
                                String flipkartSerialNumber = sheet.getRow(iterator).getCell(9).getStringCellValue();
                                if (flipkartSerialNumber.length()==0 && new_item){
                                        sb.append(sku + "  New Item -  Flipkart serial number cannot be empty"+"\n");
                                        continue;
                                }
                                flipkartItem.setFlipkartSerialNumber(flipkartSerialNumber);
                        }

                        double weight = item.getWeight();


                        if(weight==0){
                                sb.append(sku + " Please add weight"+"\n");
                                continue;
                        }
                        if (weight!=0){
                                weight = weight+.05;
                                int slabs = (int) ((weight - .001)/(.5));

                                for(int i=0;i<slabs;i++){
                                        courierCost = courierCost + 40;
                                }
                        }
                        warehouse = inventoryClient.getWarehouse(flipkartItem.getWarehouseId());
                        marketplaceItem.setCourierCost(courierCost);
                        transferPrice = roundTwoDecimals(marketplaceItem.getCurrentSp()- marketplaceItem.getCurrentSp()*(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))-(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+(marketplaceItem.getServiceTax()/100)));
                        marketplaceItem.setCurrentTp(transferPrice);
                        commission = roundTwoDecimals(((marketplaceItem.getCommission()/100)*marketplaceItem.getCurrentSp()));
                        flipkartItem.setCommissionValue(commission);
                        serviceTax = roundTwoDecimals((marketplaceItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+marketplaceItem.getCourierCost())); 
                        flipkartItem.setServiceTaxValue(serviceTax);
                        double vatRate = catalogClientProd.getVatPercentageForItem(flipkartItem.getItem_id(),warehouse.getStateId(),marketplaceItem.getCurrentSp());
                        marketplaceItem.setVat(vatRate);
                        double vat = roundTwoDecimals((marketplaceItem.getCurrentSp()/(1+(marketplaceItem.getVat()/100))-(flipkartItem.getMaxNlc()/(1+(marketplaceItem.getVat()/100))))*(marketplaceItem.getVat()/100));
                        double inHouseCost = roundTwoDecimals(15+vat+(marketplaceItem.getReturnProvision()/100)*marketplaceItem.getCurrentSp()+marketplaceItem.getOtherCost());
                        double lowest_possible_tp = roundTwoDecimals(flipkartItem.getMaxNlc()+inHouseCost);
                        marketplaceItem.setMinimumPossibleTp(lowest_possible_tp);
                        double lowest_possible_sp = roundTwoDecimals((flipkartItem.getMaxNlc()+(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+marketplaceItem.getServiceTax()/100)*(1+(marketplaceItem.getVat()/100))+(15+marketplaceItem.getOtherCost())*(1+(marketplaceItem.getVat())/100))/(1-(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))*(1+(marketplaceItem.getVat())/100)-(marketplaceItem.getReturnProvision()/100)*(1+(marketplaceItem.getVat())/100)));
                        marketplaceItem.setMinimumPossibleSp(lowest_possible_sp);
                        flipkartItem.setUpdatedBy(updatedBy);
                        flipkartItem.setMarketplaceItems(marketplaceItem);
                        if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
                                sb.append(sku + " Service Error\n");
                        }       
                }
                File file = new File("/tmp/flipkartbulk");
                FileWriter writer = new FileWriter(file);
                writer.append(sb.toString());
                writer.close();
                byte[] buffer = new byte[(int)file.length()];
                InputStream input = null;
                try {
                        int totalBytesRead = 0;
                        input = new BufferedInputStream(new FileInputStream(file));
                        while(totalBytesRead < buffer.length){
                                int bytesRemaining = buffer.length - totalBytesRead;
                                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
                                if (bytesRead > 0){
                                        totalBytesRead = totalBytesRead + bytesRead;
                                }
                        }
                }
                finally {
                        input.close();
                        file.delete();
                }

                response.setHeader("Content-Type", "text/javascript");

                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        sos.write(buffer);
                        sos.flush();
                } catch (IOException e) {
                        System.out.println("Unable to stream the manifest file");
                }   
        }

        public boolean checkEmptyString(Cell cell){
                if (cell==null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
                        return true;
                }
                return false;
        }

        double roundTwoDecimals(double d) {
                DecimalFormat twoPlaces = new DecimalFormat("#.##");
                return Double.valueOf(twoPlaces.format(d));
        }

        /*String getLocation(String location){
                logger.info("Inside trim"+location);
                int loc = location.lastIndexOf(',');
                logger.info("end result "+location.substring(loc+1));
                return location.substring(loc+1);
        }*/


        public String show() {
                if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
                        return "authfail";
                }

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

                return "id";
        }

        public void setId(String id) {
                this.id = id;
        }

        public String getUserName(){
                return session.getAttribute(ReportsUtils.USER_NAME).toString();
        }

        public HttpServletRequest getRequest() {
                logger.info("set request"+request.toString());
                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 String getItemId() {
                return itemId;
        }

        public void setItemId(String itemId) {
                this.itemId = itemId;
        }

        public String getExceptionPrice() {
                return exceptionPrice;
        }

        public void setExceptionPrice(String exceptionPrice) {
                this.exceptionPrice = exceptionPrice;
        }

        public String getWarehouseId() {
                return warehouseId;
        }

        public void setWarehouseId(String warehouseId) {
                this.warehouseId = warehouseId;
        }

        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 getNext() {
                return next;
        }

        public void setNext(String next) {
                this.next = next;
        }

        public String getId() {
                return id;
        }

        public void setServletRequest(HttpServletRequest req) {
                this.request = req;
                this.session = req.getSession();        
        }

        public void setServletContext(ServletContext arg0) {
                // TODO Auto-generated method stub

        }

        public void setServletResponse(HttpServletResponse response) {
                this.response = response;
        }

        public void setSearchText(String searchText) {
                this.searchText = searchText;
        }

        public String getSearchText() {
                return searchText;
        }

        public long getSearchCount() {
                return searchCount;
        }

        public long getTotalCount() {
                return totalCount;
        }

        public void setSearchCount(long count) {
                this.searchCount = count;
        }

        public List<FlipkartItemDetails> getFlipkartItems(){
                return flipkartItems;
        }

        public void setSellingPrice(String sellingPrice) {
                this.sellingPrice = sellingPrice;
        }

        public String getSellingPrice() {
                return sellingPrice;
        }

        public void setTransferPrice(String transferPrice) {
                this.transferPrice = transferPrice;
        }

        public String getTransferPrice() {
                return transferPrice;
        }

        public void setWebisteMrp(String webisteMrp) {
                this.webisteMrp = webisteMrp;
        }

        public String getWebisteMrp() {
                return webisteMrp;
        }

        public void setWebisteSellingPrice(String webisteSellingPrice) {
                this.webisteSellingPrice = webisteSellingPrice;
        }

        public String getWebisteSellingPrice() {
                return webisteSellingPrice;
        }

        public void setIsListedOnFlipkart(String isListedOnFlipkart) {
                this.isListedOnFlipkart = isListedOnFlipkart;
        }

        public String getIsSuppressInventoryFeed() {
                return isSuppressInventoryFeed;
        }

        public void setIsSuppressInventoryFeed(String isSuppressInventoryFeed) {
                this.isSuppressInventoryFeed = isSuppressInventoryFeed;
        }

        public String getIsSuppressPriceFeed() {
                return isSuppressPriceFeed;
        }

        public void setIsSuppressPriceFeed(String isSuppressPriceFeed) {
                this.isSuppressPriceFeed = isSuppressPriceFeed;
        }

        public String getIsListedOnFlipkart() {
                return isListedOnFlipkart;
        }

        public void setCommission(String commission) {
                this.commission = commission;
        }

        public String getCommission() {
                return commission;
        }

        public void setServiceTax(String serviceTax) {
                this.serviceTax = serviceTax;
        }

        public String getServiceTax() {
                return serviceTax;
        }

        public void setCourierCost(String courierCost) {
                this.courierCost = courierCost;
        }

        public String getCourierCost() {
                return courierCost;
        }

        public void setMaxNlc(String maxNlc) {
                this.maxNlc = maxNlc;
        }

        public String getMaxNlc() {
                return maxNlc;
        }

        public String getItemDetails(){
                return itemObj.toString();
        }

        public double getRoundOfValue(String val){
                return roundTwoDecimals(Double.valueOf(val));
        }

        public String getVaildName(String name){
                return name!=null?name:"";
        }



}