Subversion Repositories SmartDukaan

Rev

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

package com.amazonaws.mws.samples;

import in.shop2020.thrift.clients.HelperClient;
import in.shop2020.thrift.clients.TransactionClient;

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.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 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 fullfilledShipmentReportRequest = new RequestReportRequest()
                .withMerchant(merchantId)
                .withMarketplaceIdList(marketplaces)
                .withReportType("_GET_AMAZON_FULFILLED_SHIPMENTS_DATA_")
                .withReportOptions("ShowSalesChannel=true");

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

                // demonstrates how to set the date range
                DatatypeFactory df = null;
                try {
                        df = DatatypeFactory.newInstance();
                } catch (DatatypeConfigurationException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                }
                Calendar start_Date= new GregorianCalendar();

                XMLGregorianCalendar endDate2 = df.newXMLGregorianCalendar(new GregorianCalendar(start_Date.get(Calendar.YEAR),start_Date.get(Calendar.MONTH),start_Date.get(Calendar.DAY_OF_MONTH)));
                
                start_Date.add(Calendar.DAY_OF_MONTH, -21);

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

                XMLGregorianCalendar endDate1 = df.newXMLGregorianCalendar(new GregorianCalendar(start_Date.get(Calendar.YEAR),start_Date.get(Calendar.MONTH),start_Date.get(Calendar.DAY_OF_MONTH)));
                
                fullfilledShipmentReportRequest.setStartDate(startDate);
                fullfilledShipmentReportRequest.setEndDate(endDate1);

                // @TODO: set additional request parameters here
                Map<String,String> requestIdShipmentReportIdmap;

                returnsReportRequest.setStartDate(startDate);
                returnsReportRequest.setEndDate(endDate2);

                Map<String,String> requestIdReturnsReportIdmap;

                List<String> fbaCustomersEmails  = new ArrayList<String>();
                ///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.<br><br>" +
                "Please do not leave any negative feedback. 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";
                TransactionClient transactionServiceClient = null;
                
                try{
                        transactionServiceClient= new TransactionClient();
                }
                catch(Exception e){
                        log.error("Error While initializing Transaction Client :- ", e);
                }
                

                String shipmentReportRequestId = RequestReportSample.invokeRequestReport(service, fullfilledShipmentReportRequest);
                String returnsReportRequestId = RequestReportSample.invokeRequestReport(service, returnsReportRequest);
                while(true){
                        GetReportListRequest requestShipmentReportList = new GetReportListRequest();
                        requestShipmentReportList.setMerchant( merchantId );

                        GetReportListRequest requestReturnsReportList = new GetReportListRequest();
                        requestReturnsReportList.setMerchant( merchantId );

                        final IdList shipmentReportRequestIdList = new IdList(Arrays.asList(shipmentReportRequestId));        
                        requestShipmentReportList.setReportRequestIdList(shipmentReportRequestIdList);
                        ///Request report status
                        requestIdShipmentReportIdmap = GetReportListSample.invokeGetReportList(service, requestShipmentReportList);

                        final IdList returnsReportRequestIdList = new IdList(Arrays.asList(returnsReportRequestId));        
                        requestReturnsReportList.setReportRequestIdList(returnsReportRequestIdList);

                        requestIdReturnsReportIdmap= GetReportListSample.invokeGetReportList(service, requestReturnsReportList);

                        GetReportRequest requestShipmentReport = new GetReportRequest();
                        requestShipmentReport.setMerchant( merchantId );

                        GetReportRequest requestReturnsReport = new GetReportRequest();
                        requestReturnsReport.setMerchant( merchantId );


                        ///Fetch report only if it is ready
                        if(requestIdShipmentReportIdmap.get(shipmentReportRequestId)!=null && requestIdReturnsReportIdmap.get(returnsReportRequestId)!=null){
                                requestShipmentReport.setReportId( requestIdShipmentReportIdmap.get(shipmentReportRequestId) );
                                OutputStream shipmentReport=null;
                                try {
                                        shipmentReport = new FileOutputStream( "/tmp/AmazonFullFilledShipmentReport.txt" );
                                } catch (FileNotFoundException e) {
                                        log.error("Error Getting Shipment Report :- ", e);
                                }
                                requestShipmentReport.setReportOutputStream( shipmentReport );
                                GetReportSample.invokeGetReport(service, requestShipmentReport);

                                log.info("Shipment Report ready please check\n");
                                CSVReader shipmentReportReader = null; 
                                try {
                                        shipmentReportReader = new CSVReader(new FileReader("/tmp/AmazonFullFilledShipmentReport.txt"),'\t');
                                } catch (FileNotFoundException e) {
                                        log.error("Error Reading Shipment Report :- ", e);
                                }

                                requestReturnsReport.setReportId( requestIdReturnsReportIdmap.get(returnsReportRequestId) );
                                OutputStream returnsReport=null;
                                try {
                                        returnsReport = new FileOutputStream( "/tmp/AmazonReturnsReport.txt" );
                                } catch (FileNotFoundException e) {
                                        log.error("Error Getting Returns Report :- ", e);
                                }
                                requestReturnsReport.setReportOutputStream( returnsReport );
                                GetReportSample.invokeGetReport(service, requestReturnsReport);

                                log.info("Return Report ready please check\n");
                                CSVReader returnsReportReader = null; 
                                try {
                                        returnsReportReader = new CSVReader(new FileReader("/tmp/AmazonReturnsReport.txt"),'\t');
                                } catch (FileNotFoundException e) {
                                        log.error("Error Reading Returns Report :- ", e);
                                }


                                String [] shipmentReportData;
                                String [] returnsReportData;

                                boolean matchFoundInReturns= false;

                                try {
                                        while ((shipmentReportData = shipmentReportReader.readNext()) != null) {
                                                if(!shipmentReportData[0].equalsIgnoreCase("amazon-order-id")){
                                                        returnReportWhile:while((returnsReportData = returnsReportReader.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);
                                } 
                                
                                break;
                        }
                        else{ 
                                log.info("Report not ready\n");
                                try {
                                        Thread.sleep(5*60*1000);
                                } catch (InterruptedException e) {
                                        log.error("Error During getting Response :- ", e);
                                }
                        }
                }

                HelperClient helperServiceClient;
                try {
                        helperServiceClient = new HelperClient();
                        in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
                        log.info("Email Id List: \n");
                        for(int i=0; i<fbaCustomersEmails.size();i++){
                                log.info(fbaCustomersEmails.get(i)+"\n");
                                client.saveUserEmailForSending(Arrays.asList(new String[] {fbaCustomersEmails.get(i)}), emailIdFrom, "Feedback Request", emailBody, "AmazonMFN", "AmazonFeedback", Arrays.asList(new String[] {" "}), 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.
                //


        }

}