Subversion Repositories SmartDukaan

Rev

Rev 11000 | Rev 11002 | 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());
11000 vikram.rag 307
			if(logisticinfo.getShippingTime() > 5 && stock > 0){
11001 vikram.rag 308
				System.out.println("Product : "+getProductName(item)+" Item ID : " + item.getId() + " Stock : " +  stock +" "+ "  SLA : " + logisticinfo.getShippingTime());	
11000 vikram.rag 309
			}
10160 vikram.rag 310
			if(!updatedFlipkartInventoryMap.containsKey(entry.getKey())){
10122 vikram.rag 311
				inventoryItems.append("<tr>" 
312
						+ "<td>" +getProductName(item)+"</td>"
313
						+"<td>" + item.getId() + "</td>"
314
						+"<td>" + actualstock + "</td>"
315
						+"<td>" + orders + "</td>"
316
						+"<td>" + stock + "</td>"
317
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
318
						+"<td>" + heldorders + "</td>"
319
						+"</tr>");
320
			}
10160 vikram.rag 321
			else if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) != stock){
322
				inventoryItems.append("<tr>" 
323
						+ "<td>" +getProductName(item)+"</td>"
324
						+"<td>" + item.getId() + "</td>"
325
						+"<td>" + actualstock + "</td>"
326
						+"<td>" + orders + "</td>"
327
						+"<td>" + stock + "</td>"
328
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
329
						+"<td>" + heldorders + "</td>"
330
						+"</tr>");
331
			}
10122 vikram.rag 332
			if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) == 0 && stock!=0){
333
				backInStockItems.append("<tr>" 
334
						+ "<td>" +getProductName(item)+"</td>"
335
						+"<td>" + item.getId() + "</td>"
336
						+"<td>" + actualstock + "</td>"
337
						+"<td>" + orders + "</td>"
338
						+"<td>" + stock + "</td>"
339
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
340
						+"<td>" + heldorders + "</td>"
341
						+"</tr>");
342
			}
343
			if(updatedFlipkartInventoryMap.containsKey(entry.getKey()) && updatedFlipkartInventoryMap.get(entry.getKey()) != 0 && stock==0){
344
				outOfStockItems.append("<tr>" 
345
						+ "<td>" +getProductName(item)+"</td>"
346
						+"<td>" + item.getId() + "</td>"
347
						+"<td>" + actualstock + "</td>"
348
						+"<td>" + orders + "</td>"
349
						+"<td>" + stock + "</td>"
350
						+"<td>" + logisticinfo.getShippingTime() + "</td>"
351
						+"<td>" + heldorders + "</td>"
352
						+"</tr>");
353
			}
10028 vikram.rag 354
			i++;
355
			if(flipkartItemsInventoryMap.entrySet().size()!=1 && (i!=flipkartItemsInventoryMap.entrySet().size()) ){
10026 vikram.rag 356
				if(i%10!=0){
357
					jsonRequest.append(",");
358
				}
9947 vikram.rag 359
			}
360
			if(i%10==0 || i==flipkartItemsInventoryMap.entrySet().size()){
9968 vikram.rag 361
				StringEntity input = null;
362
				try {
9983 vikram.rag 363
					input = new StringEntity(jsonStart+jsonRequest.toString()+jsonEnd);
364
					System.out.println("Json input " + jsonStart+jsonRequest.toString()+jsonEnd);
365
					jsonRequest = new StringBuffer();
9968 vikram.rag 366
				} catch (UnsupportedEncodingException e) {
367
					e.printStackTrace();
368
				}
9947 vikram.rag 369
				input.setContentType("application/json");
10049 vikram.rag 370
 
9947 vikram.rag 371
				httppost.setEntity(input);
9968 vikram.rag 372
				HttpResponse response = null;
373
				try {
9970 vikram.rag 374
					System.out.println("Before send " );
9968 vikram.rag 375
					response = httpclient.execute(httppost);
9970 vikram.rag 376
					System.out.println("After send " );
9968 vikram.rag 377
				} catch (IOException e) {
378
					e.printStackTrace();
379
				}
9969 vikram.rag 380
				BufferedReader rd = null;
9968 vikram.rag 381
				try {
382
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
383
				} catch (IllegalStateException e) {
384
					e.printStackTrace();
385
				} catch (IOException e) {
386
					e.printStackTrace();
387
				}
9947 vikram.rag 388
				String line;
10049 vikram.rag 389
				in.shop2020.model.v1.inventory.InventoryService.Client inventoryServiceClient;
9969 vikram.rag 390
				try {
391
					while ((line = rd.readLine()) != null) {
392
						System.out.println("Response " + line);
9983 vikram.rag 393
						if(line.equalsIgnoreCase("{\"status\":\"success\"}")){
10154 vikram.rag 394
							inventoryServiceClient = new InventoryClient().getClient();
10158 vikram.rag 395
							try{
10450 vikram.rag 396
								inventoryServiceClient.addOrUpdateFlipkartInventorySnapshot(inventorysnapshotlist,timestamp);
10158 vikram.rag 397
							}
398
							catch(TTransportException e){
399
								inventoryServiceClient = new InventoryClient().getClient();
10450 vikram.rag 400
								inventoryServiceClient.addOrUpdateFlipkartInventorySnapshot(inventorysnapshotlist,timestamp);
10158 vikram.rag 401
							}
10049 vikram.rag 402
							inventorysnapshotlist = new ArrayList<FlipkartInventorySnapshot>();
9983 vikram.rag 403
						}
404
						else{
405
							feedResponse.append(line);
406
						}
10049 vikram.rag 407
 
9969 vikram.rag 408
					}
409
				} catch (IOException e) {
410
					e.printStackTrace();
9947 vikram.rag 411
				}
412
			}
413
		}
9983 vikram.rag 414
		System.out.println("Before sending email");
10179 vikram.rag 415
		if(feedResponse.toString().length()>0){
416
			try {
417
				mailer.sendSSLMessage(sendTo, "Flipkart Inventory could not be updated " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
10181 vikram.rag 418
			} catch (Exception e) {
10183 vikram.rag 419
				emailFromAddress = "build-staging@shop2020.in"; 
420
				password = "shop2020";
10179 vikram.rag 421
				try {
422
					mailer.sendSSLMessage(sendTo, "Flipkart Inventory could not be updated " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
423
				} catch (MessagingException e1) {
424
					e1.printStackTrace();
425
				}
426
				e.printStackTrace();
427
			}
428
		}
429
		else{
430
			try {
431
				mailer.sendSSLMessage(sendTo, "Flipkart Inventory updated successfully " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
432
			} catch (MessagingException e) {
10183 vikram.rag 433
				emailFromAddress = "build-staging@shop2020.in"; 
434
				password = "shop2020";
10179 vikram.rag 435
				try {
436
					mailer.sendSSLMessage(sendTo, "Flipkart Inventory updated successfully " + sdf.format(System.currentTimeMillis()), feedResponse.toString(), emailFromAddress, password,new ArrayList<File>());
437
				} catch (MessagingException e1) {
438
					e1.printStackTrace();
439
				}
440
				e.printStackTrace();
441
			}
442
		}
443
 
444
		String text;
10159 vikram.rag 445
		if(inventoryItems.toString().length()>0){
10179 vikram.rag 446
			text = tableHeader+inventoryItems.toString()+tableFooter;
10159 vikram.rag 447
			try {
448
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Sent Details " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
449
			} catch (MessagingException e) {
450
				e.printStackTrace();
451
			}
9983 vikram.rag 452
		}
10122 vikram.rag 453
		if(backInStockItems.toString().length()>0){
454
			try {
455
				text = tableHeader+backInStockItems.toString()+tableFooter;
10123 vikram.rag 456
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Back in Stock " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
10122 vikram.rag 457
			} catch (MessagingException e) {
458
				e.printStackTrace();
459
			}
10159 vikram.rag 460
 
10122 vikram.rag 461
		}
462
		if(outOfStockItems.toString().length()>0){
463
			try {
464
				text = tableHeader+outOfStockItems.toString()+tableFooter;
10123 vikram.rag 465
				mailer.sendSSLMessage(sendTo,"Flipkart Inventory Out of Stock " + sdf.format(System.currentTimeMillis()), emailFromAddress, password, text);
10122 vikram.rag 466
			} catch (MessagingException e) {
467
				e.printStackTrace();
468
			}
10159 vikram.rag 469
 
10122 vikram.rag 470
		}
9947 vikram.rag 471
	}
9983 vikram.rag 472
 
9947 vikram.rag 473
	private static void calculateinventory(){
474
		CatalogClient catalogServiceClient = null;
475
		Map<Long,ItemInventory> availability= new HashMap<Long,ItemInventory>();
476
		try {
10154 vikram.rag 477
			catalogServiceClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port");
9947 vikram.rag 478
		} catch (TTransportException e) {
479
			e.printStackTrace();
480
		}
481
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
482
		try {
483
			List<Item> aliveItems = catalogClient.getAllAliveItems();
484
			for(in.shop2020.model.v1.catalog.Item thriftItem:aliveItems){
485
				aliveItemsMap.put(thriftItem.getId(), thriftItem);
486
 
487
			}
488
			InventoryClient inventoryServiceClient = new InventoryClient();
489
			try {
490
				inventoryServiceClient = new InventoryClient();
491
			} catch (TTransportException e) {
492
				e.printStackTrace();
493
			}
494
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
495
			List<in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems> ignoreItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
496
			availability = inventoryClient.getInventorySnapshot(0);
497
			List<Warehouse> allwarehouses = inventoryClient.getWarehouses(null,null,0,0,0);
498
			Map<Long,Warehouse> allWarehousesMap = new HashMap<Long,Warehouse>();
499
			for(Warehouse warehouse:allwarehouses){
500
				allWarehousesMap.put(warehouse.getId(),warehouse);
501
			}
502
			List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS_THIRDPARTY,null,0,0,0);
503
			List<Warehouse> ours_warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, 0, 0);
504
			List<Long> thirdpartywarehouseids = new ArrayList<Long>();
505
			List<Long> oursGoodWarehouse = new ArrayList<Long>();
506
			for(Warehouse warehouse:warehouses){
507
				thirdpartywarehouseids.add(warehouse.getId());
508
			}
509
			for (Warehouse warehouse:ours_warehouses){
510
				oursGoodWarehouse.add(warehouse.getId());
511
			}
512
			long available=0;
513
			long reserve=0;
514
			long total_warehouse_held=0;
515
			long heldForSource=0;
516
			long total_held=0;
517
			double nlc=0;
518
			double maxnlc=0;
519
			Item thriftItem;
520
			for(FlipkartItem flipkartItem:flipkartInventoryItems){
521
				if(aliveItemsMap.get(flipkartItem.getItem_id()) != null){
522
					thriftItem = aliveItemsMap.get(flipkartItem.getItem_id());	
523
				}
524
				else{
525
					continue;
526
				}
527
				available=0;
528
				reserve=0;
529
				total_warehouse_held=0;
530
				heldForSource=0;
531
				total_held=0;
532
				nlc=0;
533
				List<Warehouse> vendor_warehouses=null;
534
				FlipkartInventoryItem item;
535
				if(availability.get(thriftItem.getId())!=null){ 
536
					ItemInventory iteminventory = availability.get(thriftItem.getId());
537
					Map<Long,Long> itemavailability = new HashMap<Long,Long>();
538
					itemavailability = iteminventory.getAvailability();
539
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
540
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());						
541
						vendor_warehouses = inventoryClient.getWarehouses(WarehouseType.THIRD_PARTY,InventoryType.GOOD , thriftItem.getPreferredVendor(), 0, 0);
542
						vendor_warehouses.addAll(ours_warehouses);
543
						for (Warehouse warehouse:vendor_warehouses){
544
							if(warehouse.getBillingWarehouseId()!=7){
545
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
546
 
547
								}
548
								else{
549
									continue;
550
								}
551
							}
552
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
553
							ignoredItem.setItemId(thriftItem.getId());
554
							ignoredItem.setWarehouseId(warehouse.getId());
555
							if (itemavailability.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(ignoredItem)){
556
								try{
557
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
558
								}
559
								catch(TTransportException e){
560
									inventoryClient = inventoryServiceClient.getClient(); 
561
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
562
								}
563
								maxnlc = flipkartItem.getMaxNlc();
564
 
565
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
566
								if(nlc !=0 && (maxnlc >= nlc)){
567
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
568
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 8);
569
									available = available + itemavailability.get(warehouse.getId());
570
									total_held = total_held + total_warehouse_held; 
571
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
572
								}
573
								else if(maxnlc==0){
574
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
575
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 8);
576
									available = available + itemavailability.get(warehouse.getId());
577
									total_held = total_held + total_warehouse_held;
578
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
579
								}
580
							}
581
						}
582
					}
583
					else{
584
						for (Map.Entry<Long,Long> entry :  itemavailability.entrySet()) {
585
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
586
								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){
587
 
588
								}
589
								else{
590
									continue;
591
								}
592
							}
593
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
594
							ignoredItem.setItemId(thriftItem.getId());
595
							ignoredItem.setWarehouseId(entry.getKey());
596
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
597
 
598
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
599
								maxnlc = flipkartItem.getMaxNlc();
600
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
601
								if(nlc !=0 && (maxnlc >= nlc)){
602
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
603
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 8);
604
									available =  available + entry.getValue();
605
									total_held = total_held + total_warehouse_held;
606
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
607
								}
608
								else if(maxnlc==0){
609
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
610
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 8);
611
									available = available + itemavailability.get(entry.getKey());
612
									total_held = total_held + total_warehouse_held;
613
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
614
								}
615
 
616
							}
617
						}
618
					}
619
					Map<Long,Long> itemreserve = new HashMap<Long,Long>();
620
					itemreserve = iteminventory.getReserved();
621
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
622
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating Reserve)"+thriftItem.getPreferredVendor());
623
						for (Warehouse warehouse:vendor_warehouses){
624
							if(warehouse.getBillingWarehouseId()!=7){
625
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
626
 
627
								}
628
								else{
629
									continue;
630
								}
631
							}
632
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
633
							ignoredItem.setItemId(thriftItem.getId());
634
							ignoredItem.setWarehouseId(warehouse.getId());
635
							if (itemreserve.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(warehouse.getId())){
636
								nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
637
								maxnlc = flipkartItem.getMaxNlc();
638
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
639
								if(nlc !=0 && (maxnlc >= nlc)){
640
									reserve = reserve + itemreserve.get(warehouse.getId());
641
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
642
								}
643
								else if(maxnlc==0){
644
									reserve = reserve + itemreserve.get(warehouse.getId());
645
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
646
								}
647
 
648
							}
649
						}
650
					}else{
651
						for (Map.Entry<Long,Long> entry : itemreserve.entrySet()) {
652
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
653
								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){
654
 
655
								}
656
								else{
657
									continue;
658
								}
659
							}
660
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
661
							ignoredItem.setItemId(thriftItem.getId());
662
							ignoredItem.setWarehouseId(entry.getKey());
663
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
664
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
665
								maxnlc = flipkartItem.getMaxNlc();
666
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
667
								if(nlc !=0 && (maxnlc >= nlc)){
668
									reserve =  reserve + entry.getValue();
669
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
670
								}
671
								else if(maxnlc==0){
672
									reserve =  reserve + entry.getValue();
673
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
674
								}
675
 
676
							}
677
 
678
							else{
679
								//System.out.println("skipping inventory for warehouse id " + entry.getKey());
680
							}
681
						}
682
					}
683
					item= new FlipkartInventoryItem(thriftItem.getId(),available,reserve,heldForSource,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),total_held,thriftItem.isRisky(),thriftItem.getItemStatus(),flipkartItem.getSkuAtFlipkart());
684
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
685
				}
686
				else{
687
					item = new FlipkartInventoryItem(thriftItem.getId(),0,0,0,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),0,thriftItem.isRisky(),thriftItem.getItemStatus(),flipkartItem.getSkuAtFlipkart());
688
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
689
				}
690
 
691
				//System.out.println(" Item details are " + thriftItem.getId() +" " + available + " " + reserve + " " + thriftItem.getHoldInventory() + " "+ thriftItem.getDefaultInventory() + " " + thriftItem.isRisky());
692
				//System.out.println("+++++++++++++++++++++++");
693
				flipkartItemsInventoryMap.put(thriftItem.getId(),item);
694
 
695
			}
696
 
697
		} catch (TException e) {
698
			e.printStackTrace();
699
		}
700
	}
701
 
702
	static List<String> FetchOrders() throws ClientProtocolException, IOException{
703
		HttpClient client = new DefaultHttpClient();
704
		HttpPost post = new HttpPost("https://seller.flipkart.com/login");
705
		BufferedReader rd= null;
706
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
707
		nameValuePairs.add(new BasicNameValuePair("authName",
708
		"flipkart"));
709
		nameValuePairs.add(new BasicNameValuePair("username",
710
		"flipkart-support@saholic.com"));
711
		nameValuePairs.add(new BasicNameValuePair("password",
712
		"076c27ee24d7596b06608a8ed2559f87"));
713
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
714
		HttpResponse response = client.execute(post);
715
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
716
		String line = "";
717
		Gson gson;
718
		List<Order> orders = new ArrayList<Order>(); 
719
		OrderItems new_orders;
720
		OrderItems conf_orders;
721
		HttpGet get_new;
722
		HttpGet get_conf; 
723
		long time;
724
		int i=1;
725
		while ((line = rd.readLine()) != null) {
726
			System.out.println(line);
727
		}
728
		time = System.currentTimeMillis();
729
		while(true){
730
			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);
731
			response = client.execute(get_new);
732
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
733
			line = "";
734
			gson = new Gson();
735
			new_orders = (OrderItems) gson.fromJson(rd, OrderItems.class);
736
			if(new_orders.getOrder_items().size()>0){
737
				orders.addAll(new_orders.getOrder_items());
738
			}
739
			else{
740
				break;
741
			}
742
			i++;
743
		}
744
		i=1;
745
		time = System.currentTimeMillis();
746
		while(true){
747
			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);
748
			response = client.execute(get_conf);
749
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
750
			line = "";
751
			gson = new Gson();
752
			conf_orders = (OrderItems) gson.fromJson(rd, OrderItems.class);
753
			if(conf_orders.getOrder_items().size()>0){
754
				orders.addAll(conf_orders.getOrder_items());
755
			}
756
			else{
757
				break;
758
			}
759
			i++;
760
		}
761
		List<String> orderIdList = new ArrayList<String>();
10054 vikram.rag 762
		Long heldOrders = 0L;
9947 vikram.rag 763
		for(Order order:orders){
10153 vikram.rag 764
			System.out.println("Order  " + order.getExternalId() +" "+order.getOrderItemId() + " : "+ order.getStatus() + " "+order.getStatusDateMessage() + " "
765
					+ order.getStatusLabel() + " " + order.getPickup_by_date() + " "+ order.getTrackingId());
9947 vikram.rag 766
			orderIdList.add(order.getExternalId());
10049 vikram.rag 767
			if(order.getStatus().equalsIgnoreCase("on_hold")){
10062 vikram.rag 768
				if(heldOrdersMap.containsKey(String.valueOf(order.getSku()))){
10057 vikram.rag 769
					heldOrders = heldOrdersMap.get(String.valueOf(order.getSku()))+order.getQuantity();
770
					heldOrdersMap.put(String.valueOf(order.getSku()),heldOrders);
10059 vikram.rag 771
					System.out.println("Item ID " + order.getSku() + " Held Orders " + heldOrdersMap.get(String.valueOf(order.getSku())));
10049 vikram.rag 772
				}
773
				else{
10054 vikram.rag 774
					heldOrders = (long) order.getQuantity();
10057 vikram.rag 775
					heldOrdersMap.put(String.valueOf(order.getSku()),heldOrders);
10059 vikram.rag 776
					System.out.println("Item ID " + order.getSku() + " Held Orders " + heldOrdersMap.get(String.valueOf(order.getSku())));
10049 vikram.rag 777
				}
778
			}
9947 vikram.rag 779
		}
780
		return orderIdList; 
781
	}
9983 vikram.rag 782
	static String getProductName(Item item){
783
		return getName(item.getBrand())+" " + getName(item.getModelName())+" " + getName(item.getModelNumber())+" " + getName(item.getColor()); 
784
 
785
	}
786
	static String getName(String name){
787
		if(name==null || name.length()==0){
788
			return "";
789
		}
790
		else{
791
			return name;
792
		}
793
	}
9947 vikram.rag 794
}