Subversion Repositories SmartDukaan

Rev

Rev 15643 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
10367 vikram.rag 1
package in.shop2020;
2
 
3
import in.shop2020.model.v1.catalog.Item;
4
import in.shop2020.model.v1.catalog.SnapdealItemDetails;
5
import in.shop2020.model.v1.catalog.status;
6
import in.shop2020.model.v1.inventory.InventoryType;
7
import in.shop2020.model.v1.inventory.ItemInventory;
8
import in.shop2020.model.v1.inventory.SnapdealInventoryItem;
9
import in.shop2020.model.v1.inventory.Warehouse;
10
import in.shop2020.model.v1.inventory.WarehouseLocation;
11
import in.shop2020.model.v1.inventory.WarehouseType;
15602 manish.sha 12
import in.shop2020.serving.services.SnapdealSessionCookie;
10367 vikram.rag 13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.InventoryClient;
15
import in.shop2020.thrift.clients.TransactionClient;
16
import in.shop2020.utils.GmailUtils;
17
import inventory.Inventory;
18
import inventory.InventoryHistory;
19
import inventory.InventoryHistoryItems;
20
import inventory.InventoryItems;
21
import inventory.PendingOrderInventoryHistory;
22
import inventory.SnapdealItemForInventory;
23
 
24
import java.io.BufferedReader;
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileNotFoundException;
28
import java.io.FileOutputStream;
29
import java.io.IOException;
30
import java.io.InputStreamReader;
31
import java.io.UnsupportedEncodingException;
32
import java.util.ArrayList;
33
import java.util.Calendar;
34
import java.util.GregorianCalendar;
35
import java.util.HashMap;
36
import java.util.List;
37
import java.util.Map;
38
import java.util.Map.Entry;
39
 
40
import javax.mail.MessagingException;
41
import org.apache.http.HttpResponse;
42
import org.apache.http.NameValuePair;
43
import org.apache.http.client.ClientProtocolException;
44
import org.apache.http.client.entity.UrlEncodedFormEntity;
45
import org.apache.http.client.methods.HttpGet;
46
import org.apache.http.client.methods.HttpPost;
47
import org.apache.http.entity.mime.MultipartEntity;
48
import org.apache.http.entity.mime.content.ContentBody;
49
import org.apache.http.entity.mime.content.FileBody;
50
import org.apache.http.impl.client.DefaultHttpClient;
51
import org.apache.http.message.BasicNameValuePair;
15634 manish.sha 52
import org.apache.http.util.EntityUtils;
10367 vikram.rag 53
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
54
import org.apache.poi.ss.usermodel.Row;
55
import org.apache.poi.ss.usermodel.Sheet;
56
import org.apache.poi.ss.usermodel.Workbook;
57
import org.apache.thrift.TException;
58
import org.apache.thrift.transport.TTransportException;
15602 manish.sha 59
import org.json.JSONException;
60
import org.json.JSONObject;
10367 vikram.rag 61
 
62
import com.google.gson.Gson;
63
 
64
public class UpdateSDInventoryUsingPanelNew {
65
	private static final boolean PANEL = true;
66
	private static long time = System.currentTimeMillis();
67
	private static String SNAPDEAL_INVENTORY_SHEET;
68
	private static Map<Long, SnapdealItemForInventory> allItemsInventoryMap = new HashMap<Long, SnapdealItemForInventory>();
69
	private static ArrayList<Inventory> currentInventoryItemList;
70
	static Map<Long,Long> itemIdpendingOrdersMap;
71
	private static Map<String,InventoryHistory> inventoryhistoryItemMap;
72
	private static DefaultHttpClient client = new DefaultHttpClient();
73
	static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();
74
	static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();
75
	static Map<String,PendingOrderInventoryHistory> PendingOrdersInventoryHistoryMap = new HashMap<String,PendingOrderInventoryHistory>();
76
	static long lastUpdatedInventoryTime = 0;
77
	static java.text.SimpleDateFormat sdf;
78
	static String emailFromAddress;
79
	static String password;
80
	static GmailUtils mailer;
81
	static String sendTo[];
10422 vikram.rag 82
	static StringBuffer notMappedItems=null;
15602 manish.sha 83
 
84
	static Map<String, String> headers = new HashMap<String, String>();
85
	static {
86
		headers.put("User-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11");
87
		headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
88
		headers.put("Accept-Language", "en-US,en;q=0.8");
89
		headers.put("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
90
	}
10394 vikram.rag 91
 
10367 vikram.rag 92
	public static void initilaize() {
93
		sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
94
		emailFromAddress = "build@shop2020.in";
95
		password = "cafe@nes";
96
		mailer = new GmailUtils();
10502 vikram.rag 97
		//sendTo = new String[]{"vikram.raghav@shop2020.in"};
11431 vikram.rag 98
		sendTo = new String[]{ "anikendra.das@shop2020.in","sandeep.sachdeva@shop2020.in", "vikram.raghav@shop2020.in", "rajneesh.arora@shop2020.in",
10367 vikram.rag 99
				"khushal.bhatia@shop2020.in","manoj.kumar@saholic.com","chaitnaya.vats@saholic.com",
100
				"yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in"};
10502 vikram.rag 101
		 itemIdpendingOrdersMap = new HashMap<Long,Long>();
10394 vikram.rag 102
		 CatalogClient catalogServiceClient = null;
103
		 try {
104
			 catalogServiceClient = new CatalogClient();
105
		 } catch (TTransportException e1) {
106
			 e1.printStackTrace();
107
		 }
108
		 in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
109
		 List<SnapdealItemDetails> allSnapdealItems = null;
110
		 try {
111
			 allSnapdealItems = catalogClient.getAllSnapdealItems();
112
		 } catch (TException e) {
10367 vikram.rag 113
 
10394 vikram.rag 114
			 e.printStackTrace();
115
		 }
116
		 for(SnapdealItemDetails snapdealItem:allSnapdealItems){
117
			 snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);
118
			 itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);
119
			 //System.out.println("Creating Item and Snapdeal Map " + snapdealItem.getItem_id() + " " + snapdealItem.getSkuAtSnapdeal());
120
		 }
121
		 in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
122
		 try {
123
			 transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
124
			 lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
125
			 //System.out.println("Time is " + lastUpdatedInventoryTime);
126
		 } catch (Exception e) {
127
			 try {
128
				 transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
129
				 lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
130
			 } catch (Exception ex) {
131
				 ex.printStackTrace();
132
			 }
133
		 }
10367 vikram.rag 134
 
135
	}
136
 
137
	private static void calculateinventory(){
138
		CatalogClient catalogServiceClient = null;
139
		Map<Long,ItemInventory> availability= new HashMap<Long,ItemInventory>();
140
		try {
141
			catalogServiceClient = new CatalogClient();
142
		} catch (TTransportException e) {
143
 
144
			e.printStackTrace();
145
		}
146
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
147
		try {
148
			List<Item> aliveItems = catalogClient.getAllAliveItems();
149
			Map<Long,Item> aliveItemsMap = new HashMap<Long,Item>(); 
150
			for(in.shop2020.model.v1.catalog.Item thriftItem:aliveItems){
151
				aliveItemsMap.put(thriftItem.getId(), thriftItem);
152
 
153
			}
10376 vikram.rag 154
			InventoryClient inventoryServiceClient=null;
10367 vikram.rag 155
			try {
10376 vikram.rag 156
				inventoryServiceClient = new InventoryClient("inventory_service_server_host","inventory_service_server_port");
10367 vikram.rag 157
			} catch (TTransportException e) {
158
				e.printStackTrace();
159
			}
160
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
161
			List<in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems> ignoreItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
162
			SNAPDEAL_INVENTORY_SHEET = "/home/snapdeal/snapdeal-inventory-"+time+".xls";
163
			availability = inventoryClient.getInventorySnapshot(0);
164
			List<Warehouse> allwarehouses = inventoryClient.getWarehouses(null,null,0,0,0);
165
			Map<Long,Warehouse> allWarehousesMap = new HashMap<Long,Warehouse>();
166
			for(Warehouse warehouse:allwarehouses){
167
				allWarehousesMap.put(warehouse.getId(),warehouse);
168
			}
169
			List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS_THIRDPARTY,null,0,0,0);
170
			List<Warehouse> ours_warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, 0, 0);
171
			List<Long> thirdpartywarehouseids = new ArrayList<Long>();
172
			List<Long> oursGoodWarehouse = new ArrayList<Long>();
173
			for(Warehouse warehouse:warehouses){
174
				thirdpartywarehouseids.add(warehouse.getId());
175
			}
176
			for (Warehouse warehouse:ours_warehouses){
177
				oursGoodWarehouse.add(warehouse.getId());
178
			}
179
			long available=0;
180
			long reserve=0;
181
			long total_warehouse_held=0;
182
			long heldForSource=0;
183
			long total_held=0;
184
			double nlc=0;
185
			double maxnlc=0;
186
			Item thriftItem;
187
			long sku = 0;
188
			for(Inventory inventoryItem:currentInventoryItemList){
189
				if(snapdealItemMap.containsKey(inventoryItem.getSellerSku())){
190
					sku = snapdealItemMap.get(inventoryItem.getSellerSku()).getItem_id();
191
				}
192
				else{
193
					continue;
194
				}
195
				if(aliveItemsMap.get(sku) != null){
196
					thriftItem = aliveItemsMap.get(sku);	
197
				}
198
				else{
199
					continue;
200
				}
201
				available=0;
202
				reserve=0;
203
				total_warehouse_held=0;
204
				heldForSource=0;
205
				total_held=0;
206
				nlc=0;
207
				List<Warehouse> vendor_warehouses=null;
208
				SnapdealItemForInventory item;
209
				if(availability.get(thriftItem.getId())!=null){ 
210
					ItemInventory iteminventory = availability.get(thriftItem.getId());
211
					Map<Long,Long> itemavailability = new HashMap<Long,Long>();
212
					itemavailability = iteminventory.getAvailability();
213
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
214
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());						
215
						vendor_warehouses = inventoryClient.getWarehouses(WarehouseType.THIRD_PARTY,InventoryType.GOOD , thriftItem.getPreferredVendor(), 0, 0);
216
						vendor_warehouses.addAll(ours_warehouses);
217
						for (Warehouse warehouse:vendor_warehouses){
218
							if(warehouse.getBillingWarehouseId()!=7){
12794 kshitij.so 219
							    System.out.println("Item is "+thriftItem.getId());
220
							    System.out.println("Warehouse is "+warehouse.getId());
12795 kshitij.so 221
							    System.out.println("Warehouse Loc "+warehouse.getLogisticsLocation());
222
							    System.out.println("Warehouse Type "+warehouse.getWarehouseType());
223
							    System.out.println("Vendor "+warehouse.getVendor().getId());
10367 vikram.rag 224
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
225
 
226
								}
227
								else{
228
									continue;
229
								}
230
							}
231
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
232
							ignoredItem.setItemId(thriftItem.getId());
233
							ignoredItem.setWarehouseId(warehouse.getId());
234
							if (itemavailability.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(ignoredItem)){
235
								try{
236
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
237
								}
238
								catch(TTransportException e){
239
									inventoryClient = inventoryServiceClient.getClient(); 
240
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
241
								}
242
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
243
 
244
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
245
								if(nlc !=0 && (maxnlc >= nlc)){
246
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
247
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
248
									available = available + itemavailability.get(warehouse.getId());
249
									total_held = total_held + total_warehouse_held; 
250
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
251
								}
252
								else if(maxnlc==0){
253
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
254
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
255
									available = available + itemavailability.get(warehouse.getId());
256
									total_held = total_held + total_warehouse_held;
257
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
258
								}
259
							}
260
						}
261
					}
262
					else{
263
						for (Map.Entry<Long,Long> entry :  itemavailability.entrySet()) {
264
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
265
								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){
266
 
267
								}
268
								else{
269
									continue;
270
								}
271
							}
272
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
273
							ignoredItem.setItemId(thriftItem.getId());
274
							ignoredItem.setWarehouseId(entry.getKey());
275
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
276
 
277
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
278
								try{
279
									maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
280
								}
281
								catch(TTransportException e){
282
									catalogClient = catalogServiceClient.getClient();  
283
									maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
284
								}
285
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
286
								if(nlc !=0 && (maxnlc >= nlc)){
287
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
288
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
289
									available =  available + entry.getValue();
290
									total_held = total_held + total_warehouse_held;
291
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
292
								}
293
								else if(maxnlc==0){
294
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
295
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
296
									available = available + itemavailability.get(entry.getKey());
297
									total_held = total_held + total_warehouse_held;
298
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
299
								}
300
 
301
							}
302
						}
303
					}
304
					Map<Long,Long> itemreserve = new HashMap<Long,Long>();
305
					itemreserve = iteminventory.getReserved();
306
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
307
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating Reserve)"+thriftItem.getPreferredVendor());
308
						for (Warehouse warehouse:vendor_warehouses){
309
							if(warehouse.getBillingWarehouseId()!=7){
310
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
311
 
312
								}
313
								else{
314
									continue;
315
								}
316
							}
317
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
318
							ignoredItem.setItemId(thriftItem.getId());
319
							ignoredItem.setWarehouseId(warehouse.getId());
320
							if (itemreserve.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(warehouse.getId())){
321
								nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
322
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
323
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
324
								if(nlc !=0 && (maxnlc >= nlc)){
325
									reserve = reserve + itemreserve.get(warehouse.getId());
326
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
327
								}
328
								else if(maxnlc==0){
329
									reserve = reserve + itemreserve.get(warehouse.getId());
330
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
331
								}
332
 
333
							}
334
						}
335
					}else{
336
						for (Map.Entry<Long,Long> entry : itemreserve.entrySet()) {
337
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
338
								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){
339
 
340
								}
341
								else{
342
									continue;
343
								}
344
							}
345
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
346
							ignoredItem.setItemId(thriftItem.getId());
347
							ignoredItem.setWarehouseId(entry.getKey());
348
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
349
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
350
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
351
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
352
								if(nlc !=0 && (maxnlc >= nlc)){
353
									reserve =  reserve + entry.getValue();
354
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
355
								}
356
								else if(maxnlc==0){
357
									reserve =  reserve + entry.getValue();
358
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
359
								}
360
 
361
							}
362
 
363
							else{
364
								//System.out.println("skipping inventory for warehouse id " + entry.getKey());
365
							}
366
						}
367
					}
368
					item= new SnapdealItemForInventory(thriftItem.getId(),available,reserve,heldForSource,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),total_held,thriftItem.isRisky(),thriftItem.getItemStatus());
369
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
370
				}
371
				else{
372
					item = new SnapdealItemForInventory(thriftItem.getId(),0,0,0,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),0,thriftItem.isRisky(),thriftItem.getItemStatus());
373
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
374
				}
375
 
376
				//System.out.println(" Item details are " + thriftItem.getId() +" " + available + " " + reserve + " " + thriftItem.getHoldInventory() + " "+ thriftItem.getDefaultInventory() + " " + thriftItem.isRisky());
377
				//System.out.println("+++++++++++++++++++++++");
378
				allItemsInventoryMap.put(thriftItem.getId(),item);
379
 
380
			}
381
 
382
		} catch (TException e) {
383
 
384
			e.printStackTrace();
385
		}
386
 
387
	}
15602 manish.sha 388
	private static void fetchinventoryhistoryfromsnapdeal() throws Exception{
10367 vikram.rag 389
		int i = 1;
390
		Gson gson = new Gson();
391
		inventoryhistoryItemMap = new HashMap<String,InventoryHistory>();
392
		boolean exitfetchinghistory = true;
393
		System.out.println("Fetching history inventory");
394
		HttpGet get;
395
		HttpResponse response = null;
396
		BufferedReader rd = null;
15602 manish.sha 397
		SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
398
		String cookies = "";
399
		JSONObject cookieObject = null;
10367 vikram.rag 400
		while(exitfetchinghistory){
401
			System.out.println("Fetching inventory history page " +i);
402
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=dsc");
15602 manish.sha 403
			cookies = sdSessionCookie.getCookies();
404
			cookieObject = new JSONObject(cookies);
405
			for(String key:headers.keySet())
406
				get.addHeader(key, headers.get(key));
407
			get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
10367 vikram.rag 408
			try {
409
				response = client.execute(get);
410
			} catch (ClientProtocolException e) {
411
 
412
				e.printStackTrace();
413
			} catch (IOException e) {
414
 
415
				e.printStackTrace();
416
			}
417
 
418
			try {
419
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
420
 
421
			} catch (IllegalStateException e) {
422
 
423
				e.printStackTrace();
424
			} catch (IOException e) {
425
 
426
				e.printStackTrace();
427
			}
428
			InventoryHistoryItems inventoryhistoryitems = (InventoryHistoryItems) gson.fromJson(rd, InventoryHistoryItems.class);
429
			if(inventoryhistoryitems.getRows().size()!=0){
430
				//System.out.println("Parsing page " + i);
431
				for(InventoryHistory inventoryhistory : inventoryhistoryitems.getRows()){
432
					//System.out.println("Inventory History " + inventoryhistory.getSellerSku() +" "+ inventoryhistory.getSupc());
433
					if(inventoryhistory.getUpdateTime() > lastUpdatedInventoryTime){
434
						if(inventoryhistoryItemMap.containsKey(inventoryhistory.getSellerSku())){
435
							if(inventoryhistoryItemMap.get(inventoryhistory.getSellerSku()).getUpdateTime() < inventoryhistory.getUpdateTime()){  
436
								inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
437
							}
438
						}
439
						else{
440
							inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
441
						}
442
					}
443
					else{
444
						exitfetchinghistory = false;
445
					}
446
				}
447
			}
448
			else{
449
				exitfetchinghistory = false;
450
			}
15643 kshitij.so 451
			response.getEntity().consumeContent();
10367 vikram.rag 452
			i++;	
453
		}
10376 vikram.rag 454
		InventoryClient inventoryServiceClient = new InventoryClient("inventory_service_server_host","inventory_service_server_port");
10367 vikram.rag 455
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
456
		List<SnapdealInventoryItem> snapdealInventoryItemHistoryList = inventoryClient.getSnapdealInventorySnapshot();
457
		if(snapdealInventoryItemHistoryList.size()>0){
458
			for(SnapdealInventoryItem snapdealInventoryItem:snapdealInventoryItemHistoryList){
459
				if(itemSnapdealMap.containsKey(snapdealInventoryItem.getItem_id())){
460
					PendingOrderInventoryHistory pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
461
					pendingOrdersInventoryHistory.setPendingOrders(snapdealInventoryItem.getPendingOrders());
462
					pendingOrdersInventoryHistory.setInventoryHistory(snapdealInventoryItem.getAvailability());
463
					pendingOrdersInventoryHistory.setLastUpdatedTimestamp(snapdealInventoryItem.getLastUpdatedOnSnapdeal());
464
					PendingOrdersInventoryHistoryMap.put(itemSnapdealMap.get(snapdealInventoryItem.getItem_id()).getSkuAtSnapdeal(), pendingOrdersInventoryHistory);
465
				}
466
			}
467
		}
10498 vikram.rag 468
		//PendingOrderInventoryHistory  pendingOrdersInventoryHistory;
469
		/*for(Entry<String, InventoryHistory> inventoryHistoryItem :inventoryhistoryItemMap.entrySet()){
10367 vikram.rag 470
			if(PendingOrdersInventoryHistoryMap.containsKey(inventoryHistoryItem.getValue().getSellerSku())){
471
				pendingOrdersInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventoryHistoryItem.getValue().getSellerSku());
472
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
473
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
474
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
475
			}
476
			else{
477
				pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
478
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
479
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
480
				pendingOrdersInventoryHistory.setPendingOrders(0);
481
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
482
			}
10498 vikram.rag 483
		}*/
10367 vikram.rag 484
	}
485
 
15602 manish.sha 486
	private static void fetchcurrentinventoryfromsnapdeal() throws Exception{
10367 vikram.rag 487
		int i = 1;
488
		int items=0;
489
		Gson gson = new Gson();
490
		in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
491
		currentInventoryItemList = new ArrayList<Inventory>();
492
		HttpGet get;
493
		HttpResponse response = null;
494
		BufferedReader rd= null;
495
		System.out.println("Fetching current inventory ");
10422 vikram.rag 496
		notMappedItems = new StringBuffer();
15602 manish.sha 497
		SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
498
		String cookies = "";
499
		JSONObject cookieObject = null;
10367 vikram.rag 500
		while(true){
501
			//System.out.println("Fetching current inventory page " +i);
502
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=normal&_search=false&nd="+time+"&rows="+30+"&page="+i+"&sidx=&sord=asc");
15602 manish.sha 503
			cookies = sdSessionCookie.getCookies();
504
			cookieObject = new JSONObject(cookies);
505
			for(String key:headers.keySet())
506
				get.addHeader(key, headers.get(key));
507
			get.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
10367 vikram.rag 508
			try {
509
				response = client.execute(get);
510
			} catch (ClientProtocolException e) {
511
 
512
				e.printStackTrace();
513
			} catch (IOException e) {
514
 
515
				e.printStackTrace();
516
			}
517
			try {
518
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
519
			} catch (IllegalStateException e) {
520
 
521
				e.printStackTrace();
522
			} catch (IOException e) {
523
 
524
				e.printStackTrace();
525
			}
526
			InventoryItems inventoryitems = (InventoryItems) gson.fromJson(rd, InventoryItems.class);
527
			if(inventoryitems.getRows().size()!=0){
528
				for(Inventory inventory : inventoryitems.getRows()){
529
					if(snapdealItemMap.containsKey(inventory.getSellerSku())){
530
						currentInventoryItemList.add(inventory);
531
					}
532
 
533
					else{
534
						notMappedItems.append("<tr>" 
535
								+ "<td>" + inventory.getProductName() +"</td>"
536
								+"<td>" + inventory.getSellerSku() + "</td>"
537
								+"<td>" + inventory.getSupc() + "</td>"
538
								+"</tr>");
539
					}
540
					items++;
541
				}
542
			}
543
			else{
544
				System.out.println("Fetched  " + items);
545
				break;
546
			}
15643 kshitij.so 547
			response.getEntity().consumeContent();
10367 vikram.rag 548
			i++;
549
		}
10988 vikram.rag 550
		if(currentInventoryItemList.size()==0){
551
			try {
11962 vikram.rag 552
				mailer.sendSSLMessage(sendTo,"Snapdeal : Unable to fetch current inventory "+ sdf.format(System.currentTimeMillis()),"Error : Unable to fetch current inventory ", emailFromAddress, password, new ArrayList<File>());
10988 vikram.rag 553
			} catch (MessagingException e) {
554
				e.printStackTrace();
555
			}
556
			System.exit(0);
557
		}
10367 vikram.rag 558
		in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
559
		SnapdealItemDetails snapdealitem = null;
560
		long sku = 0;
561
		long created_orders;
562
		long pending_orders;
563
		Map<Long, Long> itemIdCreatedOrdersMap = null;
564
		try {
565
			transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
566
			System.out.println("Last Updated on Time is  " + lastUpdatedInventoryTime);
567
			if(lastUpdatedInventoryTime > 0){
568
				itemIdCreatedOrdersMap = transactionClient.getOrdersCreatedAfterTimestampForSource(lastUpdatedInventoryTime, 7);
569
				System.out.println("Item id orders created map size "+ itemIdCreatedOrdersMap.entrySet().size());
570
			}
571
		} catch (TTransportException e1) {
572
 
573
			e1.printStackTrace();
574
		}
575
		try {
576
			catalogServiceClient = new CatalogClient().getClient();
577
		} catch (TTransportException e1) {
578
 
579
			e1.printStackTrace();
580
		}
581
		for(Inventory inventory:currentInventoryItemList){
582
			created_orders = 0;
583
			pending_orders = 0;
584
			snapdealitem = snapdealItemMap.get(inventory.getSellerSku());
585
			if(snapdealitem==null){
586
				System.out.println("Not Mapped  " + inventory.getSellerSku());
587
				continue;
588
			}
589
			sku = snapdealitem.getItem_id();
590
			if(sku!=0){
591
				if(itemIdCreatedOrdersMap!=null && itemIdCreatedOrdersMap.containsKey(sku)){
592
					created_orders = itemIdCreatedOrdersMap.get(sku);
593
				}
594
				System.out.println("Created orders for " + sku +" " + created_orders);
595
			}
596
			else{
597
				continue;
598
			}
599
			if(PendingOrdersInventoryHistoryMap.containsKey(inventory.getSellerSku())){
600
				System.out.println("Calculating Pending Orders for " + inventory.getSellerSku());
601
				System.out.println("Current Inventory "+inventory.getAvailableInventory());
602
				System.out.println("History Inventory "+PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory());
603
				System.out.println("Created Orders "+created_orders);
604
				System.out.println("Old Pending Orders "+ PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders());
10498 vikram.rag 605
				//if(PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getLastUpdatedTimestamp() > lastUpdatedInventoryTime){
10367 vikram.rag 606
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() + PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory() - inventory.getAvailableInventory() - created_orders;
10498 vikram.rag 607
				//}
608
				/*else{
10367 vikram.rag 609
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() - created_orders;
10498 vikram.rag 610
				}*/
10367 vikram.rag 611
				System.out.println("New Pending Orders "+pending_orders);
612
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
613
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
614
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
615
			}
616
			else{
617
				System.out.print("Could not calculate pending orders " + inventory.getSellerSku() +"\n");
618
				PendingOrderInventoryHistory pendingOrderInventoryHistory = new PendingOrderInventoryHistory();
619
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
620
				pendingOrderInventoryHistory.setInventoryHistory(inventory.getAvailableInventory());
621
				pendingOrderInventoryHistory.setLastUpdatedTimestamp(System.currentTimeMillis());
622
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
623
			}
624
			itemIdpendingOrdersMap.put(sku, pending_orders);
625
		}
626
	}
627
 
628
	@SuppressWarnings("deprecation")
10371 vikram.rag 629
	public static void sendsnapdealinventory (){
10367 vikram.rag 630
		initilaize();
631
		try {
632
			fetchinventoryhistoryfromsnapdeal();
633
		} catch (UnsupportedEncodingException e2) {
634
			System.out.println("History Inventory Fetch failed");
635
			e2.printStackTrace();
10371 vikram.rag 636
		} catch (TException e) {
637
			e.printStackTrace();
15602 manish.sha 638
		} catch (Exception e) {
639
			e.printStackTrace();
10367 vikram.rag 640
		}
641
		try {
642
			fetchcurrentinventoryfromsnapdeal();
643
		} catch (UnsupportedEncodingException e2) {
644
			System.out.println("Current Inventory Fetch failed");
645
			e2.printStackTrace();
10371 vikram.rag 646
		} catch (TException e) {
647
			e.printStackTrace();
15602 manish.sha 648
		} catch (Exception e) {
649
			e.printStackTrace();
10367 vikram.rag 650
		}
651
		calculateinventory();
652
		FileInputStream fis = null;
653
		Workbook hwb = null;
654
		Sheet sheet = null;
15602 manish.sha 655
		SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
656
		String cookies = "";
657
		JSONObject cookieObject = null;
10367 vikram.rag 658
		if(!PANEL){
659
			try {
660
				fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
661
			} catch (FileNotFoundException e) {
662
				System.out.println("Template File not found");
663
				e.printStackTrace();
664
			}
665
			try {
666
				hwb = new HSSFWorkbook(fis);
667
			} catch (IOException e) {
668
				System.out.println("Could not created workbook I/O Problem");
669
				e.printStackTrace();
670
			}
671
			sheet = hwb.getSheetAt(0);
672
		}
673
		Row row = null;
674
		int iterator=1;
675
		long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
676
		SnapdealItemForInventory  inventoryItem;
677
		StringBuffer outOfStockItems =new StringBuffer();
678
		StringBuffer backInStockItems =new StringBuffer();
679
		StringBuffer inventoryChangeItems =new StringBuffer();
680
		StringBuffer heldMoreThanAvailable =new StringBuffer();
681
		long sku = 0;
682
		SnapdealItemDetails snapdealitem;
683
		long lastSentInventoryTime = System.currentTimeMillis();
10394 vikram.rag 684
		List<SnapdealInventoryItem> snapdealInventoryItemList = new ArrayList<SnapdealInventoryItem>();; 
10367 vikram.rag 685
		for(Inventory inventory:currentInventoryItemList){
686
			//System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
687
			if(snapdealItemMap.containsKey(inventory.getSellerSku())){
688
				snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
689
				sku =  snapdealitem.getItem_id();
690
			}
691
			else{
692
				continue;
693
			}
694
			if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
695
				inventoryItem = allItemsInventoryMap.get(sku);
696
				if(inventoryItem==null){
697
					continue;
698
				}
699
				available = inventoryItem.getAvailability(); 
700
				reserve = inventoryItem.getReserve();
701
				defaultinventory = inventoryItem.getDefaultInventory();
702
				holdinventory = inventoryItem.getHoldInventory();
703
				totalheld = inventoryItem.getTotalHeldInventory();
704
				heldforsource = inventoryItem.getHeldForSource();
705
				if(itemIdpendingOrdersMap.containsKey(sku)){
706
					heldorders = itemIdpendingOrdersMap.get(sku);
707
					if(heldorders < 0){
708
						heldorders = 0;
709
					}
710
				}
711
				System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
712
						"\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
713
						"\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
714
						+ defaultinventory + "\theldorders " + heldorders);
715
				if(!PANEL){
716
					row =   sheet.getRow((short) iterator);
717
				}
718
				if(!inventoryItem.getStatus().equals(status.PAUSED)){
10450 vikram.rag 719
					System.out.println("Not Paused");
10367 vikram.rag 720
					if(inventoryItem.getRisky()){
721
						if((available - reserve) < totalheld && totalheld!=0){
722
							sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
723
							heldMoreThanAvailable.append("<tr>" 
724
									+ "<td>" + inventory.getProductName() +"</td>"
725
									+"<td>" + sku + "</td>"
726
									+"<td>" + (available - reserve) +  "</td>"
727
									+"<td>" + totalheld + "</td>"
728
									+"</tr>");
729
						}
730
						else{
731
							allocable = available - reserve - totalheld - holdinventory;
732
							if(allocable < 0){
733
								allocable = 0;
734
							}
735
							sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
736
						}
737
						if(sent_inventory < 0){
738
							sent_inventory = 0;
739
						}
740
					}
741
					else{
742
						allocable = available - reserve - totalheld;
743
						if(allocable < 0){
744
							allocable = 0;
745
						}
746
						if((allocable + heldforsource ) > defaultinventory){
747
							sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
748
							//System.out.println("actual" + allocable + "\t2/3actual" + Math.round(allocable*2/3) +  "\theld for source" + heldforsource + "\theldorders" +  heldorders + "\tFinal Value is : " + (Math.round(allocable*2/3) +  heldforsource - heldorders));
749
							if(sent_inventory < 0){
750
								sent_inventory = 0;							
751
							}
752
						}
753
						else{
754
							if(defaultinventory > heldorders){
755
								sent_inventory = defaultinventory - heldorders;
756
							}
757
							else{
758
								sent_inventory = 0;
759
							}
760
						}
761
					}
762
				}
763
				else{
764
					sent_inventory = 0;
765
				}
766
				SnapdealInventoryItem snapdealInventoryItem;
10498 vikram.rag 767
				snapdealInventoryItem = new SnapdealInventoryItem();
768
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
769
				if(snapdealItemMap.containsKey(inventory.getSellerSku())){
770
					System.out.println("Found in snapdeal items map)");
771
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
772
					System.out.println("Updating snapdeal inventory snapshot Item ID :"+snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
773
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
774
					snapdealInventoryItem.setItem_id(snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
775
					snapdealInventoryItem.setPendingOrders(pendingOrderInventoryHistory.getPendingOrders());
776
					snapdealInventoryItem.setAvailability(sent_inventory);
777
					snapdealInventoryItem.setLastUpdatedOnSnapdeal(lastSentInventoryTime);
778
					if(sent_inventory > 0){
779
						snapdealInventoryItem.setIs_oos(false);
780
					}
781
					else{
782
						snapdealInventoryItem.setIs_oos(true);
783
					}
784
					snapdealInventoryItemList.add(snapdealInventoryItem);
785
				}
10450 vikram.rag 786
				System.out.println("Before incremental check");
787
				System.out.println("Before incremental available "+inventory.getAvailableInventory());
788
				System.out.println("To send "+sent_inventory);
10396 vikram.rag 789
				if(inventory.getAvailableInventory()!= sent_inventory){
10450 vikram.rag 790
					System.out.println("Incremental check success");
10367 vikram.rag 791
					if(!PANEL){
792
						row.getCell((short) 0).setCellValue(inventory.getSupc());
793
						row.getCell((short) 1).setCellValue(inventory.getSellerSku());
794
						row.getCell((short) 2).setCellValue(inventory.getProductName());
795
						row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
796
						row.getCell((short) 4).setCellValue(sent_inventory);
797
						if(inventory.isLive()){
798
							row.getCell((short) 5).setCellValue("Yes");
799
						}
800
						else{
801
							row.getCell((short) 5).setCellValue("No");
802
						}
803
					}
804
					else{
10450 vikram.rag 805
						System.out.println("Incremental check success");
10367 vikram.rag 806
						try {
13899 manish.sha 807
							HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/update");
15602 manish.sha 808
							try {
809
								cookies = sdSessionCookie.getCookies();
810
							} catch (Exception e) {
811
								e.printStackTrace();
812
							}
813
							try {
814
								cookieObject = new JSONObject(cookies);
815
							} catch (JSONException e) {
816
								e.printStackTrace();
817
							}
818
							for(String key:headers.keySet())
819
								post.addHeader(key, headers.get(key));
820
							try {
821
								post.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
822
							} catch (JSONException e) {
823
								e.printStackTrace();
824
							}
13899 manish.sha 825
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
826
							System.out.println("Calling update inventory: Supc: "+inventory.getSupc()+ " to be update stock: "+ sent_inventory);
827
							nameValuePairs.add(new BasicNameValuePair("changedField",
828
									"inventory"));
829
							nameValuePairs.add(new BasicNameValuePair("changedValue",
830
									String.valueOf(sent_inventory)));
831
							nameValuePairs.add(new BasicNameValuePair("supc",
832
									inventory.getSupc()));
833
							post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
834
							HttpResponse response = client.execute(post);
835
							BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
836
							String line = "";
837
							while ((line = rd.readLine()) != null) {
838
								System.out.println("Response of Inventory Update: "+line);
839
							}
15643 kshitij.so 840
							response.getEntity().consumeContent();
13890 manish.sha 841
							Thread.sleep(2000);
10367 vikram.rag 842
						} catch (ClientProtocolException e) {
843
							System.out.println("Could not login and update inventory");
844
							e.printStackTrace();
845
							continue;
846
						} catch (IOException e) {
847
							System.out.println("Could not login and update inventory I/O");
848
							e.printStackTrace();
849
							continue;
13885 manish.sha 850
						} catch (InterruptedException e) {
851
							System.out.println("Could not login and update inventory I/O");
852
							e.printStackTrace();
853
							continue;
10367 vikram.rag 854
						}
855
					}
856
					if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
857
						outOfStockItems.append("<tr>" 
858
								+ "<td>" + inventory.getProductName() +"</td>"
859
								+"<td>" + sku + "</td>"
860
								+"<td>" + inventory.getAvailableInventory() + "</td>"
861
								+"<td>" + sent_inventory + "</td>"
862
								+"</tr>");
863
					}
864
					else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
865
						backInStockItems.append("<tr>" 
866
								+ "<td>" + inventory.getProductName() +"</td>"
867
								+"<td>" + sku + "</td>"
868
								+"<td>" + inventory.getAvailableInventory() + "</td>"
869
								+"<td>" + sent_inventory + "</td>"
870
								+"</tr>");
871
					}
872
					else{
873
						inventoryChangeItems.append("<tr>" 
874
								+ "<td>" + inventory.getProductName() +"</td>"
875
								+"<td>" + sku + "</td>"
876
								+"<td>" + inventory.getAvailableInventory() + "</td>"
877
								+"<td>" + sent_inventory + "</td>"
878
								+"</tr>");
879
					}
880
					iterator++;
881
				}
882
			}
883
			else{
884
				continue;
885
			}
886
		}
887
		if(iterator > 1){
888
			FileOutputStream fileOut = null;
889
			if(!PANEL){
890
				try {
891
					fis.close();
892
				} catch (IOException e2) {
893
					e2.printStackTrace();
894
				}
895
				try {
896
					System.out.println("Before writing file ");
897
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
898
				} catch (FileNotFoundException e) {
899
 
900
					e.printStackTrace();
901
				}
902
				try {
903
 
904
					hwb.write(fileOut);
905
				} catch (IOException e) {
906
 
907
					e.printStackTrace();
908
				}
909
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
910
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
911
				MultipartEntity mpEntity = new MultipartEntity();
912
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
913
				mpEntity.addPart("file", cbFile);
914
				post.setEntity(mpEntity);
915
				System.out.println("Before posting file");
916
				HttpResponse response=null;
917
				try {
918
					response = client.execute(post);
919
				} catch (ClientProtocolException e2) {
920
					System.out.println("Error While Posting Inventory File");
921
					e2.printStackTrace();
922
				} catch (IOException e2) {
923
					System.out.println("I/O Error While Posting Inventory File");
924
					e2.printStackTrace();
925
				}
926
				BufferedReader rd = null;
927
				try {
928
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
929
				} catch (IllegalStateException e1) {
930
 
931
					e1.printStackTrace();
932
				} catch (IOException e1) {
933
 
934
					e1.printStackTrace();
935
				}
936
				String line = "";
937
				String feedresponse = null;
938
				try {
939
					while ((line = rd.readLine()) != null) {
940
						System.out.println(line);
941
						feedresponse = line;
942
					}
15643 kshitij.so 943
					response.getEntity().consumeContent();
10367 vikram.rag 944
				} catch (IOException e) {
945
 
946
					e.printStackTrace();
947
				}
948
				System.out.println("posting response" + feedresponse);
949
			}
950
			int retry = 24;
951
			boolean feedsuccess =false;
952
			while(retry>0){
953
				try {
10501 vikram.rag 954
					Thread.sleep(1*60*1000);
10371 vikram.rag 955
				} catch (InterruptedException e) {
956
					e.printStackTrace();
957
				}
958
				try {
10367 vikram.rag 959
					lastUpdatedInventoryTime = lastSentInventoryTime; 
960
					fetchinventoryhistoryfromsnapdeal();
961
				} catch (UnsupportedEncodingException e1) {
962
					System.out.println("Error while fetching inventory update result");
963
					e1.printStackTrace();
10371 vikram.rag 964
				} catch (TException e) {
965
					e.printStackTrace();
15602 manish.sha 966
				} catch (Exception e) {
967
					e.printStackTrace();
10367 vikram.rag 968
				}
969
				if(inventoryhistoryItemMap.entrySet().size()==iterator -1){
970
					feedsuccess = true;
971
					break;
972
				}
973
				retry --;
974
			}
975
			String PANEL_TEXT_MAIL = "";
976
			if(PANEL){
977
				PANEL_TEXT_MAIL = " (Using Panel)";
978
			}
979
			String emailSubjectTxt;
980
			String text;
981
			String tableHeader;
982
			if(feedsuccess){
10369 vikram.rag 983
				in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
984
				try {
985
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
986
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
987
				} catch (Exception e) {
988
					try {
989
						transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
990
						transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
991
					} catch (Exception ex) {
992
						ex.printStackTrace();
993
					}
994
				}
10394 vikram.rag 995
				if(snapdealInventoryItemList.size() > 0){
10450 vikram.rag 996
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = null;
10371 vikram.rag 997
					try {
10394 vikram.rag 998
						System.out.println("Before updating to database");
999
						for(SnapdealInventoryItem item:snapdealInventoryItemList){
1000
							System.out.println("Item ID " + item.getItem_id()); 
1001
							System.out.println("Availability " + item.getAvailability());
1002
							System.out.println("Updated time " + sdf.format(item.getLastUpdatedOnSnapdeal()));
1003
							System.out.println("Pending Orders " + item.getPendingOrders());
1004
						}
1005
						System.out.println("Snapdeal inventory list size" + snapdealInventoryItemList.size());
10450 vikram.rag 1006
						inventoryClient = new InventoryClient().getClient();
10371 vikram.rag 1007
						inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
10394 vikram.rag 1008
					} catch (TException e) {
1009
						e.printStackTrace();
1010
						try {
10450 vikram.rag 1011
							inventoryClient = new InventoryClient().getClient();
1012
						} catch (TTransportException e2) {
1013
							e2.printStackTrace();
1014
						}
1015
						try {
10394 vikram.rag 1016
							inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
1017
						} catch (TException e1) {
1018
							e1.printStackTrace();
1019
						}
10371 vikram.rag 1020
					}
10367 vikram.rag 1021
				}
1022
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1023
				tableHeader = "<tr>" 
1024
					+ "<td>" + "Product Name" +"</td>"
1025
					+"<td>" + "Item ID" + "</td>"
1026
					+"<td>" + "Old Inventory" + "</td>"
1027
					+"<td>" + "New Inventory" + "</td>"
1028
					+"</tr>";
10394 vikram.rag 1029
 
10367 vikram.rag 1030
				if(backInStockItems.length() > 0){
1031
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
1032
					try {
1033
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1034
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1035
					} catch (Exception e) {
10367 vikram.rag 1036
						e.printStackTrace();
1037
					}
1038
				}
1039
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1040
				if(outOfStockItems.length() > 0){
1041
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
1042
					try {
1043
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1044
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1045
					} catch (Exception e) {
10367 vikram.rag 1046
						e.printStackTrace();
1047
					}
1048
				}
1049
				emailSubjectTxt = "Snapdeal Inventory Updated for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis())+PANEL_TEXT_MAIL;
1050
				if(inventoryChangeItems.length() > 0){
1051
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
1052
					try {
1053
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
10374 vikram.rag 1054
					} catch (Exception e) {
10367 vikram.rag 1055
						e.printStackTrace();
1056
					}
1057
				}
1058
			}
1059
			else{
1060
				emailSubjectTxt = "Snapdeal Inventory Could not be updated "+PANEL_TEXT_MAIL+" " +sdf.format(System.currentTimeMillis());
10371 vikram.rag 1061
				try {
1062
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password,"Please contact Engg ");
10374 vikram.rag 1063
				} catch (Exception e) {
10371 vikram.rag 1064
					e.printStackTrace();
1065
				}
10367 vikram.rag 1066
			}
1067
			tableHeader = "<tr>" 
1068
				+ "<td>" + "Product Name" +"</td>"
1069
				+"<td>" + "Item ID" + "</td>"
1070
				+"<td>" + "Available - Reserve" + "</td>"
1071
				+"<td>" + "Total Held" + "</td>"
1072
				+"</tr>";
1073
 
1074
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
1075
			if(heldMoreThanAvailable.length() > 0){
1076
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1077
				try {
1078
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1079
					//mailer.sendSSLMessage(sendTo,"Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis()),inventoryChangeItems.toString(), emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1080
				} catch (Exception e) {
10367 vikram.rag 1081
					e.printStackTrace();
1082
				}
1083
			}
15833 kshitij.so 1084
			System.exit(0);
10367 vikram.rag 1085
		}
1086
		else{
1087
			try {
1088
				mailer.sendSSLMessage(sendTo,"No changes in Snapdeal inventory to update "+ sdf.format(System.currentTimeMillis()),"No change in Snapdeal Inventory to be updated ", emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1089
			} catch (Exception e) {
10367 vikram.rag 1090
				e.printStackTrace();
1091
			}
15833 kshitij.so 1092
			System.exit(0);
10367 vikram.rag 1093
		}
1094
		String tableHeader = "<tr>" 
1095
			+ "<td>" + "Product Name" +"</td>"
1096
			+"<td>" + "SKU at Snapdeal" + "</td>"
1097
			+"<td>" + "SUPC" + "</td>"
1098
			+"</tr>";
1099
		String text;
1100
 
1101
		if(notMappedItems.length() >0){
1102
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
10371 vikram.rag 1103
			try {
1104
				mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
10374 vikram.rag 1105
			} catch (Exception e) {
10371 vikram.rag 1106
				e.printStackTrace();
1107
			}
10367 vikram.rag 1108
		}
1109
 
1110
	}
1111
 
10394 vikram.rag 1112
	public static void main(String[] args){
1113
		while(true){
1114
			sendsnapdealinventory();
1115
		}
10367 vikram.rag 1116
 
10394 vikram.rag 1117
	}
1118
 
10367 vikram.rag 1119
}