Subversion Repositories SmartDukaan

Rev

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