Subversion Repositories SmartDukaan

Rev

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