Subversion Repositories SmartDukaan

Rev

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