Subversion Repositories SmartDukaan

Rev

Rev 15602 | Rev 15643 | Go to most recent revision | 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
			}
15634 manish.sha 451
			EntityUtils.consume(response.getEntity());
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
			}
15634 manish.sha 547
			EntityUtils.consume(response.getEntity());
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
 
629
	@SuppressWarnings("deprecation")
10371 vikram.rag 630
	public static void sendsnapdealinventory (){
10367 vikram.rag 631
		initilaize();
632
		try {
633
			fetchinventoryhistoryfromsnapdeal();
634
		} catch (UnsupportedEncodingException e2) {
635
			System.out.println("History Inventory Fetch failed");
636
			e2.printStackTrace();
10371 vikram.rag 637
		} catch (TException e) {
638
			e.printStackTrace();
15602 manish.sha 639
		} catch (Exception e) {
640
			e.printStackTrace();
10367 vikram.rag 641
		}
642
		try {
643
			fetchcurrentinventoryfromsnapdeal();
644
		} catch (UnsupportedEncodingException e2) {
645
			System.out.println("Current Inventory Fetch failed");
646
			e2.printStackTrace();
10371 vikram.rag 647
		} catch (TException e) {
648
			e.printStackTrace();
15602 manish.sha 649
		} catch (Exception e) {
650
			e.printStackTrace();
10367 vikram.rag 651
		}
652
		calculateinventory();
653
		FileInputStream fis = null;
654
		Workbook hwb = null;
655
		Sheet sheet = null;
15602 manish.sha 656
		SnapdealSessionCookie sdSessionCookie = new SnapdealSessionCookie();
657
		String cookies = "";
658
		JSONObject cookieObject = null;
10367 vikram.rag 659
		if(!PANEL){
660
			try {
661
				fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
662
			} catch (FileNotFoundException e) {
663
				System.out.println("Template File not found");
664
				e.printStackTrace();
665
			}
666
			try {
667
				hwb = new HSSFWorkbook(fis);
668
			} catch (IOException e) {
669
				System.out.println("Could not created workbook I/O Problem");
670
				e.printStackTrace();
671
			}
672
			sheet = hwb.getSheetAt(0);
673
		}
674
		Row row = null;
675
		int iterator=1;
676
		long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
677
		SnapdealItemForInventory  inventoryItem;
678
		StringBuffer outOfStockItems =new StringBuffer();
679
		StringBuffer backInStockItems =new StringBuffer();
680
		StringBuffer inventoryChangeItems =new StringBuffer();
681
		StringBuffer heldMoreThanAvailable =new StringBuffer();
682
		long sku = 0;
683
		SnapdealItemDetails snapdealitem;
684
		long lastSentInventoryTime = System.currentTimeMillis();
10394 vikram.rag 685
		List<SnapdealInventoryItem> snapdealInventoryItemList = new ArrayList<SnapdealInventoryItem>();; 
10367 vikram.rag 686
		for(Inventory inventory:currentInventoryItemList){
687
			//System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
688
			if(snapdealItemMap.containsKey(inventory.getSellerSku())){
689
				snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
690
				sku =  snapdealitem.getItem_id();
691
			}
692
			else{
693
				continue;
694
			}
695
			if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
696
				inventoryItem = allItemsInventoryMap.get(sku);
697
				if(inventoryItem==null){
698
					continue;
699
				}
700
				available = inventoryItem.getAvailability(); 
701
				reserve = inventoryItem.getReserve();
702
				defaultinventory = inventoryItem.getDefaultInventory();
703
				holdinventory = inventoryItem.getHoldInventory();
704
				totalheld = inventoryItem.getTotalHeldInventory();
705
				heldforsource = inventoryItem.getHeldForSource();
706
				if(itemIdpendingOrdersMap.containsKey(sku)){
707
					heldorders = itemIdpendingOrdersMap.get(sku);
708
					if(heldorders < 0){
709
						heldorders = 0;
710
					}
711
				}
712
				System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
713
						"\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
714
						"\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
715
						+ defaultinventory + "\theldorders " + heldorders);
716
				if(!PANEL){
717
					row =   sheet.getRow((short) iterator);
718
				}
719
				if(!inventoryItem.getStatus().equals(status.PAUSED)){
10450 vikram.rag 720
					System.out.println("Not Paused");
10367 vikram.rag 721
					if(inventoryItem.getRisky()){
722
						if((available - reserve) < totalheld && totalheld!=0){
723
							sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
724
							heldMoreThanAvailable.append("<tr>" 
725
									+ "<td>" + inventory.getProductName() +"</td>"
726
									+"<td>" + sku + "</td>"
727
									+"<td>" + (available - reserve) +  "</td>"
728
									+"<td>" + totalheld + "</td>"
729
									+"</tr>");
730
						}
731
						else{
732
							allocable = available - reserve - totalheld - holdinventory;
733
							if(allocable < 0){
734
								allocable = 0;
735
							}
736
							sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
737
						}
738
						if(sent_inventory < 0){
739
							sent_inventory = 0;
740
						}
741
					}
742
					else{
743
						allocable = available - reserve - totalheld;
744
						if(allocable < 0){
745
							allocable = 0;
746
						}
747
						if((allocable + heldforsource ) > defaultinventory){
748
							sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
749
							//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));
750
							if(sent_inventory < 0){
751
								sent_inventory = 0;							
752
							}
753
						}
754
						else{
755
							if(defaultinventory > heldorders){
756
								sent_inventory = defaultinventory - heldorders;
757
							}
758
							else{
759
								sent_inventory = 0;
760
							}
761
						}
762
					}
763
				}
764
				else{
765
					sent_inventory = 0;
766
				}
767
				SnapdealInventoryItem snapdealInventoryItem;
10498 vikram.rag 768
				snapdealInventoryItem = new SnapdealInventoryItem();
769
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
770
				if(snapdealItemMap.containsKey(inventory.getSellerSku())){
771
					System.out.println("Found in snapdeal items map)");
772
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
773
					System.out.println("Updating snapdeal inventory snapshot Item ID :"+snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
774
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
775
					snapdealInventoryItem.setItem_id(snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
776
					snapdealInventoryItem.setPendingOrders(pendingOrderInventoryHistory.getPendingOrders());
777
					snapdealInventoryItem.setAvailability(sent_inventory);
778
					snapdealInventoryItem.setLastUpdatedOnSnapdeal(lastSentInventoryTime);
779
					if(sent_inventory > 0){
780
						snapdealInventoryItem.setIs_oos(false);
781
					}
782
					else{
783
						snapdealInventoryItem.setIs_oos(true);
784
					}
785
					snapdealInventoryItemList.add(snapdealInventoryItem);
786
				}
10450 vikram.rag 787
				System.out.println("Before incremental check");
788
				System.out.println("Before incremental available "+inventory.getAvailableInventory());
789
				System.out.println("To send "+sent_inventory);
10396 vikram.rag 790
				if(inventory.getAvailableInventory()!= sent_inventory){
10450 vikram.rag 791
					System.out.println("Incremental check success");
10367 vikram.rag 792
					if(!PANEL){
793
						row.getCell((short) 0).setCellValue(inventory.getSupc());
794
						row.getCell((short) 1).setCellValue(inventory.getSellerSku());
795
						row.getCell((short) 2).setCellValue(inventory.getProductName());
796
						row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
797
						row.getCell((short) 4).setCellValue(sent_inventory);
798
						if(inventory.isLive()){
799
							row.getCell((short) 5).setCellValue("Yes");
800
						}
801
						else{
802
							row.getCell((short) 5).setCellValue("No");
803
						}
804
					}
805
					else{
10450 vikram.rag 806
						System.out.println("Incremental check success");
10367 vikram.rag 807
						try {
13899 manish.sha 808
							HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/update");
15602 manish.sha 809
							try {
810
								cookies = sdSessionCookie.getCookies();
811
							} catch (Exception e) {
812
								e.printStackTrace();
813
							}
814
							try {
815
								cookieObject = new JSONObject(cookies);
816
							} catch (JSONException e) {
817
								e.printStackTrace();
818
							}
819
							for(String key:headers.keySet())
820
								post.addHeader(key, headers.get(key));
821
							try {
822
								post.addHeader("Cookie","SERVERID="+cookieObject.get("SERVERID")+";sfJSESSIONID="+cookieObject.get("sfJSESSIONID")+";");
823
							} catch (JSONException e) {
824
								e.printStackTrace();
825
							}
13899 manish.sha 826
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
827
							System.out.println("Calling update inventory: Supc: "+inventory.getSupc()+ " to be update stock: "+ sent_inventory);
828
							nameValuePairs.add(new BasicNameValuePair("changedField",
829
									"inventory"));
830
							nameValuePairs.add(new BasicNameValuePair("changedValue",
831
									String.valueOf(sent_inventory)));
832
							nameValuePairs.add(new BasicNameValuePair("supc",
833
									inventory.getSupc()));
834
							post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
835
							HttpResponse response = client.execute(post);
836
							BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
837
							String line = "";
838
							while ((line = rd.readLine()) != null) {
839
								System.out.println("Response of Inventory Update: "+line);
840
							}
15634 manish.sha 841
							EntityUtils.consume(response.getEntity());
13890 manish.sha 842
							Thread.sleep(2000);
10367 vikram.rag 843
						} catch (ClientProtocolException e) {
844
							System.out.println("Could not login and update inventory");
845
							e.printStackTrace();
846
							continue;
847
						} catch (IOException e) {
848
							System.out.println("Could not login and update inventory I/O");
849
							e.printStackTrace();
850
							continue;
13885 manish.sha 851
						} catch (InterruptedException e) {
852
							System.out.println("Could not login and update inventory I/O");
853
							e.printStackTrace();
854
							continue;
10367 vikram.rag 855
						}
856
					}
857
					if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
858
						outOfStockItems.append("<tr>" 
859
								+ "<td>" + inventory.getProductName() +"</td>"
860
								+"<td>" + sku + "</td>"
861
								+"<td>" + inventory.getAvailableInventory() + "</td>"
862
								+"<td>" + sent_inventory + "</td>"
863
								+"</tr>");
864
					}
865
					else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
866
						backInStockItems.append("<tr>" 
867
								+ "<td>" + inventory.getProductName() +"</td>"
868
								+"<td>" + sku + "</td>"
869
								+"<td>" + inventory.getAvailableInventory() + "</td>"
870
								+"<td>" + sent_inventory + "</td>"
871
								+"</tr>");
872
					}
873
					else{
874
						inventoryChangeItems.append("<tr>" 
875
								+ "<td>" + inventory.getProductName() +"</td>"
876
								+"<td>" + sku + "</td>"
877
								+"<td>" + inventory.getAvailableInventory() + "</td>"
878
								+"<td>" + sent_inventory + "</td>"
879
								+"</tr>");
880
					}
881
					iterator++;
882
				}
883
			}
884
			else{
885
				continue;
886
			}
887
		}
888
		if(iterator > 1){
889
			FileOutputStream fileOut = null;
890
			if(!PANEL){
891
				try {
892
					fis.close();
893
				} catch (IOException e2) {
894
					e2.printStackTrace();
895
				}
896
				try {
897
					System.out.println("Before writing file ");
898
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
899
				} catch (FileNotFoundException e) {
900
 
901
					e.printStackTrace();
902
				}
903
				try {
904
 
905
					hwb.write(fileOut);
906
				} catch (IOException e) {
907
 
908
					e.printStackTrace();
909
				}
910
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
911
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
912
				MultipartEntity mpEntity = new MultipartEntity();
913
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
914
				mpEntity.addPart("file", cbFile);
915
				post.setEntity(mpEntity);
916
				System.out.println("Before posting file");
917
				HttpResponse response=null;
918
				try {
919
					response = client.execute(post);
920
				} catch (ClientProtocolException e2) {
921
					System.out.println("Error While Posting Inventory File");
922
					e2.printStackTrace();
923
				} catch (IOException e2) {
924
					System.out.println("I/O Error While Posting Inventory File");
925
					e2.printStackTrace();
926
				}
927
				BufferedReader rd = null;
928
				try {
929
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
930
				} catch (IllegalStateException e1) {
931
 
932
					e1.printStackTrace();
933
				} catch (IOException e1) {
934
 
935
					e1.printStackTrace();
936
				}
937
				String line = "";
938
				String feedresponse = null;
939
				try {
940
					while ((line = rd.readLine()) != null) {
941
						System.out.println(line);
942
						feedresponse = line;
943
					}
15634 manish.sha 944
					EntityUtils.consume(response.getEntity());
10367 vikram.rag 945
				} catch (IOException e) {
946
 
947
					e.printStackTrace();
948
				}
949
				System.out.println("posting response" + feedresponse);
950
			}
951
			int retry = 24;
952
			boolean feedsuccess =false;
953
			while(retry>0){
954
				try {
10501 vikram.rag 955
					Thread.sleep(1*60*1000);
10371 vikram.rag 956
				} catch (InterruptedException e) {
957
					e.printStackTrace();
958
				}
959
				try {
10367 vikram.rag 960
					lastUpdatedInventoryTime = lastSentInventoryTime; 
961
					fetchinventoryhistoryfromsnapdeal();
962
				} catch (UnsupportedEncodingException e1) {
963
					System.out.println("Error while fetching inventory update result");
964
					e1.printStackTrace();
10371 vikram.rag 965
				} catch (TException e) {
966
					e.printStackTrace();
15602 manish.sha 967
				} catch (Exception e) {
968
					e.printStackTrace();
10367 vikram.rag 969
				}
970
				if(inventoryhistoryItemMap.entrySet().size()==iterator -1){
971
					feedsuccess = true;
972
					break;
973
				}
974
				retry --;
975
			}
976
			String PANEL_TEXT_MAIL = "";
977
			if(PANEL){
978
				PANEL_TEXT_MAIL = " (Using Panel)";
979
			}
980
			String emailSubjectTxt;
981
			String text;
982
			String tableHeader;
983
			if(feedsuccess){
10369 vikram.rag 984
				in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
985
				try {
986
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
987
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
988
				} catch (Exception e) {
989
					try {
990
						transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
991
						transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
992
					} catch (Exception ex) {
993
						ex.printStackTrace();
994
					}
995
				}
10394 vikram.rag 996
				if(snapdealInventoryItemList.size() > 0){
10450 vikram.rag 997
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = null;
10371 vikram.rag 998
					try {
10394 vikram.rag 999
						System.out.println("Before updating to database");
1000
						for(SnapdealInventoryItem item:snapdealInventoryItemList){
1001
							System.out.println("Item ID " + item.getItem_id()); 
1002
							System.out.println("Availability " + item.getAvailability());
1003
							System.out.println("Updated time " + sdf.format(item.getLastUpdatedOnSnapdeal()));
1004
							System.out.println("Pending Orders " + item.getPendingOrders());
1005
						}
1006
						System.out.println("Snapdeal inventory list size" + snapdealInventoryItemList.size());
10450 vikram.rag 1007
						inventoryClient = new InventoryClient().getClient();
10371 vikram.rag 1008
						inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
10394 vikram.rag 1009
					} catch (TException e) {
1010
						e.printStackTrace();
1011
						try {
10450 vikram.rag 1012
							inventoryClient = new InventoryClient().getClient();
1013
						} catch (TTransportException e2) {
1014
							e2.printStackTrace();
1015
						}
1016
						try {
10394 vikram.rag 1017
							inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
1018
						} catch (TException e1) {
1019
							e1.printStackTrace();
1020
						}
10371 vikram.rag 1021
					}
10367 vikram.rag 1022
				}
1023
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1024
				tableHeader = "<tr>" 
1025
					+ "<td>" + "Product Name" +"</td>"
1026
					+"<td>" + "Item ID" + "</td>"
1027
					+"<td>" + "Old Inventory" + "</td>"
1028
					+"<td>" + "New Inventory" + "</td>"
1029
					+"</tr>";
10394 vikram.rag 1030
 
10367 vikram.rag 1031
				if(backInStockItems.length() > 0){
1032
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
1033
					try {
1034
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1035
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1036
					} catch (Exception e) {
10367 vikram.rag 1037
						e.printStackTrace();
1038
					}
1039
				}
1040
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1041
				if(outOfStockItems.length() > 0){
1042
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
1043
					try {
1044
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1045
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1046
					} catch (Exception e) {
10367 vikram.rag 1047
						e.printStackTrace();
1048
					}
1049
				}
1050
				emailSubjectTxt = "Snapdeal Inventory Updated for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis())+PANEL_TEXT_MAIL;
1051
				if(inventoryChangeItems.length() > 0){
1052
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
1053
					try {
1054
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
10374 vikram.rag 1055
					} catch (Exception e) {
10367 vikram.rag 1056
						e.printStackTrace();
1057
					}
1058
				}
1059
			}
1060
			else{
1061
				emailSubjectTxt = "Snapdeal Inventory Could not be updated "+PANEL_TEXT_MAIL+" " +sdf.format(System.currentTimeMillis());
10371 vikram.rag 1062
				try {
1063
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password,"Please contact Engg ");
10374 vikram.rag 1064
				} catch (Exception e) {
10371 vikram.rag 1065
					e.printStackTrace();
1066
				}
10367 vikram.rag 1067
			}
1068
			tableHeader = "<tr>" 
1069
				+ "<td>" + "Product Name" +"</td>"
1070
				+"<td>" + "Item ID" + "</td>"
1071
				+"<td>" + "Available - Reserve" + "</td>"
1072
				+"<td>" + "Total Held" + "</td>"
1073
				+"</tr>";
1074
 
1075
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
1076
			if(heldMoreThanAvailable.length() > 0){
1077
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1078
				try {
1079
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1080
					//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 1081
				} catch (Exception e) {
10367 vikram.rag 1082
					e.printStackTrace();
1083
				}
1084
			}
10499 vikram.rag 1085
			try {
1086
				System.out.println("++++++++++++++++++++++++++++++");
1087
				System.out.println("Thread Sleeping for 30 minutes");
1088
				System.out.println("++++++++++++++++++++++++++++++");
1089
				Thread.sleep(30*60*1000);
1090
			} catch (InterruptedException e) {
1091
				e.printStackTrace();
1092
			}
10367 vikram.rag 1093
		}
1094
		else{
1095
			try {
1096
				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 1097
			} catch (Exception e) {
10367 vikram.rag 1098
				e.printStackTrace();
1099
			}
10371 vikram.rag 1100
			try {
10398 vikram.rag 1101
				System.out.println("++++++++++++++++++++++++++++++");
1102
				System.out.println("Thread Sleeping for 30 minutes");
1103
				System.out.println("++++++++++++++++++++++++++++++");
10371 vikram.rag 1104
				Thread.sleep(30*60*1000);
1105
			} catch (InterruptedException e) {
1106
				e.printStackTrace();
1107
			}
10367 vikram.rag 1108
		}
1109
		String tableHeader = "<tr>" 
1110
			+ "<td>" + "Product Name" +"</td>"
1111
			+"<td>" + "SKU at Snapdeal" + "</td>"
1112
			+"<td>" + "SUPC" + "</td>"
1113
			+"</tr>";
1114
		String text;
1115
 
1116
		if(notMappedItems.length() >0){
1117
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
10371 vikram.rag 1118
			try {
1119
				mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
10374 vikram.rag 1120
			} catch (Exception e) {
10371 vikram.rag 1121
				e.printStackTrace();
1122
			}
10367 vikram.rag 1123
		}
1124
 
1125
	}
1126
 
10394 vikram.rag 1127
	public static void main(String[] args){
1128
		while(true){
1129
			sendsnapdealinventory();
1130
		}
10367 vikram.rag 1131
 
10394 vikram.rag 1132
	}
1133
 
10367 vikram.rag 1134
}