Subversion Repositories SmartDukaan

Rev

Rev 8293 | Rev 8363 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8285 kshitij.so 1
package com.amazonaws.mws.samples;
2
 
3
import in.shop2020.model.v1.catalog.Amazonlisted;
4
import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;
5
import in.shop2020.model.v1.order.AmazonFbaSalesSnapshot;
6
import in.shop2020.thrift.clients.CatalogClient;
7
import in.shop2020.thrift.clients.InventoryClient;
8
import in.shop2020.thrift.clients.TransactionClient;
9
 
10
import java.io.FileNotFoundException;
11
import java.io.FileOutputStream;
12
import java.io.FileReader;
13
import java.io.IOException;
14
import java.io.OutputStream;
15
import java.text.ParseException;
16
import java.text.SimpleDateFormat;
17
import java.util.Arrays;
18
import java.util.Calendar;
19
import java.util.Date;
20
import java.util.GregorianCalendar;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.TimeZone;
25
 
26
import javax.xml.datatype.DatatypeConfigurationException;
27
import javax.xml.datatype.DatatypeFactory;
28
import javax.xml.datatype.Duration;
29
import javax.xml.datatype.XMLGregorianCalendar;
30
 
31
import org.apache.thrift.TException;
32
import org.apache.thrift.transport.TTransportException;
33
 
34
import au.com.bytecode.opencsv.CSVReader;
35
 
36
import com.amazonaws.mws.MarketplaceWebService;
37
import com.amazonaws.mws.MarketplaceWebServiceClient;
38
import com.amazonaws.mws.MarketplaceWebServiceConfig;
39
import com.amazonaws.mws.model.GetReportListRequest;
40
import com.amazonaws.mws.model.GetReportRequest;
41
import com.amazonaws.mws.model.IdList;
42
import com.amazonaws.mws.model.RequestReportRequest;
43
 
44
public class FetchAmazonSalesSnapshot {
45
	public static void main(String... args){
46
		/************************************************************************
47
		 * Access Key ID and Secret Access Key ID, obtained from:
48
		 * http://aws.amazon.com
49
		 ***********************************************************************/
50
		final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
51
		final String secretAccessKey = "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";
52
 
53
		final String appName = "Test";
54
		final String appVersion = "1.0";
55
		final String merchantId = "AF6E3O0VE0X4D";
56
 
57
		MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
58
 
59
		/************************************************************************
60
		 * Uncomment to set the appropriate MWS endpoint.
61
		 ************************************************************************/
62
		// US
63
		// config.setServiceURL("https://mws.amazonservices.com");
64
		// UK
65
		// config.setServiceURL("https://mws.amazonservices.co.uk");
66
		// Germany
67
		// config.setServiceURL("https://mws.amazonservices.de");
68
		// France
69
		// config.setServiceURL("https://mws.amazonservices.fr");
70
		// Italy
71
		// config.setServiceURL("https://mws.amazonservices.it");
72
		// Japan
73
		// config.setServiceURL("https://mws.amazonservices.jp");
74
		// China
75
		// config.setServiceURL("https://mws.amazonservices.com.cn");
76
		// Canada
77
		// config.setServiceURL("https://mws.amazonservices.ca");
78
		// India
79
		config.setServiceURL("https://mws.amazonservices.in");
80
 
81
		/************************************************************************
82
		 * You can also try advanced configuration options. Available options are:
83
		 *
84
		 *  - Signature Version
85
		 *  - Proxy Host and Proxy Port
86
		 *  - User Agent String to be sent to Marketplace Web Service
87
		 *
88
		 ***********************************************************************/
89
 
90
		/************************************************************************
91
		 * Instantiate Http Client Implementation of Marketplace Web Service        
92
		 ***********************************************************************/
93
 
94
		MarketplaceWebService service = new MarketplaceWebServiceClient(
95
				accessKeyId, secretAccessKey, appName, appVersion, config);
96
 
97
		/************************************************************************
98
		 * Uncomment to try out Mock Service that simulates Marketplace Web Service 
99
		 * responses without calling Marketplace Web Service  service.
100
		 *
101
		 * Responses are loaded from local XML files. You can tweak XML files to
102
		 * experiment with various outputs during development
103
		 *
104
		 * XML files available under com/amazonaws/mws/mock tree
105
		 *
106
		 ***********************************************************************/
107
		// MarketplaceWebService service = new MarketplaceWebServiceMock();
108
 
109
		/************************************************************************
110
		 * Setup request parameters and uncomment invoke to try out 
111
		 * sample for Request Report 
112
		 ***********************************************************************/
113
 
114
		/************************************************************************
115
		 * Marketplace and Merchant IDs are required parameters for all 
116
		 * Marketplace Web Service calls.
117
		 ***********************************************************************/
118
		// marketplaces from which data should be included in the report; look at the
119
		// API reference document on the MWS website to see which marketplaces are
120
		// included if you do not specify the list yourself
121
		final IdList marketplaces = new IdList(Arrays.asList(
122
		"A21TJRUUN4KGV"));        
123
		RequestReportRequest orderreportrequest = new RequestReportRequest()
124
		.withMerchant(merchantId)
125
		.withMarketplaceIdList(marketplaces)
126
		.withReportType("_GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_")
127
		.withReportOptions("ShowSalesChannel=true");
128
 
129
		RequestReportRequest inventoryhealthreportrequest = new RequestReportRequest()
130
		.withMerchant(merchantId)
131
		.withMarketplaceIdList(marketplaces)
132
		.withReportType("_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_")
133
		.withReportOptions("ShowSalesChannel=true");
134
 
135
		DatatypeFactory df = null;
136
		try {
137
			df = DatatypeFactory.newInstance();
138
		} catch (DatatypeConfigurationException e) {
139
			e.printStackTrace();
140
			throw new RuntimeException(e);
141
		}
142
		long ordertimediff = System.currentTimeMillis() - 7*24*60*60*1000;
143
		GregorianCalendar ost = new GregorianCalendar();
144
		ost.setTimeInMillis(ordertimediff);
145
		XMLGregorianCalendar  orderStartDate = df.newXMLGregorianCalendar(ost);
146
		XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
147
		System.out.println("Order Start Date  " + orderStartDate  + "Order End Date  " + orderEndDate);
148
		orderreportrequest.setStartDate(orderStartDate);
149
		orderreportrequest.setEndDate(orderEndDate);
150
		long inventorytimediff = System.currentTimeMillis() - 7*24*60*60*1000;
151
		GregorianCalendar ist = new GregorianCalendar();
152
		ist.setTimeInMillis(inventorytimediff);
153
		ist.setTimeInMillis(ordertimediff);
154
		XMLGregorianCalendar  inventoryStartDate = df.newXMLGregorianCalendar(ist);
155
		XMLGregorianCalendar inventoryEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
156
		System.out.println("Inventory Start Date  " + inventoryStartDate  + "Inventory End Date  " + inventoryEndDate);
157
		inventoryhealthreportrequest.setStartDate(inventoryStartDate);
158
		inventoryhealthreportrequest.setEndDate(inventoryEndDate);
159
		Map<String,String> requestIdreportIdmap;
160
		String orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);
161
		String inventoryhealthreportrequestId = RequestReportSample.invokeRequestReport(service, inventoryhealthreportrequest);
8294 kshitij.so 162
		int retry2=0;
8285 kshitij.so 163
		while(true){
8294 kshitij.so 164
			int retry1 = 0;
165
			while(true){
166
				GetReportListRequest requestreportlist = new GetReportListRequest();
167
				requestreportlist.setMerchant( merchantId );
168
				final IdList requestIdList = new IdList(Arrays.asList(orderreportrequestId,inventoryhealthreportrequestId));        
169
				requestreportlist.setReportRequestIdList(requestIdList);
170
				requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);
171
				if(requestIdreportIdmap.get(orderreportrequestId)!=null && requestIdreportIdmap.get(inventoryhealthreportrequestId)!=null){
172
					GetReportRequest requestorderreport = new GetReportRequest();
173
					GetReportRequest requestinventoryhealthreport = new GetReportRequest();
174
					requestorderreport.setMerchant( merchantId );
175
					requestinventoryhealthreport.setMerchant(merchantId);
176
					requestorderreport.setReportId( requestIdreportIdmap.get(orderreportrequestId));
177
					requestinventoryhealthreport.setReportId(requestIdreportIdmap.get(inventoryhealthreportrequestId));
178
					OutputStream orderreport=null;
179
					OutputStream inventoryhealthreport=null;
180
					try {
181
						orderreport = new FileOutputStream( "/home/vikram/Desktop/amazonorderreport.csv" );
182
						inventoryhealthreport = new FileOutputStream( "/home/vikram/Desktop/inventoryhealthreport.csv" );
183
					} catch (FileNotFoundException e) {
184
						// TODO Auto-generated catch block
185
						e.printStackTrace();
8285 kshitij.so 186
					}
8294 kshitij.so 187
					requestorderreport.setReportOutputStream(orderreport);
188
					requestinventoryhealthreport.setReportOutputStream(inventoryhealthreport);
189
					GetReportSample.invokeGetReport(service, requestorderreport);
190
					GetReportSample.invokeGetReport(service, requestinventoryhealthreport);
191
					System.out.println("Order and Inventory Reports are ready please check");
192
					CSVReader orderreportreader = null;
193
					CSVReader inventoryhealthreportreader = null;
8285 kshitij.so 194
					try {
8294 kshitij.so 195
						orderreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/amazonorderreport.csv"),'\t');
196
						inventoryhealthreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/inventoryhealthreport.csv"),'\t');
197
					} catch (FileNotFoundException e) {
8285 kshitij.so 198
						// TODO Auto-generated catch block
199
						e.printStackTrace();
8294 kshitij.so 200
					}
201
					String [] nextLine;
202
					try {
203
						int count =1;
204
						Map<Date,Map<Long,Integer>> orderDateItemIdCountMap = new HashMap<Date,Map<Long,Integer>>();
205
						while ((nextLine = orderreportreader.readNext()) != null) {
206
							if(count!=1 && nextLine[5].equalsIgnoreCase("Amazon") && (nextLine[13].equalsIgnoreCase("Unshipped") || nextLine[13].equalsIgnoreCase("Shipped"))){
207
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
208
								istFormatter .setLenient(false);
209
								TimeZone zone= TimeZone.getTimeZone("GMT");
210
								istFormatter.setTimeZone(zone);
211
								Date date = istFormatter.parse(nextLine[2]);
212
								SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
213
								Date date_key = dateFormat.parse(dateFormat.format(date));
214
								System.out.println(nextLine[0]+" "+date_key+" "+ nextLine[11] +" " + nextLine[13] + " " + nextLine[14]);
215
								Long itemid = Long.parseLong(nextLine[11].replaceAll("FBA",""));
216
								Integer qty = new Integer(nextLine[14]);
217
								if(orderDateItemIdCountMap.containsKey(date_key)){
218
									if(orderDateItemIdCountMap.get(date_key).containsKey(itemid)){
219
										orderDateItemIdCountMap.get(date_key).put(itemid,orderDateItemIdCountMap.get(date_key).get(itemid)+qty);
220
									}
221
									else{
222
										orderDateItemIdCountMap.get(date_key).put(itemid,qty);
223
									}
8285 kshitij.so 224
								}
8294 kshitij.so 225
								else{
8293 kshitij.so 226
 
8294 kshitij.so 227
									Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();
228
									itemIdcountMap.put(itemid,qty);
229
									orderDateItemIdCountMap.put(date_key,itemIdcountMap);
230
								}
231
 
232
							} 
233
							count++;
234
						}
235
						InventoryClient inventoryServiceClient = null;
236
						TransactionClient transactionServiceClient = null;
237
						CatalogClient catalogServiceClient = null;
238
						try {
239
							inventoryServiceClient = new InventoryClient();
240
							transactionServiceClient = new TransactionClient();
241
							catalogServiceClient = new CatalogClient();
242
							//catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
243
						} catch (Exception e) {
244
							// TODO Auto-generated catch block
245
							e.printStackTrace();
246
						}	
247
						in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
248
						in.shop2020.model.v1.order.TransactionService.Client transactionClient   = transactionServiceClient.getClient();
249
						in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
250
						SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
251
						Date date_today = dateFormat.parse(dateFormat.format(new Date()));
252
						List<AmazonFbaInventorySnapshot> nonzeroFbaInventorySnapshotlist =  inventoryClient.getAllNonzeroAmazonFbaItemInventory();
253
						if(nonzeroFbaInventorySnapshotlist!=null){
254
							for(AmazonFbaInventorySnapshot amazonFbaInventory:nonzeroFbaInventorySnapshotlist){
255
								if(orderDateItemIdCountMap.containsKey(date_today) ){ 
256
									if(!orderDateItemIdCountMap.get(date_today).containsKey(amazonFbaInventory.getItem_id())){
257
										orderDateItemIdCountMap.get(date_today).put(amazonFbaInventory.getItem_id(),0);
258
									}
259
 
260
								}
261
								else{
262
									Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();
263
									itemIdcountMap.put(amazonFbaInventory.getItem_id(),0);
264
									orderDateItemIdCountMap.put(date_today,itemIdcountMap);
265
								}
8293 kshitij.so 266
							}
8285 kshitij.so 267
						}
8294 kshitij.so 268
						else{
269
							System.out.println("No inventory in FBA");
8285 kshitij.so 270
						}
8294 kshitij.so 271
						orderDateItemIdCountMap.get(date_today);
272
						Map<Long,Double> itemIdSalePriceMap = new HashMap<Long,Double>();
273
						Map<Long,Double> itemIdminFBAPriceMap = new HashMap<Long,Double>();
274
						Map<Long,Double> itemIdminMFNPriceMap = new HashMap<Long,Double>();
275
						count=1;
276
						while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
277
							if(count!=1){
278
								//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
279
								Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));
280
								Double salePrice = Double.parseDouble(nextLine[31]);
281
								Double minFBAPrice = Double.parseDouble(nextLine[32]);
282
								Double minMFNPrice = Double.parseDouble(nextLine[34]);
283
								itemIdSalePriceMap.put(item_id,salePrice);
284
								itemIdminFBAPriceMap.put(item_id,minFBAPrice);
285
								itemIdminMFNPriceMap.put(item_id,minMFNPrice);
8285 kshitij.so 286
							}
8294 kshitij.so 287
							count++;
288
						}
289
						boolean oos;
290
						for (Map.Entry<Date, Map<Long, Integer>> entry : orderDateItemIdCountMap.entrySet()){
291
							Date orderDate = entry.getKey();
292
							for(Map.Entry<Long, Integer> entry1 :entry.getValue().entrySet()){
293
								Long inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
294
								oos=false;
295
								if(inventory==0 && entry1.getValue()==0)
296
									oos=true;
297
								Long item_id = entry1.getKey();
298
								System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
299
								AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
300
								amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
301
								amazonfbasalessnapshot.setItem_id(entry1.getKey());
302
								amazonfbasalessnapshot.setOrderCount(entry1.getValue());
303
								amazonfbasalessnapshot.setIsOutOfStock(oos);
304
								Amazonlisted amazon_item = catalogClient.getAmazonItemDetails(item_id);
305
								if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id)!=0){
306
									amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id));
307
								}
308
								else{
309
									amazonfbasalessnapshot.setSalePrice(amazon_item.getFbaPrice());
310
								}
311
								if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){
312
									amazonfbasalessnapshot.setMinFbaPrice(itemIdminMFNPriceMap.get(item_id));
313
								}
314
								if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){
315
									amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id));
316
								}
317
								amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
318
								transactionClient.addOrUpdateAmazonFbaSalesSnapshot(amazonfbasalessnapshot);
8285 kshitij.so 319
							}
320
						}
8294 kshitij.so 321
					} catch (IOException e) {
322
						// TODO Auto-generated catch block
323
						e.printStackTrace();
324
					} catch (ParseException e) {
325
						// TODO Auto-generated catch block
326
						e.printStackTrace();
327
					} catch (TException e) {
328
						// TODO Auto-generated catch block
329
						e.printStackTrace();
8285 kshitij.so 330
					}
8294 kshitij.so 331
					break;
8285 kshitij.so 332
				}
8294 kshitij.so 333
				else{ 
334
					System.out.println("Report not ready");
335
					try {
336
						Thread.sleep(5*60*1000);
337
					} catch (InterruptedException e) {
338
						// TODO Auto-generated catch block
339
						e.printStackTrace();
340
					}
341
				}
342
				retry1++;
343
				if(retry1==5){
344
					break;
345
				}
346
			}
347
			Thread.sleep(10*60*1000);
348
			retry2++;
349
			if(retry2==5){
8285 kshitij.so 350
				break;
351
			}
352
		}
353
 
354
		// Note that depending on the type of report being downloaded, a report can reach 
355
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
356
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
357
		// the in-memory size limit and have to re-work your solution.
358
		//
359
 
360
 
361
	}
362
 
363
}