Subversion Repositories SmartDukaan

Rev

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

package com.amazonaws.mws.samples;

import in.shop2020.thrift.clients.HelperClient;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;


import org.apache.log4j.Logger;

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.GetReportListRequest;
import com.amazonaws.mws.model.GetReportRequest;
import com.amazonaws.mws.model.IdList;
import com.amazonaws.mws.model.RequestReportRequest;
import com.amazonaws.mws.samples.GetReportSample;

public class FeedbackRequestEmailSender {
        protected static Logger log = Logger.getLogger(FeedbackRequestEmailSender.class);

        public RequestReportRequest getReportRequest(String merchantId, IdList marketplaces, String reporttype, String reportOptions, XMLGregorianCalendar startDate, XMLGregorianCalendar endDate){
                System.out.println("In method of getting Report Request");
                RequestReportRequest reqReportRequest = new RequestReportRequest()
                .withMerchant(merchantId)
                .withMarketplaceIdList(marketplaces)
                .withReportType(reporttype)
                .withReportOptions(reportOptions);
                reqReportRequest.setStartDate(startDate);
                reqReportRequest.setEndDate(endDate);
                System.out.println("Got Report Request");
                return reqReportRequest;
        }
        
        public String getReportRequestId(MarketplaceWebService webservice, RequestReportRequest reqReportRequest){
                System.out.println("In method of getting Report Request Id");
                String requestReportRequestId = null;
                while(true){
                        try {
                                requestReportRequestId = RequestReportSample.invokeRequestReport(webservice, reqReportRequest);
                                break;
                        } catch (MarketplaceWebServiceException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        }
                }
                System.out.println("Got Report Request Id");
                System.out.println(requestReportRequestId);
                System.out.println("requestReportRequestId success");
                return requestReportRequestId;
        }
        
        
         public Map<String,String> getrequestReportIdmap(String merchantId, MarketplaceWebService webservice, String requestReportRequestId){
                 System.out.println("In method of getting Report Request Id Map");
                 Map<String,String> requestReportIdmap;
        whileLoop:while(true){
                     GetReportListRequest requestShipmentReportList = new GetReportListRequest();
                         requestShipmentReportList.setMerchant( merchantId );
        
                         final IdList shipmentReportRequestIdList = new IdList(Arrays.asList(requestReportRequestId));        
                         requestShipmentReportList.setReportRequestIdList(shipmentReportRequestIdList);
                         
                         requestReportIdmap = GetReportListSample.invokeGetReportList(webservice, requestShipmentReportList);
                        
                         if(requestReportIdmap.get(requestReportRequestId)!=null){
                                 break whileLoop;
                         }
                         else{ 
                                log.info("Report not ready\n");
                                try {
                                        Thread.sleep(5*60*1000);
                                } catch (InterruptedException e) {
                                        System.out.println("Error During getting Map Response");
                                        log.error("Error During getting Response :- ", e);
                                }
                         }
                 }
                 System.out.println("Got Report Request Id Map");
                 return requestReportIdmap;
         }
        
        public void writeReportLocally(MarketplaceWebService webservice, String merchantId, String reportId, String filePath, String reportType){
                System.out.println("In method of writting Report");
                GetReportRequest requestReport = new GetReportRequest();
                requestReport.setMerchant( merchantId );                

                requestReport.setReportId(reportId);
                OutputStream report=null;
                try {
                        report = new FileOutputStream(filePath);
                } catch (FileNotFoundException e) {
                        log.error("Error Getting Shipment Report :- ", e);
                }
                requestReport.setReportOutputStream( report );
                GetReportSample.invokeGetReport(webservice, requestReport);

                System.out.println(reportType +" Report ready please check");
        }
        
        public CSVReader getReportReader(String filePath, String reportType){
                System.out.println("In method of getting report reader");
                CSVReader reportReader = null; 
                try {
                        reportReader = new CSVReader(new FileReader(filePath),'\t');
                } catch (FileNotFoundException e) {
                        System.out.println("Error Reading "+reportType+" Report ");
                        log.error("Error Reading Shipment Report :- ", e);
                }
                System.out.println("Got Report reader");
                return reportReader;
        }
        
        public List<String> getFBACustomerEmails(CSVReader shpmntReportReader, CSVReader rtrnsReportReader, DatatypeFactory df){
                
                List<String> fbaCustomersEmails  = new ArrayList<String>();
                
                String [] shipmentReportData;
                String [] returnsReportData;

                boolean matchFoundInReturns= false;
                System.out.println("In method of getting email ids");
                try {
                        while ((shipmentReportData = shpmntReportReader.readNext()) != null) {
                                if(!shipmentReportData[0].equalsIgnoreCase("amazon-order-id")){
                                        returnReportWhile:while((returnsReportData = rtrnsReportReader.readNext()) != null){
                                                if(!returnsReportData[1].equalsIgnoreCase("amazon-order-id")){
                                                        if(shipmentReportData[0].equalsIgnoreCase(returnsReportData[1])){
                                                                matchFoundInReturns= true;
                                                                break returnReportWhile;
                                                        }
                                                        else{
                                                                XMLGregorianCalendar shipmentDate= df.newXMLGregorianCalendar(shipmentReportData[8].substring(0, shipmentReportData[8].indexOf("T")));
                                                                XMLGregorianCalendar estimatedDate= df.newXMLGregorianCalendar(shipmentReportData[44].substring(0, shipmentReportData[44].indexOf("T")));
                                                                if(shipmentDate.compare(estimatedDate)==-1)
                                                                        matchFoundInReturns= false;
                                                        }
                                                }
                                        }

                                if(!matchFoundInReturns){
                                        fbaCustomersEmails.add(shipmentReportData[10]);
                                }
                                }

                        }
                } catch (IOException e) {
                        log.error("Error Reading IO operations :- ", e);
                }
                System.out.println("Got email ids");
                return fbaCustomersEmails;
        }
        
        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";
                /************************************************************************
                 * 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
                
                
                /************************************************************************
                 * 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        
                 ***********************************************************************/
                

                MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
                config.setServiceURL("https://mws.amazonservices.in");
                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"));        
                FeedbackRequestEmailSender feedbackRequestEmailSender = new FeedbackRequestEmailSender();
                
                // demonstrates how to set the date range
                DatatypeFactory df = null;
                try {
                        df = DatatypeFactory.newInstance();
                } catch (DatatypeConfigurationException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                }
                Calendar current_Date= new GregorianCalendar();

                XMLGregorianCalendar endDateReturnReport = df.newXMLGregorianCalendar(new GregorianCalendar(current_Date.get(Calendar.YEAR),current_Date.get(Calendar.MONTH),current_Date.get(Calendar.DAY_OF_MONTH)));

                current_Date.add(Calendar.DAY_OF_MONTH, -21);

                XMLGregorianCalendar startDateBoth = df.newXMLGregorianCalendar(new GregorianCalendar(current_Date.get(Calendar.YEAR),current_Date.get(Calendar.MONTH),current_Date.get(Calendar.DAY_OF_MONTH)));
                current_Date.add(Calendar.DAY_OF_MONTH, 1);

                XMLGregorianCalendar endDateFullFilledReport = df.newXMLGregorianCalendar(new GregorianCalendar(current_Date.get(Calendar.YEAR),current_Date.get(Calendar.MONTH),current_Date.get(Calendar.DAY_OF_MONTH)));

                RequestReportRequest fullfilledShipmentReportRequest = feedbackRequestEmailSender.getReportRequest(merchantId, marketplaces, "_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_", "ShowSalesChannel=true", startDateBoth, endDateFullFilledReport);
                
                RequestReportRequest returnsReportRequest = feedbackRequestEmailSender.getReportRequest(merchantId, marketplaces, "_GET_FBA_FULFILLMENT_CUSTOMER_RETURNS_DATA_", "ShowSalesChannel=true", startDateBoth, endDateReturnReport);
                
                String shipmentReportRequestId = feedbackRequestEmailSender.getReportRequestId(service, fullfilledShipmentReportRequest);
                
                String returnsReportRequestId = feedbackRequestEmailSender.getReportRequestId(service, returnsReportRequest);
                
                Map<String,String> requestIdShipmentReportIdmap = feedbackRequestEmailSender.getrequestReportIdmap(merchantId, service, shipmentReportRequestId);


                Map<String,String> requestIdReturnsReportIdmap = feedbackRequestEmailSender.getrequestReportIdmap(merchantId, service, returnsReportRequestId);

                
                ///Request report

                String emailBody= "Dear Customer, <br><br>" +
                "Thank you very much for shopping with Saholic at Amazon.in .<br><br>"+
                "We hope that you are happy with your purchase and if you are, please spare some time to leave positive feedback for us.<br><br>" +
                "Kindly follow below mentioned steps:-<br><br>" +
                "1. Login into your Amazon account<br>" +
                "2. Go to Your Order Section<br>" +
                "3. Click on Seller Feedback<br><br>" +
                "Your comments and feedback help us improve our products and services for other customers. If you have any problems or concerns about your recent purchase, please get in touch with our customer service as soon as possible and we will do everything we can to help.<br><br>" +
                "Yours Sincerely,<br>" +
                "Saholic Team<br>";

                String emailIdFrom= "help@saholic.com";
                        //Fetch report only if it is ready
                feedbackRequestEmailSender.writeReportLocally(service, merchantId, requestIdShipmentReportIdmap.get(shipmentReportRequestId), "/tmp/AmazonFullFilledShipmentReport.txt", "Fullfilled Shipment");
                feedbackRequestEmailSender.writeReportLocally(service, merchantId, requestIdReturnsReportIdmap.get(returnsReportRequestId), "/tmp/AmazonReturnsReport.txt", "Returns"); 
                
                CSVReader shipmentReportReader = feedbackRequestEmailSender.getReportReader("/tmp/AmazonFullFilledShipmentReport.txt", "Fullfilled Shipment") ;
                CSVReader returnsReportReader = feedbackRequestEmailSender.getReportReader("/tmp/AmazonReturnsReport.txt", "Returns") ; 
                                
                List<String> fbaCustomersEmails  = feedbackRequestEmailSender.getFBACustomerEmails(shipmentReportReader, returnsReportReader, df);

                HelperClient helperServiceClient;
                try {
                        helperServiceClient = new HelperClient("helper_service_server_host_prod", "helper_service_server_port_prod");
                        in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
                        System.out.print("Email Id List: \n");
                        for(int i=0; i<fbaCustomersEmails.size();i++){
                                System.out.print(fbaCustomersEmails.get(i)+"\n");
                                client.saveUserEmailForSending(Arrays.asList(new String[] {fbaCustomersEmails.get(i)}), emailIdFrom, "Feedback Request", emailBody, "AmazonMFN", "AmazonFeedback", null, Arrays.asList(new String[] {"amit.sirohi@shop2020.in"}), 1);
                        }
                } catch (Exception e) {
                        log.error("Error Getting Helper Client :- ", e);
                }



                // 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.
                //
                System.exit(0);

        }

}