Subversion Repositories SmartDukaan

Rev

Rev 10997 | Rev 11172 | 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
						e.printStackTrace();
485
					}	
486
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
487
					in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
488
					SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
489
					//Date date_today = dateFormat.parse(dateFormat.format(new Date()));
490
					List<Date> dates = new ArrayList<Date>();
491
					Calendar cal = Calendar.getInstance();
492
					cal.add(Calendar.DATE, -1);
493
					Date date_end = dateFormat.parse(dateFormat.format(cal.getTime()));
494
					cal.add(Calendar.DATE, -5);
495
					Date date_start = dateFormat.parse(dateFormat.format(cal.getTime()));
496
					System.out.println("Start Date = " + date_start);
497
					System.out.println("End Date = " + date_end);
498
					Date d = date_start;
499
					while(!d.equals(date_end)){
500
						cal.setTime(d);
501
						cal.add(Calendar.DATE,1);
502
						d = cal.getTime();
503
						dates.add(d);
504
					}
505
					List<AmazonFbaInventorySnapshot> nonzeroFbaInventorySnapshotlist =  inventoryClient.getAllAmazonFbaItemInventory();
506
					for(Date date:dates){
507
						if(nonzeroFbaInventorySnapshotlist!=null){
508
							for(AmazonFbaInventorySnapshot amazonFbaInventory:nonzeroFbaInventorySnapshotlist){
509
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date) ){ 
510
									if(!orderDateItemIdFbaSaleSnapshotMap.get(date).containsKey(amazonFbaInventory.getItem_id())){
511
										Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
512
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
513
										fbaSalesSnapshot.setTotalOrderCount(0);
514
										fbaSalesSnapshot.setPromotionOrderCount(0);
515
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
516
										fbaSalesSnapshot.setTotalSale((float) 0);
517
										ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
518
										orderDateItemIdFbaSaleSnapshotMap.get(date).put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
519
									}
520
 
521
								}
522
								else{
523
									Map<Long,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<Long,FbaSalesSnapshot>();
524
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
525
									fbaSalesSnapshot.setTotalOrderCount(0);
526
									fbaSalesSnapshot.setPromotionOrderCount(0);
527
									fbaSalesSnapshot.setTotalPromotionSale((float) 0);
528
									fbaSalesSnapshot.setTotalSale((float) 0);
529
									ItemIdFbaSaleSnapshotMap.put(amazonFbaInventory.getItem_id(),fbaSalesSnapshot);
530
									orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
531
								}
532
							}
533
						}
534
						else{
535
							System.out.println("No inventory in FBA");
536
						}
537
					}
538
					Map<Long,PriceAtDate> itemIdOurPriceMap = new HashMap<Long,PriceAtDate>();
539
					Map<Long,PriceAtDate> itemIdSalePriceMap = new HashMap<Long,PriceAtDate>();
540
					Map<Long,PriceAtDate> itemIdminFBAPriceMap = new HashMap<Long,PriceAtDate>();
541
					Map<Long,PriceAtDate> itemIdminMFNPriceMap = new HashMap<Long,PriceAtDate>();
542
					count=1;
543
					while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
544
						try{
545
							if(count!=1){
546
								//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
547
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
548
								istFormatter .setLenient(false);
549
								TimeZone zone= TimeZone.getTimeZone("GMT");
550
								istFormatter.setTimeZone(zone);
551
								Date date = istFormatter.parse(nextLine[0]);
552
								Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));
553
								Double ourPrice = null;
554
								Double minFBAPrice= null;
555
								Double minMFNPrice= null;
556
								Double salePrice= null; 
557
								if(nextLine[30].length() >0){
558
									ourPrice = Double.parseDouble(nextLine[30]);
559
									if(itemIdOurPriceMap.containsKey(item_id)){
560
										if(itemIdOurPriceMap.get(item_id).getDate().getTime() < date.getTime()){
561
											PriceAtDate priceAtDate= new PriceAtDate();
562
											priceAtDate.setDate(date);
563
											priceAtDate.setPrice(ourPrice);
564
											itemIdOurPriceMap.put(item_id,priceAtDate);
565
										}
566
									}
567
									else{	
568
										PriceAtDate priceAtDate= new PriceAtDate();
569
										priceAtDate.setDate(date);
570
										priceAtDate.setPrice(ourPrice);
571
										itemIdOurPriceMap.put(item_id,priceAtDate);
572
									}
573
								}
574
								if(nextLine[31].length() >0){
575
									salePrice = Double.parseDouble(nextLine[31]);
576
									if(itemIdSalePriceMap.containsKey(item_id) ){
577
										if(itemIdSalePriceMap.get(item_id).getDate().getTime() < date.getTime()){
578
											PriceAtDate priceAtDate= new PriceAtDate();
579
											priceAtDate.setDate(date);
580
											priceAtDate.setPrice(salePrice);
581
											itemIdSalePriceMap.put(item_id,priceAtDate);
582
										}
583
									}
584
									else{	
585
										PriceAtDate priceAtDate= new PriceAtDate();
586
										priceAtDate.setDate(date);
587
										priceAtDate.setPrice(salePrice);
588
										itemIdSalePriceMap.put(item_id,priceAtDate);
589
									}
590
								}
591
								if(nextLine[32].length() >0){
592
									minFBAPrice = Double.parseDouble(nextLine[32]);
593
									if(itemIdminFBAPriceMap.containsKey(item_id)){
594
										if(itemIdminFBAPriceMap.get(item_id).getDate().getTime() < date.getTime()){
595
											PriceAtDate priceAtDate= new PriceAtDate();
596
											priceAtDate.setDate(date);
597
											priceAtDate.setPrice(minFBAPrice);
598
											itemIdminFBAPriceMap.put(item_id,priceAtDate);
599
										}
600
									}
601
									else{	
602
										PriceAtDate priceAtDate= new PriceAtDate();
603
										priceAtDate.setDate(date);
604
										priceAtDate.setPrice(minFBAPrice);
605
										itemIdminFBAPriceMap.put(item_id,priceAtDate);
606
									}
607
								}
608
								if(nextLine[34].length() >0){
609
									minMFNPrice = Double.parseDouble(nextLine[34]);
610
									if(itemIdminMFNPriceMap.containsKey(item_id)){
611
										if(itemIdminMFNPriceMap.get(item_id).getDate().getTime() < date.getTime()){
612
											PriceAtDate priceAtDate= new PriceAtDate();
613
											priceAtDate.setDate(date);
614
											priceAtDate.setPrice(minMFNPrice);
615
											itemIdminMFNPriceMap.put(item_id,priceAtDate);
616
										}
617
									}
618
									else{	
619
										PriceAtDate priceAtDate= new PriceAtDate();
620
										priceAtDate.setDate(date);
621
										priceAtDate.setPrice(minMFNPrice);
622
										itemIdminMFNPriceMap.put(item_id,priceAtDate);
623
									}
624
								}
625
							}
626
						}
627
						catch(Exception e){
628
							e.printStackTrace();
629
						}
630
						count++;
631
					}
632
					boolean oos;
9802 manish.sha 633
					List<AmazonFbaSalesSnapshot> fbaSalesSnapShotList = new ArrayList<AmazonFbaSalesSnapshot>();
9777 manish.sha 634
					for (Entry<Date, Map<Long, FbaSalesSnapshot>> entry : orderDateItemIdFbaSaleSnapshotMap.entrySet()){
635
						Date orderDate = entry.getKey();
636
						for(Entry<Long, FbaSalesSnapshot> entry1 :entry.getValue().entrySet()){
637
							System.out.println("Item ID is " + entry1.getKey());
10906 vikram.rag 638
							Long inventory;
639
							try{
640
								inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
641
							}
642
							catch(TTransportException e){
643
								inventoryClient = inventoryServiceClient.getClient();
644
								inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
645
							}
9777 manish.sha 646
							if(inventory==0 && entry1.getValue().getTotalOrderCount()==0){
647
								oos=true;
648
							}
649
							else{
650
								oos=false;
651
							}
652
							Long item_id = entry1.getKey();
10905 vikram.rag 653
							Amazonlisted amazon_item;
654
							try{
655
								amazon_item=catalogClient.getAmazonItemDetails(item_id);
656
							}
657
							catch(TTransportException e){
658
								catalogClient   = catalogServiceClient.getClient();
659
								amazon_item=catalogClient.getAmazonItemDetails(item_id);
660
							}
9777 manish.sha 661
							if(amazon_item.getItemid()==0){
662
								continue;
663
							}
664
							System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
665
							AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
666
							amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
667
							amazonfbasalessnapshot.setItem_id(entry1.getKey());
668
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getPromotionOrderCount());
669
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getTotalOrderCount());
670
							amazonfbasalessnapshot.setTotalSale(entry1.getValue().getTotalSale());
671
							amazonfbasalessnapshot.setPromotionSale(entry1.getValue().getTotalPromotionSale());
672
							amazonfbasalessnapshot.setIsOutOfStock(oos);
673
							if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id).getPrice()!=0){
674
								amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id).getPrice());
675
								amazonfbasalessnapshot.setSalePriceSnapshotDate(itemIdSalePriceMap.get(item_id).getDate().getTime());
676
							}
677
							else{
678
								amazonfbasalessnapshot.setSalePrice(0.0);
679
								amazonfbasalessnapshot.setSalePriceSnapshotDate(0);
680
							}
681
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id).getPrice()!=0){
682
								amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id).getPrice());
683
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(itemIdminMFNPriceMap.get(item_id).getDate().getTime());
684
							}
685
							else{
686
								amazonfbasalessnapshot.setMinMfnPrice(0.0);
687
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(0);
688
							}
689
							if(itemIdminFBAPriceMap.containsKey(item_id) && itemIdminFBAPriceMap.get(item_id).getPrice()!=0){
690
								amazonfbasalessnapshot.setMinFbaPrice(itemIdminFBAPriceMap.get(item_id).getPrice());
691
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(itemIdminFBAPriceMap.get(item_id).getDate().getTime());
692
							}
693
							else{
694
								amazonfbasalessnapshot.setMinFbaPrice(0.0);
695
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(0);
696
							}
697
							if(itemIdOurPriceMap.containsKey(item_id) && itemIdOurPriceMap.get(item_id).getPrice()!=0){
698
								amazonfbasalessnapshot.setOurPrice(itemIdOurPriceMap.get(item_id).getPrice());
699
								amazonfbasalessnapshot.setOurPriceSnapshotDate(itemIdOurPriceMap.get(item_id).getDate().getTime());
700
							}
701
							else{
702
								amazonfbasalessnapshot.setOurPrice(amazon_item.getFbaPrice());
703
								amazonfbasalessnapshot.setOurPriceSnapshotDate(0);
704
							}
705
							amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
9802 manish.sha 706
							fbaSalesSnapShotList.add(amazonfbasalessnapshot);
9777 manish.sha 707
						}
708
					}
9917 manish.sha 709
					System.out.println("Order Details to be Updated Size... "+fbaSalesSnapShotList.size());
11062 vikram.rag 710
					try{
711
						transactionServiceClient.getClient().bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
712
					}
713
					catch(TTransportException ex){
714
						new TransactionClient().getClient().bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
715
					}
9777 manish.sha 716
				} catch (IOException e) {
717
					// TODO Auto-generated catch block
718
					e.printStackTrace();
719
				} catch (ParseException e) {
720
					// TODO Auto-generated catch block
11062 vikram.rag 721
					e.printStackTrace(); 
9777 manish.sha 722
				} catch (TException e) {
723
					// TODO Auto-generated catch block
724
					e.printStackTrace();
10905 vikram.rag 725
 
9777 manish.sha 726
				}
727
				break;
728
 
729
			}
730
			else{ 
731
				System.out.println("Report not ready");
732
				try {
733
					Thread.sleep(5*60*1000);
734
				} catch (InterruptedException e) {
735
					// TODO Auto-generated catch block
736
					e.printStackTrace();
737
				}
738
			}
739
		}
740
 
741
		// Note that depending on the type of report being downloaded, a report can reach 
742
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
743
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
744
		// the in-memory size limit and have to re-work your solution.
745
		//
746
 
747
 
748
	}
749
 
10905 vikram.rag 750
 
751
 
9777 manish.sha 752
}