Subversion Repositories SmartDukaan

Rev

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