Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
9947 vikram.rag 1
package in.shop2020;
2
 
3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsInfo;
5
import in.shop2020.logistics.LogisticsServiceException;
6
import in.shop2020.model.v1.catalog.CatalogService.Client;
7
import in.shop2020.model.v1.catalog.FlipkartItem;
8
import in.shop2020.model.v1.catalog.Item;
10174 vikram.rag 9
import in.shop2020.model.v1.catalog.SnapdealItemDetails;
9947 vikram.rag 10
import in.shop2020.model.v1.catalog.status;
10049 vikram.rag 11
import in.shop2020.model.v1.inventory.FlipkartInventorySnapshot;
9947 vikram.rag 12
import in.shop2020.model.v1.inventory.InventoryType;
13
import in.shop2020.model.v1.inventory.ItemInventory;
14
import in.shop2020.model.v1.inventory.Warehouse;
15
import in.shop2020.model.v1.inventory.WarehouseLocation;
16
import in.shop2020.model.v1.inventory.WarehouseType;
17
import in.shop2020.model.v1.order.OrderSource;
18
import in.shop2020.serving.model.Order;
19
import in.shop2020.serving.model.OrderItems;
20
import in.shop2020.thrift.clients.CatalogClient;
21
import in.shop2020.thrift.clients.InventoryClient;
22
import in.shop2020.thrift.clients.LogisticsClient;
23
import in.shop2020.thrift.clients.TransactionClient;
9983 vikram.rag 24
import in.shop2020.utils.GmailUtils;
9947 vikram.rag 25
import inventory.FlipkartInventoryItem;
26
 
27
import java.io.BufferedReader;
9983 vikram.rag 28
import java.io.File;
9947 vikram.rag 29
import java.io.IOException;
30
import java.io.InputStreamReader;
9968 vikram.rag 31
import java.io.UnsupportedEncodingException;
9947 vikram.rag 32
import java.util.ArrayList;
33
import java.util.HashMap;
34
import java.util.List;
35
import java.util.Map;
36
import java.util.Map.Entry;
37
 
9983 vikram.rag 38
import javax.mail.MessagingException;
39
 
9947 vikram.rag 40
import org.apache.http.HttpResponse;
41
import org.apache.http.NameValuePair;
42
import org.apache.http.auth.AuthScope;
43
import org.apache.http.auth.UsernamePasswordCredentials;
44
import org.apache.http.client.ClientProtocolException;
45
import org.apache.http.client.HttpClient;
46
import org.apache.http.client.entity.UrlEncodedFormEntity;
47
import org.apache.http.client.methods.HttpGet;
48
import org.apache.http.client.methods.HttpPost;
49
import org.apache.http.entity.StringEntity;
50
import org.apache.http.impl.client.DefaultHttpClient;
51
import org.apache.http.message.BasicNameValuePair;
52
import org.apache.thrift.TException;
53
import org.apache.thrift.transport.TTransportException;
54
 
55
import com.google.gson.Gson;
56
 
57
 
58
 
59
public class CreateSubmitFlipkartInventoryFeed {
60
	private static Map<Long, FlipkartInventoryItem> flipkartItemsInventoryMap = new HashMap<Long, FlipkartInventoryItem>();
61
	private static List<FlipkartItem> flipkartItems;
62
	private static List<FlipkartItem> flipkartInventoryItems = new ArrayList<FlipkartItem>();
63
	private static Map<Long,Long> itemIdOrdersMap = new HashMap<Long,Long>();
9983 vikram.rag 64
	private static Map<Long,Item> aliveItemsMap = new HashMap<Long,Item>();
10057 vikram.rag 65
	private static Map<String,Long> heldOrdersMap = new HashMap<String,Long>();
10122 vikram.rag 66
	private static Map<Long,Long>  updatedFlipkartInventoryMap = new HashMap<Long,Long>();
9983 vikram.rag 67
	static java.text.SimpleDateFormat sdf;
68
	static String emailFromAddress;
69
	static String password;
70
	static GmailUtils mailer;
71
	static String sendTo[];
10174 vikram.rag 72
	private static List<SnapdealItemDetails> snapdealItems = new ArrayList<SnapdealItemDetails>();
73
	private static Map<Long,SnapdealItemDetails> snapdealItemsMap = new HashMap<Long,SnapdealItemDetails>();
9947 vikram.rag 74
	static
75
	{
9983 vikram.rag 76
		sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
77
		emailFromAddress = "build@shop2020.in";
78
		password = "cafe@nes";
79
		mailer = new GmailUtils();
10450 vikram.rag 80
		sendTo = new String[]{"vikram.raghav@shop2020.in"};
81
/*		sendTo = new String[]{ "sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
9983 vikram.rag 82
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
10030 vikram.rag 83
				"yukti.jain@shop2020.in","manoj.pal@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","amar.kumar@shop2020.in"};
10450 vikram.rag 84
*/		List<String> flipkartorderids = null;
10049 vikram.rag 85
		Client catalogServiceClient = null;
86
		try {
10154 vikram.rag 87
			catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
10049 vikram.rag 88
		} catch (TTransportException e) {
89
			e.printStackTrace();
90
		}
91
		try {
92
			flipkartItems = catalogServiceClient.getAllFlipkartItems();
10174 vikram.rag 93
			snapdealItems = catalogServiceClient.getAllSnapdealItems();
10049 vikram.rag 94
		} catch (TException e) {
95
			e.printStackTrace();
96
		}
97
		for(FlipkartItem flipkartItem:flipkartItems){
98
			if(flipkartItem.isIsListedOnFlipkart() && !flipkartItem.isSuppressInventoryFeed())
99
				flipkartInventoryItems.add(flipkartItem);
100
		}
10174 vikram.rag 101
		for(SnapdealItemDetails snapdealItem:snapdealItems){
102
			snapdealItemsMap.put(snapdealItem.getItem_id(),snapdealItem);
103
		}
10049 vikram.rag 104
		if(flipkartInventoryItems.size()==0){
105
			String text = "";
106
			try {
107
				mailer.sendSSLMessage(sendTo,"No items to send inventory ", emailFromAddress, password, text);
108
				System.exit(0);
109
			} catch (MessagingException e) {
110
				e.printStackTrace();
111
			}
112
		}
113
		in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
114
		try {
115
			flipkartorderids = FetchOrders();
116
		} catch (ClientProtocolException e1) {
117
			e1.printStackTrace();
118
		} catch (IOException e1) {
119
			e1.printStackTrace();
120
		}
121
		try {
10154 vikram.rag 122
			transactionClient = new TransactionClient().getClient();
10049 vikram.rag 123
			if(flipkartorderids!=null && flipkartorderids.size()>0){
9989 vikram.rag 124
				itemIdOrdersMap = transactionClient.getCreatedOrdersForFlipkart(flipkartorderids);
10049 vikram.rag 125
			}
126
		} catch (TTransportException e) {
127
			try {
128
				itemIdOrdersMap = transactionClient.getCreatedOrdersForFlipkart(flipkartorderids);
9989 vikram.rag 129
			} catch (TException e1) {
130
				e1.printStackTrace();
131
			}
10049 vikram.rag 132
		}catch (TException e) {
133
			e.printStackTrace();
134
		}
10122 vikram.rag 135
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryServiceClient = null;
136
		try {
10154 vikram.rag 137
			inventoryServiceClient = new InventoryClient().getClient();
10122 vikram.rag 138
		} catch (TTransportException e) {
139
			e.printStackTrace();
140
		}
141
		try {
142
			List<FlipkartInventorySnapshot> updatedFlipkartInventoryList = inventoryServiceClient.getFlipkartInventorySnapshot();
143
			for(FlipkartInventorySnapshot updatedFlipkartInventory:updatedFlipkartInventoryList){
144
				updatedFlipkartInventoryMap.put(updatedFlipkartInventory.getItem_id(),updatedFlipkartInventory.getAvailability());
145
			}
146
		} catch (TException e) {
147
			e.printStackTrace();
148
		}
9947 vikram.rag 149
 
10122 vikram.rag 150
 
9947 vikram.rag 151
	}
152
 
9967 vikram.rag 153
	public static void main(String[] args) throws ClientProtocolException, TException{
9947 vikram.rag 154
		calculateinventory();
155
		DefaultHttpClient httpclient = new DefaultHttpClient();
9973 vikram.rag 156
		httpclient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpclient);
10051 vikram.rag 157
		//httpclient.getCredentialsProvider().setCredentials(
158
		//		new AuthScope("sandbox-api.flipkart.net", 443),
159
		//		new UsernamePasswordCredentials("og3yg5994bxbxxc1", "8a137068-417c-4e4f-ae95-9295ab938d88"));/// Test Server Access Keys
10049 vikram.rag 160
		httpclient.getCredentialsProvider().setCredentials(
9975 vikram.rag 161
				new AuthScope("api.flipkart.net", 443),
9974 vikram.rag 162
				new UsernamePasswordCredentials("m2z93iskuj81qiid","0c7ab6a5-98c0-4cdc-8be3-72c591e0add4")); //Prod Server Access Keys
10051 vikram.rag 163
		HttpPost httppost = new HttpPost("https://api.flipkart.net/sellers/skus/listings/bulk"); // PROD
164
		//HttpPost httppost = new HttpPost("https://sandbox-api.flipkart.net/sellers/skus/listings/bulk"); // TEST
9947 vikram.rag 165
		StringBuffer jsonRequest = new StringBuffer();
9983 vikram.rag 166
		StringBuffer jsonStart = new StringBuffer();
167
		jsonStart = jsonStart.append("{\"listings\":[");
168
		StringBuffer jsonEnd = new StringBuffer();
169
		jsonEnd.append("]}");
9947 vikram.rag 170
		//System.out.println("JSON request  " + jsonRequest);
171
		LogisticsClient logisticsServiceClient;
172
		in.shop2020.logistics.LogisticsService.Client logisticsClient=null;
173
		LogisticsInfo logisticinfo = null;
174
		try {
10154 vikram.rag 175
			logisticsServiceClient = new LogisticsClient();
9947 vikram.rag 176
			logisticsClient = logisticsServiceClient.getClient();
177
 
178
		} catch (TTransportException e) {
179
			e.printStackTrace();
180
		}
181
		long stock=0;
182
		int i=0;
10176 vikram.rag 183
		long available,reserve,heldforsource,totalheld,allocable,holdinventory,defaultinventory,actualstock = 0,orders,heldorders;
184
		float allocation;
9983 vikram.rag 185
		StringBuffer inventoryItems =new StringBuffer();
10122 vikram.rag 186
		StringBuffer backInStockItems =new StringBuffer();
187
		StringBuffer outOfStockItems =new StringBuffer();
9983 vikram.rag 188
		String tableHeader = "<html><table border=\"1\" align=\"center\"><tr>" 
189
			+ "<td><b>" + "Product Name" +"</b></td>"
190
			+"<td><b>" + "Item ID" + "</b></td>"
191
			+"<td><b>" + "Inventory" + "</b></td>"
192
			+"<td><b>" + "Orders Added to Inventory" + "</b></td>"
193
			+"<td><b>" + "Sent Inventory" + "</b></td>"
10049 vikram.rag 194
			+"<td><b>" + "Procurement SLA" + "</b></td>"
195
			+"<td><b>" + "Orders on Hold" + "</b></td>"
9983 vikram.rag 196
			+"</tr>";
10159 vikram.rag 197
 
9983 vikram.rag 198
		String tableFooter = "</table></html>";
199
		Item item;
10027 vikram.rag 200
		StringBuffer feedResponse=  new StringBuffer();
10049 vikram.rag 201
		List<FlipkartInventorySnapshot> inventorysnapshotlist = new ArrayList<FlipkartInventorySnapshot>();
10450 vikram.rag 202
		long timestamp = System.currentTimeMillis();
9947 vikram.rag 203
		for(Entry<Long, FlipkartInventoryItem> entry:flipkartItemsInventoryMap.entrySet()){
10174 vikram.rag 204
			if(snapdealItemsMap.containsKey(entry.getKey()) && snapdealItemsMap.get(entry.getKey()).isIsListedOnSnapdeal()){
10306 vikram.rag 205
				allocation = (float) 0.33;
10174 vikram.rag 206
			}
207
			else{
10306 vikram.rag 208
				allocation = (float) 0.67;
10174 vikram.rag 209
			}
9985 vikram.rag 210
			actualstock=0;
211
			orders=0;
212
			stock=0;
10049 vikram.rag 213
			heldorders=0;
9947 vikram.rag 214
			available = entry.getValue().getAvailability();
215
			reserve = entry.getValue().getReserve();
216
			heldforsource = entry.getValue().getHeldForSource();
217
			totalheld = entry.getValue().getTotalHeldInventory();
218
			holdinventory = entry.getValue().getHoldInventory();
219
			defaultinventory = entry.getValue().getDefaultInventory();
9987 vikram.rag 220
			System.out.println("Item ID  " + entry.getKey());
221
			System.out.println("Available " + available);
222
			System.out.println("Reserve " + reserve);
223
			System.out.println("Held For Source " + heldforsource);
224
			System.out.println("Total Held " + totalheld);
225
			System.out.println("General Hold " + holdinventory );
226
			System.out.println("Default Inventory " + defaultinventory);
9947 vikram.rag 227
			if(!entry.getValue().getStatus().equals(status.PAUSED)){
228
				if(entry.getValue().getRisky()){
229
					if((available - reserve) < totalheld && totalheld!=0){
230
						stock = (long) Math.floor(((available - reserve)*heldforsource/totalheld));
231
					}
232
					else{
233
						allocable = available - reserve - totalheld - holdinventory;
234
						if(allocable < 0){
235
							allocable = 0;
236
						}
10174 vikram.rag 237
						stock = Math.round(allocable*allocation) + heldforsource;
9947 vikram.rag 238
					}
239
 
240
				}
241
				else{
242
					allocable = available - reserve - totalheld;
243
					if(allocable < 0){
244
						allocable = 0;
245
					}
246
					if((allocable + heldforsource ) > defaultinventory){
10174 vikram.rag 247
						stock = Math.round(allocable*allocation) +  heldforsource;
9947 vikram.rag 248
					}
249
					else{
250
						stock = defaultinventory;
251
					}
252
				}
253
				System.out.println("Item ID " + entry.getKey()+" Stock "+stock +" Orders " + itemIdOrdersMap.get(entry.getKey()));
9992 vikram.rag 254
				actualstock = stock;
9971 vikram.rag 255
				if(itemIdOrdersMap!=null && itemIdOrdersMap.containsKey(entry.getKey())){
9977 vikram.rag 256
					stock = stock + itemIdOrdersMap.get(entry.getKey());  
9983 vikram.rag 257
					orders = itemIdOrdersMap.get(entry.getKey());
9947 vikram.rag 258
				}
259
				if(stock<0){
260
					stock =0;
261
				}
9977 vikram.rag 262
				else{
263
					if(stock > 25){
264
						stock=25;
265
					}
266
				}
9947 vikram.rag 267
			}
268
			else{
269
				stock =0;
270
			}
271
			try {
272
				logisticinfo = logisticsClient.getLogisticsEstimation(entry.getValue().getId(),"110001",DeliveryType.COD);
273
			} catch (LogisticsServiceException e) {
274
				e.printStackTrace();
275
				continue;
276
			}
10029 vikram.rag 277
			catch (TTransportException e) {
10154 vikram.rag 278
				logisticsServiceClient = new LogisticsClient();
10029 vikram.rag 279
				logisticsClient = logisticsServiceClient.getClient();
280
			} 
10107 vikram.rag 281
			System.out.println("sku at flipkart " + entry.getValue().getSkuAtflipkart());
282
			System.out.println("shipping time " + logisticinfo.getShippingTime());
283
			System.out.println("stock " + stock);
9947 vikram.rag 284
			jsonRequest.append("{\"skuId\":"+"\""+entry.getValue().getSkuAtflipkart()+
285
					"\","+"\"attributeValues\""+":"+
286
					"{\"procurement_sla\""+":"+"\""+logisticinfo.getShippingTime()+
287
					"\","+"\"stock_count\""+":"+"\""+stock+"\""+"}}");
10049 vikram.rag 288
			FlipkartInventorySnapshot inventorySnapshot = new FlipkartInventorySnapshot();
289
			inventorySnapshot.setItem_id(entry.getKey());
290
			inventorySnapshot.setAvailability(stock);
10450 vikram.rag 291
			if(stock > 0){
292
				inventorySnapshot.setIs_oos(false);
293
			}
294
			else{
295
				inventorySnapshot.setIs_oos(true);
296
			}
10049 vikram.rag 297
			if(heldOrdersMap.containsKey(entry.getValue().getSkuAtflipkart())){
298
				inventorySnapshot.setHeldOrders(heldOrdersMap.get(entry.getValue().getSkuAtflipkart()));
10060 vikram.rag 299
				heldorders = heldOrdersMap.get(entry.getValue().getSkuAtflipkart());
10049 vikram.rag 300
			}
301
			else{
302
				inventorySnapshot.setHeldOrders(0);
303
			}
304
			inventorySnapshot.setCreatedOrders(orders);
305
			inventorysnapshotlist.add(inventorySnapshot);
9983 vikram.rag 306
			item = aliveItemsMap.get(entry.getValue().getId());
10999 vikram.rag 307
			System.out.println("Stock : " +  stock +" "+ "  SLA : " + logisticinfo.getShippingTime());
10160 vikram.rag 308
			if(!updatedFlipkartInventoryMap.containsKey(entry.getKey())){
10122 vikram.rag 309
				inventoryItems.append("<tr>" 
310
						+ "<td>" +getProductName(item)+"</td>"
311
						+"<td>" + item.getId() + "</td>"
312
						+"<td>" + actualstock + "</td>"
313
						+"<td>" + orders + "</td>"
314
						+"<td>" + stock + "</td>"
315
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
316
						+"<td>" + heldorders + "</td>"
317
						+"</tr>");
318
			}
10160 vikram.rag 319
			else if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) != stock){
320
				inventoryItems.append("<tr>" 
321
						+ "<td>" +getProductName(item)+"</td>"
322
						+"<td>" + item.getId() + "</td>"
323
						+"<td>" + actualstock + "</td>"
324
						+"<td>" + orders + "</td>"
325
						+"<td>" + stock + "</td>"
326
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
327
						+"<td>" + heldorders + "</td>"
328
						+"</tr>");
329
			}
10122 vikram.rag 330
			if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) == 0 && stock!=0){
331
				backInStockItems.append("<tr>" 
332
						+ "<td>" +getProductName(item)+"</td>"
333
						+"<td>" + item.getId() + "</td>"
334
						+"<td>" + actualstock + "</td>"
335
						+"<td>" + orders + "</td>"
336
						+"<td>" + stock + "</td>"
337
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
338
						+"<td>" + heldorders + "</td>"
339
						+"</tr>");
340
			}
341
			if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) != 0 && stock==0){
342
				outOfStockItems.append("<tr>" 
343
						+ "<td>" +getProductName(item)+"</td>"
344
						+"<td>" + item.getId() + "</td>"
345
						+"<td>" + actualstock + "</td>"
346
						+"<td>" + orders + "</td>"
347
						+"<td>" + stock + "</td>"
348
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
349
						+"<td>" + heldorders + "</td>"
350
						+"</tr>");
351
			}
10028 vikram.rag 352
			i++;
353
			if(flipkartItemsInventoryMap.entrySet().size()!=1 && (i!=flipkartItemsInventoryMap.entrySet().size()) ){
10026 vikram.rag 354
				if(i%10!=0){
355
					jsonRequest.append(",");
356
				}
9947 vikram.rag 357
			}
358
			if(i%10==0 || i==flipkartItemsInventoryMap.entrySet().size()){
9968 vikram.rag 359
				StringEntity input = null;
360
				try {
9983 vikram.rag 361
					input = new StringEntity(jsonStart+jsonRequest.toString()+jsonEnd);
362
					System.out.println("Json input " + jsonStart+jsonRequest.toString()+jsonEnd);
363
					jsonRequest = new StringBuffer();
9968 vikram.rag 364
				} catch (UnsupportedEncodingException e) {
365
					e.printStackTrace();
366
				}
9947 vikram.rag 367
				input.setContentType("application/json");
10049 vikram.rag 368
 
9947 vikram.rag 369
				httppost.setEntity(input);
9968 vikram.rag 370
				HttpResponse response = null;
371
				try {
9970 vikram.rag 372
					System.out.println("Before send " );
9968 vikram.rag 373
					response = httpclient.execute(httppost);
9970 vikram.rag 374
					System.out.println("After send " );
9968 vikram.rag 375
				} catch (IOException e) {
376
					e.printStackTrace();
377
				}
9969 vikram.rag 378
				BufferedReader rd = null;
9968 vikram.rag 379
				try {
380
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
381
				} catch (IllegalStateException e) {
382
					e.printStackTrace();
383
				} catch (IOException e) {
384
					e.printStackTrace();
385
				}
9947 vikram.rag 386
				String line;
10049 vikram.rag 387
				in.shop2020.model.v1.inventory.InventoryService.Client inventoryServiceClient;
9969 vikram.rag 388
				try {
389
					while ((line = rd.readLine()) != null) {
390
						System.out.println("Response " + line);
9983 vikram.rag 391
						if(line.equalsIgnoreCase("{\"status\":\"success\"}")){
10154 vikram.rag 392
							inventoryServiceClient = new InventoryClient().getClient();
10158 vikram.rag 393
							try{
10450 vikram.rag 394
								inventoryServiceClient.addOrUpdateFlipkartInventorySnapshot(inventorysnapshotlist,timestamp);
10158 vikram.rag 395
							}
396
							catch(TTransportException e){
397
								inventoryServiceClient = new InventoryClient().getClient();
10450 vikram.rag 398
								inventoryServiceClient.addOrUpdateFlipkartInventorySnapshot(inventorysnapshotlist,timestamp);
10158 vikram.rag 399
							}
10049 vikram.rag 400
							inventorysnapshotlist = new ArrayList<FlipkartInventorySnapshot>();
9983 vikram.rag 401
						}
402
						else{
403
							feedResponse.append(line);
404
						}
10049 vikram.rag 405
 
9969 vikram.rag 406
					}
407
				} catch (IOException e) {
408
					e.printStackTrace();
9947 vikram.rag 409
				}
410
			}
411
		}
9983 vikram.rag 412
		System.out.println("Before sending email");
10179 vikram.rag 413
		if(feedResponse.toString().length()>0){
414
			try {
415
				mailer.sendSSLMessage(sendTo, "Flipkart Inventory could not be updated " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
10181 vikram.rag 416
			} catch (Exception e) {
10183 vikram.rag 417
				emailFromAddress = "build-staging@shop2020.in"; 
418
				password = "shop2020";
10179 vikram.rag 419
				try {
420
					mailer.sendSSLMessage(sendTo, "Flipkart Inventory could not be updated " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
421
				} catch (MessagingException e1) {
422
					e1.printStackTrace();
423
				}
424
				e.printStackTrace();
425
			}
426
		}
427
		else{
428
			try {
429
				mailer.sendSSLMessage(sendTo, "Flipkart Inventory updated successfully " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
430
			} catch (MessagingException e) {
10183 vikram.rag 431
				emailFromAddress = "build-staging@shop2020.in"; 
432
				password = "shop2020";
10179 vikram.rag 433
				try {
434
					mailer.sendSSLMessage(sendTo, "Flipkart Inventory updated successfully " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
435
				} catch (MessagingException e1) {
436
					e1.printStackTrace();
437
				}
438
				e.printStackTrace();
439
			}
440
		}
441
 
442
		String text;
10159 vikram.rag 443
		if(inventoryItems.toString().length()>0){
10179 vikram.rag 444
			text = tableHeader+inventoryItems.toString()+tableFooter;
10159 vikram.rag 445
			try {
446
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Sent Details " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
447
			} catch (MessagingException e) {
448
				e.printStackTrace();
449
			}
9983 vikram.rag 450
		}
10122 vikram.rag 451
		if(backInStockItems.toString().length()>0){
452
			try {
453
				text = tableHeader+backInStockItems.toString()+tableFooter;
10123 vikram.rag 454
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Back in Stock " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
10122 vikram.rag 455
			} catch (MessagingException e) {
456
				e.printStackTrace();
457
			}
10159 vikram.rag 458
 
10122 vikram.rag 459
		}
460
		if(outOfStockItems.toString().length()>0){
461
			try {
462
				text = tableHeader+outOfStockItems.toString()+tableFooter;
10123 vikram.rag 463
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Out of Stock " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
10122 vikram.rag 464
			} catch (MessagingException e) {
465
				e.printStackTrace();
466
			}
10159 vikram.rag 467
 
10122 vikram.rag 468
		}
9947 vikram.rag 469
	}
9983 vikram.rag 470
 
9947 vikram.rag 471
	private static void calculateinventory(){
472
		CatalogClient catalogServiceClient = null;
473
		Map<Long,ItemInventory> availability= new HashMap<Long,ItemInventory>();
474
		try {
10154 vikram.rag 475
			catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
9947 vikram.rag 476
		} catch (TTransportException e) {
477
			e.printStackTrace();
478
		}
479
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
480
		try {
481
			List<Item> aliveItems = catalogClient.getAllAliveItems();
482
			for(in.shop2020.model.v1.catalog.Item thriftItem:aliveItems){
483
				aliveItemsMap.put(thriftItem.getId(), thriftItem);
484
 
485
			}
486
			InventoryClient inventoryServiceClient = new InventoryClient();
487
			try {
488
				inventoryServiceClient = new InventoryClient();
489
			} catch (TTransportException e) {
490
				e.printStackTrace();
491
			}
492
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
493
			List<in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems> ignoreItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
494
			availability = inventoryClient.getInventorySnapshot(0);
495
			List<Warehouse> allwarehouses = inventoryClient.getWarehouses(null,null,0,0,0);
496
			Map<Long,Warehouse> allWarehousesMap = new HashMap<Long,Warehouse>();
497
			for(Warehouse warehouse:allwarehouses){
498
				allWarehousesMap.put(warehouse.getId(),warehouse);
499
			}
500
			List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS_THIRDPARTY,null,0,0,0);
501
			List<Warehouse> ours_warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, 0, 0);
502
			List<Long> thirdpartywarehouseids = new ArrayList<Long>();
503
			List<Long> oursGoodWarehouse = new ArrayList<Long>();
504
			for(Warehouse warehouse:warehouses){
505
				thirdpartywarehouseids.add(warehouse.getId());
506
			}
507
			for (Warehouse warehouse:ours_warehouses){
508
				oursGoodWarehouse.add(warehouse.getId());
509
			}
510
			long available=0;
511
			long reserve=0;
512
			long total_warehouse_held=0;
513
			long heldForSource=0;
514
			long total_held=0;
515
			double nlc=0;
516
			double maxnlc=0;
517
			Item thriftItem;
518
			for(FlipkartItem flipkartItem:flipkartInventoryItems){
519
				if(aliveItemsMap.get(flipkartItem.getItem_id()) != null){
520
					thriftItem = aliveItemsMap.get(flipkartItem.getItem_id());	
521
				}
522
				else{
523
					continue;
524
				}
525
				available=0;
526
				reserve=0;
527
				total_warehouse_held=0;
528
				heldForSource=0;
529
				total_held=0;
530
				nlc=0;
531
				List<Warehouse> vendor_warehouses=null;
532
				FlipkartInventoryItem item;
533
				if(availability.get(thriftItem.getId())!=null){ 
534
					ItemInventory iteminventory = availability.get(thriftItem.getId());
535
					Map<Long,Long> itemavailability = new HashMap<Long,Long>();
536
					itemavailability = iteminventory.getAvailability();
537
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
538
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());						
539
						vendor_warehouses = inventoryClient.getWarehouses(WarehouseType.THIRD_PARTY,InventoryType.GOOD , thriftItem.getPreferredVendor(), 0, 0);
540
						vendor_warehouses.addAll(ours_warehouses);
541
						for (Warehouse warehouse:vendor_warehouses){
542
							if(warehouse.getBillingWarehouseId()!=7){
543
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
544
 
545
								}
546
								else{
547
									continue;
548
								}
549
							}
550
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
551
							ignoredItem.setItemId(thriftItem.getId());
552
							ignoredItem.setWarehouseId(warehouse.getId());
553
							if (itemavailability.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(ignoredItem)){
554
								try{
555
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
556
								}
557
								catch(TTransportException e){
558
									inventoryClient = inventoryServiceClient.getClient(); 
559
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
560
								}
561
								maxnlc = flipkartItem.getMaxNlc();
562
 
563
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
564
								if(nlc !=0 && (maxnlc >= nlc)){
565
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
566
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 8);
567
									available = available + itemavailability.get(warehouse.getId());
568
									total_held = total_held + total_warehouse_held; 
569
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
570
								}
571
								else if(maxnlc==0){
572
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
573
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 8);
574
									available = available + itemavailability.get(warehouse.getId());
575
									total_held = total_held + total_warehouse_held;
576
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
577
								}
578
							}
579
						}
580
					}
581
					else{
582
						for (Map.Entry<Long,Long> entry :  itemavailability.entrySet()) {
583
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
584
								if(allWarehousesMap.get(entry.getKey()).getLogisticsLocation().equals(WarehouseLocation.Delhi) && allWarehousesMap.get(entry.getKey()).getWarehouseType().equals(WarehouseType.THIRD_PARTY) && allWarehousesMap.get(entry.getKey()).getVendor().getId()!=1){
585
 
586
								}
587
								else{
588
									continue;
589
								}
590
							}
591
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
592
							ignoredItem.setItemId(thriftItem.getId());
593
							ignoredItem.setWarehouseId(entry.getKey());
594
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
595
 
596
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
597
								maxnlc = flipkartItem.getMaxNlc();
598
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
599
								if(nlc !=0 && (maxnlc >= nlc)){
600
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
601
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 8);
602
									available =  available + entry.getValue();
603
									total_held = total_held + total_warehouse_held;
604
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
605
								}
606
								else if(maxnlc==0){
607
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
608
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 8);
609
									available = available + itemavailability.get(entry.getKey());
610
									total_held = total_held + total_warehouse_held;
611
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
612
								}
613
 
614
							}
615
						}
616
					}
617
					Map<Long,Long> itemreserve = new HashMap<Long,Long>();
618
					itemreserve = iteminventory.getReserved();
619
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
620
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating Reserve)"+thriftItem.getPreferredVendor());
621
						for (Warehouse warehouse:vendor_warehouses){
622
							if(warehouse.getBillingWarehouseId()!=7){
623
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
624
 
625
								}
626
								else{
627
									continue;
628
								}
629
							}
630
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
631
							ignoredItem.setItemId(thriftItem.getId());
632
							ignoredItem.setWarehouseId(warehouse.getId());
633
							if (itemreserve.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(warehouse.getId())){
634
								nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
635
								maxnlc = flipkartItem.getMaxNlc();
636
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
637
								if(nlc !=0 && (maxnlc >= nlc)){
638
									reserve = reserve + itemreserve.get(warehouse.getId());
639
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
640
								}
641
								else if(maxnlc==0){
642
									reserve = reserve + itemreserve.get(warehouse.getId());
643
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
644
								}
645
 
646
							}
647
						}
648
					}else{
649
						for (Map.Entry<Long,Long> entry : itemreserve.entrySet()) {
650
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
651
								if(allWarehousesMap.get(entry.getKey()).getLogisticsLocation().equals(WarehouseLocation.Delhi) && allWarehousesMap.get(entry.getKey()).getWarehouseType().equals(WarehouseType.THIRD_PARTY) && allWarehousesMap.get(entry.getKey()).getVendor().getId()!=1){
652
 
653
								}
654
								else{
655
									continue;
656
								}
657
							}
658
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
659
							ignoredItem.setItemId(thriftItem.getId());
660
							ignoredItem.setWarehouseId(entry.getKey());
661
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
662
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
663
								maxnlc = flipkartItem.getMaxNlc();
664
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
665
								if(nlc !=0 && (maxnlc >= nlc)){
666
									reserve =  reserve + entry.getValue();
667
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
668
								}
669
								else if(maxnlc==0){
670
									reserve =  reserve + entry.getValue();
671
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
672
								}
673
 
674
							}
675
 
676
							else{
677
								//System.out.println("skipping inventory for warehouse id " + entry.getKey());
678
							}
679
						}
680
					}
681
					item= new FlipkartInventoryItem(thriftItem.getId(),available,reserve,heldForSource,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),total_held,thriftItem.isRisky(),thriftItem.getItemStatus(),flipkartItem.getSkuAtFlipkart());
682
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
683
				}
684
				else{
685
					item = new FlipkartInventoryItem(thriftItem.getId(),0,0,0,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),0,thriftItem.isRisky(),thriftItem.getItemStatus(),flipkartItem.getSkuAtFlipkart());
686
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
687
				}
688
 
689
				//System.out.println(" Item details are " + thriftItem.getId() +" " + available + " " + reserve + " " + thriftItem.getHoldInventory() + " "+ thriftItem.getDefaultInventory() + " " + thriftItem.isRisky());
690
				//System.out.println("+++++++++++++++++++++++");
691
				flipkartItemsInventoryMap.put(thriftItem.getId(),item);
692
 
693
			}
694
 
695
		} catch (TException e) {
696
			e.printStackTrace();
697
		}
698
	}
699
 
700
	static List<String> FetchOrders() throws ClientProtocolException, IOException{
701
		HttpClient client = new DefaultHttpClient();
702
		HttpPost post = new HttpPost("https://seller.flipkart.com/login");
703
		BufferedReader rd= null;
704
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
705
		nameValuePairs.add(new BasicNameValuePair("authName",
706
		"flipkart"));
707
		nameValuePairs.add(new BasicNameValuePair("username",
708
		"flipkart-support@saholic.com"));
709
		nameValuePairs.add(new BasicNameValuePair("password",
710
		"076c27ee24d7596b06608a8ed2559f87"));
711
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
712
		HttpResponse response = client.execute(post);
713
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
714
		String line = "";
715
		Gson gson;
716
		List<Order> orders = new ArrayList<Order>(); 
717
		OrderItems new_orders;
718
		OrderItems conf_orders;
719
		HttpGet get_new;
720
		HttpGet get_conf; 
721
		long time;
722
		int i=1;
723
		while ((line = rd.readLine()) != null) {
724
			System.out.println(line);
725
		}
726
		time = System.currentTimeMillis();
727
		while(true){
728
			get_new = new HttpGet("https://seller.flipkart.com/dashboard/som/new_order_items?status=on_hold%2Capproved.payment_approved&sort=confirm_by_date&page="+i+"&page_size=100&_="+time);
729
			response = client.execute(get_new);
730
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
731
			line = "";
732
			gson = new Gson();
733
			new_orders = (OrderItems) gson.fromJson(rd, OrderItems.class);
734
			if(new_orders.getOrder_items().size()>0){
735
				orders.addAll(new_orders.getOrder_items());
736
			}
737
			else{
738
				break;
739
			}
740
			i++;
741
		}
742
		i=1;
743
		time = System.currentTimeMillis();
744
		while(true){
745
			get_conf = new HttpGet("https://seller.flipkart.com/dashboard/som/confirmed_order_items?status=approved.seller_approved&sort=confirm_by_date&page="+i+"&page_size=100&_="+time);
746
			response = client.execute(get_conf);
747
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
748
			line = "";
749
			gson = new Gson();
750
			conf_orders = (OrderItems) gson.fromJson(rd, OrderItems.class);
751
			if(conf_orders.getOrder_items().size()>0){
752
				orders.addAll(conf_orders.getOrder_items());
753
			}
754
			else{
755
				break;
756
			}
757
			i++;
758
		}
759
		List<String> orderIdList = new ArrayList<String>();
10054 vikram.rag 760
		Long heldOrders = 0L;
9947 vikram.rag 761
		for(Order order:orders){
10153 vikram.rag 762
			System.out.println("Order  " + order.getExternalId() +" "+order.getOrderItemId() + " : "+ order.getStatus() + " "+order.getStatusDateMessage() + " "
763
					+ order.getStatusLabel() + " " + order.getPickup_by_date() + " "+ order.getTrackingId());
9947 vikram.rag 764
			orderIdList.add(order.getExternalId());
10049 vikram.rag 765
			if(order.getStatus().equalsIgnoreCase("on_hold")){
10062 vikram.rag 766
				if(heldOrdersMap.containsKey(String.valueOf(order.getSku()))){
10057 vikram.rag 767
					heldOrders = heldOrdersMap.get(String.valueOf(order.getSku()))+order.getQuantity();
768
					heldOrdersMap.put(String.valueOf(order.getSku()),heldOrders);
10059 vikram.rag 769
					System.out.println("Item ID " + order.getSku() + " Held Orders " + heldOrdersMap.get(String.valueOf(order.getSku())));
10049 vikram.rag 770
				}
771
				else{
10054 vikram.rag 772
					heldOrders = (long) order.getQuantity();
10057 vikram.rag 773
					heldOrdersMap.put(String.valueOf(order.getSku()),heldOrders);
10059 vikram.rag 774
					System.out.println("Item ID " + order.getSku() + " Held Orders " + heldOrdersMap.get(String.valueOf(order.getSku())));
10049 vikram.rag 775
				}
776
			}
9947 vikram.rag 777
		}
778
		return orderIdList; 
779
	}
9983 vikram.rag 780
	static String getProductName(Item item){
781
		return getName(item.getBrand())+" " + getName(item.getModelName())+" " + getName(item.getModelNumber())+" " + getName(item.getColor()); 
782
 
783
	}
784
	static String getName(String name){
785
		if(name==null || name.length()==0){
786
			return "";
787
		}
788
		else{
789
			return name;
790
		}
791
	}
9947 vikram.rag 792
}