Subversion Repositories SmartDukaan

Rev

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