Subversion Repositories SmartDukaan

Rev

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

package com.amazonaws.mws.samples;

import in.shop2020.model.v1.catalog.Amazonlisted;
import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;
import in.shop2020.model.v1.order.AmazonFCWarehouseLocation;
import in.shop2020.model.v1.order.AmazonFbaSalesSnapshot;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.utils.GmailUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.Map.Entry;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.commons.io.IOUtils;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import au.com.bytecode.opencsv.CSVReader;

import com.amazonaws.mws.MarketplaceWebService;
import com.amazonaws.mws.MarketplaceWebServiceClient;
import com.amazonaws.mws.MarketplaceWebServiceConfig;
import com.amazonaws.mws.MarketplaceWebServiceException;
import com.amazonaws.mws.model.AmazonEnvelope;
import com.amazonaws.mws.model.FulfillmentData;
import com.amazonaws.mws.model.GetReportListRequest;
import com.amazonaws.mws.model.GetReportRequest;
import com.amazonaws.mws.model.IdList;
import com.amazonaws.mws.model.Message;
import com.amazonaws.mws.model.Order;
import com.amazonaws.mws.model.RequestReportRequest;

import com.amazonaws.mws.samples.Consumer;

public class FetchAmazonXMLSalesSnapshot{
        public static void main(String... args){
                /************************************************************************
                 * Access Key ID and Secret Access Key ID, obtained from:
                 * http://aws.amazon.com
                 ***********************************************************************/
                final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
                final String secretAccessKey = "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";

                final String appName = "Test";
                final String appVersion = "1.0";
                final String merchantId = "AF6E3O0VE0X4D";

                MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();

                /************************************************************************
                 * Uncomment to set the appropriate MWS endpoint.
                 ************************************************************************/
                // US
                // config.setServiceURL("https://mws.amazonservices.com");
                // UK
                // config.setServiceURL("https://mws.amazonservices.co.uk");
                // Germany
                // config.setServiceURL("https://mws.amazonservices.de");
                // France
                // config.setServiceURL("https://mws.amazonservices.fr");
                // Italy
                // config.setServiceURL("https://mws.amazonservices.it");
                // Japan
                // config.setServiceURL("https://mws.amazonservices.jp");
                // China
                // config.setServiceURL("https://mws.amazonservices.com.cn");
                // Canada
                // config.setServiceURL("https://mws.amazonservices.ca");
                // India
                config.setServiceURL("https://mws.amazonservices.in");

                /************************************************************************
                 * You can also try advanced configuration options. Available options are:
                 *
                 *  - Signature Version
                 *  - Proxy Host and Proxy Port
                 *  - User Agent String to be sent to Marketplace Web Service
                 *
                 ***********************************************************************/

                /************************************************************************
                 * Instantiate Http Client Implementation of Marketplace Web Service        
                 ***********************************************************************/

                MarketplaceWebService service = new MarketplaceWebServiceClient(
                                accessKeyId, secretAccessKey, appName, appVersion, config);

                /************************************************************************
                 * Uncomment to try out Mock Service that simulates Marketplace Web Service 
                 * responses without calling Marketplace Web Service  service.
                 *
                 * Responses are loaded from local XML files. You can tweak XML files to
                 * experiment with various outputs during development
                 *
                 * XML files available under com/amazonaws/mws/mock tree
                 *
                 ***********************************************************************/
                // MarketplaceWebService service = new MarketplaceWebServiceMock();

                /************************************************************************
                 * Setup request parameters and uncomment invoke to try out 
                 * sample for Request Report 
                 ***********************************************************************/

                /************************************************************************
                 * Marketplace and Merchant IDs are required parameters for all 
                 * Marketplace Web Service calls.
                 ***********************************************************************/
                // marketplaces from which data should be included in the report; look at the
                // API reference document on the MWS website to see which marketplaces are
                // included if you do not specify the list yourself
                final IdList marketplaces = new IdList(Arrays.asList(
                "A21TJRUUN4KGV"));        
                RequestReportRequest orderreportrequest = new RequestReportRequest()
                .withMerchant(merchantId)
                .withMarketplaceIdList(marketplaces)
                .withReportType("_GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_")
                .withReportOptions("ShowSalesChannel=true");

                RequestReportRequest inventoryhealthreportrequest = new RequestReportRequest()
                .withMerchant(merchantId)
                .withMarketplaceIdList(marketplaces)
                .withReportType("_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_")
                .withReportOptions("ShowSalesChannel=true");

                DatatypeFactory df = null;
                try {
                        df = DatatypeFactory.newInstance();
                } catch (DatatypeConfigurationException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                }
                long ordertimediff = System.currentTimeMillis() - 7*24*60*60*1000;
                GregorianCalendar ost = new GregorianCalendar();
                ost.setTimeInMillis(ordertimediff);
                XMLGregorianCalendar  orderStartDate = df.newXMLGregorianCalendar(ost);
                XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
                System.out.println("Order Start Date  " + orderStartDate  + "Order End Date  " + orderEndDate);
                orderreportrequest.setStartDate(orderStartDate);
                orderreportrequest.setEndDate(orderEndDate);
                long inventorytimediff = System.currentTimeMillis() - 7*24*60*60*1000;
                GregorianCalendar ist = new GregorianCalendar();
        ist.setTimeInMillis(inventorytimediff);
        ist.setTimeInMillis(ordertimediff);
        XMLGregorianCalendar  inventoryStartDate = df.newXMLGregorianCalendar(ist);
        XMLGregorianCalendar inventoryEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
        System.out.println("Inventory Start Date  " + inventoryStartDate  + "Inventory End Date  " + inventoryEndDate);
                inventoryhealthreportrequest.setStartDate(inventoryStartDate);
                inventoryhealthreportrequest.setEndDate(inventoryEndDate);
                Map<String,String> requestIdreportIdmap;
                String orderreportrequestId = null;
                String inventoryhealthreportrequestId = null;
                boolean retry=true;
                int retryCount =0;
                while(retry && retryCount!=5){
                        if(retryCount==4){
                                String emailFromAddress = "build@shop2020.in";
                                String password = "cafe@nes";
                                String[] sendTo = new String[]{ "kshitij.sood@saholic.com","anikendra.das@shop2020.in"};
                                String emailSubjectTxt = "Fetch FBA Sale failure";
                                try {
                                        GmailUtils mailer = new GmailUtils();
                                        mailer.sendSSLMessage(sendTo, emailSubjectTxt, "", emailFromAddress, password,"");
                                }
                                catch (Exception ex) {
                                        ex.printStackTrace();
                                }

                                System.exit(1);
                        }
                        try {
                                orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);
                                inventoryhealthreportrequestId = RequestReportSample.invokeRequestReport(service, inventoryhealthreportrequest);
                                retry = false;
                        } catch (MarketplaceWebServiceException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                try {
                                        Thread.sleep(10*60*1000);
                                        retryCount++;
                                } catch (InterruptedException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                }
                        }
                }
                while(true){
                        GetReportListRequest requestreportlist = new GetReportListRequest();
                        requestreportlist.setMerchant( merchantId );
                        final IdList requestIdList = new IdList(Arrays.asList(orderreportrequestId,inventoryhealthreportrequestId));        
                        requestreportlist.setReportRequestIdList(requestIdList);
                        requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);
                        if(requestIdreportIdmap.get(orderreportrequestId)!=null && requestIdreportIdmap.get(inventoryhealthreportrequestId)!=null){
                                GetReportRequest requestorderreport = new GetReportRequest();
                                GetReportRequest requestinventoryhealthreport = new GetReportRequest();
                                requestorderreport.setMerchant( merchantId );
                                requestinventoryhealthreport.setMerchant(merchantId);
                                requestorderreport.setReportId( requestIdreportIdmap.get(orderreportrequestId));
                                requestinventoryhealthreport.setReportId(requestIdreportIdmap.get(inventoryhealthreportrequestId));
                                OutputStream orderreport=null;
                                OutputStream inventoryhealthreport=null;
                                try {
                                        orderreport = new FileOutputStream( "/tmp/amazonorderreport.xml" );
                                        inventoryhealthreport = new FileOutputStream( "/tmp/inventoryhealthreport.csv" );
                                } catch (FileNotFoundException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                requestorderreport.setReportOutputStream(orderreport);
                                requestinventoryhealthreport.setReportOutputStream(inventoryhealthreport);
                                GetReportSample.invokeGetReport(service, requestorderreport);
                                GetReportSample.invokeGetReport(service, requestinventoryhealthreport);
                                System.out.println("Order and Inventory Reports are ready please check");

                                String toFind = "<AmazonEnvelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"amzn-envelope.xsd\">";
                                String toReplace = "<AmazonEnvelope xmlns=\"http://mws.amazonaws.com/doc/2009-01-01/\">";
                                File orderReportFile = new File("/tmp/amazonorderreport.xml");
                                String content = "";
                                try {
                                        content = IOUtils.toString(new FileInputStream(orderReportFile));
                                } catch (FileNotFoundException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                }
                                content = content.replaceAll(toFind, toReplace);
                                try {
                                        IOUtils.write(content, new FileOutputStream(orderReportFile));
                                } catch (FileNotFoundException e1) {
                                        e1.printStackTrace();
                                } catch (IOException e1) {
                                        e1.printStackTrace();
                                }

                                JAXBContext jc = null;
                                Unmarshaller unmarshaller = null;
                                AmazonEnvelope amazonOrderData = null;
                                try {
                                        jc = JAXBContext.newInstance(AmazonEnvelope.class);
                                        unmarshaller = jc.createUnmarshaller();
                                        amazonOrderData = (AmazonEnvelope)unmarshaller.unmarshal(orderReportFile);
                                } catch (JAXBException e1) {
                                        e1.printStackTrace();
                                }

                                /*CSVReader orderreportreader = null;*/
                                CSVReader inventoryhealthreportreader = null;
                                try {
                                        /*orderreportreader = new CSVReader(new FileReader("/tmp/amazonorderreport.csv"),'\t');*/
                                        inventoryhealthreportreader = new CSVReader(new FileReader("/tmp/inventoryhealthreport.csv"),'\t');
                                } catch (FileNotFoundException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                String [] nextLine;
                                try {
                                        int count =1;
                                        Map<Date,Map<String,FbaSalesSnapshot>> orderDateItemIdFbaSaleSnapshotMap = new HashMap<Date,Map<String,FbaSalesSnapshot>>();

                                        if(amazonOrderData!=null){
                                                List<Message> orderMessageList = amazonOrderData.getMessage();
                                                System.out.println("Amazon Order List ... "+orderMessageList.size());
                                                for(Message orderMessage : orderMessageList){
                                                        Order amazonOrder = orderMessage.getOrder();
                                                        FulfillmentData orderFullfillmentData = amazonOrder.getFulfillmentData();
                                                        if("Amazon.in".equalsIgnoreCase(amazonOrder.getSalesChannel()) && "Amazon".equalsIgnoreCase(orderFullfillmentData.getFulfillmentChannel())){
                                                                SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                                                                istFormatter .setLenient(false);
                                                                TimeZone zone= TimeZone.getTimeZone("GMT");
                                                                istFormatter.setTimeZone(zone);
                                                                Date date = istFormatter.parse(amazonOrder.getPurchaseDate().toString());
                                                                SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
                                                                Date date_key = dateFormat.parse(dateFormat.format(date));
                                                                Long itemid;
                                                                AmazonFCWarehouseLocation fcLocation;
                                                                if(amazonOrder.getOrderItem().get(0).getSKU().startsWith("FBA")){
                                                                        try{
                                                                                itemid = Long.parseLong(amazonOrder.getOrderItem().get(0).getSKU().replaceAll("FBA",""));
                                                                        }
                                                                        catch(Exception ex){
                                                                                continue;
                                                                        }
                                                                        fcLocation = AmazonFCWarehouseLocation.Mumbai;
                                                                }
                                                                else if(amazonOrder.getOrderItem().get(0).getSKU().startsWith("FBB")){
                                                                        try{
                                                                                itemid = Long.parseLong(amazonOrder.getOrderItem().get(0).getSKU().replaceAll("FBB",""));
                                                                        }
                                                                        catch(Exception ex){
                                                                                continue;
                                                                        }
                                                                        fcLocation = AmazonFCWarehouseLocation.Bangalore;
                                                                }
                                                                else if(amazonOrder.getOrderItem().get(0).getSKU().startsWith("FBG")){
                                                                        try{
                                                                                itemid = Long.parseLong(amazonOrder.getOrderItem().get(0).getSKU().replaceAll("FBG",""));
                                                                        }
                                                                        catch(Exception ex){
                                                                                continue;
                                                                        }
                                                                        fcLocation = AmazonFCWarehouseLocation.Gurgaon;
                                                                }
                                                                else{
                                                                        //System.out.println("Skipping Order not FBB or FBA" + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
                                                                        continue;
                                                                }
                                                                Integer qty=0;
                                                                if(amazonOrder.getOrderItem().get(0).getQuantity()!=0){
                                                                        qty = new Integer(amazonOrder.getOrderItem().get(0).getQuantity());
                                                                }
                                                                Float itemSale = null;
                                                                if(amazonOrder.getOrderItem().get(0).getItemPrice()!=null && amazonOrder.getOrderItem().get(0).getItemPrice().getComponent()!=null && amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().size()>0){
                                                                        if(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getValue()!=0){
                                                                                itemSale = new Float(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getValue());
                                                                        }
                                                                        else{
                                                                                itemSale = (float) 0;
                                                                        }
                                                                }

                                                                else{
                                                                        itemSale = (float) 0;
                                                                }

                                                                Float itemDiscount; 
                                                                if(amazonOrder.getOrderItem().get(0).getPromotion()!=null){
                                                                        if(amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount()!=null && amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount().floatValue()!=0.0f){
                                                                                itemDiscount = amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount();
                                                                        }
                                                                        else{
                                                                                itemDiscount = new Float(0);
                                                                        }
                                                                }
                                                                else{
                                                                        itemDiscount = new Float(0);
                                                                }

                                                                if(("Cancelled").equalsIgnoreCase(amazonOrder.getOrderStatus()) || ("Cancelled").equalsIgnoreCase(amazonOrder.getOrderItem().get(0).getItemStatus())){
                                                                        itemSale = (float) 0; 
                                                                        itemDiscount = (float) 0;
                                                                        qty = 0;
                                                                        //System.out.println("Cancelled Order " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
                                                                }
                                                                if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date_key)){
                                                                        FbaSalesSnapshot fbaSalesSnapshot;
                                                                        if(orderDateItemIdFbaSaleSnapshotMap.get(date_key).containsKey(amazonOrder.getOrderItem().get(0).getSKU())){
                                                                                fbaSalesSnapshot = orderDateItemIdFbaSaleSnapshotMap.get(date_key).get(amazonOrder.getOrderItem().get(0).getSKU());
                                                                                if(itemDiscount!=0){
                                                                                        fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);
                                                                                        fbaSalesSnapshot.setTotalPromotionSale(fbaSalesSnapshot.getTotalPromotionSale() + (itemSale - itemDiscount));
                                                                                }
                                                                                fbaSalesSnapshot.setFcLocation(fcLocation);
                                                                                fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);
                                                                                fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);
                                                                                Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = orderDateItemIdFbaSaleSnapshotMap.get(date_key);
                                                                                ItemIdFbaSaleSnapshotMap.put(amazonOrder.getOrderItem().get(0).getSKU(), fbaSalesSnapshot);
                                                                                //System.out.println("Adding Order to list entry exists " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
                                                                                orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
                                                                        }
                                                                        else{
                                                                                fbaSalesSnapshot = new FbaSalesSnapshot();
                                                                                fbaSalesSnapshot.setFcLocation(fcLocation);
                                                                                fbaSalesSnapshot.setTotalOrderCount(qty);
                                                                                fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);
                                                                                if(itemDiscount!=0){
                                                                                        fbaSalesSnapshot.setPromotionOrderCount(qty);
                                                                                        fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
                                                                                }
                                                                                else{
                                                                                        fbaSalesSnapshot.setPromotionOrderCount(0);
                                                                                        fbaSalesSnapshot.setTotalPromotionSale((float) 0);
                                                                                }
                                                                                Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = orderDateItemIdFbaSaleSnapshotMap.get(date_key);
                                                                                ItemIdFbaSaleSnapshotMap.put(amazonOrder.getOrderItem().get(0).getSKU(), fbaSalesSnapshot);
                                                                                //System.out.println("Adding Order to list new entry " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
                                                                                orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
                                                                        }
                                                                }
                                                                else{
                                                                        Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<String,FbaSalesSnapshot>();
                                                                        FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
                                                                        fbaSalesSnapshot.setFcLocation(fcLocation);
                                                                        fbaSalesSnapshot.setTotalOrderCount(qty);
                                                                        fbaSalesSnapshot.setTotalSale(itemSale);
                                                                        if(itemDiscount!=0){
                                                                                fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
                                                                                fbaSalesSnapshot.setPromotionOrderCount(qty);
                                                                        }
                                                                        else{
                                                                                fbaSalesSnapshot.setTotalPromotionSale((float) 0);
                                                                                fbaSalesSnapshot.setPromotionOrderCount(0);
                                                                        }
                                                                        ItemIdFbaSaleSnapshotMap.put(amazonOrder.getOrderItem().get(0).getSKU(),fbaSalesSnapshot);
                                                                        //System.out.println("Adding Order to list date doesnt exists " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
                                                                        orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
                                                                }
                                                        }
                                                }
                                        }

                                        InventoryClient inventoryServiceClient = null;
                                        //TransactionClient transactionServiceClient = null;
                                        CatalogClient catalogServiceClient = null;
                                        try {
                                                inventoryServiceClient = new InventoryClient();
                                                //transactionServiceClient = new TransactionClient();
                                                //catalogServiceClient = new CatalogClient();
                                                catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
                                        } catch (Exception e) {
                                                e.printStackTrace();
                                        }       
                                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
                                        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
                                        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
                                        //Date date_today = dateFormat.parse(dateFormat.format(new Date()));
                                        List<Date> dates = new ArrayList<Date>();
                                        Calendar cal = Calendar.getInstance();
                                        cal.add(Calendar.DATE, -1);
                                        Date date_end = dateFormat.parse(dateFormat.format(cal.getTime()));
                                        cal.add(Calendar.DATE, -5);
                                        Date date_start = dateFormat.parse(dateFormat.format(cal.getTime()));
                                        System.out.println("Start Date = " + date_start);
                                        System.out.println("End Date = " + date_end);
                                        Date d = date_start;
                                        while(!d.equals(date_end)){
                                                cal.setTime(d);
                                                cal.add(Calendar.DATE,1);
                                                d = cal.getTime();
                                                dates.add(d);
                                        }
                                        List<AmazonFbaInventorySnapshot> fbaInventorySnapshotlist =  inventoryClient.getAllAmazonFbaItemInventory();
                                        String prefix;
                                        for(Date date:dates){
                                                if(fbaInventorySnapshotlist!=null){
                                                        for(AmazonFbaInventorySnapshot amazonFbaInventory:fbaInventorySnapshotlist){
                                                                AmazonFCWarehouseLocation location;
                                                                if(amazonFbaInventory.getLocation().getValue()==AmazonFCWarehouseLocation.Bangalore.getValue()){
                                                                        prefix = "FBB";
                                                                        location = AmazonFCWarehouseLocation.Bangalore;
                                                                }
                                                                else if(amazonFbaInventory.getLocation().getValue()==AmazonFCWarehouseLocation.Mumbai.getValue()){
                                                                        prefix = "FBA";
                                                                        location = AmazonFCWarehouseLocation.Mumbai;
                                                                }
                                                                else if(amazonFbaInventory.getLocation().getValue()==AmazonFCWarehouseLocation.Gurgaon.getValue()){
                                                                        prefix = "FBG";
                                                                        location = AmazonFCWarehouseLocation.Gurgaon;
                                                                }
                                                                
                                                                else{
                                                                        continue;
                                                                }
                                                                if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date) ){
                                                                        if(!orderDateItemIdFbaSaleSnapshotMap.get(date).containsKey(prefix+String.valueOf(amazonFbaInventory.getItem_id()))){
                                                                                Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = orderDateItemIdFbaSaleSnapshotMap.get(date);
                                                                                FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
                                                                                fbaSalesSnapshot.setTotalOrderCount(0);
                                                                                fbaSalesSnapshot.setPromotionOrderCount(0);
                                                                                fbaSalesSnapshot.setTotalPromotionSale((float) 0);
                                                                                fbaSalesSnapshot.setTotalSale((float) 0);
                                                                                fbaSalesSnapshot.setFcLocation(location);
                                                                                ItemIdFbaSaleSnapshotMap.put(prefix+String.valueOf(amazonFbaInventory.getItem_id()),fbaSalesSnapshot);
                                                                                orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
                                                                        }
                                                                }
                                                                else{
                                                                        Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<String,FbaSalesSnapshot>();
                                                                        FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
                                                                        fbaSalesSnapshot.setTotalOrderCount(0);
                                                                        fbaSalesSnapshot.setPromotionOrderCount(0);
                                                                        fbaSalesSnapshot.setTotalPromotionSale((float) 0);
                                                                        fbaSalesSnapshot.setTotalSale((float) 0);
                                                                        fbaSalesSnapshot.setFcLocation(location);
                                                                        ItemIdFbaSaleSnapshotMap.put(prefix+String.valueOf(amazonFbaInventory.getItem_id()),fbaSalesSnapshot);
                                                                        orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
                                                                }
                                                        }
                                                }
                                                else{
                                                        System.out.println("No inventory at Amazon FC");
                                                }
                                        }
                                        Map<Long,PriceAtDate> itemIdOurPriceMap = new HashMap<Long,PriceAtDate>();
                                        Map<Long,PriceAtDate> itemIdSalePriceMap = new HashMap<Long,PriceAtDate>();
                                        Map<Long,PriceAtDate> itemIdminFBAPriceMap = new HashMap<Long,PriceAtDate>();
                                        Map<Long,PriceAtDate> itemIdminMFNPriceMap = new HashMap<Long,PriceAtDate>();
                                        count=1;
                                        while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
                                                try{
                                                        if(count!=1){
                                                                //System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
                                                                SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                                                                istFormatter .setLenient(false);
                                                                TimeZone zone= TimeZone.getTimeZone("GMT");
                                                                istFormatter.setTimeZone(zone);
                                                                Date date = istFormatter.parse(nextLine[0]);
                                                                if(nextLine[1].length()> 0 && (nextLine[1].startsWith("FBA"))){
                                                                        nextLine[1] = nextLine[1].replaceAll("FBA",""); 
                                                                }
                                                                else if(nextLine[1].length()> 0 && nextLine[1].startsWith("FBB")){
                                                                        nextLine[1] = nextLine[1].replaceAll("FBB","");
                                                                }
                                                                else if(nextLine[1].length()> 0 && nextLine[1].startsWith("FBG")){
                                                                        nextLine[1] = nextLine[1].replaceAll("FBG","");
                                                                }
                                                                else{
                                                                        continue;
                                                                }
                                                                Long item_id;
                                                                try{
                                                                        item_id = Long.parseLong(nextLine[1]);
                                                                }
                                                                catch(Exception ex){
                                                                        continue;
                                                                }
                                                                Double ourPrice = null;
                                                                Double minFBAPrice= null;
                                                                Double minMFNPrice= null;
                                                                Double salePrice= null; 
                                                                if(nextLine[30].length() >0){
                                                                        ourPrice = Double.parseDouble(nextLine[30]);
                                                                        if(itemIdOurPriceMap.containsKey(item_id)){
                                                                                if(itemIdOurPriceMap.get(item_id).getDate().getTime() < date.getTime()){
                                                                                        PriceAtDate priceAtDate= new PriceAtDate();
                                                                                        priceAtDate.setDate(date);
                                                                                        priceAtDate.setPrice(ourPrice);
                                                                                        itemIdOurPriceMap.put(item_id,priceAtDate);
                                                                                }
                                                                        }
                                                                        else{   
                                                                                PriceAtDate priceAtDate= new PriceAtDate();
                                                                                priceAtDate.setDate(date);
                                                                                priceAtDate.setPrice(ourPrice);
                                                                                itemIdOurPriceMap.put(item_id,priceAtDate);
                                                                        }
                                                                }
                                                                if(nextLine[31].length() >0){
                                                                        salePrice = Double.parseDouble(nextLine[31]);
                                                                        if(itemIdSalePriceMap.containsKey(item_id) ){
                                                                                if(itemIdSalePriceMap.get(item_id).getDate().getTime() < date.getTime()){
                                                                                        PriceAtDate priceAtDate= new PriceAtDate();
                                                                                        priceAtDate.setDate(date);
                                                                                        priceAtDate.setPrice(salePrice);
                                                                                        itemIdSalePriceMap.put(item_id,priceAtDate);
                                                                                }
                                                                        }
                                                                        else{   
                                                                                PriceAtDate priceAtDate= new PriceAtDate();
                                                                                priceAtDate.setDate(date);
                                                                                priceAtDate.setPrice(salePrice);
                                                                                itemIdSalePriceMap.put(item_id,priceAtDate);
                                                                        }
                                                                }
                                                                if(nextLine[32].length() >0){
                                                                        minFBAPrice = Double.parseDouble(nextLine[32]);
                                                                        if(itemIdminFBAPriceMap.containsKey(item_id)){
                                                                                if(itemIdminFBAPriceMap.get(item_id).getDate().getTime() < date.getTime()){
                                                                                        PriceAtDate priceAtDate= new PriceAtDate();
                                                                                        priceAtDate.setDate(date);
                                                                                        priceAtDate.setPrice(minFBAPrice);
                                                                                        itemIdminFBAPriceMap.put(item_id,priceAtDate);
                                                                                }
                                                                        }
                                                                        else{   
                                                                                PriceAtDate priceAtDate= new PriceAtDate();
                                                                                priceAtDate.setDate(date);
                                                                                priceAtDate.setPrice(minFBAPrice);
                                                                                itemIdminFBAPriceMap.put(item_id,priceAtDate);
                                                                        }
                                                                }
                                                                if(nextLine[34].length() >0){
                                                                        minMFNPrice = Double.parseDouble(nextLine[34]);
                                                                        if(itemIdminMFNPriceMap.containsKey(item_id)){
                                                                                if(itemIdminMFNPriceMap.get(item_id).getDate().getTime() < date.getTime()){
                                                                                        PriceAtDate priceAtDate= new PriceAtDate();
                                                                                        priceAtDate.setDate(date);
                                                                                        priceAtDate.setPrice(minMFNPrice);
                                                                                        itemIdminMFNPriceMap.put(item_id,priceAtDate);
                                                                                }
                                                                        }
                                                                        else{   
                                                                                PriceAtDate priceAtDate= new PriceAtDate();
                                                                                priceAtDate.setDate(date);
                                                                                priceAtDate.setPrice(minMFNPrice);
                                                                                itemIdminMFNPriceMap.put(item_id,priceAtDate);
                                                                        }
                                                                }
                                                        }
                                                }
                                                catch(Exception e){
                                                        e.printStackTrace();
                                                }
                                                count++;
                                        }
                                        boolean oos;
                                        List<AmazonFbaSalesSnapshot> fbaSalesSnapShotList = new ArrayList<AmazonFbaSalesSnapshot>();
                                        for (Entry<Date, Map<String, FbaSalesSnapshot>> entry : orderDateItemIdFbaSaleSnapshotMap.entrySet()){
                                                Date orderDate = entry.getKey();
                                                AmazonFCWarehouseLocation location;
                                                Long item_id = null;
                                                for(Entry<String, FbaSalesSnapshot> entry1 :entry.getValue().entrySet()){
                                                        if(entry1.getKey().startsWith("FBA")){
                                                                location = AmazonFCWarehouseLocation.Mumbai;
                                                                try{
                                                                        item_id = Long.parseLong(entry1.getKey().replaceAll("FBA",""));
                                                                }
                                                                catch(Exception ex){
                                                                        continue;
                                                                }
                                                        }
                                                        else if(entry1.getKey().startsWith("FBB")){
                                                                location = AmazonFCWarehouseLocation.Bangalore;
                                                                try{
                                                                        item_id = Long.parseLong(entry1.getKey().replaceAll("FBB",""));
                                                                }
                                                                catch(Exception ex){
                                                                        continue;
                                                                }
                                                        }
                                                        else if(entry1.getKey().startsWith("FBG")){
                                                                location = AmazonFCWarehouseLocation.Gurgaon;
                                                                try{
                                                                        item_id = Long.parseLong(entry1.getKey().replaceAll("FBG",""));
                                                                }
                                                                catch(Exception ex){
                                                                        continue;
                                                                }
                                                        }
                                                        else{
                                                                System.out.println("Skipping Item ID " + entry1.getKey() +" date : "+orderDate);
                                                                continue;
                                                        }
                                                        List<AmazonFbaInventorySnapshot> iteminventory;
                                                        Long inventory = 0L;
                                                        try{
                                                                iteminventory = inventoryClient.getAmazonFbaItemInventory(item_id);
                                                        }
                                                        catch(TTransportException e){
                                                                inventoryClient = inventoryServiceClient.getClient();
                                                                iteminventory = inventoryClient.getAmazonFbaItemInventory(item_id);
                                                        }
                                                        for(AmazonFbaInventorySnapshot inv:iteminventory){
                                                                if(inv.getLocation().getValue()==location.getValue()){
                                                                        inventory = inv.getAvailability(); 
                                                                }
                                                        }
                                                        if(inventory==0 && entry1.getValue().getTotalOrderCount()==0){
                                                                oos=true;
                                                        }
                                                        else{
                                                                oos=false;
                                                        }
                                                        //System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
                                                        AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
                                                        amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
                                                        amazonfbasalessnapshot.setItem_id(item_id);
                                                        amazonfbasalessnapshot.setPromotionOrderCount(entry1.getValue().getPromotionOrderCount());
                                                        amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getTotalOrderCount());
                                                        amazonfbasalessnapshot.setTotalSale(entry1.getValue().getTotalSale());
                                                        amazonfbasalessnapshot.setPromotionSale(entry1.getValue().getTotalPromotionSale());
                                                        amazonfbasalessnapshot.setIsOutOfStock(oos);
                                                        if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id).getPrice()!=0){
                                                                amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id).getPrice());
                                                                amazonfbasalessnapshot.setSalePriceSnapshotDate(itemIdSalePriceMap.get(item_id).getDate().getTime());
                                                        }
                                                        else{
                                                                amazonfbasalessnapshot.setSalePrice(0.0);
                                                        }
                                                        if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id).getPrice()!=0){
                                                                amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id).getPrice());
                                                                amazonfbasalessnapshot.setSalePriceSnapshotDate(0);
                                                                amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(itemIdminMFNPriceMap.get(item_id).getDate().getTime());
                                                        }
                                                        else{
                                                                amazonfbasalessnapshot.setMinMfnPrice(0.0);
                                                                amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(0);
                                                        }
                                                        if(itemIdminFBAPriceMap.containsKey(item_id) && itemIdminFBAPriceMap.get(item_id).getPrice()!=0){
                                                                amazonfbasalessnapshot.setMinFbaPrice(itemIdminFBAPriceMap.get(item_id).getPrice());
                                                                amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(itemIdminFBAPriceMap.get(item_id).getDate().getTime());
                                                        }
                                                        else{
                                                                amazonfbasalessnapshot.setMinFbaPrice(0.0);
                                                                amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(0);
                                                        }
                                                        if(itemIdOurPriceMap.containsKey(item_id) && itemIdOurPriceMap.get(item_id).getPrice()!=0){
                                                                amazonfbasalessnapshot.setOurPrice(itemIdOurPriceMap.get(item_id).getPrice());
                                                                amazonfbasalessnapshot.setOurPriceSnapshotDate(itemIdOurPriceMap.get(item_id).getDate().getTime());
                                                        }
                                                        else{
                                                                Amazonlisted amazon_item;
                                                                try{
                                                                        amazon_item=catalogClient.getAmazonItemDetails(item_id);
                                                                }
                                                                catch(TTransportException e){
                                                                        catalogClient   = catalogServiceClient.getClient();
                                                                        amazon_item=catalogClient.getAmazonItemDetails(item_id);
                                                                }
                                                                if(amazon_item.getItemid()==0){
                                                                        //System.out.println("Skipping Item ID listing not present" + entry1.getKey() +" date : "+orderDate);
                                                                        continue;
                                                                }
                                                                amazonfbasalessnapshot.setOurPrice(amazon_item.getFbaPrice());
                                                                amazonfbasalessnapshot.setOurPriceSnapshotDate(0);
                                                        }
                                                        amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
                                                        amazonfbasalessnapshot.setFcLocation(entry1.getValue().getFcLocation());
                                                        if(item_id==12530L){
                                                                System.out.println("Item ID " + amazonfbasalessnapshot.getItem_id()+" "
                                                                                +"Order Count " + amazonfbasalessnapshot.getTotalOrderCount()+" "
                                                                                +"Order Date " + new Date(amazonfbasalessnapshot.getDateOfSale())+" "+"Location "+amazonfbasalessnapshot.getFcLocation()+"\n");
                                                        }
                                                        fbaSalesSnapShotList.add(amazonfbasalessnapshot);
                                                }
                                        }
                                        System.out.println("Order Details to be Updated Size... "+fbaSalesSnapShotList.size());
                                        boolean tryagain = true;
                                        while(tryagain){
                                                try{
                                                        Consumer.bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
                                                        tryagain=false;
                                                }
                                                catch(Exception ex){
                                                }
                                        }
                                } catch (IOException e) {
                                        e.printStackTrace();
                                } catch (ParseException e) {
                                        e.printStackTrace(); 
                                } catch (TException e) {
                                        e.printStackTrace();
                                }
                                break;
                        }
                        else{ 
                                System.out.println("Report not ready.Sleeping for two minutes.");
                                try {
                                        Thread.sleep(2*60*1000);
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                        }
                }

                // Note that depending on the type of report being downloaded, a report can reach 
                // sizes greater than 1GB. For this reason we recommend that you _always_ program to
                // MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
                // the in-memory size limit and have to re-work your solution.
                //


        }



}