Subversion Repositories SmartDukaan

Rev

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