Subversion Repositories SmartDukaan

Rev

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