Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.amazonaws.mws.samples;import in.shop2020.model.v1.catalog.AmazonPromotion;import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;import in.shop2020.model.v1.order.AmazonFCWarehouseLocation;import in.shop2020.model.v1.order.AmazonHourlySaleSnapshot;import in.shop2020.thrift.clients.InventoryClient;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 AmazonFbaSingleDaySnapshot{public final static String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";public final static String secretAccessKey = "B92xTbNBTYygbGs98w01nFQUhbec1pNCkCsKVfpg";public final static String appName = "Test";public final static String appVersion = "1.0";public final static String merchantId = "AF6E3O0VE0X4D";public final static String FILE_PATH = "/tmp/amazonorderreport.xml";public final static long now = System.currentTimeMillis();public static Map<String, AmazonFbaInventorySnapshot> fbaInventoryMap = new HashMap<String,AmazonFbaInventorySnapshot>();public static Map<String,AmazonHourlySaleSnapshot> skuSaleMap = new HashMap<String,AmazonHourlySaleSnapshot>();public static void terminate(String msg){String emailFromAddress = "build@shop2020.in";String password = "cafe@nes";String[] sendTo = new String[]{ "kshitij.sood@saholic.com","anikendra.das@shop2020.in"};String emailSubjectTxt = msg;try {GmailUtils mailer = new GmailUtils();mailer.sendSSLMessage(sendTo, emailSubjectTxt, "", emailFromAddress, password,"");}catch (Exception ex) {ex.printStackTrace();}System.exit(1);}public static String invokeServiceRequest() throws InterruptedException{/* Returns request id of the OrderReport */MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();config.setServiceURL("https://mws.amazonservices.in");MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);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");DatatypeFactory df = null;try {df = DatatypeFactory.newInstance();} catch (DatatypeConfigurationException e) {e.printStackTrace();throw new RuntimeException(e);}Calendar cal = Calendar.getInstance();cal.set(Calendar.HOUR_OF_DAY, 00);cal.set(Calendar.MINUTE,00);cal.set(Calendar.SECOND,00);cal.set(Calendar.MILLISECOND,00);GregorianCalendar ost = new GregorianCalendar();ost.setTimeInMillis(cal.getTimeInMillis());XMLGregorianCalendar orderStartDate = df.newXMLGregorianCalendar(ost);XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());orderreportrequest.setStartDate(orderStartDate);orderreportrequest.setEndDate(orderEndDate);System.out.println(orderStartDate);System.out.println(orderEndDate);String orderreportrequestId = null;boolean retry=true;int retryCount =1;while(retry){if(retryCount==10){terminate("Fba Hourly Sales - Unable to get request id");}try {orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);retry = false;} catch (MarketplaceWebServiceException e) {e.printStackTrace();Thread.sleep(1*60*1000);retryCount++;}}return orderreportrequestId;}public static void writeDataToDisk(String requestId) throws FileNotFoundException, IOException, InterruptedException{/* Write OrderXml file to disk */int retryCount = 1;while(true){GetReportListRequest requestreportlist = new GetReportListRequest();requestreportlist.setMerchant( merchantId );final IdList requestIdList = new IdList(Arrays.asList(requestId));requestreportlist.setReportRequestIdList(requestIdList);MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();config.setServiceURL("https://mws.amazonservices.in");MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, appName, appVersion, config);Map<String, String> requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);if(requestIdreportIdmap.get(requestId)!=null){GetReportRequest requestorderreport = new GetReportRequest();requestorderreport.setMerchant( merchantId );requestorderreport.setReportId( requestIdreportIdmap.get(requestId));OutputStream orderreport=null;try {orderreport = new FileOutputStream( "/tmp/amazonorderreport.xml" );} catch (FileNotFoundException e) {e.printStackTrace();}requestorderreport.setReportOutputStream(orderreport);GetReportSample.invokeGetReport(service, requestorderreport);System.out.println("Order Report is 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(FILE_PATH);String content = "";try {content = IOUtils.toString(new FileInputStream(orderReportFile));} catch (FileNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}content = content.replaceAll(toFind, toReplace);IOUtils.write(content, new FileOutputStream(orderReportFile));break;}else{if (retryCount == 5){terminate("Unable to pull FBA Hourly sales report");}retryCount++;Thread.sleep(1*60*1000);}}}public static void populateInventory() throws TException{/* Populate fba inventory by fcLocation */InventoryClient inventoryServiceClient = new InventoryClient();in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();List<AmazonFbaInventorySnapshot> fbaInventory = inventoryClient.getAllAvailableAmazonFbaItemInventory();for(AmazonFbaInventorySnapshot inventory : fbaInventory){String prefix = "";if (inventory.getLocation().getValue()==AmazonFCWarehouseLocation.Mumbai.getValue()){prefix = "FBA";}else if (inventory.getLocation().getValue()==AmazonFCWarehouseLocation.Bangalore.getValue()){prefix = "FBB";}else if (inventory.getLocation().getValue()==AmazonFCWarehouseLocation.Gurgaon.getValue()){prefix = "FBG";}else{continue;}fbaInventoryMap.put(prefix+String.valueOf(inventory.getItem_id()), inventory);}}public static void populateAndCommitSale() throws ParseException{JAXBContext jc = null;Unmarshaller unmarshaller = null;AmazonEnvelope amazonOrderData = null;try {jc = JAXBContext.newInstance(AmazonEnvelope.class);unmarshaller = jc.createUnmarshaller();amazonOrderData = (AmazonEnvelope)unmarshaller.unmarshal(new File(FILE_PATH));} catch (JAXBException e1) {e1.printStackTrace();}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())&& !("Cancelled".equalsIgnoreCase(amazonOrder.getOrderStatus()) || "Cancelled".equalsIgnoreCase(amazonOrder.getOrderItem().get(0).getItemStatus()))){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;String prefix = "";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;prefix = "FBA";}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;prefix = "FBB";}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;prefix = "FBG";}else{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);}AmazonHourlySaleSnapshot fbaSalesSnapshot;if(skuSaleMap.containsKey(prefix+String.valueOf(itemid))){fbaSalesSnapshot = skuSaleMap.get(prefix+String.valueOf(itemid));if(itemDiscount!=0){fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);fbaSalesSnapshot.setPromotionSale(fbaSalesSnapshot.getPromotionSale() + (itemSale - itemDiscount));}fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);}else{fbaSalesSnapshot = new AmazonHourlySaleSnapshot();fbaSalesSnapshot.setTotalOrderCount(qty);fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);if(itemDiscount!=0){fbaSalesSnapshot.setPromotionOrderCount(qty);fbaSalesSnapshot.setPromotionSale(itemSale - itemDiscount);}else{fbaSalesSnapshot.setPromotionOrderCount(0);fbaSalesSnapshot.setPromotionSale((float) 0);}}fbaSalesSnapshot.setItem_id(itemid);if (fbaInventoryMap.containsKey(prefix+String.valueOf(itemid))){fbaSalesSnapshot.setAmazonFbaInventory(fbaInventoryMap.get(prefix+String.valueOf(itemid)).getAvailability());fbaSalesSnapshot.setIsOutOfStock(false);}else{fbaSalesSnapshot.setAmazonFbaInventory(0);fbaSalesSnapshot.setIsOutOfStock(true);}fbaSalesSnapshot.setSnapshotTime(now);fbaSalesSnapshot.setFcLocation(fcLocation);skuSaleMap.put(prefix+String.valueOf(itemid),fbaSalesSnapshot);}}List<AmazonHourlySaleSnapshot> sales = new ArrayList<AmazonHourlySaleSnapshot>(skuSaleMap.values());boolean result = Consumer.addHourlySnapshot(sales);System.out.println("Data Committed ? " + result);if (!result){terminate("Unable to commit hourly FBA sales data to mongo");}}public static void main (String[] args) throws InterruptedException, FileNotFoundException, IOException, TException, ParseException{String requestId= invokeServiceRequest();writeDataToDisk(requestId);populateInventory();populateAndCommitSale();}}