Subversion Repositories SmartDukaan

Rev

Rev 10366 | Rev 10974 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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