Subversion Repositories SmartDukaan

Rev

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