Subversion Repositories SmartDukaan

Rev

Rev 8285 | Rev 8294 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8285 kshitij.so 1
package com.amazonaws.mws.samples;
2
 
3
import in.shop2020.model.v1.catalog.Amazonlisted;
4
import in.shop2020.model.v1.inventory.AmazonFbaInventorySnapshot;
5
import in.shop2020.model.v1.order.AmazonFbaSalesSnapshot;
6
import in.shop2020.thrift.clients.CatalogClient;
7
import in.shop2020.thrift.clients.InventoryClient;
8
import in.shop2020.thrift.clients.TransactionClient;
9
 
10
import java.io.FileNotFoundException;
11
import java.io.FileOutputStream;
12
import java.io.FileReader;
13
import java.io.IOException;
14
import java.io.OutputStream;
15
import java.text.ParseException;
16
import java.text.SimpleDateFormat;
17
import java.util.Arrays;
18
import java.util.Calendar;
19
import java.util.Date;
20
import java.util.GregorianCalendar;
21
import java.util.HashMap;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.TimeZone;
25
 
26
import javax.xml.datatype.DatatypeConfigurationException;
27
import javax.xml.datatype.DatatypeFactory;
28
import javax.xml.datatype.Duration;
29
import javax.xml.datatype.XMLGregorianCalendar;
30
 
31
import org.apache.thrift.TException;
32
import org.apache.thrift.transport.TTransportException;
33
 
34
import au.com.bytecode.opencsv.CSVReader;
35
 
36
import com.amazonaws.mws.MarketplaceWebService;
37
import com.amazonaws.mws.MarketplaceWebServiceClient;
38
import com.amazonaws.mws.MarketplaceWebServiceConfig;
39
import com.amazonaws.mws.model.GetReportListRequest;
40
import com.amazonaws.mws.model.GetReportRequest;
41
import com.amazonaws.mws.model.IdList;
42
import com.amazonaws.mws.model.RequestReportRequest;
43
 
44
public class FetchAmazonSalesSnapshot {
45
	public static void main(String... args){
46
		/************************************************************************
47
		 * Access Key ID and Secret Access Key ID, obtained from:
48
		 * http://aws.amazon.com
49
		 ***********************************************************************/
50
		final String accessKeyId = "AKIAII3SGRXBJDPCHSGQ";
51
		final String secretAccessKey = "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";
52
 
53
		final String appName = "Test";
54
		final String appVersion = "1.0";
55
		final String merchantId = "AF6E3O0VE0X4D";
56
 
57
		MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
58
 
59
		/************************************************************************
60
		 * Uncomment to set the appropriate MWS endpoint.
61
		 ************************************************************************/
62
		// US
63
		// config.setServiceURL("https://mws.amazonservices.com");
64
		// UK
65
		// config.setServiceURL("https://mws.amazonservices.co.uk");
66
		// Germany
67
		// config.setServiceURL("https://mws.amazonservices.de");
68
		// France
69
		// config.setServiceURL("https://mws.amazonservices.fr");
70
		// Italy
71
		// config.setServiceURL("https://mws.amazonservices.it");
72
		// Japan
73
		// config.setServiceURL("https://mws.amazonservices.jp");
74
		// China
75
		// config.setServiceURL("https://mws.amazonservices.com.cn");
76
		// Canada
77
		// config.setServiceURL("https://mws.amazonservices.ca");
78
		// India
79
		config.setServiceURL("https://mws.amazonservices.in");
80
 
81
		/************************************************************************
82
		 * You can also try advanced configuration options. Available options are:
83
		 *
84
		 *  - Signature Version
85
		 *  - Proxy Host and Proxy Port
86
		 *  - User Agent String to be sent to Marketplace Web Service
87
		 *
88
		 ***********************************************************************/
89
 
90
		/************************************************************************
91
		 * Instantiate Http Client Implementation of Marketplace Web Service        
92
		 ***********************************************************************/
93
 
94
		MarketplaceWebService service = new MarketplaceWebServiceClient(
95
				accessKeyId, secretAccessKey, appName, appVersion, config);
96
 
97
		/************************************************************************
98
		 * Uncomment to try out Mock Service that simulates Marketplace Web Service 
99
		 * responses without calling Marketplace Web Service  service.
100
		 *
101
		 * Responses are loaded from local XML files. You can tweak XML files to
102
		 * experiment with various outputs during development
103
		 *
104
		 * XML files available under com/amazonaws/mws/mock tree
105
		 *
106
		 ***********************************************************************/
107
		// MarketplaceWebService service = new MarketplaceWebServiceMock();
108
 
109
		/************************************************************************
110
		 * Setup request parameters and uncomment invoke to try out 
111
		 * sample for Request Report 
112
		 ***********************************************************************/
113
 
114
		/************************************************************************
115
		 * Marketplace and Merchant IDs are required parameters for all 
116
		 * Marketplace Web Service calls.
117
		 ***********************************************************************/
118
		// marketplaces from which data should be included in the report; look at the
119
		// API reference document on the MWS website to see which marketplaces are
120
		// included if you do not specify the list yourself
121
		final IdList marketplaces = new IdList(Arrays.asList(
122
		"A21TJRUUN4KGV"));        
123
		RequestReportRequest orderreportrequest = new RequestReportRequest()
124
		.withMerchant(merchantId)
125
		.withMarketplaceIdList(marketplaces)
126
		.withReportType("_GET_FLAT_FILE_ALL_ORDERS_DATA_BY_ORDER_DATE_")
127
		.withReportOptions("ShowSalesChannel=true");
128
 
129
		RequestReportRequest inventoryhealthreportrequest = new RequestReportRequest()
130
		.withMerchant(merchantId)
131
		.withMarketplaceIdList(marketplaces)
132
		.withReportType("_GET_FBA_FULFILLMENT_INVENTORY_HEALTH_DATA_")
133
		.withReportOptions("ShowSalesChannel=true");
134
 
135
		DatatypeFactory df = null;
136
		try {
137
			df = DatatypeFactory.newInstance();
138
		} catch (DatatypeConfigurationException e) {
139
			e.printStackTrace();
140
			throw new RuntimeException(e);
141
		}
142
		long ordertimediff = System.currentTimeMillis() - 7*24*60*60*1000;
143
		GregorianCalendar ost = new GregorianCalendar();
144
		ost.setTimeInMillis(ordertimediff);
145
		XMLGregorianCalendar  orderStartDate = df.newXMLGregorianCalendar(ost);
146
		XMLGregorianCalendar orderEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
147
		System.out.println("Order Start Date  " + orderStartDate  + "Order End Date  " + orderEndDate);
148
		orderreportrequest.setStartDate(orderStartDate);
149
		orderreportrequest.setEndDate(orderEndDate);
150
		long inventorytimediff = System.currentTimeMillis() - 7*24*60*60*1000;
151
		GregorianCalendar ist = new GregorianCalendar();
152
		ist.setTimeInMillis(inventorytimediff);
153
		ist.setTimeInMillis(ordertimediff);
154
		XMLGregorianCalendar  inventoryStartDate = df.newXMLGregorianCalendar(ist);
155
		XMLGregorianCalendar inventoryEndDate = df.newXMLGregorianCalendar(new GregorianCalendar());
156
		System.out.println("Inventory Start Date  " + inventoryStartDate  + "Inventory End Date  " + inventoryEndDate);
157
		inventoryhealthreportrequest.setStartDate(inventoryStartDate);
158
		inventoryhealthreportrequest.setEndDate(inventoryEndDate);
159
		Map<String,String> requestIdreportIdmap;
160
		String orderreportrequestId = RequestReportSample.invokeRequestReport(service, orderreportrequest);
161
		String inventoryhealthreportrequestId = RequestReportSample.invokeRequestReport(service, inventoryhealthreportrequest);
162
		while(true){
163
			GetReportListRequest requestreportlist = new GetReportListRequest();
164
			requestreportlist.setMerchant( merchantId );
165
			final IdList requestIdList = new IdList(Arrays.asList(orderreportrequestId,inventoryhealthreportrequestId));        
166
			requestreportlist.setReportRequestIdList(requestIdList);
167
			requestIdreportIdmap = GetReportListSample.invokeGetReportList(service, requestreportlist);
168
			if(requestIdreportIdmap.get(orderreportrequestId)!=null && requestIdreportIdmap.get(inventoryhealthreportrequestId)!=null){
169
				GetReportRequest requestorderreport = new GetReportRequest();
170
				GetReportRequest requestinventoryhealthreport = new GetReportRequest();
171
				requestorderreport.setMerchant( merchantId );
172
				requestinventoryhealthreport.setMerchant(merchantId);
173
				requestorderreport.setReportId( requestIdreportIdmap.get(orderreportrequestId));
174
				requestinventoryhealthreport.setReportId(requestIdreportIdmap.get(inventoryhealthreportrequestId));
175
				OutputStream orderreport=null;
176
				OutputStream inventoryhealthreport=null;
177
				try {
178
					orderreport = new FileOutputStream( "/home/vikram/Desktop/amazonorderreport.csv" );
179
					inventoryhealthreport = new FileOutputStream( "/home/vikram/Desktop/inventoryhealthreport.csv" );
180
				} catch (FileNotFoundException e) {
181
					// TODO Auto-generated catch block
182
					e.printStackTrace();
183
				}
184
				requestorderreport.setReportOutputStream(orderreport);
185
				requestinventoryhealthreport.setReportOutputStream(inventoryhealthreport);
186
				GetReportSample.invokeGetReport(service, requestorderreport);
187
				GetReportSample.invokeGetReport(service, requestinventoryhealthreport);
188
				System.out.println("Order and Inventory Reports are ready please check");
189
				CSVReader orderreportreader = null;
190
				CSVReader inventoryhealthreportreader = null;
191
				try {
192
					orderreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/amazonorderreport.csv"),'\t');
193
					inventoryhealthreportreader = new CSVReader(new FileReader("/home/vikram/Desktop/inventoryhealthreport.csv"),'\t');
194
				} catch (FileNotFoundException e) {
195
					// TODO Auto-generated catch block
196
					e.printStackTrace();
197
				}
198
				String [] nextLine;
199
				try {
200
					int count =1;
201
					Map<Date,Map<Long,Integer>> orderDateItemIdCountMap = new HashMap<Date,Map<Long,Integer>>();
202
					while ((nextLine = orderreportreader.readNext()) != null) {
203
						if(count!=1 && nextLine[5].equalsIgnoreCase("Amazon") && (nextLine[13].equalsIgnoreCase("Unshipped") || nextLine[13].equalsIgnoreCase("Shipped"))){
204
							SimpleDateFormat istFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
205
							istFormatter .setLenient(false);
206
							TimeZone zone= TimeZone.getTimeZone("GMT");
207
							istFormatter.setTimeZone(zone);
208
							Date date = istFormatter.parse(nextLine[2]);
209
							SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
210
							Date date_key = dateFormat.parse(dateFormat.format(date));
211
							System.out.println(nextLine[0]+" "+date_key+" "+ nextLine[11] +" " + nextLine[13] + " " + nextLine[14]);
212
							Long itemid = Long.parseLong(nextLine[11].replaceAll("FBA",""));
213
							Integer qty = new Integer(nextLine[14]);
214
							if(orderDateItemIdCountMap.containsKey(date_key)){
215
								if(orderDateItemIdCountMap.get(date_key).containsKey(itemid)){
216
									orderDateItemIdCountMap.get(date_key).put(itemid,orderDateItemIdCountMap.get(date_key).get(itemid)+qty);
217
								}
218
								else{
219
									orderDateItemIdCountMap.get(date_key).put(itemid,qty);
220
								}
221
							}
222
							else{
223
 
224
								Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();
225
								itemIdcountMap.put(itemid,qty);
226
								orderDateItemIdCountMap.put(date_key,itemIdcountMap);
227
							}
228
 
229
						} 
230
						count++;
231
					}
232
					InventoryClient inventoryServiceClient = null;
233
					TransactionClient transactionServiceClient = null;
234
					CatalogClient catalogServiceClient = null;
235
					try {
236
						inventoryServiceClient = new InventoryClient();
237
						transactionServiceClient = new TransactionClient();
238
						catalogServiceClient = new CatalogClient();
239
						//catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
240
					} catch (Exception e) {
241
						// TODO Auto-generated catch block
242
						e.printStackTrace();
243
					}	
244
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
245
					in.shop2020.model.v1.order.TransactionService.Client transactionClient   = transactionServiceClient.getClient();
246
					in.shop2020.model.v1.catalog.CatalogService.Client catalogClient   = catalogServiceClient.getClient();
247
					SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
248
					Date date_today = dateFormat.parse(dateFormat.format(new Date()));
8293 kshitij.so 249
					List<AmazonFbaInventorySnapshot> nonzeroFbaInventorySnapshotlist =  inventoryClient.getAllNonzeroAmazonFbaItemInventory();
250
					if(nonzeroFbaInventorySnapshotlist!=null){
251
						for(AmazonFbaInventorySnapshot amazonFbaInventory:nonzeroFbaInventorySnapshotlist){
252
							if(orderDateItemIdCountMap.containsKey(date_today) ){ 
253
								if(!orderDateItemIdCountMap.get(date_today).containsKey(amazonFbaInventory.getItem_id())){
254
									orderDateItemIdCountMap.get(date_today).put(amazonFbaInventory.getItem_id(),0);
8285 kshitij.so 255
								}
8293 kshitij.so 256
 
257
							}
258
							else{
259
								Map<Long,Integer> itemIdcountMap = new HashMap<Long,Integer>();
260
								itemIdcountMap.put(amazonFbaInventory.getItem_id(),0);
261
								orderDateItemIdCountMap.put(date_today,itemIdcountMap);
262
							}
8285 kshitij.so 263
						}
264
					}
8293 kshitij.so 265
					else{
266
						System.out.println("No inventory in FBA");
267
					}
8285 kshitij.so 268
					orderDateItemIdCountMap.get(date_today);
269
					Map<Long,Double> itemIdSalePriceMap = new HashMap<Long,Double>();
270
					Map<Long,Double> itemIdminFBAPriceMap = new HashMap<Long,Double>();
271
					Map<Long,Double> itemIdminMFNPriceMap = new HashMap<Long,Double>();
272
					count=1;
273
					while ((nextLine = inventoryhealthreportreader.readNext()) != null ) {
274
						if(count!=1){
275
							//System.out.println(nextLine[1] +" "+ nextLine[31] +" " + nextLine[32] + " " + nextLine[34]);
276
							Long item_id = Long.parseLong(nextLine[1].replaceAll("FBA",""));
277
							Double salePrice = Double.parseDouble(nextLine[31]);
278
							Double minFBAPrice = Double.parseDouble(nextLine[32]);
279
							Double minMFNPrice = Double.parseDouble(nextLine[34]);
280
							itemIdSalePriceMap.put(item_id,salePrice);
281
							itemIdminFBAPriceMap.put(item_id,minFBAPrice);
282
							itemIdminMFNPriceMap.put(item_id,minMFNPrice);
283
						}
284
						count++;
285
					}
286
					boolean oos;
287
					for (Map.Entry<Date, Map<Long, Integer>> entry : orderDateItemIdCountMap.entrySet()){
288
						Date orderDate = entry.getKey();
289
						for(Map.Entry<Long, Integer> entry1 :entry.getValue().entrySet()){
290
							Long inventory = inventoryClient.getAmazonFbaItemInventory(entry1.getKey());
291
							oos=false;
292
							if(inventory==0 && entry1.getValue()==0)
293
								oos=true;
294
							Long item_id = entry1.getKey();
295
							System.out.println(orderDate +","+entry1.getKey()+","+entry1.getValue()+","+ inventory +","+ oos+","+itemIdSalePriceMap.get(item_id)+","+itemIdminFBAPriceMap.get(item_id)+","+itemIdminMFNPriceMap.get(item_id));
296
							AmazonFbaSalesSnapshot amazonfbasalessnapshot = new AmazonFbaSalesSnapshot();
297
							amazonfbasalessnapshot.setDateOfSale(orderDate.getTime());
298
							amazonfbasalessnapshot.setItem_id(entry1.getKey());
299
							amazonfbasalessnapshot.setOrderCount(entry1.getValue());
300
							amazonfbasalessnapshot.setIsOutOfStock(oos);
301
							Amazonlisted amazon_item = catalogClient.getAmazonItemDetails(item_id);
302
							if(itemIdSalePriceMap.containsKey(item_id) && itemIdSalePriceMap.get(item_id)!=0){
303
								amazonfbasalessnapshot.setSalePrice(itemIdSalePriceMap.get(item_id));
304
							}
305
							else{
306
								amazonfbasalessnapshot.setSalePrice(amazon_item.getFbaPrice());
307
							}
308
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){
309
								amazonfbasalessnapshot.setMinFbaPrice(itemIdminMFNPriceMap.get(item_id));
310
							}
311
							if(itemIdminMFNPriceMap.containsKey(item_id) && itemIdminMFNPriceMap.get(item_id)!=0){
312
								amazonfbasalessnapshot.setMinMfnPrice(itemIdminMFNPriceMap.get(item_id));
313
							}
314
							amazonfbasalessnapshot.setAmazonFbaInventory(inventory);
315
							transactionClient.addOrUpdateAmazonFbaSalesSnapshot(amazonfbasalessnapshot);
316
						}
317
					}
318
				} catch (IOException e) {
319
					// TODO Auto-generated catch block
320
					e.printStackTrace();
321
				} catch (ParseException e) {
322
					// TODO Auto-generated catch block
323
					e.printStackTrace();
324
				} catch (TException e) {
325
					// TODO Auto-generated catch block
326
					e.printStackTrace();
327
				}
328
				break;
329
			}
330
			else{ 
331
				System.out.println("Report not ready");
332
				try {
333
					Thread.sleep(5*60*1000);
334
				} catch (InterruptedException e) {
335
					// TODO Auto-generated catch block
336
					e.printStackTrace();
337
				}
338
			}
339
		}
340
 
341
		// Note that depending on the type of report being downloaded, a report can reach 
342
		// sizes greater than 1GB. For this reason we recommend that you _always_ program to
343
		// MWS in a streaming fashion. Otherwise, as your business grows you may silently reach
344
		// the in-memory size limit and have to re-work your solution.
345
		//
346
 
347
 
348
	}
349
 
350
}