Subversion Repositories SmartDukaan

Rev

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