Subversion Repositories SmartDukaan

Rev

Rev 11962 | Rev 12795 | 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();
10502 vikram.rag 85
		//sendTo = new String[]{"vikram.raghav@shop2020.in"};
11431 vikram.rag 86
		sendTo = new String[]{ "anikendra.das@shop2020.in","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"};
10502 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){
12794 kshitij.so 207
							    System.out.println("Item is "+thriftItem.getId());
208
							    System.out.println("Warehouse is "+warehouse.getId());
10367 vikram.rag 209
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
210
 
211
								}
212
								else{
213
									continue;
214
								}
215
							}
216
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
217
							ignoredItem.setItemId(thriftItem.getId());
218
							ignoredItem.setWarehouseId(warehouse.getId());
219
							if (itemavailability.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(ignoredItem)){
220
								try{
221
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
222
								}
223
								catch(TTransportException e){
224
									inventoryClient = inventoryServiceClient.getClient(); 
225
									nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
226
								}
227
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
228
 
229
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
230
								if(nlc !=0 && (maxnlc >= nlc)){
231
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
232
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
233
									available = available + itemavailability.get(warehouse.getId());
234
									total_held = total_held + total_warehouse_held; 
235
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
236
								}
237
								else if(maxnlc==0){
238
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 0);
239
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), warehouse.getId(), 7);
240
									available = available + itemavailability.get(warehouse.getId());
241
									total_held = total_held + total_warehouse_held;
242
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
243
								}
244
							}
245
						}
246
					}
247
					else{
248
						for (Map.Entry<Long,Long> entry :  itemavailability.entrySet()) {
249
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
250
								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){
251
 
252
								}
253
								else{
254
									continue;
255
								}
256
							}
257
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
258
							ignoredItem.setItemId(thriftItem.getId());
259
							ignoredItem.setWarehouseId(entry.getKey());
260
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
261
 
262
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
263
								try{
264
									maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
265
								}
266
								catch(TTransportException e){
267
									catalogClient = catalogServiceClient.getClient();  
268
									maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
269
								}
270
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
271
								if(nlc !=0 && (maxnlc >= nlc)){
272
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
273
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
274
									available =  available + entry.getValue();
275
									total_held = total_held + total_warehouse_held;
276
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
277
								}
278
								else if(maxnlc==0){
279
									total_warehouse_held = inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 0);
280
									heldForSource = heldForSource + total_warehouse_held - inventoryClient.getHoldInventoryDetailForItemForWarehouseIdExceptSource(thriftItem.getId(), entry.getKey(), 7);
281
									available = available + itemavailability.get(entry.getKey());
282
									total_held = total_held + total_warehouse_held;
283
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\tavailable:" + available);
284
								}
285
 
286
							}
287
						}
288
					}
289
					Map<Long,Long> itemreserve = new HashMap<Long,Long>();
290
					itemreserve = iteminventory.getReserved();
291
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
292
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating Reserve)"+thriftItem.getPreferredVendor());
293
						for (Warehouse warehouse:vendor_warehouses){
294
							if(warehouse.getBillingWarehouseId()!=7){
295
								if(warehouse.getLogisticsLocation().equals(WarehouseLocation.Delhi) && warehouse.getWarehouseType().equals(WarehouseType.THIRD_PARTY) && warehouse.getVendor().getId()!=1){
296
 
297
								}
298
								else{
299
									continue;
300
								}
301
							}
302
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
303
							ignoredItem.setItemId(thriftItem.getId());
304
							ignoredItem.setWarehouseId(warehouse.getId());
305
							if (itemreserve.get(warehouse.getId())!=null && !thirdpartywarehouseids.contains(warehouse.getId()) && !ignoreItems.contains(warehouse.getId())){
306
								nlc = inventoryClient.getNlcForWarehouse(warehouse.getId(),thriftItem.getId());
307
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
308
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + warehouse.getId() );
309
								if(nlc !=0 && (maxnlc >= nlc)){
310
									reserve = reserve + itemreserve.get(warehouse.getId());
311
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
312
								}
313
								else if(maxnlc==0){
314
									reserve = reserve + itemreserve.get(warehouse.getId());
315
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
316
								}
317
 
318
							}
319
						}
320
					}else{
321
						for (Map.Entry<Long,Long> entry : itemreserve.entrySet()) {
322
							if(allWarehousesMap.get(entry.getKey()).getBillingWarehouseId()!=7){
323
								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){
324
 
325
								}
326
								else{
327
									continue;
328
								}
329
							}
330
							in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems ignoredItem = new in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems();
331
							ignoredItem.setItemId(thriftItem.getId());
332
							ignoredItem.setWarehouseId(entry.getKey());
333
							if(!thirdpartywarehouseids.contains(entry.getKey()) && !ignoreItems.contains(ignoredItem)){
334
								nlc = inventoryClient.getNlcForWarehouse(entry.getKey(),thriftItem.getId());
335
								maxnlc = catalogClient.getSnapdealItem(thriftItem.getId()).getMaxNlc();
336
								//System.out.println("itemId:" + thriftItem.getId() + "\tmaxnlc: " + maxnlc + "\tnlc:" + nlc + "\twid:" + entry.getKey() );
337
								if(nlc !=0 && (maxnlc >= nlc)){
338
									reserve =  reserve + entry.getValue();
339
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
340
								}
341
								else if(maxnlc==0){
342
									reserve =  reserve + entry.getValue();
343
									//System.out.println("itemId:" + thriftItem.getId() + "\ttotal_held: " + total_held + "\theldForSource:" + heldForSource + "\treserve:" + reserve);
344
								}
345
 
346
							}
347
 
348
							else{
349
								//System.out.println("skipping inventory for warehouse id " + entry.getKey());
350
							}
351
						}
352
					}
353
					item= new SnapdealItemForInventory(thriftItem.getId(),available,reserve,heldForSource,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),total_held,thriftItem.isRisky(),thriftItem.getItemStatus());
354
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
355
				}
356
				else{
357
					item = new SnapdealItemForInventory(thriftItem.getId(),0,0,0,thriftItem.getHoldInventory(),thriftItem.getDefaultInventory(),0,thriftItem.isRisky(),thriftItem.getItemStatus());
358
					//System.out.println("itemId:" + thriftItem.getId() + "\tavailable: " + available + "\treserve" + reserve + "\theldForSource:" + heldForSource + "\twebsite_hold:" + thriftItem.getHoldInventory() + "\tdefault_inv:" +thriftItem.getDefaultInventory());
359
				}
360
 
361
				//System.out.println(" Item details are " + thriftItem.getId() +" " + available + " " + reserve + " " + thriftItem.getHoldInventory() + " "+ thriftItem.getDefaultInventory() + " " + thriftItem.isRisky());
362
				//System.out.println("+++++++++++++++++++++++");
363
				allItemsInventoryMap.put(thriftItem.getId(),item);
364
 
365
			}
366
 
367
		} catch (TException e) {
368
 
369
			e.printStackTrace();
370
		}
371
 
372
	}
373
	private static void fetchinventoryhistoryfromsnapdeal() throws UnsupportedEncodingException, TException{
374
		int i = 1;
375
		Gson gson = new Gson();
376
		inventoryhistoryItemMap = new HashMap<String,InventoryHistory>();
377
		boolean exitfetchinghistory = true;
378
		System.out.println("Fetching history inventory");
379
		HttpGet get;
380
		HttpResponse response = null;
381
		BufferedReader rd = null;
382
		while(exitfetchinghistory){
383
			System.out.println("Fetching inventory history page " +i);
384
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=dsc");
385
 
386
			try {
387
				response = client.execute(get);
388
			} catch (ClientProtocolException e) {
389
 
390
				e.printStackTrace();
391
			} catch (IOException e) {
392
 
393
				e.printStackTrace();
394
			}
395
 
396
			try {
397
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
398
 
399
			} catch (IllegalStateException e) {
400
 
401
				e.printStackTrace();
402
			} catch (IOException e) {
403
 
404
				e.printStackTrace();
405
			}
406
			InventoryHistoryItems inventoryhistoryitems = (InventoryHistoryItems) gson.fromJson(rd, InventoryHistoryItems.class);
407
			if(inventoryhistoryitems.getRows().size()!=0){
408
				//System.out.println("Parsing page " + i);
409
				for(InventoryHistory inventoryhistory : inventoryhistoryitems.getRows()){
410
					//System.out.println("Inventory History " + inventoryhistory.getSellerSku() +" "+ inventoryhistory.getSupc());
411
					if(inventoryhistory.getUpdateTime() > lastUpdatedInventoryTime){
412
						if(inventoryhistoryItemMap.containsKey(inventoryhistory.getSellerSku())){
413
							if(inventoryhistoryItemMap.get(inventoryhistory.getSellerSku()).getUpdateTime() < inventoryhistory.getUpdateTime()){  
414
								inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
415
							}
416
						}
417
						else{
418
							inventoryhistoryItemMap.put(inventoryhistory.getSellerSku(),inventoryhistory);
419
						}
420
					}
421
					else{
422
						exitfetchinghistory = false;
423
					}
424
				}
425
			}
426
			else{
427
				exitfetchinghistory = false;
428
			}
429
			i++;	
430
		}
10376 vikram.rag 431
		InventoryClient inventoryServiceClient = new InventoryClient("inventory_service_server_host","inventory_service_server_port");
10367 vikram.rag 432
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
433
		List<SnapdealInventoryItem> snapdealInventoryItemHistoryList = inventoryClient.getSnapdealInventorySnapshot();
434
		if(snapdealInventoryItemHistoryList.size()>0){
435
			for(SnapdealInventoryItem snapdealInventoryItem:snapdealInventoryItemHistoryList){
436
				if(itemSnapdealMap.containsKey(snapdealInventoryItem.getItem_id())){
437
					PendingOrderInventoryHistory pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
438
					pendingOrdersInventoryHistory.setPendingOrders(snapdealInventoryItem.getPendingOrders());
439
					pendingOrdersInventoryHistory.setInventoryHistory(snapdealInventoryItem.getAvailability());
440
					pendingOrdersInventoryHistory.setLastUpdatedTimestamp(snapdealInventoryItem.getLastUpdatedOnSnapdeal());
441
					PendingOrdersInventoryHistoryMap.put(itemSnapdealMap.get(snapdealInventoryItem.getItem_id()).getSkuAtSnapdeal(), pendingOrdersInventoryHistory);
442
				}
443
			}
444
		}
10498 vikram.rag 445
		//PendingOrderInventoryHistory  pendingOrdersInventoryHistory;
446
		/*for(Entry<String, InventoryHistory> inventoryHistoryItem :inventoryhistoryItemMap.entrySet()){
10367 vikram.rag 447
			if(PendingOrdersInventoryHistoryMap.containsKey(inventoryHistoryItem.getValue().getSellerSku())){
448
				pendingOrdersInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventoryHistoryItem.getValue().getSellerSku());
449
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
450
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
451
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
452
			}
453
			else{
454
				pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
455
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
456
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
457
				pendingOrdersInventoryHistory.setPendingOrders(0);
458
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
459
			}
10498 vikram.rag 460
		}*/
10367 vikram.rag 461
	}
462
 
463
	private static void fetchcurrentinventoryfromsnapdeal() throws UnsupportedEncodingException, TException{
464
		int i = 1;
465
		int items=0;
466
		Gson gson = new Gson();
467
		in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
468
		currentInventoryItemList = new ArrayList<Inventory>();
469
		HttpGet get;
470
		HttpResponse response = null;
471
		BufferedReader rd= null;
472
		System.out.println("Fetching current inventory ");
10422 vikram.rag 473
		notMappedItems = new StringBuffer();
10367 vikram.rag 474
		while(true){
475
			//System.out.println("Fetching current inventory page " +i);
476
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=normal&_search=false&nd="+time+"&rows="+30+"&page="+i+"&sidx=&sord=asc");
477
			try {
478
				response = client.execute(get);
479
			} catch (ClientProtocolException e) {
480
 
481
				e.printStackTrace();
482
			} catch (IOException e) {
483
 
484
				e.printStackTrace();
485
			}
486
			try {
487
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
488
			} catch (IllegalStateException e) {
489
 
490
				e.printStackTrace();
491
			} catch (IOException e) {
492
 
493
				e.printStackTrace();
494
			}
495
			InventoryItems inventoryitems = (InventoryItems) gson.fromJson(rd, InventoryItems.class);
496
			if(inventoryitems.getRows().size()!=0){
497
				for(Inventory inventory : inventoryitems.getRows()){
498
					if(snapdealItemMap.containsKey(inventory.getSellerSku())){
499
						currentInventoryItemList.add(inventory);
500
					}
501
 
502
					else{
503
						notMappedItems.append("<tr>" 
504
								+ "<td>" + inventory.getProductName() +"</td>"
505
								+"<td>" + inventory.getSellerSku() + "</td>"
506
								+"<td>" + inventory.getSupc() + "</td>"
507
								+"</tr>");
508
					}
509
					items++;
510
				}
511
			}
512
			else{
513
				System.out.println("Fetched  " + items);
514
				break;
515
			}
516
			i++;
517
		}
10988 vikram.rag 518
		if(currentInventoryItemList.size()==0){
519
			try {
11962 vikram.rag 520
				mailer.sendSSLMessage(sendTo,"Snapdeal : Unable to fetch current inventory "+ sdf.format(System.currentTimeMillis()),"Error : Unable to fetch current inventory ", emailFromAddress, password, new ArrayList<File>());
10988 vikram.rag 521
			} catch (MessagingException e) {
522
				e.printStackTrace();
523
			}
524
			System.exit(0);
525
		}
10367 vikram.rag 526
		in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
527
		SnapdealItemDetails snapdealitem = null;
528
		long sku = 0;
529
		long created_orders;
530
		long pending_orders;
531
		Map<Long, Long> itemIdCreatedOrdersMap = null;
532
		try {
533
			transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
534
			System.out.println("Last Updated on Time is  " + lastUpdatedInventoryTime);
535
			if(lastUpdatedInventoryTime > 0){
536
				itemIdCreatedOrdersMap = transactionClient.getOrdersCreatedAfterTimestampForSource(lastUpdatedInventoryTime, 7);
537
				System.out.println("Item id orders created map size "+ itemIdCreatedOrdersMap.entrySet().size());
538
			}
539
		} catch (TTransportException e1) {
540
 
541
			e1.printStackTrace();
542
		}
543
		try {
544
			catalogServiceClient = new CatalogClient().getClient();
545
		} catch (TTransportException e1) {
546
 
547
			e1.printStackTrace();
548
		}
549
		for(Inventory inventory:currentInventoryItemList){
550
			created_orders = 0;
551
			pending_orders = 0;
552
			snapdealitem = snapdealItemMap.get(inventory.getSellerSku());
553
			if(snapdealitem==null){
554
				System.out.println("Not Mapped  " + inventory.getSellerSku());
555
				continue;
556
			}
557
			sku = snapdealitem.getItem_id();
558
			if(sku!=0){
559
				if(itemIdCreatedOrdersMap!=null && itemIdCreatedOrdersMap.containsKey(sku)){
560
					created_orders = itemIdCreatedOrdersMap.get(sku);
561
				}
562
				System.out.println("Created orders for " + sku +" " + created_orders);
563
			}
564
			else{
565
				continue;
566
			}
567
			if(PendingOrdersInventoryHistoryMap.containsKey(inventory.getSellerSku())){
568
				System.out.println("Calculating Pending Orders for " + inventory.getSellerSku());
569
				System.out.println("Current Inventory "+inventory.getAvailableInventory());
570
				System.out.println("History Inventory "+PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory());
571
				System.out.println("Created Orders "+created_orders);
572
				System.out.println("Old Pending Orders "+ PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders());
10498 vikram.rag 573
				//if(PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getLastUpdatedTimestamp() > lastUpdatedInventoryTime){
10367 vikram.rag 574
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() + PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory() - inventory.getAvailableInventory() - created_orders;
10498 vikram.rag 575
				//}
576
				/*else{
10367 vikram.rag 577
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() - created_orders;
10498 vikram.rag 578
				}*/
10367 vikram.rag 579
				System.out.println("New Pending Orders "+pending_orders);
580
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
581
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
582
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
583
			}
584
			else{
585
				System.out.print("Could not calculate pending orders " + inventory.getSellerSku() +"\n");
586
				PendingOrderInventoryHistory pendingOrderInventoryHistory = new PendingOrderInventoryHistory();
587
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
588
				pendingOrderInventoryHistory.setInventoryHistory(inventory.getAvailableInventory());
589
				pendingOrderInventoryHistory.setLastUpdatedTimestamp(System.currentTimeMillis());
590
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
591
			}
592
			itemIdpendingOrdersMap.put(sku, pending_orders);
593
 
594
		}
595
	}
596
 
597
	public static void handleLogin() throws ClientProtocolException, IOException{
598
		HttpGet get = new HttpGet("http://selleraccounts.snapdeal.com/keymaker/login");
599
		HttpResponse response = null;
600
		try {
601
			response = client.execute(get);
602
		} catch (ClientProtocolException e) {
603
 
604
			e.printStackTrace();
605
		} catch (IOException e) {
606
 
607
			e.printStackTrace();
608
		}
609
		BufferedReader rd = null;
610
		try {
611
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
612
		} catch (IllegalStateException e1) {
613
 
614
			e1.printStackTrace();
615
		} catch (IOException e1) {
616
 
617
			e1.printStackTrace();
618
		}
619
		String line = "";
620
		StringBuffer sb = new StringBuffer();
621
		try {
622
			while ((line = rd.readLine()) != null) {
623
				sb.append(line);
624
				//System.out.println(line);
625
			}
626
		} catch (IOException e) {
627
 
628
			e.printStackTrace();
629
		}
630
		int i= sb.toString().indexOf("name=\"lt\" value=");
631
		char[] charArray = sb.toString().toCharArray();
632
		String lt = "";
633
		int j=0;
634
		for(j=i+16;j<=charArray.length;j++){
635
 
636
			if(charArray[j]==' '){
637
				break;
638
			}
639
		}
640
		lt = sb.substring(i+17,j-1);
641
		System.out.println("LT VALUE " + lt);
642
		i= sb.toString().indexOf("name=\"execution\" value=");
643
		charArray = sb.toString().toCharArray();
644
		String ex = "";
645
		j=0;
646
		for(j=i+24;j<=charArray.length;j++){
647
			if(charArray[j]==' '){
648
				break;
649
			}
650
		}
651
		ex = sb.substring(i+24,j-1);
652
		System.out.println("EXECUTION VALUE " + ex);
653
		HttpPost post = new HttpPost("http://selleraccounts.snapdeal.com/login?service=http%3A%2F%2Fseller.snapdeal.com%2Fj_spring_cas_security_check");
654
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
655
		//nameValuePairs.add(new BasicNameValuePair("username",
656
		//"khushal.bhatia@saholic.com"));
657
		nameValuePairs.add(new BasicNameValuePair("username",
658
		"saholic-snapdeal@saholic.com"));
659
		//nameValuePairs.add(new BasicNameValuePair("password",
660
		//"sonline"));
661
		nameValuePairs.add(new BasicNameValuePair("password",
11266 vikram.rag 662
		"snapsaholic"));
10367 vikram.rag 663
		nameValuePairs.add(new BasicNameValuePair("_eventId","submit"));
664
		nameValuePairs.add(new BasicNameValuePair("execution",ex));
665
		nameValuePairs.add(new BasicNameValuePair("lt",lt));
11961 vikram.rag 666
		//nameValuePairs.add(new BasicNameValuePair("submit","LOGIN"));
10367 vikram.rag 667
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
668
		response = client.execute(post);
669
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
670
		line = "";
671
		while ((line = rd.readLine()) != null) {
672
			System.out.println(line);
673
		}
674
		get = new HttpGet("http://seller.snapdeal.com/inventory/");
675
		response = client.execute(get);
676
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
677
		while ((line = rd.readLine()) != null) {
678
			//System.out.println(line);
679
		}
680
	}
681
 
682
 
683
 
684
 
685
	@SuppressWarnings("deprecation")
10371 vikram.rag 686
	public static void sendsnapdealinventory (){
10367 vikram.rag 687
		initilaize();
688
		try {
689
			handleLogin();
690
		} catch (ClientProtocolException e2) {
691
			System.out.println("Handle login failed");
692
			e2.printStackTrace();
693
		} catch (IOException e2) {
694
			System.out.println("Handle login failed");
695
			e2.printStackTrace();
696
		}
697
		try {
698
			fetchinventoryhistoryfromsnapdeal();
699
		} catch (UnsupportedEncodingException e2) {
700
			System.out.println("History Inventory Fetch failed");
701
			e2.printStackTrace();
10371 vikram.rag 702
		} catch (TException e) {
703
			e.printStackTrace();
10367 vikram.rag 704
		}
705
		try {
706
			fetchcurrentinventoryfromsnapdeal();
707
		} catch (UnsupportedEncodingException e2) {
708
			System.out.println("Current Inventory Fetch failed");
709
			e2.printStackTrace();
10371 vikram.rag 710
		} catch (TException e) {
711
			e.printStackTrace();
10367 vikram.rag 712
		}
713
		calculateinventory();
714
		FileInputStream fis = null;
715
		Workbook hwb = null;
716
		Sheet sheet = null;
717
		if(!PANEL){
718
			try {
719
				fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
720
			} catch (FileNotFoundException e) {
721
				System.out.println("Template File not found");
722
				e.printStackTrace();
723
			}
724
			try {
725
				hwb = new HSSFWorkbook(fis);
726
			} catch (IOException e) {
727
				System.out.println("Could not created workbook I/O Problem");
728
				e.printStackTrace();
729
			}
730
			sheet = hwb.getSheetAt(0);
731
		}
732
		Row row = null;
733
		int iterator=1;
734
		long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
735
		SnapdealItemForInventory  inventoryItem;
736
		StringBuffer outOfStockItems =new StringBuffer();
737
		StringBuffer backInStockItems =new StringBuffer();
738
		StringBuffer inventoryChangeItems =new StringBuffer();
739
		StringBuffer heldMoreThanAvailable =new StringBuffer();
740
		long sku = 0;
741
		SnapdealItemDetails snapdealitem;
742
		long lastSentInventoryTime = System.currentTimeMillis();
10394 vikram.rag 743
		List<SnapdealInventoryItem> snapdealInventoryItemList = new ArrayList<SnapdealInventoryItem>();; 
10367 vikram.rag 744
		for(Inventory inventory:currentInventoryItemList){
745
			//System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
746
			if(snapdealItemMap.containsKey(inventory.getSellerSku())){
747
				snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
748
				sku =  snapdealitem.getItem_id();
749
			}
750
			else{
751
				continue;
752
			}
753
			if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
754
				inventoryItem = allItemsInventoryMap.get(sku);
755
				if(inventoryItem==null){
756
					continue;
757
				}
758
				available = inventoryItem.getAvailability(); 
759
				reserve = inventoryItem.getReserve();
760
				defaultinventory = inventoryItem.getDefaultInventory();
761
				holdinventory = inventoryItem.getHoldInventory();
762
				totalheld = inventoryItem.getTotalHeldInventory();
763
				heldforsource = inventoryItem.getHeldForSource();
764
				if(itemIdpendingOrdersMap.containsKey(sku)){
765
					heldorders = itemIdpendingOrdersMap.get(sku);
766
					if(heldorders < 0){
767
						heldorders = 0;
768
					}
769
				}
770
				System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
771
						"\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
772
						"\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
773
						+ defaultinventory + "\theldorders " + heldorders);
774
				if(!PANEL){
775
					row =   sheet.getRow((short) iterator);
776
				}
777
				if(!inventoryItem.getStatus().equals(status.PAUSED)){
10450 vikram.rag 778
					System.out.println("Not Paused");
10367 vikram.rag 779
					if(inventoryItem.getRisky()){
780
						if((available - reserve) < totalheld && totalheld!=0){
781
							sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
782
							heldMoreThanAvailable.append("<tr>" 
783
									+ "<td>" + inventory.getProductName() +"</td>"
784
									+"<td>" + sku + "</td>"
785
									+"<td>" + (available - reserve) +  "</td>"
786
									+"<td>" + totalheld + "</td>"
787
									+"</tr>");
788
						}
789
						else{
790
							allocable = available - reserve - totalheld - holdinventory;
791
							if(allocable < 0){
792
								allocable = 0;
793
							}
794
							sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
795
						}
796
						if(sent_inventory < 0){
797
							sent_inventory = 0;
798
						}
799
					}
800
					else{
801
						allocable = available - reserve - totalheld;
802
						if(allocable < 0){
803
							allocable = 0;
804
						}
805
						if((allocable + heldforsource ) > defaultinventory){
806
							sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
807
							//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));
808
							if(sent_inventory < 0){
809
								sent_inventory = 0;							
810
							}
811
						}
812
						else{
813
							if(defaultinventory > heldorders){
814
								sent_inventory = defaultinventory - heldorders;
815
							}
816
							else{
817
								sent_inventory = 0;
818
							}
819
						}
820
					}
821
				}
822
				else{
823
					sent_inventory = 0;
824
				}
825
				SnapdealInventoryItem snapdealInventoryItem;
10498 vikram.rag 826
				snapdealInventoryItem = new SnapdealInventoryItem();
827
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
828
				if(snapdealItemMap.containsKey(inventory.getSellerSku())){
829
					System.out.println("Found in snapdeal items map)");
830
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
831
					System.out.println("Updating snapdeal inventory snapshot Item ID :"+snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
832
					System.out.println("++++++++++++++++++++++++++++++++++++++++");
833
					snapdealInventoryItem.setItem_id(snapdealItemMap.get(inventory.getSellerSku()).getItem_id());
834
					snapdealInventoryItem.setPendingOrders(pendingOrderInventoryHistory.getPendingOrders());
835
					snapdealInventoryItem.setAvailability(sent_inventory);
836
					snapdealInventoryItem.setLastUpdatedOnSnapdeal(lastSentInventoryTime);
837
					if(sent_inventory > 0){
838
						snapdealInventoryItem.setIs_oos(false);
839
					}
840
					else{
841
						snapdealInventoryItem.setIs_oos(true);
842
					}
843
					snapdealInventoryItemList.add(snapdealInventoryItem);
844
				}
10450 vikram.rag 845
				System.out.println("Before incremental check");
846
				System.out.println("Before incremental available "+inventory.getAvailableInventory());
847
				System.out.println("To send "+sent_inventory);
10396 vikram.rag 848
				if(inventory.getAvailableInventory()!= sent_inventory){
10450 vikram.rag 849
					System.out.println("Incremental check success");
10367 vikram.rag 850
					if(!PANEL){
851
						row.getCell((short) 0).setCellValue(inventory.getSupc());
852
						row.getCell((short) 1).setCellValue(inventory.getSellerSku());
853
						row.getCell((short) 2).setCellValue(inventory.getProductName());
854
						row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
855
						row.getCell((short) 4).setCellValue(sent_inventory);
856
						if(inventory.isLive()){
857
							row.getCell((short) 5).setCellValue("Yes");
858
						}
859
						else{
860
							row.getCell((short) 5).setCellValue("No");
861
						}
862
					}
863
					else{
10450 vikram.rag 864
						System.out.println("Incremental check success");
10367 vikram.rag 865
						UpdateSDIUsingPanel UDSI = new UpdateSDIUsingPanel();
866
						try {
867
							UDSI.handleLogin();
868
							UDSI.updateInventory(sent_inventory,inventory.getSupc());
869
						} catch (ClientProtocolException e) {
870
							System.out.println("Could not login and update inventory");
871
							e.printStackTrace();
872
							continue;
873
						} catch (IOException e) {
874
							System.out.println("Could not login and update inventory I/O");
875
							e.printStackTrace();
876
							continue;
877
						}
878
					}
879
					if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
880
						outOfStockItems.append("<tr>" 
881
								+ "<td>" + inventory.getProductName() +"</td>"
882
								+"<td>" + sku + "</td>"
883
								+"<td>" + inventory.getAvailableInventory() + "</td>"
884
								+"<td>" + sent_inventory + "</td>"
885
								+"</tr>");
886
					}
887
					else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
888
						backInStockItems.append("<tr>" 
889
								+ "<td>" + inventory.getProductName() +"</td>"
890
								+"<td>" + sku + "</td>"
891
								+"<td>" + inventory.getAvailableInventory() + "</td>"
892
								+"<td>" + sent_inventory + "</td>"
893
								+"</tr>");
894
					}
895
					else{
896
						inventoryChangeItems.append("<tr>" 
897
								+ "<td>" + inventory.getProductName() +"</td>"
898
								+"<td>" + sku + "</td>"
899
								+"<td>" + inventory.getAvailableInventory() + "</td>"
900
								+"<td>" + sent_inventory + "</td>"
901
								+"</tr>");
902
					}
903
					iterator++;
904
				}
905
			}
906
			else{
907
				continue;
908
			}
909
		}
910
		if(iterator > 1){
911
			FileOutputStream fileOut = null;
912
			if(!PANEL){
913
				try {
914
					fis.close();
915
				} catch (IOException e2) {
916
					e2.printStackTrace();
917
				}
918
				try {
919
					System.out.println("Before writing file ");
920
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
921
				} catch (FileNotFoundException e) {
922
 
923
					e.printStackTrace();
924
				}
925
				try {
926
 
927
					hwb.write(fileOut);
928
				} catch (IOException e) {
929
 
930
					e.printStackTrace();
931
				}
932
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
933
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
934
				MultipartEntity mpEntity = new MultipartEntity();
935
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
936
				mpEntity.addPart("file", cbFile);
937
				post.setEntity(mpEntity);
938
				System.out.println("Before posting file");
939
				HttpResponse response=null;
940
				try {
941
					response = client.execute(post);
942
				} catch (ClientProtocolException e2) {
943
					System.out.println("Error While Posting Inventory File");
944
					e2.printStackTrace();
945
				} catch (IOException e2) {
946
					System.out.println("I/O Error While Posting Inventory File");
947
					e2.printStackTrace();
948
				}
949
				BufferedReader rd = null;
950
				try {
951
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
952
				} catch (IllegalStateException e1) {
953
 
954
					e1.printStackTrace();
955
				} catch (IOException e1) {
956
 
957
					e1.printStackTrace();
958
				}
959
				String line = "";
960
				String feedresponse = null;
961
				try {
962
					while ((line = rd.readLine()) != null) {
963
						System.out.println(line);
964
						feedresponse = line;
965
					}
966
				} catch (IOException e) {
967
 
968
					e.printStackTrace();
969
				}
970
				System.out.println("posting response" + feedresponse);
971
 
972
			}
973
			int retry = 24;
974
			boolean feedsuccess =false;
975
			while(retry>0){
976
				try {
10501 vikram.rag 977
					Thread.sleep(1*60*1000);
10371 vikram.rag 978
				} catch (InterruptedException e) {
979
					e.printStackTrace();
980
				}
981
				try {
10367 vikram.rag 982
					lastUpdatedInventoryTime = lastSentInventoryTime; 
983
					fetchinventoryhistoryfromsnapdeal();
984
				} catch (UnsupportedEncodingException e1) {
985
					System.out.println("Error while fetching inventory update result");
986
					e1.printStackTrace();
10371 vikram.rag 987
				} catch (TException e) {
988
					e.printStackTrace();
10367 vikram.rag 989
				}
990
				if(inventoryhistoryItemMap.entrySet().size()==iterator -1){
991
					feedsuccess = true;
992
					break;
993
				}
994
				retry --;
995
			}
996
			String PANEL_TEXT_MAIL = "";
997
			if(PANEL){
998
				PANEL_TEXT_MAIL = " (Using Panel)";
999
			}
1000
			String emailSubjectTxt;
1001
			String text;
1002
			String tableHeader;
1003
			if(feedsuccess){
10369 vikram.rag 1004
				in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
1005
				try {
1006
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
1007
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
1008
				} catch (Exception e) {
1009
					try {
1010
						transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
1011
						transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
1012
					} catch (Exception ex) {
1013
						ex.printStackTrace();
1014
					}
1015
				}
10394 vikram.rag 1016
				if(snapdealInventoryItemList.size() > 0){
10450 vikram.rag 1017
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = null;
10371 vikram.rag 1018
					try {
10394 vikram.rag 1019
						System.out.println("Before updating to database");
1020
						for(SnapdealInventoryItem item:snapdealInventoryItemList){
1021
							System.out.println("Item ID " + item.getItem_id()); 
1022
							System.out.println("Availability " + item.getAvailability());
1023
							System.out.println("Updated time " + sdf.format(item.getLastUpdatedOnSnapdeal()));
1024
							System.out.println("Pending Orders " + item.getPendingOrders());
1025
						}
1026
						System.out.println("Snapdeal inventory list size" + snapdealInventoryItemList.size());
10450 vikram.rag 1027
						inventoryClient = new InventoryClient().getClient();
10371 vikram.rag 1028
						inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
10394 vikram.rag 1029
					} catch (TException e) {
1030
						e.printStackTrace();
1031
						try {
10450 vikram.rag 1032
							inventoryClient = new InventoryClient().getClient();
1033
						} catch (TTransportException e2) {
1034
							e2.printStackTrace();
1035
						}
1036
						try {
10394 vikram.rag 1037
							inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
1038
						} catch (TException e1) {
1039
							e1.printStackTrace();
1040
						}
10371 vikram.rag 1041
					}
10367 vikram.rag 1042
				}
1043
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1044
				tableHeader = "<tr>" 
1045
					+ "<td>" + "Product Name" +"</td>"
1046
					+"<td>" + "Item ID" + "</td>"
1047
					+"<td>" + "Old Inventory" + "</td>"
1048
					+"<td>" + "New Inventory" + "</td>"
1049
					+"</tr>";
10394 vikram.rag 1050
 
10367 vikram.rag 1051
				if(backInStockItems.length() > 0){
1052
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
1053
					try {
1054
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1055
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1056
					} catch (Exception e) {
10367 vikram.rag 1057
						e.printStackTrace();
1058
					}
1059
				}
1060
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1061
				if(outOfStockItems.length() > 0){
1062
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
1063
					try {
1064
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1065
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1066
					} catch (Exception e) {
10367 vikram.rag 1067
						e.printStackTrace();
1068
					}
1069
				}
1070
				emailSubjectTxt = "Snapdeal Inventory Updated for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis())+PANEL_TEXT_MAIL;
1071
				if(inventoryChangeItems.length() > 0){
1072
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
1073
					try {
1074
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
10374 vikram.rag 1075
					} catch (Exception e) {
10367 vikram.rag 1076
						e.printStackTrace();
1077
					}
1078
				}
1079
			}
1080
			else{
1081
				emailSubjectTxt = "Snapdeal Inventory Could not be updated "+PANEL_TEXT_MAIL+" " +sdf.format(System.currentTimeMillis());
10371 vikram.rag 1082
				try {
1083
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password,"Please contact Engg ");
10374 vikram.rag 1084
				} catch (Exception e) {
10371 vikram.rag 1085
					e.printStackTrace();
1086
				}
10367 vikram.rag 1087
			}
1088
			tableHeader = "<tr>" 
1089
				+ "<td>" + "Product Name" +"</td>"
1090
				+"<td>" + "Item ID" + "</td>"
1091
				+"<td>" + "Available - Reserve" + "</td>"
1092
				+"<td>" + "Total Held" + "</td>"
1093
				+"</tr>";
1094
 
1095
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
1096
			if(heldMoreThanAvailable.length() > 0){
1097
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1098
				try {
1099
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1100
					//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 1101
				} catch (Exception e) {
10367 vikram.rag 1102
					e.printStackTrace();
1103
				}
1104
			}
10499 vikram.rag 1105
			try {
1106
				System.out.println("++++++++++++++++++++++++++++++");
1107
				System.out.println("Thread Sleeping for 30 minutes");
1108
				System.out.println("++++++++++++++++++++++++++++++");
1109
				Thread.sleep(30*60*1000);
1110
			} catch (InterruptedException e) {
1111
				e.printStackTrace();
1112
			}
10367 vikram.rag 1113
 
1114
		}
1115
		else{
1116
			try {
1117
				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 1118
			} catch (Exception e) {
10367 vikram.rag 1119
				e.printStackTrace();
1120
			}
10371 vikram.rag 1121
			try {
10398 vikram.rag 1122
				System.out.println("++++++++++++++++++++++++++++++");
1123
				System.out.println("Thread Sleeping for 30 minutes");
1124
				System.out.println("++++++++++++++++++++++++++++++");
10371 vikram.rag 1125
				Thread.sleep(30*60*1000);
1126
			} catch (InterruptedException e) {
1127
				e.printStackTrace();
1128
			}
10367 vikram.rag 1129
		}
1130
		String tableHeader = "<tr>" 
1131
			+ "<td>" + "Product Name" +"</td>"
1132
			+"<td>" + "SKU at Snapdeal" + "</td>"
1133
			+"<td>" + "SUPC" + "</td>"
1134
			+"</tr>";
1135
		String text;
1136
 
1137
		if(notMappedItems.length() >0){
1138
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
10371 vikram.rag 1139
			try {
1140
				mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
10374 vikram.rag 1141
			} catch (Exception e) {
10371 vikram.rag 1142
				e.printStackTrace();
1143
			}
10367 vikram.rag 1144
		}
1145
 
1146
	}
1147
 
10394 vikram.rag 1148
	public static void main(String[] args){
1149
		while(true){
1150
			sendsnapdealinventory();
1151
		}
10367 vikram.rag 1152
 
10394 vikram.rag 1153
	}
1154
 
10367 vikram.rag 1155
}