Subversion Repositories SmartDukaan

Rev

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