Subversion Repositories SmartDukaan

Rev

Rev 9785 | Rev 9917 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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