Subversion Repositories SmartDukaan

Rev

Rev 11196 | Rev 11471 | 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){
11196 vikram.rag 442
								if(amazonFbaInventory.getLocation().getValue()==AmazonFCWarehouseLocation.Bangalore.getValue()){
11172 vikram.rag 443
									prefix = "FBB";
444
								}
11196 vikram.rag 445
								else if(amazonFbaInventory.getLocation().getValue()==AmazonFCWarehouseLocation.Mumbai.getValue()){
11172 vikram.rag 446
									prefix = "FBA";
447
								}
448
								else{
449
									continue;
450
								}
451
								if(orderDateItemIdFbaSaleSnapshotMap.containsKey(date) ){
452
									if(!orderDateItemIdFbaSaleSnapshotMap.get(date).containsKey(prefix+String.valueOf(amazonFbaInventory.getItem_id()))){
453
										Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = orderDateItemIdFbaSaleSnapshotMap.get(date);
9777 manish.sha 454
										FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
455
										fbaSalesSnapshot.setTotalOrderCount(0);
456
										fbaSalesSnapshot.setPromotionOrderCount(0);
457
										fbaSalesSnapshot.setTotalPromotionSale((float) 0);
458
										fbaSalesSnapshot.setTotalSale((float) 0);
11172 vikram.rag 459
										ItemIdFbaSaleSnapshotMap.put(prefix+String.valueOf(amazonFbaInventory.getItem_id()),fbaSalesSnapshot);
460
										orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
9777 manish.sha 461
									}
462
								}
463
								else{
11172 vikram.rag 464
									Map<String,FbaSalesSnapshot> ItemIdFbaSaleSnapshotMap = new HashMap<String,FbaSalesSnapshot>();
9777 manish.sha 465
									FbaSalesSnapshot fbaSalesSnapshot = new FbaSalesSnapshot();
466
									fbaSalesSnapshot.setTotalOrderCount(0);
467
									fbaSalesSnapshot.setPromotionOrderCount(0);
468
									fbaSalesSnapshot.setTotalPromotionSale((float) 0);
469
									fbaSalesSnapshot.setTotalSale((float) 0);
11172 vikram.rag 470
									ItemIdFbaSaleSnapshotMap.put(prefix+String.valueOf(amazonFbaInventory.getItem_id()),fbaSalesSnapshot);
9777 manish.sha 471
									orderDateItemIdFbaSaleSnapshotMap.put(date,ItemIdFbaSaleSnapshotMap);
472
								}
473
							}
474
						}
475
						else{
11172 vikram.rag 476
							System.out.println("No inventory at Amazon FC");
9777 manish.sha 477
						}
478
					}
479
					Map<Long,PriceAtDate> itemIdOurPriceMap = new HashMap<Long,PriceAtDate>();
480
					Map<Long,PriceAtDate> itemIdSalePriceMap = new HashMap<Long,PriceAtDate>();
481
					Map<Long,PriceAtDate> itemIdminFBAPriceMap = new HashMap<Long,PriceAtDate>();
482
					Map<Long,PriceAtDate> itemIdminMFNPriceMap = new HashMap<Long,PriceAtDate>();
483
					count=1;
484
					while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
485
						try{
486
							if(count!=1){
487
								//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
488
								SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
489
								istFormatter .setLenient(false);
490
								TimeZone zone= TimeZone.getTimeZone("GMT");
491
								istFormatter.setTimeZone(zone);
492
								Date date = istFormatter.parse(nextLine[0]);
11172 vikram.rag 493
								if(nextLine[1].length()> 0 && (nextLine[1].startsWith("FBA") || nextLine[1].startsWith("FBB"))){
494
									nextLine[1] = nextLine[1].replaceAll("FBA",""); 
495
									nextLine[1] = nextLine[1].replaceAll("FBB","");
11406 vikram.rag 496
								}
11172 vikram.rag 497
								else{
498
									continue;
499
								}
500
								Long item_id = Long.parseLong(nextLine[1]);
9777 manish.sha 501
								Double ourPrice = null;
502
								Double minFBAPrice= null;
503
								Double minMFNPrice= null;
504
								Double salePrice= null; 
505
								if(nextLine[30].length() >0){
506
									ourPrice = Double.parseDouble(nextLine[30]);
507
									if(itemIdOurPriceMap.containsKey(item_id)){
508
										if(itemIdOurPriceMap.get(item_id).getDate().getTime() < date.getTime()){
509
											PriceAtDate priceAtDate= new PriceAtDate();
510
											priceAtDate.setDate(date);
511
											priceAtDate.setPrice(ourPrice);
512
											itemIdOurPriceMap.put(item_id,priceAtDate);
513
										}
514
									}
515
									else{	
516
										PriceAtDate priceAtDate= new PriceAtDate();
517
										priceAtDate.setDate(date);
518
										priceAtDate.setPrice(ourPrice);
519
										itemIdOurPriceMap.put(item_id,priceAtDate);
520
									}
521
								}
522
								if(nextLine[31].length() >0){
523
									salePrice = Double.parseDouble(nextLine[31]);
524
									if(itemIdSalePriceMap.containsKey(item_id) ){
525
										if(itemIdSalePriceMap.get(item_id).getDate().getTime() < date.getTime()){
526
											PriceAtDate priceAtDate= new PriceAtDate();
527
											priceAtDate.setDate(date);
528
											priceAtDate.setPrice(salePrice);
529
											itemIdSalePriceMap.put(item_id,priceAtDate);
530
										}
531
									}
532
									else{	
533
										PriceAtDate priceAtDate= new PriceAtDate();
534
										priceAtDate.setDate(date);
535
										priceAtDate.setPrice(salePrice);
536
										itemIdSalePriceMap.put(item_id,priceAtDate);
537
									}
538
								}
539
								if(nextLine[32].length() >0){
540
									minFBAPrice = Double.parseDouble(nextLine[32]);
541
									if(itemIdminFBAPriceMap.containsKey(item_id)){
542
										if(itemIdminFBAPriceMap.get(item_id).getDate().getTime() < date.getTime()){
543
											PriceAtDate priceAtDate= new PriceAtDate();
544
											priceAtDate.setDate(date);
545
											priceAtDate.setPrice(minFBAPrice);
546
											itemIdminFBAPriceMap.put(item_id,priceAtDate);
547
										}
548
									}
549
									else{	
550
										PriceAtDate priceAtDate= new PriceAtDate();
551
										priceAtDate.setDate(date);
552
										priceAtDate.setPrice(minFBAPrice);
553
										itemIdminFBAPriceMap.put(item_id,priceAtDate);
554
									}
555
								}
556
								if(nextLine[34].length() >0){
557
									minMFNPrice = Double.parseDouble(nextLine[34]);
558
									if(itemIdminMFNPriceMap.containsKey(item_id)){
559
										if(itemIdminMFNPriceMap.get(item_id).getDate().getTime() < date.getTime()){
560
											PriceAtDate priceAtDate= new PriceAtDate();
561
											priceAtDate.setDate(date);
562
											priceAtDate.setPrice(minMFNPrice);
563
											itemIdminMFNPriceMap.put(item_id,priceAtDate);
564
										}
565
									}
566
									else{	
567
										PriceAtDate priceAtDate= new PriceAtDate();
568
										priceAtDate.setDate(date);
569
										priceAtDate.setPrice(minMFNPrice);
570
										itemIdminMFNPriceMap.put(item_id,priceAtDate);
571
									}
572
								}
573
							}
574
						}
575
						catch(Exception e){
576
							e.printStackTrace();
577
						}
578
						count++;
579
					}
580
					boolean oos;
9802 manish.sha 581
					List<AmazonFbaSalesSnapshot> fbaSalesSnapShotList = new ArrayList<AmazonFbaSalesSnapshot>();
11172 vikram.rag 582
					for (Entry<Date, Map<String, FbaSalesSnapshot>> entry : orderDateItemIdFbaSaleSnapshotMap.entrySet()){
9777 manish.sha 583
						Date orderDate = entry.getKey();
11172 vikram.rag 584
						AmazonFCWarehouseLocation location;
11406 vikram.rag 585
						Long item_id = null;
11172 vikram.rag 586
						for(Entry<String, FbaSalesSnapshot> entry1 :entry.getValue().entrySet()){
587
							if(entry1.getKey().startsWith("FBA")){
588
								location = AmazonFCWarehouseLocation.Mumbai;
589
								item_id = Long.parseLong(entry1.getKey().replaceAll("FBA",""));
590
							}
591
							else if(entry1.getKey().startsWith("FBB")){
592
								location = AmazonFCWarehouseLocation.Bangalore;
593
								item_id = Long.parseLong(entry1.getKey().replaceAll("FBB",""));
594
							}
595
							else{
11406 vikram.rag 596
								System.out.println("Skipping Item ID " + entry1.getKey() +" date : "+orderDate);
11172 vikram.rag 597
								continue;
598
							}
599
							List<AmazonFbaInventorySnapshot> iteminventory;
600
							Long inventory = 0L;
10906 vikram.rag 601
							try{
11172 vikram.rag 602
								iteminventory = inventoryClient.getAmazonFbaItemInventory(item_id);
10906 vikram.rag 603
							}
604
							catch(TTransportException e){
605
								inventoryClient = inventoryServiceClient.getClient();
11172 vikram.rag 606
								iteminventory = inventoryClient.getAmazonFbaItemInventory(item_id);
10906 vikram.rag 607
							}
11172 vikram.rag 608
							for(AmazonFbaInventorySnapshot inv:iteminventory){
11196 vikram.rag 609
								if(inv.getLocation().getValue()==location.getValue()){
11172 vikram.rag 610
									inventory = inv.getAvailability(); 
611
								}
612
							}
9777 manish.sha 613
							if(inventory==0 && entry1.getValue().getTotalOrderCount()==0){
614
								oos=true;
615
							}
616
							else{
617
								oos=false;
618
							}
11172 vikram.rag 619
							//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 620
							AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
621
							amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
11172 vikram.rag 622
							amazonfbasalessnapshot.setItem_id(item_id);
9777 manish.sha 623
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getPromotionOrderCount());
624
							amazonfbasalessnapshot.setTotalOrderCount(entry1.getValue().getTotalOrderCount());
625
							amazonfbasalessnapshot.setTotalSale(entry1.getValue().getTotalSale());
626
							amazonfbasalessnapshot.setPromotionSale(entry1.getValue().getTotalPromotionSale());
627
							amazonfbasalessnapshot.setIsOutOfStock(oos);
628
							if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id).getPrice()!=0){
629
								amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id).getPrice());
630
								amazonfbasalessnapshot.setSalePriceSnapshotDate(itemIdSalePriceMap.get(item_id).getDate().getTime());
631
							}
632
							else{
633
								amazonfbasalessnapshot.setSalePrice(0.0);
634
								amazonfbasalessnapshot.setSalePriceSnapshotDate(0);
635
							}
636
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id).getPrice()!=0){
637
								amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id).getPrice());
638
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(itemIdminMFNPriceMap.get(item_id).getDate().getTime());
639
							}
640
							else{
641
								amazonfbasalessnapshot.setMinMfnPrice(0.0);
642
								amazonfbasalessnapshot.setMinMfnPriceSnapshotDate(0);
643
							}
644
							if(itemIdminFBAPriceMap.containsKey(item_id) && itemIdminFBAPriceMap.get(item_id).getPrice()!=0){
645
								amazonfbasalessnapshot.setMinFbaPrice(itemIdminFBAPriceMap.get(item_id).getPrice());
646
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(itemIdminFBAPriceMap.get(item_id).getDate().getTime());
647
							}
648
							else{
649
								amazonfbasalessnapshot.setMinFbaPrice(0.0);
650
								amazonfbasalessnapshot.setMinFbaPriceSnapshotDate(0);
651
							}
652
							if(itemIdOurPriceMap.containsKey(item_id) && itemIdOurPriceMap.get(item_id).getPrice()!=0){
653
								amazonfbasalessnapshot.setOurPrice(itemIdOurPriceMap.get(item_id).getPrice());
654
								amazonfbasalessnapshot.setOurPriceSnapshotDate(itemIdOurPriceMap.get(item_id).getDate().getTime());
655
							}
656
							else{
11406 vikram.rag 657
								Amazonlisted amazon_item;
658
								try{
659
									amazon_item=catalogClient.getAmazonItemDetails(item_id);
660
								}
661
								catch(TTransportException e){
662
									catalogClient   = catalogServiceClient.getClient();
663
									amazon_item=catalogClient.getAmazonItemDetails(item_id);
664
								}
665
								if(amazon_item.getItemid()==0){
666
									System.out.println("Skipping Item ID listing not present" + entry1.getKey() +" date : "+orderDate);
667
									continue;
668
								}
9777 manish.sha 669
								amazonfbasalessnapshot.setOurPrice(amazon_item.getFbaPrice());
670
								amazonfbasalessnapshot.setOurPriceSnapshotDate(0);
671
							}
672
							amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
11172 vikram.rag 673
							amazonfbasalessnapshot.setFcLocation(location);
9802 manish.sha 674
							fbaSalesSnapShotList.add(amazonfbasalessnapshot);
9777 manish.sha 675
						}
676
					}
9917 manish.sha 677
					System.out.println("Order Details to be Updated Size... "+fbaSalesSnapShotList.size());
11062 vikram.rag 678
					try{
679
						transactionServiceClient.getClient().bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
680
					}
681
					catch(TTransportException ex){
682
						new TransactionClient().getClient().bulkAddOrUpdateAmazonFbaSalesSnapshot(fbaSalesSnapShotList);
683
					}
9777 manish.sha 684
				} catch (IOException e) {
685
					// TODO Auto-generated catch block
686
					e.printStackTrace();
687
				} catch (ParseException e) {
688
					// TODO Auto-generated catch block
11062 vikram.rag 689
					e.printStackTrace(); 
9777 manish.sha 690
				} catch (TException e) {
691
					// TODO Auto-generated catch block
692
					e.printStackTrace();
693
				}
694
				break;
695
			}
696
			else{ 
697
				System.out.println("Report not ready");
698
				try {
699
					Thread.sleep(5*60*1000);
700
				} catch (InterruptedException e) {
701
					// TODO Auto-generated catch block
702
					e.printStackTrace();
703
				}
704
			}
705
		}
706
 
707
		// Note that depending on the type of report being downloaded, a report can reach 
708
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
709
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
710
		// the in-memory size limit and have to re-work your solution.
711
		//
712
 
713
 
714
	}
715
 
10905 vikram.rag 716
 
717
 
9777 manish.sha 718
}