Subversion Repositories SmartDukaan

Rev

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

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