Subversion Repositories SmartDukaan

Rev

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