Subversion Repositories SmartDukaan

Rev

Rev 9917 | Rev 10905 | Go to most recent revision | Details | Compare with Previous | 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();
9917 manish.sha 285
						System.out.println("Amazon Order List ... "+orderMessageList.size());
9777 manish.sha 286
						for(Message orderMessage : orderMessageList){
287
							Order amazonOrder = orderMessage.getOrder();
288
							FulfillmentData orderFullfillmentData = amazonOrder.getFulfillmentData();
289
							if("Amazon.in".equalsIgnoreCase(amazonOrder.getSalesChannel()) && "Amazon".equalsIgnoreCase(orderFullfillmentData.getFulfillmentChannel())){
290
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
291
								istFormatter .setLenient(false);
292
								TimeZone zone= TimeZone.getTimeZone("GMT");
293
								istFormatter.setTimeZone(zone);
294
								Date date = istFormatter.parse(amazonOrder.getPurchaseDate().toString());
295
								SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
296
								Date date_key = dateFormat.parse(dateFormat.format(date));
297
								System.out.println("Order Details " + amazonOrder.getAmazonOrderID()+" "+date_key+" "+ amazonOrder.getOrderItem().get(0).getSKU()  +" " + amazonOrder.getOrderItem().get(0).getItemStatus() + " " + amazonOrder.getOrderItem().get(0).getQuantity());
298
								Long itemid = Long.parseLong(amazonOrder.getOrderItem().get(0).getSKU().replaceAll("FBA",""));
299
								Integer qty=0;
300
								if(amazonOrder.getOrderItem().get(0).getQuantity()!=0){
301
									qty = new Integer(amazonOrder.getOrderItem().get(0).getQuantity());
302
								}
303
								Float itemSale = null;
9785 manish.sha 304
								if(amazonOrder.getOrderItem().get(0).getItemPrice()!=null && amazonOrder.getOrderItem().get(0).getItemPrice().getComponent()!=null && amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().size()>0){
305
									if(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getValue()!=0){
306
										itemSale = new Float(amazonOrder.getOrderItem().get(0).getItemPrice().getComponent().get(0).getAmount().getValue());
307
									}
308
									else{
309
										continue;
310
									}
9777 manish.sha 311
								}
9785 manish.sha 312
 
9777 manish.sha 313
								else{
314
									continue;
315
								}
316
 
317
								Float itemDiscount; 
318
								if(amazonOrder.getOrderItem().get(0).getPromotion()!=null){
9785 manish.sha 319
									if(amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount()!=null && amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount().floatValue()!=0.0f){
320
										itemDiscount = amazonOrder.getOrderItem().get(0).getPromotion().getItemPromotionDiscount();
9777 manish.sha 321
									}
322
									else{
323
										itemDiscount = new Float(0);
324
									}
325
								}
326
								else{
327
									itemDiscount = new Float(0);
328
								}
329
 
330
								if(("Cancelled").equalsIgnoreCase(amazonOrder.getOrderStatus()) || ("Cancelled").equalsIgnoreCase(amazonOrder.getOrderItem().get(0).getItemStatus())){
331
									itemSale = (float) 0; 
332
									itemDiscount = (float) 0;
333
									qty = 0;
334
								}
335
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date_key)){
336
									if(orderDateItemIdFbaSaleSnapshotMap.get(date_key).containsKey(itemid)){
337
										FbaSalesSnapshot fbaSalesSnapshot = orderDateItemIdFbaSaleSnapshotMap.get(date_key).get(itemid);
338
										if(itemDiscount!=0){
339
											fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);
340
											fbaSalesSnapshot.setTotalPromotionSale(fbaSalesSnapshot.getTotalPromotionSale() + (itemSale - itemDiscount));
341
										}
342
										else{
343
											fbaSalesSnapshot.setPromotionOrderCount(0);
344
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
345
										}
346
										fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);
347
										fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);
348
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
349
									}
350
									else{
351
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
352
										fbaSalesSnapshot.setTotalOrderCount(qty);
353
										fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);
354
										if(itemDiscount!=0){
355
											fbaSalesSnapshot.setPromotionOrderCount(qty);
356
											fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
357
										}
358
										else{
359
											fbaSalesSnapshot.setPromotionOrderCount(0);
360
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
361
										}
362
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
363
									}
364
								}
365
								else{
366
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
367
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
368
									fbaSalesSnapshot.setTotalOrderCount(qty);
369
									fbaSalesSnapshot.setTotalSale(itemSale);
370
									if(itemDiscount!=0){
371
										fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
372
										fbaSalesSnapshot.setPromotionOrderCount(qty);
373
									}
374
									else{
375
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
376
										fbaSalesSnapshot.setPromotionOrderCount(0);
377
									}
378
									ItemIdFbaSaleSnapshotMap.put(itemid,fbaSalesSnapshot);
379
									orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
380
								}
381
							}
382
						}
383
					}
384
 
385
					/*while ((nextLine = orderreportreader.readNext()) != null) {
386
						try{
387
							if(count!=1 && nextLine[5].equalsIgnoreCase("Amazon") && nextLine[6].equalsIgnoreCase("Amazon.in")){
388
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
389
								istFormatter .setLenient(false);
390
								TimeZone zone= TimeZone.getTimeZone("GMT");
391
								istFormatter.setTimeZone(zone);
392
								Date date = istFormatter.parse(nextLine[2]);
393
								SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
394
								Date date_key = dateFormat.parse(dateFormat.format(date));
395
								System.out.println("Order Details " + nextLine[0]+" "+date_key+" "+ nextLine[11] +" " + nextLine[13] + " " + nextLine[14]);
396
								// 0- amazon-order-id 11- sku 13- item-status 14 - quantity
397
								Long itemid = Long.parseLong(nextLine[11].replaceAll("FBA",""));
398
								Integer qty=0;
399
								if(nextLine[14].length()!=0){
400
									qty = new Integer(nextLine[14]);
401
								}
402
								Float itemSale = null;
403
								if(nextLine[16].length()!=0){
404
									itemSale = new Float(nextLine[16]);
405
								}
406
								else{
407
									continue;
408
								}
409
								Float itemDiscount; 
410
								if(nextLine[22].length()!=0){
411
									itemDiscount = new Float(nextLine[22]);
412
								}
413
								else{
414
									itemDiscount = new Float(0);
415
								}
416
								if(nextLine[4].equalsIgnoreCase("Cancelled") || nextLine[13].equalsIgnoreCase("Cancelled")){
417
									itemSale = (float) 0; 
418
									itemDiscount = (float) 0;
419
									qty = 0;
420
								}
421
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date_key)){
422
									if(orderDateItemIdFbaSaleSnapshotMap.get(date_key).containsKey(itemid)){
423
										FbaSalesSnapshot fbaSalesSnapshot = orderDateItemIdFbaSaleSnapshotMap.get(date_key).get(itemid);
424
										if(itemDiscount!=0){
425
											fbaSalesSnapshot.setPromotionOrderCount(fbaSalesSnapshot.getPromotionOrderCount()+qty);
426
											fbaSalesSnapshot.setTotalPromotionSale(fbaSalesSnapshot.getTotalPromotionSale() + (itemSale - itemDiscount));
427
										}
428
										else{
429
											fbaSalesSnapshot.setPromotionOrderCount(0);
430
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
431
										}
432
										fbaSalesSnapshot.setTotalOrderCount(fbaSalesSnapshot.getTotalOrderCount() + qty);
433
										fbaSalesSnapshot.setTotalSale(fbaSalesSnapshot.getTotalSale() + itemSale - itemDiscount);
434
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
435
									}
436
									else{
437
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
438
										fbaSalesSnapshot.setTotalOrderCount(qty);
439
										fbaSalesSnapshot.setTotalSale(itemSale - itemDiscount);
440
										if(itemDiscount!=0){
441
											fbaSalesSnapshot.setPromotionOrderCount(qty);
442
											fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
443
										}
444
										else{
445
											fbaSalesSnapshot.setPromotionOrderCount(0);
446
											fbaSalesSnapshot.setTotalPromotionSale((float) 0);
447
										}
448
										orderDateItemIdFbaSaleSnapshotMap.get(date_key).put(itemid,fbaSalesSnapshot);
449
									}
450
								}
451
								else{
452
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
453
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
454
									fbaSalesSnapshot.setTotalOrderCount(qty);
455
									fbaSalesSnapshot.setTotalSale(itemSale);
456
									if(itemDiscount!=0){
457
										fbaSalesSnapshot.setTotalPromotionSale(itemSale - itemDiscount);
458
										fbaSalesSnapshot.setPromotionOrderCount(qty);
459
									}
460
									else{
461
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
462
										fbaSalesSnapshot.setPromotionOrderCount(0);
463
									}
464
									ItemIdFbaSaleSnapshotMap.put(itemid,fbaSalesSnapshot);
465
									orderDateItemIdFbaSaleSnapshotMap.put(date_key,ItemIdFbaSaleSnapshotMap);
466
								}
467
							}
468
						}
469
						catch(Exception e){
470
							e.printStackTrace();
471
						}
472
						count++;
473
					}*/
474
					InventoryClient inventoryServiceClient = null;
475
					TransactionClient transactionServiceClient = null;
476
					CatalogClient catalogServiceClient = null;
477
					try {
478
						inventoryServiceClient = new InventoryClient();
479
						transactionServiceClient = new TransactionClient();
10532 vikram.rag 480
						//catalogServiceClient = new CatalogClient();
481
						catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
9777 manish.sha 482
					} catch (Exception e) {
483
						// TODO Auto-generated catch block
484
						e.printStackTrace();
485
					}	
486
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
487
					in.shop2020.model.v1.order.TransactionService.Client transactionClient   = transactionServiceClient.getClient();
488
					in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
489
					SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
490
					//Date date_today = dateFormat.parse(dateFormat.format(new Date()));
491
					List<Date> dates = new ArrayList<Date>();
492
					Calendar cal = Calendar.getInstance();
493
					cal.add(Calendar.DATE, -1);
494
					Date date_end = dateFormat.parse(dateFormat.format(cal.getTime()));
495
					cal.add(Calendar.DATE, -5);
496
					Date date_start = dateFormat.parse(dateFormat.format(cal.getTime()));
497
					System.out.println("Start Date = " + date_start);
498
					System.out.println("End Date = " + date_end);
499
					Date d = date_start;
500
					while(!d.equals(date_end)){
501
						cal.setTime(d);
502
						cal.add(Calendar.DATE,1);
503
						d = cal.getTime();
504
						dates.add(d);
505
					}
506
					List<AmazonFbaInventorySnapshot> nonzeroFbaInventorySnapshotlist =  inventoryClient.getAllAmazonFbaItemInventory();
507
					for(Date date:dates){
508
						if(nonzeroFbaInventorySnapshotlist!=null){
509
							for(AmazonFbaInventorySnapshot amazonFbaInventory:nonzeroFbaInventorySnapshotlist){
510
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date) ){ 
511
									if(!orderDateItemIdFbaSaleSnapshotMap.get(date).containsKey(amazonFbaInventory.getItem_id())){
512
										Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
513
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
514
										fbaSalesSnapshot.setTotalOrderCount(0);
515
										fbaSalesSnapshot.setPromotionOrderCount(0);
516
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
517
										fbaSalesSnapshot.setTotalSale((float) 0);
518
										ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
519
										orderDateItemIdFbaSaleSnapshotMap.get(date).put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
520
									}
521
 
522
								}
523
								else{
524
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
525
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
526
									fbaSalesSnapshot.setTotalOrderCount(0);
527
									fbaSalesSnapshot.setPromotionOrderCount(0);
528
									fbaSalesSnapshot.setTotalPromotionSale((float) 0);
529
									fbaSalesSnapshot.setTotalSale((float) 0);
530
									ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
531
									orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
532
								}
533
							}
534
						}
535
						else{
536
							System.out.println("No inventory in FBA");
537
						}
538
					}
539
					Map<Long,PriceAtDate> itemIdOurPriceMap = new HashMap<Long,PriceAtDate>();
540
					Map<Long,PriceAtDate> itemIdSalePriceMap = new HashMap<Long,PriceAtDate>();
541
					Map<Long,PriceAtDate> itemIdminFBAPriceMap = new HashMap<Long,PriceAtDate>();
542
					Map<Long,PriceAtDate> itemIdminMFNPriceMap = new HashMap<Long,PriceAtDate>();
543
					count=1;
544
					while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
545
						try{
546
							if(count!=1){
547
								//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
548
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
549
								istFormatter .setLenient(false);
550
								TimeZone zone= TimeZone.getTimeZone("GMT");
551
								istFormatter.setTimeZone(zone);
552
								Date date = istFormatter.parse(nextLine[0]);
553
								Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));
554
								Double ourPrice = null;
555
								Double minFBAPrice= null;
556
								Double minMFNPrice= null;
557
								Double salePrice= null; 
558
								if(nextLine[30].length() >0){
559
									ourPrice = Double.parseDouble(nextLine[30]);
560
									if(itemIdOurPriceMap.containsKey(item_id)){
561
										if(itemIdOurPriceMap.get(item_id).getDate().getTime() < date.getTime()){
562
											PriceAtDate priceAtDate= new PriceAtDate();
563
											priceAtDate.setDate(date);
564
											priceAtDate.setPrice(ourPrice);
565
											itemIdOurPriceMap.put(item_id,priceAtDate);
566
										}
567
									}
568
									else{	
569
										PriceAtDate priceAtDate= new PriceAtDate();
570
										priceAtDate.setDate(date);
571
										priceAtDate.setPrice(ourPrice);
572
										itemIdOurPriceMap.put(item_id,priceAtDate);
573
									}
574
								}
575
								if(nextLine[31].length() >0){
576
									salePrice = Double.parseDouble(nextLine[31]);
577
									if(itemIdSalePriceMap.containsKey(item_id) ){
578
										if(itemIdSalePriceMap.get(item_id).getDate().getTime() < date.getTime()){
579
											PriceAtDate priceAtDate= new PriceAtDate();
580
											priceAtDate.setDate(date);
581
											priceAtDate.setPrice(salePrice);
582
											itemIdSalePriceMap.put(item_id,priceAtDate);
583
										}
584
									}
585
									else{	
586
										PriceAtDate priceAtDate= new PriceAtDate();
587
										priceAtDate.setDate(date);
588
										priceAtDate.setPrice(salePrice);
589
										itemIdSalePriceMap.put(item_id,priceAtDate);
590
									}
591
								}
592
								if(nextLine[32].length() >0){
593
									minFBAPrice = Double.parseDouble(nextLine[32]);
594
									if(itemIdminFBAPriceMap.containsKey(item_id)){
595
										if(itemIdminFBAPriceMap.get(item_id).getDate().getTime() < date.getTime()){
596
											PriceAtDate priceAtDate= new PriceAtDate();
597
											priceAtDate.setDate(date);
598
											priceAtDate.setPrice(minFBAPrice);
599
											itemIdminFBAPriceMap.put(item_id,priceAtDate);
600
										}
601
									}
602
									else{	
603
										PriceAtDate priceAtDate= new PriceAtDate();
604
										priceAtDate.setDate(date);
605
										priceAtDate.setPrice(minFBAPrice);
606
										itemIdminFBAPriceMap.put(item_id,priceAtDate);
607
									}
608
								}
609
								if(nextLine[34].length() >0){
610
									minMFNPrice = Double.parseDouble(nextLine[34]);
611
									if(itemIdminMFNPriceMap.containsKey(item_id)){
612
										if(itemIdminMFNPriceMap.get(item_id).getDate().getTime() < date.getTime()){
613
											PriceAtDate priceAtDate= new PriceAtDate();
614
											priceAtDate.setDate(date);
615
											priceAtDate.setPrice(minMFNPrice);
616
											itemIdminMFNPriceMap.put(item_id,priceAtDate);
617
										}
618
									}
619
									else{	
620
										PriceAtDate priceAtDate= new PriceAtDate();
621
										priceAtDate.setDate(date);
622
										priceAtDate.setPrice(minMFNPrice);
623
										itemIdminMFNPriceMap.put(item_id,priceAtDate);
624
									}
625
								}
626
							}
627
						}
628
						catch(Exception e){
629
							e.printStackTrace();
630
						}
631
						count++;
632
					}
633
					boolean oos;
9802 manish.sha 634
					List<AmazonFbaSalesSnapshot> fbaSalesSnapShotList = new ArrayList<AmazonFbaSalesSnapshot>();
9777 manish.sha 635
					for (Entry<Date, Map<Long, FbaSalesSnapshot>> entry : orderDateItemIdFbaSaleSnapshotMap.entrySet()){
636
						Date orderDate = entry.getKey();
637
						for(Entry<Long, FbaSalesSnapshot> entry1 :entry.getValue().entrySet()){
638
							System.out.println("Item ID is " + entry1.getKey());
639
							Long inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
640
 
641
							if(inventory==0 && entry1.getValue().getTotalOrderCount()==0){
642
								oos=true;
643
							}
644
							else{
645
								oos=false;
646
							}
647
							Long item_id = entry1.getKey();
648
							Amazonlisted amazon_item=catalogClient.getAmazonItemDetails(item_id);
649
							if(amazon_item.getItemid()==0){
650
								continue;
651
							}
652
							System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
653
							AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
654
							amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
655
							amazonfbasalessnapshot.setItem_id(entry1.getKey());
656
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getPromotionOrderCount());
657
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getTotalOrderCount());
658
							amazonfbasalessnapshot.setTotalSale(entry1.getValue().getTotalSale());
659
							amazonfbasalessnapshot.setPromotionSale(entry1.getValue().getTotalPromotionSale());
660
							amazonfbasalessnapshot.setIsOutOfStock(oos);
661
							if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id).getPrice()!=0){
662
								amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id).getPrice());
663
								amazonfbasalessnapshot.setSalePriceSnapshotDate(itemIdSalePriceMap.get(item_id).getDate().getTime());
664
							}
665
							else{
666
								amazonfbasalessnapshot.setSalePrice(0.0);
667
								amazonfbasalessnapshot.setSalePriceSnapshotDate(0);
668
							}
669
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id).getPrice()!=0){
670
								amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id).getPrice());
671
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(itemIdminMFNPriceMap.get(item_id).getDate().getTime());
672
							}
673
							else{
674
								amazonfbasalessnapshot.setMinMfnPrice(0.0);
675
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(0);
676
							}
677
							if(itemIdminFBAPriceMap.containsKey(item_id) && itemIdminFBAPriceMap.get(item_id).getPrice()!=0){
678
								amazonfbasalessnapshot.setMinFbaPrice(itemIdminFBAPriceMap.get(item_id).getPrice());
679
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(itemIdminFBAPriceMap.get(item_id).getDate().getTime());
680
							}
681
							else{
682
								amazonfbasalessnapshot.setMinFbaPrice(0.0);
683
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(0);
684
							}
685
							if(itemIdOurPriceMap.containsKey(item_id) && itemIdOurPriceMap.get(item_id).getPrice()!=0){
686
								amazonfbasalessnapshot.setOurPrice(itemIdOurPriceMap.get(item_id).getPrice());
687
								amazonfbasalessnapshot.setOurPriceSnapshotDate(itemIdOurPriceMap.get(item_id).getDate().getTime());
688
							}
689
							else{
690
								amazonfbasalessnapshot.setOurPrice(amazon_item.getFbaPrice());
691
								amazonfbasalessnapshot.setOurPriceSnapshotDate(0);
692
							}
693
							amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
9802 manish.sha 694
							fbaSalesSnapShotList.add(amazonfbasalessnapshot);
9777 manish.sha 695
						}
696
					}
9917 manish.sha 697
					System.out.println("Order Details to be Updated Size... "+fbaSalesSnapShotList.size());
9802 manish.sha 698
					transactionServiceClient.getClient().bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
9777 manish.sha 699
				} catch (IOException e) {
700
					// TODO Auto-generated catch block
701
					e.printStackTrace();
702
				} catch (ParseException e) {
703
					// TODO Auto-generated catch block
704
					e.printStackTrace();
705
				} catch (TException e) {
706
					// TODO Auto-generated catch block
707
					e.printStackTrace();
9917 manish.sha 708
 
9777 manish.sha 709
				}
710
				break;
711
 
712
			}
713
			else{ 
714
				System.out.println("Report not ready");
715
				try {
716
					Thread.sleep(5*60*1000);
717
				} catch (InterruptedException e) {
718
					// TODO Auto-generated catch block
719
					e.printStackTrace();
720
				}
721
			}
722
		}
723
 
724
		// Note that depending on the type of report being downloaded, a report can reach 
725
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
726
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
727
		// the in-memory size limit and have to re-work your solution.
728
		//
729
 
730
 
731
	}
732
 
733
 
734
 
735
}