Subversion Repositories SmartDukaan

Rev

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

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