Subversion Repositories SmartDukaan

Rev

Rev 11095 | Rev 14862 | 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.Item;
import in.shop2020.model.v1.catalog.MarketplaceHistory;
import in.shop2020.model.v1.catalog.MarketplaceItems;
import in.shop2020.model.v1.catalog.MarketplacePercentage;
import in.shop2020.model.v1.catalog.SnapdealItem;
import in.shop2020.model.v1.catalog.SnapdealItemDetails;
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.model.v1.order.OrderSource;
import in.shop2020.model.v1.order.SnapdealOrder;
import in.shop2020.support.utils.ReportsUtils;
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.google.gson.Gson;
import com.opensymphony.xwork2.ValidationAwareSupport;

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

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

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


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


    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;
    private ServletContext context;
    private String url;
    private String itemId;
    private String isSnapdealListed;
    private String exceptionPrice;
    private String warehouseId;
    private File file;
    private String errMsg;
    private String next;
    private String id;
    private String searchText;
    private List<SnapdealItemDetails> snapdealItems;
    private long searchCount;
    private long totalCount;
    private String sellingPrice;
    private String transferPrice;
    private String webisteMrp;
    private String webisteSellingPrice;
    private String isListedOnSnapdeal;
    private String commission;
    private String serviceTax;
    private String courierCost;
    private JSONObject itemObj;
    private String isSuppressInventoryFeed;
    private String isSuppressPriceFeed;
    private String maxNlc;
    private String sdItemCode;
    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 static String live;
    private List<MarketplaceHistory> compData;
    private String productName;
    private String startDate;
    private String endDate;
    private String courierCostMarketplace;
    private String packagingCost;


    public String courierCostMarketplace() {
        return courierCostMarketplace;
    }

    public void setCourierCostMarketplace(String courierCostMarketplace) {
        this.courierCostMarketplace = courierCostMarketplace;
    }

    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 setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }

    public String getEndDate() {
        return endDate;
    }

    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 getSdItemCode() {
        return sdItemCode;
    }

    public void setSdItemCode(String sdItemCode) {
        this.sdItemCode = sdItemCode;
    }


    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) {
            snapdealItems = CatalogClient.getSnapdealItems(Long.valueOf(next), 10);
            totalCount = CatalogClient.getCountForSnapdealItems();
            setSearchCount(totalCount);
        } else {
            List<String> subString = Arrays.asList(searchText.split(" "));
            snapdealItems = CatalogClient.searchSnapdealItems(subString,Long.valueOf(next), 10);
            totalCount = CatalogClient.getCountForSnapdealItems();
            searchCount = CatalogClient.getSnapdealSearchResultCount(subString);
        }
        return "snapdeal-item-table";
    }

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

    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), 7);
        lastCheckedTimeStampForItem(mpItemDetails.getLastCheckedTimestamp());
        return mpItemDetails;
    }

    public String getDate(long timestamp){
        return new java.util.Date(timestamp).toLocaleString();

    }

    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 "snapdeal-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();
        Long timestamp = System.currentTimeMillis();
        SnapdealItem snapdealItem = catalogClient.getSnapdealItem(Long.valueOf(itemId));
        boolean toUpdate = false;
        if (snapdealItem.getSellingPrice()!=Double.valueOf(sellingPrice) || snapdealItem.isIsListedOnSnapdeal()!=Boolean.valueOf(isListedOnSnapdeal) || snapdealItem.isSuppressPriceFeed()!=Boolean.valueOf(isSuppressPriceFeed)){
            toUpdate=true;
        }
        Item item = catalogClient.getItem(Long.valueOf(itemId));
        MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(7, Long.valueOf(itemId));
        if (mpCosting.getSource()==0){
            throw new CatalogServiceException();
        }
        MarketplaceItems mpItem = catalogClient.getMarketplacedetailsForItem(Long.valueOf(itemId),7);
        mpItem.setEmiFee(mpCosting.getEmiFee());
        mpItem.setReturnProvision(mpCosting.getReturnProvision());
        mpItem.setClosingFee(mpCosting.getClosingFee());
        mpItem.setServiceTax(mpCosting.getServiceTax());
        mpItem.setCommission(mpCosting.getCommission());
        mpItem.setPgFee(mpCosting.getPgFee());
        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();
                }*/
        snapdealItem.setWarehouseId(Long.valueOf(warehouseId));
        snapdealItem.setIsListedOnSnapdeal(Boolean.valueOf(isListedOnSnapdeal));
        snapdealItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
        snapdealItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
        snapdealItem.setTransferPrice(Double.valueOf(transferPrice));
        snapdealItem.setExceptionPrice(Double.valueOf(exceptionPrice));
        snapdealItem.setSellingPrice(Double.valueOf(sellingPrice));
        snapdealItem.setCourierCost(Double.valueOf(courierCost));
        snapdealItem.setCommission(Double.valueOf(commission));
        snapdealItem.setServiceTax(Double.valueOf(serviceTax));
        snapdealItem.setMaxNlc(Double.valueOf(maxNlc));
        snapdealItem.setSkuAtSnapdeal(sdItemCode);
        snapdealItem.setSupc(supc);
        snapdealItem.setCourierCostMarketplace(Double.valueOf(courierCostMarketplace));
        MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
        //double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
        //t_mpItem.setVat(vat);
        t_mpItem.setCourierCostMarketplace(Double.valueOf(courierCostMarketplace));
        snapdealItem.setUpdatedBy(getUserName());
        snapdealItem.setMarketplaceItems(t_mpItem);

        if(!compareParameters(t_mpItem,snapdealItem,warehouse,item.getWeight(),item.getCategory())){
            setComparsionResult("0");
            return "snapdeal-update-result";
        }
        else{
            setComparsionResult("1");
        }

        if(!catalogClient.addOrUpdateSnapdealItem(snapdealItem)){
            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) && (!snapdealItem.isSuppressPriceFeed()) && snapdealItem.isIsListedOnSnapdeal()){
            logger.info("Calling Method to update price at snapdeal");
            UpdateSDPricingUsingPanel updatePriceOnSnapdeal = new UpdateSDPricingUsingPanel(Float.valueOf(sellingPrice),supc,item,timestamp);
            logger.info("Calling Thread to update price at snapdeal");
            updatePriceOnSnapdeal.start();      
        }
        return "snapdeal-update-result";
    }


    public void updateForAutoPricing() throws NumberFormatException, CatalogServiceException, TException{
        logger.info("Calling Method to update price at snapdeal for auto pricing");
        Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        Item item = catalogClient.getItem(Long.valueOf(itemId));
        UpdateSDPricingUsingPanel updatePriceOnSnapdeal = new UpdateSDPricingUsingPanel(Float.valueOf(sellingPrice),supc,item,System.currentTimeMillis());
        logger.info("Calling Thread to update price at snapdeal for auto pricing");
        updatePriceOnSnapdeal.start();  
    }


    public boolean compareParameters(MarketplaceItems mpItem, SnapdealItem snapdealItem, Warehouse warehouse,double weight, Long categoryId) throws TException, JSONException, CatalogServiceException{
        double nlc =getNlcForWarehouse(snapdealItem.getWarehouseId(),snapdealItem.getItem_id());
        double vat = (snapdealItem.getSellingPrice()/(1+(mpItem.getVat()/100))-(nlc/(1+(mpItem.getVat()/100))))*(mpItem.getVat()/100);
        double inHouseCost = mpItem.getPackagingCost()+vat+(mpItem.getReturnProvision()/100)*snapdealItem.getSellingPrice()+mpItem.getOtherCost();
        double lowest_possible_tp = nlc+inHouseCost;
        double our_tp =  snapdealItem.getSellingPrice()- snapdealItem.getSellingPrice()*((mpItem.getCommission()/100)+mpItem.getEmiFee()/100)*(1+(mpItem.getServiceTax()/100))-(snapdealItem.getCourierCostMarketplace()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100))-(Math.max(20,(mpItem.getPgFee()/100)*snapdealItem.getSellingPrice())*(1+(mpItem.getServiceTax()/100)));
        double commission=0.0;
        if ((mpItem.getPgFee()/100)*snapdealItem.getSellingPrice()>=20){
            commission =  (((mpItem.getCommission()/100)+mpItem.getPgFee()/100)*snapdealItem.getSellingPrice());
        }
        else{
            commission =  ((mpItem.getCommission()/100)*snapdealItem.getSellingPrice()+20);
        }
        double service_tax = (mpItem.getServiceTax()/100)*(snapdealItem.getCommission()+snapdealItem.getCourierCostMarketplace());
        double lowest_possible_sp = 0.0;
        if ((mpItem.getPgFee()/100)*snapdealItem.getSellingPrice()>=20){
            lowest_possible_sp = (nlc+(snapdealItem.getCourierCostMarketplace()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat()/100))+(mpItem.getPackagingCost()+mpItem.getOtherCost())*(1+(mpItem.getVat())/100))/(1-((mpItem.getCommission()/100)+mpItem.getEmiFee()/100+mpItem.getPgFee()/100)*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat())/100)-(mpItem.getReturnProvision()/100)*(1+(mpItem.getVat())/100));
        }
        else{
            lowest_possible_sp = (nlc+(snapdealItem.getCourierCostMarketplace()+mpItem.getClosingFee()+20)*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat()/100))+(mpItem.getPackagingCost()+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,snapdealItem.getSellingPrice(),snapdealItem.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("Snapdeal Backend validation "+x.toString());
        boolean compare_result=true;

        if(!(mpItem.getPackagingCost()==computePackagingCost(categoryId))){
            compare_result=false;
        }

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

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

        if(!(nlc==snapdealItem.getMaxNlc())){
            compare_result=false;
        }
        if(!(lowest_possible_tp-mpItem.getMinimumPossibleTp()>-1 && lowest_possible_tp-mpItem.getMinimumPossibleTp()<1)){
            compare_result=false;
        }
        if(!(our_tp-snapdealItem.getTransferPrice()>-1 && our_tp-snapdealItem.getTransferPrice()<1)){
            compare_result=false;
        }
        if(!(commission-snapdealItem.getCommission()>-1 && commission-snapdealItem.getCommission()<1)){
            compare_result=false;
        }
        if(!(service_tax-snapdealItem.getServiceTax()>-1 && service_tax-snapdealItem.getServiceTax()<1)){
            compare_result=false;
        }
        if(!(lowest_possible_sp-mpItem.getMinimumPossibleSp()>-1 && lowest_possible_sp-mpItem.getMinimumPossibleSp()<1)){
            compare_result=false;
        }
        return compare_result;

    }

    private double computePackagingCost(Long categoryId) {
        double pc = 15.0;
        if (categoryId==10006 || categoryId==10010){
            pc =pc + 43.0;
        }
        return pc;
    }

    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 = 45.0;
        int slabs = (int) ((weight+.05 - .001)/(.5));
        for(int i=0;i<slabs;i++){
            cCost = cCost + 35;
        }
        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), 7, 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(7);
        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="Snapdeal 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(7, 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();
                }*/
        SnapdealItem snapdealItem = new SnapdealItem();
        snapdealItem.setItem_id(Long.valueOf(itemId));
        snapdealItem.setWarehouseId(Long.valueOf(warehouseId));
        snapdealItem.setIsListedOnSnapdeal(Boolean.valueOf(isListedOnSnapdeal));
        snapdealItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
        snapdealItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
        snapdealItem.setTransferPrice(Double.valueOf(transferPrice));
        snapdealItem.setExceptionPrice(Double.valueOf(exceptionPrice));
        snapdealItem.setSellingPrice(Double.valueOf(sellingPrice));
        snapdealItem.setCourierCost(Double.valueOf(courierCost));
        snapdealItem.setCommission(Double.valueOf(commission));
        snapdealItem.setServiceTax(Double.valueOf(serviceTax));
        snapdealItem.setMaxNlc(Double.valueOf(maxNlc));
        snapdealItem.setSkuAtSnapdeal(sdItemCode);
        snapdealItem.setSupc(supc);
        snapdealItem.setUpdatedBy(getUserName());
        snapdealItem.setCourierCostMarketplace(Double.valueOf(courierCostMarketplace));

        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());
        t_mpItem.setPgFee(mpCosting.getPgFee());
        t_mpItem.setCourierCostMarketplace(Double.valueOf(courierCostMarketplace));
        t_mpItem.setPackagingCost(Double.valueOf(packagingCost));
        if(!compareParameters(t_mpItem,snapdealItem,warehouse,item.getWeight(),item.getCategory())){
            setComparsionResult("0");
            return "snapdeal-update-result";
        }
        else{
            setComparsionResult("1");
        }
        snapdealItem.setMarketplaceItems(t_mpItem);
        Long timestamp = System.currentTimeMillis();
        boolean result = catalogClient.addOrUpdateSnapdealItem(snapdealItem);
        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(live) && (!snapdealItem.isSuppressPriceFeed()) && snapdealItem.isIsListedOnSnapdeal()){
            logger.info("Calling Method to update new item price at snapdeal");
            UpdateSDPricingUsingPanel updatePriceOnSnapdeal = new UpdateSDPricingUsingPanel(Float.valueOf(sellingPrice),supc,item,timestamp);
            logger.info("Calling Thread to update new item price at snapdeal");
            updatePriceOnSnapdeal.start();
        }
        return "snapdeal-update-result";
    }


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

    /*public String getCompetitionAnalyis() throws NumberFormatException, TException{
            Client cc = new CatalogClient().getClient();
            compData = cc.getMarketplaceHistory(7, 0, Long.valueOf(itemId));
            //Gson gson = new Gson();
            //competitionJson = gson.toJson(compData);
            return "competition-details";

        }*/

    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();
        SnapdealItem snapdealItem = catalogClient.getSnapdealItem(Long.valueOf(itemId));
        MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(7, Long.valueOf(itemId));
        if (snapdealItem.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());
        itemObj.put("PgFee", mpCosting.getPgFee());
        itemObj.put("PackagingCost", computePackagingCost(item.getCategory()));
        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),7);
    }

    public void downloadSnapdealListings() throws IOException, TException{
        File file = new File("/tmp/snapdeal-bulk-upload-template.xls");
        HSSFWorkbook hwb=new HSSFWorkbook();
        HSSFSheet sheet =  hwb.createSheet("Snapdeal-Listings");
        HSSFRow rowhead=   sheet.createRow((short)0);
        rowhead.createCell((short) 0).setCellValue("ITEM-ID");
        rowhead.createCell((short) 1).setCellValue("PRODUCT");
        rowhead.createCell((short) 2).setCellValue("WAREHOUSE-ID");
        rowhead.createCell((short) 3).setCellValue("EXCEPTIONAL-PRICE");
        rowhead.createCell((short) 4).setCellValue("SNAPDEAL-LISTED");
        rowhead.createCell((short) 5).setCellValue("TRANSFER-PRICE");
        rowhead.createCell((short) 6).setCellValue("SELLING-PRICE");
        rowhead.createCell((short) 7).setCellValue("LOWEST POSSIBLE SP");
        rowhead.createCell((short) 8).setCellValue("LOWEST POSSIBLE TP");
        rowhead.createCell((short) 9).setCellValue("OTHER COST");
        rowhead.createCell((short) 10).setCellValue("COURIER-COST");
        rowhead.createCell((short) 11).setCellValue("COURIER-COST-Snapdeal");
        rowhead.createCell((short) 12).setCellValue("COMMISION");
        rowhead.createCell((short) 13).setCellValue("SERVICE-TAX");
        rowhead.createCell((short) 14).setCellValue("Suppress Inventory Feed");
        rowhead.createCell((short) 15).setCellValue("Suppress Price Feed");
        rowhead.createCell((short) 16).setCellValue("AUTO FAVOURITE");
        rowhead.createCell((short) 17).setCellValue("MANUAL FAVOURITE");
        rowhead.createCell((short) 18).setCellValue("AUTO INCREMENT");
        rowhead.createCell((short) 19).setCellValue("AUTO DECREMENT");
        rowhead.createCell((short) 20).setCellValue("Max NLC");
        rowhead.createCell((short) 21).setCellValue("SKU @ Snapdeal");
        rowhead.createCell((short) 22).setCellValue("SUPC");
        Client catalogClient = null;
        List<SnapdealItem> snapdealItems = null;
        try {
            catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
            snapdealItems = catalogClient.getAllSnapdealMarketplaceItem();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int iterator=1;
        Item item;
        MarketplaceItems marketplaceItem;
        for(SnapdealItem snapdealItem:snapdealItems){
            marketplaceItem = snapdealItem.getMarketplaceItems();
            item = snapdealItem.getItem();
            HSSFRow row = sheet.createRow((short)iterator);
            row.createCell((short) 0).setCellValue(snapdealItem.getItem_id());
            row.createCell((short) 1).setCellValue(getVaildName(item.getBrand())+" "+getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor()));
            row.createCell((short) 2).setCellValue(snapdealItem.getWarehouseId());
            row.createCell((short) 3).setCellValue(roundTwoDecimals(snapdealItem.getExceptionPrice()));
            if(snapdealItem.isIsListedOnSnapdeal()){
                row.createCell((short) 4).setCellValue(1);
            }
            else{
                row.createCell((short) 4).setCellValue(0);
            }
            row.createCell((short) 5).setCellValue(roundTwoDecimals(snapdealItem.getTransferPrice()));
            row.createCell((short) 6).setCellValue(roundTwoDecimals(snapdealItem.getSellingPrice()));
            row.createCell((short) 7).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleSp()));
            row.createCell((short) 8).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleTp()));
            row.createCell((short) 9).setCellValue(roundTwoDecimals(marketplaceItem.getOtherCost()));
            row.createCell((short) 10).setCellValue(snapdealItem.getCourierCost());
            row.createCell((short) 11).setCellValue(snapdealItem.getCourierCostMarketplace());
            row.createCell((short) 12).setCellValue(roundTwoDecimals(snapdealItem.getCommission()));
            row.createCell((short) 13).setCellValue(roundTwoDecimals(snapdealItem.getServiceTax()));
            if(snapdealItem.isSuppressInventoryFeed()){
                row.createCell((short) 14).setCellValue(1);
            }
            else{
                row.createCell((short) 14).setCellValue(0);
            }
            if(snapdealItem.isSuppressPriceFeed()){
                row.createCell((short) 15).setCellValue(1);
            }
            else{
                row.createCell((short) 15).setCellValue(0);
            }
            if(marketplaceItem.isAutoFavourite()){
                row.createCell((short) 16).setCellValue(1);
            }
            else{
                row.createCell((short) 16).setCellValue(0);
            }
            if(marketplaceItem.isManualFavourite()){
                row.createCell((short) 17).setCellValue(1);
            }
            else{
                row.createCell((short) 17).setCellValue(0);
            }
            if(marketplaceItem.isAutoIncrement()){
                row.createCell((short) 18).setCellValue(1);
            }
            else{
                row.createCell((short) 18).setCellValue(0);
            }
            if(marketplaceItem.isAutoDecrement()){
                row.createCell((short) 19).setCellValue(1);
            }
            else{
                row.createCell((short) 19).setCellValue(0);
            }
            row.createCell((short) 20).setCellValue(snapdealItem.getMaxNlc());
            row.createCell((short) 21).setCellValue(snapdealItem.getSkuAtSnapdeal());
            row.createCell((short) 22).setCellValue(snapdealItem.getSupc());
            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=\"Snapdeal-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 uploadsnapdealBulkSheet() throws IOException, TException, NumberFormatException, InventoryServiceException, CatalogServiceException{
        File fileToCreate = new File("/tmp/", "Snapdeal-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;
            }
            SnapdealItem snapdealItem = 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();
                snapdealItem = catalogClient.getSnapdealItem(sku);
                mpCosting = catalogClient.getCostingForMarketplace(7, sku);
                marketplaceItem  = catalogClient.getMarketplacedetailsForItem(sku, 7);
                marketplaceItem.setItemId(sku);
                marketplaceItem.setSource(7);
                marketplaceItem.setCommission(mpCosting.getCommission());
                marketplaceItem.setServiceTax(mpCosting.getServiceTax());
                marketplaceItem.setReturnProvision(mpCosting.getReturnProvision());
                marketplaceItem.setEmiFee(mpCosting.getEmiFee());
                marketplaceItem.setClosingFee(mpCosting.getClosingFee());
                marketplaceItem.setPgFee(mpCosting.getPgFee());

                try {
                    item = catalogClient.getItem(sku);
                    marketplaceItem.setPackagingCost(computePackagingCost(item.getCategory()));
                    if (item.getId()==0){
                        sb.append(sku + " Item not valid"+"\n");
                        continue;
                    }
                } catch (CatalogServiceException e) {
                    sb.append(sku + " Item not valid"+"\n");
                    continue;
                }
                if(snapdealItem.getItem_id()==0){
                    new_item = true;
                    snapdealItem = new SnapdealItem();
                    snapdealItem.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;
                }
                snapdealItem.setWarehouseId(warehouseId);
                snapdealItem.setMaxNlc(maxNLC);
            }

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

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

            double transferPrice = 0,sellingPrice,commission,courierCost =45,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;
                }
                snapdealItem.setSellingPrice(sellingPrice);
                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){
                    snapdealItem.setSuppressPriceFeed(true);
                }
                if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
                    snapdealItem.setSuppressPriceFeed(false);
                }
            }

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

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

            if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
                sheet.getRow(iterator).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
                String snapdealItemCode = sheet.getRow(iterator).getCell(8).getStringCellValue();
                if (snapdealItemCode.length()==0 && new_item){
                    sb.append(sku + " New Item -  SKU@Snapdeal cannot be empty"+"\n");
                    continue;
                }
                snapdealItem.setSkuAtSnapdeal(snapdealItemCode);
            }

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

            if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
                sheet.getRow(iterator).getCell(9).setCellType(Cell.CELL_TYPE_STRING);
                String supc = sheet.getRow(iterator).getCell(9).getStringCellValue();
                if (supc.length()==0 && new_item){
                    sb.append(sku + "  New Item -  SUPC code cannot be empty"+"\n");
                    continue;
                }
                snapdealItem.setSupc(supc);
            }
            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 + 35;
                }
            }

            warehouse = inventoryClient.getWarehouse(snapdealItem.getWarehouseId());
            snapdealItem.setCourierCost(courierCost);
            marketplaceItem.setCourierCost(courierCost);
            if (new_item){
                snapdealItem.setCourierCostMarketplace(courierCost);
                marketplaceItem.setCourierCostMarketplace(courierCost);
            }
            transferPrice = roundTwoDecimals(snapdealItem.getSellingPrice()- snapdealItem.getSellingPrice()*((marketplaceItem.getCommission()/100)+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))-(snapdealItem.getCourierCostMarketplace()+marketplaceItem.getClosingFee())*(1+(marketplaceItem.getServiceTax()/100))-(Math.max(20,(marketplaceItem.getPgFee()/100)*snapdealItem.getSellingPrice())*(1+(marketplaceItem.getServiceTax()/100))));
            snapdealItem.setTransferPrice(transferPrice);
            marketplaceItem.setCurrentTp(transferPrice);
            if ((marketplaceItem.getPgFee()/100)*snapdealItem.getSellingPrice()>=20){
                commission =  (((marketplaceItem.getCommission()/100)+marketplaceItem.getPgFee()/100)*snapdealItem.getSellingPrice());
            }
            else{
                commission =  ((marketplaceItem.getCommission()/100)*snapdealItem.getSellingPrice()+20);
            }
            commission = roundTwoDecimals(commission);
            snapdealItem.setCommission(commission);
            serviceTax = roundTwoDecimals((marketplaceItem.getServiceTax()/100)*(snapdealItem.getCommission()+snapdealItem.getCourierCostMarketplace())); 
            snapdealItem.setServiceTax(serviceTax);
            double vatRate = catalogClientProd.getVatPercentageForItem(snapdealItem.getItem_id(),warehouse.getStateId(),snapdealItem.getSellingPrice());
            marketplaceItem.setVat(vatRate);
            double vat = roundTwoDecimals((snapdealItem.getSellingPrice()/(1+(marketplaceItem.getVat()/100))-(snapdealItem.getMaxNlc()/(1+(marketplaceItem.getVat()/100))))*(marketplaceItem.getVat()/100));
            double inHouseCost = roundTwoDecimals(marketplaceItem.getPackagingCost()+vat+(marketplaceItem.getReturnProvision()/100)*snapdealItem.getSellingPrice()+marketplaceItem.getOtherCost());
            double lowest_possible_tp = roundTwoDecimals(snapdealItem.getMaxNlc()+inHouseCost);
            marketplaceItem.setMinimumPossibleTp(lowest_possible_tp);
            double lowest_possible_sp=0.0;
            if ((marketplaceItem.getPgFee()/100)*snapdealItem.getSellingPrice()>=20){
                lowest_possible_sp = roundTwoDecimals((snapdealItem.getMaxNlc()+(snapdealItem.getCourierCostMarketplace()+marketplaceItem.getClosingFee())*(1+marketplaceItem.getServiceTax()/100)*(1+(marketplaceItem.getVat()/100))+(marketplaceItem.getPackagingCost()+marketplaceItem.getOtherCost())*(1+(marketplaceItem.getVat())/100))/(1-((marketplaceItem.getCommission()/100)+marketplaceItem.getEmiFee()/100+marketplaceItem.getPgFee()/100)*(1+(marketplaceItem.getServiceTax()/100))*(1+(marketplaceItem.getVat())/100)-(marketplaceItem.getReturnProvision()/100)*(1+(marketplaceItem.getVat())/100)));
            }
            else{
                lowest_possible_sp = roundTwoDecimals((snapdealItem.getMaxNlc()+(snapdealItem.getCourierCostMarketplace()+marketplaceItem.getClosingFee()+20)*(1+marketplaceItem.getServiceTax()/100)*(1+(marketplaceItem.getVat()/100))+(marketplaceItem.getPackagingCost()+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);
            snapdealItem.setUpdatedBy(updatedBy);
            snapdealItem.setMarketplaceItems(marketplaceItem);
            //logger.info(snapdealItem.toString());
            if(!catalogClient.addOrUpdateSnapdealItem(snapdealItem)){
                sb.append(sku + " Service Error\n");
            }   
        }
        File file = new File("/tmp/snapdealbulk");
        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, "snapdeal-options")){
            return "snapdeal-options";
        }

        if (StringUtils.equals(id, "competition-analysis")){
            //setAnalysisData(Long.valueOf(itemId));

            return "competition-details";
        }

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

        return "id";
    }

    //  public void setAnalysisData(long itemId){
    //        try {
    //            Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
    //            compData = cc.getMarketplaceHistory(7, 0, itemId);
    //        } catch (Exception e) {
    //            // TODO Auto-generated catch block
    //            logger.error("Unable to set analysis data for itemId "+itemId +" "+e);
    //        }
    //        //Gson gson = new Gson();
    //        //competitionJson = gson.toJson(compData);
    //        
    //  }

    public String getCountForCompetitionData(String itemId) throws TException, NumberFormatException, CatalogServiceException{
        Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
        Item item = cc.getItem(Long.valueOf(itemId));
        setProductName(getVaildName(item.getBrand())+" "+getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor()));
        return String.valueOf(cc.getCountForMarketplaceHistory(7, Long.valueOf(itemId)));
    }

    public void setProductName(String productName){
        this.productName = productName;
    }

    public String getProductName(){
        return productName;
    }


    public String fetchCompetitionData(){
        try {
            Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
            compData = cc.getMarketplaceHistory(7, Long.valueOf(next), Long.valueOf(itemId));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Unable to set analysis data for itemId "+itemId +" "+e);
        }
        return "snapdeal-competition-table";

    }

    public String fetchCompetitionDataTest(){
        try {
            Client cc = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
            compData = cc.getMarketplaceHistoryByDate(7, Long.valueOf(startDate), Long.valueOf(endDate),999999L,999999L,Long.valueOf(itemId));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.error("Unable to set analysis data for itemId "+itemId +" "+e);
        }
        return "snapdeal-duplicate-records";

    }


    public List<MarketplaceHistory> getAnalysisData() {
        return compData;
    }

    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 getIsSnapdealListed() {
        return isSnapdealListed;
    }

    public void setIsSnapdealListed(String isSnapdealListed) {
        this.isSnapdealListed = isSnapdealListed;
    }

    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<SnapdealItemDetails> getSnapdealItems(){
        return snapdealItems;
    }

    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 setIsListedOnSnapdeal(String isListedOnSnapdeal) {
        this.isListedOnSnapdeal = isListedOnSnapdeal;
    }

    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 getIsListedOnSnapdeal() {
        return isListedOnSnapdeal;
    }

    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:"";
    }

    public String getPackagingCost() {
        return packagingCost;
    }

    public void setPackagingCost(String packagingCost) {
        this.packagingCost = packagingCost;
    }

}