Subversion Repositories SmartDukaan

Rev

Rev 9785 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
9777 manish.sha 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
import in.shop2020.utils.GmailUtils;
10
 
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileNotFoundException;
14
import java.io.FileOutputStream;
15
import java.io.FileReader;
16
import java.io.IOException;
17
import java.io.OutputStream;
18
import java.text.ParseException;
19
import java.text.SimpleDateFormat;
20
import java.util.ArrayList;
21
import java.util.Arrays;
22
import java.util.Calendar;
23
import java.util.Date;
24
import java.util.GregorianCalendar;
25
import java.util.HashMap;
26
import java.util.List;
27
import java.util.Map;
28
import java.util.TimeZone;
29
import java.util.Map.Entry;
30
 
31
import javax.xml.bind.JAXBContext;
32
import javax.xml.bind.JAXBException;
33
import javax.xml.bind.Unmarshaller;
34
import javax.xml.datatype.DatatypeConfigurationException;
35
import javax.xml.datatype.DatatypeFactory;
36
import javax.xml.datatype.XMLGregorianCalendar;
37
 
38
import org.apache.commons.io.IOUtils;
39
import org.apache.thrift.TException;
40
 
41
import au.com.bytecode.opencsv.CSVReader;
42
 
43
import com.amazonaws.mws.MarketplaceWebService;
44
import com.amazonaws.mws.MarketplaceWebServiceClient;
45
import com.amazonaws.mws.MarketplaceWebServiceConfig;
46
import com.amazonaws.mws.MarketplaceWebServiceException;
47
import com.amazonaws.mws.model.AmazonEnvelope;
48
import com.amazonaws.mws.model.FulfillmentData;
49
import com.amazonaws.mws.model.GetReportListRequest;
50
import com.amazonaws.mws.model.GetReportRequest;
51
import com.amazonaws.mws.model.IdList;
52
import com.amazonaws.mws.model.Message;
53
import com.amazonaws.mws.model.Order;
54
import com.amazonaws.mws.model.RequestReportRequest;
55
 
56
public class FetchAmazonXMLSalesSnapshot{
57
	public static void main(String... args){
58
		/************************************************************************
59
		 * Access Key ID and Secret Access Key ID, obtained from:
60
		 * http://aws.amazon.com
61
		 ***********************************************************************/
62
		final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
63
		final String secretAccessKey = "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";
64
 
65
		final String appName = "Test";
66
		final String appVersion = "1.0";
67
		final String merchantId = "AF6E3O0VE0X4D";
68
 
69
		MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
70
 
71
		/************************************************************************
72
		 * Uncomment to set the appropriate MWS endpoint.
73
		 ************************************************************************/
74
		// US
75
		// config.setServiceURL("https://mws.amazonservices.com");
76
		// UK
77
		// config.setServiceURL("https://mws.amazonservices.co.uk");
78
		// Germany
79
		// config.setServiceURL("https://mws.amazonservices.de");
80
		// France
81
		// config.setServiceURL("https://mws.amazonservices.fr");
82
		// Italy
83
		// config.setServiceURL("https://mws.amazonservices.it");
84
		// Japan
85
		// config.setServiceURL("https://mws.amazonservices.jp");
86
		// China
87
		// config.setServiceURL("https://mws.amazonservices.com.cn");
88
		// Canada
89
		// config.setServiceURL("https://mws.amazonservices.ca");
90
		// India
91
		config.setServiceURL("https://mws.amazonservices.in");
92
 
93
		/************************************************************************
94
		 * You can also try advanced configuration options. Available options are:
95
		 *
96
		 *  - Signature Version
97
		 *  - Proxy Host and Proxy Port
98
		 *  - User Agent String to be sent to Marketplace Web Service
99
		 *
100
		 ***********************************************************************/
101
 
102
		/************************************************************************
103
		 * Instantiate Http Client Implementation of Marketplace Web Service        
104
		 ***********************************************************************/
105
 
106
		MarketplaceWebService service = new MarketplaceWebServiceClient(
107
				accessKeyId, secretAccessKey, appName, appVersion, config);
108
 
109
		/************************************************************************
110
		 * Uncomment to try out Mock Service that simulates Marketplace Web Service 
111
		 * responses without calling Marketplace Web Service  service.
112
		 *
113
		 * Responses are loaded from local XML files. You can tweak XML files to
114
		 * experiment with various outputs during development
115
		 *
116
		 * XML files available under com/amazonaws/mws/mock tree
117
		 *
118
		 ***********************************************************************/
119
		// MarketplaceWebService service = new MarketplaceWebServiceMock();
120
 
121
		/************************************************************************
122
		 * Setup request parameters and uncomment invoke to try out 
123
		 * sample for Request Report 
124
		 ***********************************************************************/
125
 
126
		/************************************************************************
127
		 * Marketplace and Merchant IDs are required parameters for all 
128
		 * Marketplace Web Service calls.
129
		 ***********************************************************************/
130
		// marketplaces from which data should be included in the report; look at the
131
		// API reference document on the MWS website to see which marketplaces are
132
		// included if you do not specify the list yourself
133
		final IdList marketplaces = new IdList(Arrays.asList(
134
		"A21TJRUUN4KGV"));        
135
		RequestReportRequest orderreportrequest = new RequestReportRequest()
136
		.withMerchant(merchantId)
137
		.withMarketplaceIdList(marketplaces)
138
		.withReportType("_GET_XML_ALL_ORDERS_DATA_BY_ORDER_DATE_")
139
		.withReportOptions("ShowSalesChannel=true");
140
 
141
		RequestReportRequest inventoryhealthreportrequest = new RequestReportRequest()
142
		.withMerchant(merchantId)
143
		.withMarketplaceIdList(marketplaces)
144
		.withReportType("_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_")
145
		.withReportOptions("ShowSalesChannel=true");
146
 
147
		DatatypeFactory df = null;
148
		try {
149
			df = DatatypeFactory.newInstance();
150
		} catch (DatatypeConfigurationException e) {
151
			e.printStackTrace();
152
			throw new RuntimeException(e);
153
		}
154
		long ordertimediff = System.currentTimeMillis() - 7*24*60*60*1000;
155
		GregorianCalendar ost = new GregorianCalendar();
156
		ost.setTimeInMillis(ordertimediff);
157
		XMLGregorianCalendar  orderStartDate = df.newXMLGregorianCalendar(ost);
158
		XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
159
		System.out.println("Order Start Date  " + orderStartDate  + "Order End Date  " + orderEndDate);
160
		orderreportrequest.setStartDate(orderStartDate);
161
		orderreportrequest.setEndDate(orderEndDate);
162
		long inventorytimediff = System.currentTimeMillis() - 7*24*60*60*1000;
163
		GregorianCalendar ist = new GregorianCalendar();
164
		ist.setTimeInMillis(inventorytimediff);
165
		ist.setTimeInMillis(ordertimediff);
166
		XMLGregorianCalendar  inventoryStartDate = df.newXMLGregorianCalendar(ist);
167
		XMLGregorianCalendar inventoryEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
168
		System.out.println("Inventory Start Date  " + inventoryStartDate  + "Inventory End Date  " + inventoryEndDate);
169
		inventoryhealthreportrequest.setStartDate(inventoryStartDate);
170
		inventoryhealthreportrequest.setEndDate(inventoryEndDate);
171
		Map<String,String> requestIdreportIdmap;
172
		String orderreportrequestId = null;
173
		String inventoryhealthreportrequestId = null;
174
		boolean retry=true;
175
		int retryCount =0;
176
		while(retry && retryCount!=5){
177
			if(retryCount==4){
178
				String emailFromAddress = "build@shop2020.in";
179
				String password = "cafe@nes";
180
				String[] sendTo = new String[]{ "vikram.raghav@shop2020.in"};
181
				String emailSubjectTxt = "Fetch FBA Sale failure";
182
				try {
183
					GmailUtils mailer = new GmailUtils();
184
					mailer.sendSSLMessage(sendTo, emailSubjectTxt, "", emailFromAddress, password,"");
185
				}
186
				catch (Exception ex) {
187
					ex.printStackTrace();
188
				}
189
 
190
				System.exit(1);
191
			}
192
			try {
193
				orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);
194
				inventoryhealthreportrequestId = RequestReportSample.invokeRequestReport(service, inventoryhealthreportrequest);
195
				retry = false;
196
			} catch (MarketplaceWebServiceException e) {
197
				// TODO Auto-generated catch block
198
				e.printStackTrace();
199
				try {
200
					Thread.sleep(10*60*1000);
201
					retryCount++;
202
				} catch (InterruptedException e1) {
203
					// TODO Auto-generated catch block
204
					e1.printStackTrace();
205
				}
206
			}
207
		}
208
		while(true){
209
			GetReportListRequest requestreportlist = new GetReportListRequest();
210
			requestreportlist.setMerchant( merchantId );
211
			final IdList requestIdList = new IdList(Arrays.asList(orderreportrequestId,inventoryhealthreportrequestId));        
212
			requestreportlist.setReportRequestIdList(requestIdList);
213
			requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);
214
			if(requestIdreportIdmap.get(orderreportrequestId)!=null && requestIdreportIdmap.get(inventoryhealthreportrequestId)!=null){
215
				GetReportRequest requestorderreport = new GetReportRequest();
216
				GetReportRequest requestinventoryhealthreport = new GetReportRequest();
217
				requestorderreport.setMerchant( merchantId );
218
				requestinventoryhealthreport.setMerchant(merchantId);
219
				requestorderreport.setReportId( requestIdreportIdmap.get(orderreportrequestId));
220
				requestinventoryhealthreport.setReportId(requestIdreportIdmap.get(inventoryhealthreportrequestId));
221
				OutputStream orderreport=null;
222
				OutputStream inventoryhealthreport=null;
223
				try {
224
					orderreport = new FileOutputStream( "/home/amazonorderreport.xml" );
225
					inventoryhealthreport = new FileOutputStream( "/home/inventoryhealthreport.csv" );
226
				} catch (FileNotFoundException e) {
227
					// TODO Auto-generated catch block
228
					e.printStackTrace();
229
				}
230
				requestorderreport.setReportOutputStream(orderreport);
231
				requestinventoryhealthreport.setReportOutputStream(inventoryhealthreport);
232
				GetReportSample.invokeGetReport(service, requestorderreport);
233
				GetReportSample.invokeGetReport(service, requestinventoryhealthreport);
234
				System.out.println("Order and Inventory Reports are ready please check");
235
 
236
				String toFind = "<AmazonEnvelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"amzn-envelope.xsd\">";
237
				String toReplace = "<AmazonEnvelope xmlns=\"http://mws.amazonaws.com/doc/2009-01-01/\">";
238
				File orderReportFile = new File("/home/amazonorderreport.xml");
239
				String content = "";
240
				try {
241
					content = IOUtils.toString(new FileInputStream(orderReportFile));
242
				} catch (FileNotFoundException e1) {
243
					// TODO Auto-generated catch block
244
					e1.printStackTrace();
245
				} catch (IOException e1) {
246
					// TODO Auto-generated catch block
247
					e1.printStackTrace();
248
				}
249
				content = content.replaceAll(toFind, toReplace);
250
				try {
251
					IOUtils.write(content, new FileOutputStream(orderReportFile));
252
				} catch (FileNotFoundException e1) {
253
					e1.printStackTrace();
254
				} catch (IOException e1) {
255
					e1.printStackTrace();
256
				}
257
 
258
				JAXBContext jc = null;
259
				Unmarshaller unmarshaller = null;
260
				AmazonEnvelope amazonOrderData = null;
261
				try {
262
					jc = JAXBContext.newInstance(AmazonEnvelope.class);
263
					unmarshaller = jc.createUnmarshaller();
264
					amazonOrderData = (AmazonEnvelope)unmarshaller.unmarshal(orderReportFile);
265
				} catch (JAXBException e1) {
266
					e1.printStackTrace();
267
				}
268
 
269
				/*CSVReader orderreportreader = null;*/
270
				CSVReader inventoryhealthreportreader = null;
271
				try {
272
					/*orderreportreader = new CSVReader(new FileReader("/home/amazonorderreport.csv"),'\t');*/
273
					inventoryhealthreportreader = new CSVReader(new FileReader("/home/inventoryhealthreport.csv"),'\t');
274
				} catch (FileNotFoundException e) {
275
					// TODO Auto-generated catch block
276
					e.printStackTrace();
277
				}
278
				String [] nextLine;
279
				try {
280
					int count =1;
281
					Map<Date,Map<Long,FbaSalesSnapshot>> orderDateItemIdFbaSaleSnapshotMap = new HashMap<Date,Map<Long,FbaSalesSnapshot>>();
282
 
283
					if(amazonOrderData!=null){
284
						List<Message> orderMessageList = amazonOrderData.getMessage();
285
						for(Message orderMessage : orderMessageList){
286
							Order amazonOrder = orderMessage.getOrder();
287
							FulfillmentData orderFullfillmentData = amazonOrder.getFulfillmentData();
288
							if("Amazon.in".equalsIgnoreCase(amazonOrder.getSalesChannel()) && "Amazon".equalsIgnoreCase(orderFullfillmentData.getFulfillmentChannel())){
289
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
290
								istFormatter .setLenient(false);
291
								TimeZone zone= TimeZone.getTimeZone("GMT");
292
								istFormatter.setTimeZone(zone);
293
								Date date = istFormatter.parse(amazonOrder.getPurchaseDate().toString());
294
								SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
295
								Date date_key = dateFormat.parse(dateFormat.format(date));
296
								System.out.println("Order Details " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
297
								Long itemid = Long.parseLong(amazonOrder.getOrderItem().get(0).getSKU().replaceAll("FBA",""));
298
								Integer qty=0;
299
								if(amazonOrder.getOrderItem().get(0).getQuantity()!=0){
300
									qty = new Integer(amazonOrder.getOrderItem().get(0).getQuantity());
301
								}
302
								Float itemSale = null;
303
								if(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getCurrency().length()!=0){
304
									itemSale = new Float(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getCurrency());
305
								}
306
								else{
307
									continue;
308
								}
309
 
310
								Float itemDiscount; 
311
								if(amazonOrder.getOrderItem().get(0).getPromotion()!=null){
312
									if(amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount()!=0.0f){
313
									itemDiscount = amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount();
314
									}
315
									else{
316
										itemDiscount = new Float(0);
317
									}
318
								}
319
								else{
320
									itemDiscount = new Float(0);
321
								}
322
 
323
								if(("Cancelled").equalsIgnoreCase(amazonOrder.getOrderStatus()) || ("Cancelled").equalsIgnoreCase(amazonOrder.getOrderItem().get(0).getItemStatus())){
324
									itemSale = (float) 0; 
325
									itemDiscount = (float) 0;
326
									qty = 0;
327
								}
328
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date_key)){
329
									if(orderDateItemIdFbaSaleSnapshotMap.get(date_key).containsKey(itemid)){
330
										FbaSalesSnapshot fbaSalesSnapshot = orderDateItemIdFbaSaleSnapshotMap.get(date_key).get(itemid);
331
										if(itemDiscount!=0){
332
											fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);
333
											fbaSalesSnapshot.setTotalPromotionSale(fbaSalesSnapshot.getTotalPromotionSale() + (itemSale - itemDiscount));
334
										}
335
										else{
336
											fbaSalesSnapshot.setPromotionOrderCount(0);
337
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
338
										}
339
										fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);
340
										fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);
341
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
342
									}
343
									else{
344
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
345
										fbaSalesSnapshot.setTotalOrderCount(qty);
346
										fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);
347
										if(itemDiscount!=0){
348
											fbaSalesSnapshot.setPromotionOrderCount(qty);
349
											fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
350
										}
351
										else{
352
											fbaSalesSnapshot.setPromotionOrderCount(0);
353
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
354
										}
355
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
356
									}
357
								}
358
								else{
359
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
360
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
361
									fbaSalesSnapshot.setTotalOrderCount(qty);
362
									fbaSalesSnapshot.setTotalSale(itemSale);
363
									if(itemDiscount!=0){
364
										fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
365
										fbaSalesSnapshot.setPromotionOrderCount(qty);
366
									}
367
									else{
368
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
369
										fbaSalesSnapshot.setPromotionOrderCount(0);
370
									}
371
									ItemIdFbaSaleSnapshotMap.put(itemid,fbaSalesSnapshot);
372
									orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
373
								}
374
							}
375
						}
376
					}
377
 
378
					/*while ((nextLine = orderreportreader.readNext()) != null) {
379
						try{
380
							if(count!=1 && nextLine[5].equalsIgnoreCase("Amazon") && nextLine[6].equalsIgnoreCase("Amazon.in")){
381
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
382
								istFormatter .setLenient(false);
383
								TimeZone zone= TimeZone.getTimeZone("GMT");
384
								istFormatter.setTimeZone(zone);
385
								Date date = istFormatter.parse(nextLine[2]);
386
								SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
387
								Date date_key = dateFormat.parse(dateFormat.format(date));
388
								System.out.println("Order Details " + nextLine[0]+" "+date_key+" "+ nextLine[11] +" " + nextLine[13] + " " + nextLine[14]);
389
								// 0- amazon-order-id 11- sku 13- item-status 14 - quantity
390
								Long itemid = Long.parseLong(nextLine[11].replaceAll("FBA",""));
391
								Integer qty=0;
392
								if(nextLine[14].length()!=0){
393
									qty = new Integer(nextLine[14]);
394
								}
395
								Float itemSale = null;
396
								if(nextLine[16].length()!=0){
397
									itemSale = new Float(nextLine[16]);
398
								}
399
								else{
400
									continue;
401
								}
402
								Float itemDiscount; 
403
								if(nextLine[22].length()!=0){
404
									itemDiscount = new Float(nextLine[22]);
405
								}
406
								else{
407
									itemDiscount = new Float(0);
408
								}
409
								if(nextLine[4].equalsIgnoreCase("Cancelled") || nextLine[13].equalsIgnoreCase("Cancelled")){
410
									itemSale = (float) 0; 
411
									itemDiscount = (float) 0;
412
									qty = 0;
413
								}
414
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date_key)){
415
									if(orderDateItemIdFbaSaleSnapshotMap.get(date_key).containsKey(itemid)){
416
										FbaSalesSnapshot fbaSalesSnapshot = orderDateItemIdFbaSaleSnapshotMap.get(date_key).get(itemid);
417
										if(itemDiscount!=0){
418
											fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);
419
											fbaSalesSnapshot.setTotalPromotionSale(fbaSalesSnapshot.getTotalPromotionSale() + (itemSale - itemDiscount));
420
										}
421
										else{
422
											fbaSalesSnapshot.setPromotionOrderCount(0);
423
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
424
										}
425
										fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);
426
										fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);
427
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
428
									}
429
									else{
430
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
431
										fbaSalesSnapshot.setTotalOrderCount(qty);
432
										fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);
433
										if(itemDiscount!=0){
434
											fbaSalesSnapshot.setPromotionOrderCount(qty);
435
											fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
436
										}
437
										else{
438
											fbaSalesSnapshot.setPromotionOrderCount(0);
439
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
440
										}
441
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
442
									}
443
								}
444
								else{
445
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
446
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
447
									fbaSalesSnapshot.setTotalOrderCount(qty);
448
									fbaSalesSnapshot.setTotalSale(itemSale);
449
									if(itemDiscount!=0){
450
										fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
451
										fbaSalesSnapshot.setPromotionOrderCount(qty);
452
									}
453
									else{
454
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
455
										fbaSalesSnapshot.setPromotionOrderCount(0);
456
									}
457
									ItemIdFbaSaleSnapshotMap.put(itemid,fbaSalesSnapshot);
458
									orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
459
								}
460
							}
461
						}
462
						catch(Exception e){
463
							e.printStackTrace();
464
						}
465
						count++;
466
					}*/
467
					InventoryClient inventoryServiceClient = null;
468
					TransactionClient transactionServiceClient = null;
469
					CatalogClient catalogServiceClient = null;
470
					try {
471
						inventoryServiceClient = new InventoryClient();
472
						transactionServiceClient = new TransactionClient();
473
						catalogServiceClient = new CatalogClient();
474
						//catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
475
					} catch (Exception e) {
476
						// TODO Auto-generated catch block
477
						e.printStackTrace();
478
					}	
479
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
480
					in.shop2020.model.v1.order.TransactionService.Client transactionClient   = transactionServiceClient.getClient();
481
					in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
482
					SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
483
					//Date date_today = dateFormat.parse(dateFormat.format(new Date()));
484
					List<Date> dates = new ArrayList<Date>();
485
					Calendar cal = Calendar.getInstance();
486
					cal.add(Calendar.DATE, -1);
487
					Date date_end = dateFormat.parse(dateFormat.format(cal.getTime()));
488
					cal.add(Calendar.DATE, -5);
489
					Date date_start = dateFormat.parse(dateFormat.format(cal.getTime()));
490
					System.out.println("Start Date = " + date_start);
491
					System.out.println("End Date = " + date_end);
492
					Date d = date_start;
493
					while(!d.equals(date_end)){
494
						cal.setTime(d);
495
						cal.add(Calendar.DATE,1);
496
						d = cal.getTime();
497
						dates.add(d);
498
					}
499
					List<AmazonFbaInventorySnapshot> nonzeroFbaInventorySnapshotlist =  inventoryClient.getAllAmazonFbaItemInventory();
500
					for(Date date:dates){
501
						if(nonzeroFbaInventorySnapshotlist!=null){
502
							for(AmazonFbaInventorySnapshot amazonFbaInventory:nonzeroFbaInventorySnapshotlist){
503
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date) ){ 
504
									if(!orderDateItemIdFbaSaleSnapshotMap.get(date).containsKey(amazonFbaInventory.getItem_id())){
505
										Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
506
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
507
										fbaSalesSnapshot.setTotalOrderCount(0);
508
										fbaSalesSnapshot.setPromotionOrderCount(0);
509
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
510
										fbaSalesSnapshot.setTotalSale((float) 0);
511
										ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
512
										orderDateItemIdFbaSaleSnapshotMap.get(date).put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
513
									}
514
 
515
								}
516
								else{
517
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
518
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
519
									fbaSalesSnapshot.setTotalOrderCount(0);
520
									fbaSalesSnapshot.setPromotionOrderCount(0);
521
									fbaSalesSnapshot.setTotalPromotionSale((float) 0);
522
									fbaSalesSnapshot.setTotalSale((float) 0);
523
									ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
524
									orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
525
								}
526
							}
527
						}
528
						else{
529
							System.out.println("No inventory in FBA");
530
						}
531
					}
532
					Map<Long,PriceAtDate> itemIdOurPriceMap = new HashMap<Long,PriceAtDate>();
533
					Map<Long,PriceAtDate> itemIdSalePriceMap = new HashMap<Long,PriceAtDate>();
534
					Map<Long,PriceAtDate> itemIdminFBAPriceMap = new HashMap<Long,PriceAtDate>();
535
					Map<Long,PriceAtDate> itemIdminMFNPriceMap = new HashMap<Long,PriceAtDate>();
536
					count=1;
537
					while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
538
						try{
539
							if(count!=1){
540
								//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
541
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
542
								istFormatter .setLenient(false);
543
								TimeZone zone= TimeZone.getTimeZone("GMT");
544
								istFormatter.setTimeZone(zone);
545
								Date date = istFormatter.parse(nextLine[0]);
546
								Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));
547
								Double ourPrice = null;
548
								Double minFBAPrice= null;
549
								Double minMFNPrice= null;
550
								Double salePrice= null; 
551
								if(nextLine[30].length() >0){
552
									ourPrice = Double.parseDouble(nextLine[30]);
553
									if(itemIdOurPriceMap.containsKey(item_id)){
554
										if(itemIdOurPriceMap.get(item_id).getDate().getTime() < date.getTime()){
555
											PriceAtDate priceAtDate= new PriceAtDate();
556
											priceAtDate.setDate(date);
557
											priceAtDate.setPrice(ourPrice);
558
											itemIdOurPriceMap.put(item_id,priceAtDate);
559
										}
560
									}
561
									else{	
562
										PriceAtDate priceAtDate= new PriceAtDate();
563
										priceAtDate.setDate(date);
564
										priceAtDate.setPrice(ourPrice);
565
										itemIdOurPriceMap.put(item_id,priceAtDate);
566
									}
567
								}
568
								if(nextLine[31].length() >0){
569
									salePrice = Double.parseDouble(nextLine[31]);
570
									if(itemIdSalePriceMap.containsKey(item_id) ){
571
										if(itemIdSalePriceMap.get(item_id).getDate().getTime() < date.getTime()){
572
											PriceAtDate priceAtDate= new PriceAtDate();
573
											priceAtDate.setDate(date);
574
											priceAtDate.setPrice(salePrice);
575
											itemIdSalePriceMap.put(item_id,priceAtDate);
576
										}
577
									}
578
									else{	
579
										PriceAtDate priceAtDate= new PriceAtDate();
580
										priceAtDate.setDate(date);
581
										priceAtDate.setPrice(salePrice);
582
										itemIdSalePriceMap.put(item_id,priceAtDate);
583
									}
584
								}
585
								if(nextLine[32].length() >0){
586
									minFBAPrice = Double.parseDouble(nextLine[32]);
587
									if(itemIdminFBAPriceMap.containsKey(item_id)){
588
										if(itemIdminFBAPriceMap.get(item_id).getDate().getTime() < date.getTime()){
589
											PriceAtDate priceAtDate= new PriceAtDate();
590
											priceAtDate.setDate(date);
591
											priceAtDate.setPrice(minFBAPrice);
592
											itemIdminFBAPriceMap.put(item_id,priceAtDate);
593
										}
594
									}
595
									else{	
596
										PriceAtDate priceAtDate= new PriceAtDate();
597
										priceAtDate.setDate(date);
598
										priceAtDate.setPrice(minFBAPrice);
599
										itemIdminFBAPriceMap.put(item_id,priceAtDate);
600
									}
601
								}
602
								if(nextLine[34].length() >0){
603
									minMFNPrice = Double.parseDouble(nextLine[34]);
604
									if(itemIdminMFNPriceMap.containsKey(item_id)){
605
										if(itemIdminMFNPriceMap.get(item_id).getDate().getTime() < date.getTime()){
606
											PriceAtDate priceAtDate= new PriceAtDate();
607
											priceAtDate.setDate(date);
608
											priceAtDate.setPrice(minMFNPrice);
609
											itemIdminMFNPriceMap.put(item_id,priceAtDate);
610
										}
611
									}
612
									else{	
613
										PriceAtDate priceAtDate= new PriceAtDate();
614
										priceAtDate.setDate(date);
615
										priceAtDate.setPrice(minMFNPrice);
616
										itemIdminMFNPriceMap.put(item_id,priceAtDate);
617
									}
618
								}
619
							}
620
						}
621
						catch(Exception e){
622
							e.printStackTrace();
623
						}
624
						count++;
625
					}
626
					boolean oos;
627
					for (Entry<Date, Map<Long, FbaSalesSnapshot>> entry : orderDateItemIdFbaSaleSnapshotMap.entrySet()){
628
						Date orderDate = entry.getKey();
629
						for(Entry<Long, FbaSalesSnapshot> entry1 :entry.getValue().entrySet()){
630
							System.out.println("Item ID is " + entry1.getKey());
631
							Long inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
632
 
633
							if(inventory==0 && entry1.getValue().getTotalOrderCount()==0){
634
								oos=true;
635
							}
636
							else{
637
								oos=false;
638
							}
639
							Long item_id = entry1.getKey();
640
							Amazonlisted amazon_item=catalogClient.getAmazonItemDetails(item_id);
641
							if(amazon_item.getItemid()==0){
642
								continue;
643
							}
644
							System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
645
							AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
646
							amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
647
							amazonfbasalessnapshot.setItem_id(entry1.getKey());
648
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getPromotionOrderCount());
649
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getTotalOrderCount());
650
							amazonfbasalessnapshot.setTotalSale(entry1.getValue().getTotalSale());
651
							amazonfbasalessnapshot.setPromotionSale(entry1.getValue().getTotalPromotionSale());
652
							amazonfbasalessnapshot.setIsOutOfStock(oos);
653
							if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id).getPrice()!=0){
654
								amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id).getPrice());
655
								amazonfbasalessnapshot.setSalePriceSnapshotDate(itemIdSalePriceMap.get(item_id).getDate().getTime());
656
							}
657
							else{
658
								amazonfbasalessnapshot.setSalePrice(0.0);
659
								amazonfbasalessnapshot.setSalePriceSnapshotDate(0);
660
							}
661
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id).getPrice()!=0){
662
								amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id).getPrice());
663
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(itemIdminMFNPriceMap.get(item_id).getDate().getTime());
664
							}
665
							else{
666
								amazonfbasalessnapshot.setMinMfnPrice(0.0);
667
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(0);
668
							}
669
							if(itemIdminFBAPriceMap.containsKey(item_id) && itemIdminFBAPriceMap.get(item_id).getPrice()!=0){
670
								amazonfbasalessnapshot.setMinFbaPrice(itemIdminFBAPriceMap.get(item_id).getPrice());
671
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(itemIdminFBAPriceMap.get(item_id).getDate().getTime());
672
							}
673
							else{
674
								amazonfbasalessnapshot.setMinFbaPrice(0.0);
675
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(0);
676
							}
677
							if(itemIdOurPriceMap.containsKey(item_id) && itemIdOurPriceMap.get(item_id).getPrice()!=0){
678
								amazonfbasalessnapshot.setOurPrice(itemIdOurPriceMap.get(item_id).getPrice());
679
								amazonfbasalessnapshot.setOurPriceSnapshotDate(itemIdOurPriceMap.get(item_id).getDate().getTime());
680
							}
681
							else{
682
								amazonfbasalessnapshot.setOurPrice(amazon_item.getFbaPrice());
683
								amazonfbasalessnapshot.setOurPriceSnapshotDate(0);
684
							}
685
							amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
686
							transactionClient.addOrUpdateAmazonFbaSalesSnapshot(amazonfbasalessnapshot);
687
						}
688
					}
689
				} catch (IOException e) {
690
					// TODO Auto-generated catch block
691
					e.printStackTrace();
692
				} catch (ParseException e) {
693
					// TODO Auto-generated catch block
694
					e.printStackTrace();
695
				} catch (TException e) {
696
					// TODO Auto-generated catch block
697
					e.printStackTrace();
698
					continue;
699
				}
700
				break;
701
 
702
			}
703
			else{ 
704
				System.out.println("Report not ready");
705
				try {
706
					Thread.sleep(5*60*1000);
707
				} catch (InterruptedException e) {
708
					// TODO Auto-generated catch block
709
					e.printStackTrace();
710
				}
711
			}
712
		}
713
 
714
		// Note that depending on the type of report being downloaded, a report can reach 
715
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
716
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
717
		// the in-memory size limit and have to re-work your solution.
718
		//
719
 
720
 
721
	}
722
 
723
 
724
 
725
}