Subversion Repositories SmartDukaan

Rev

Rev 13890 | Rev 13950 | 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
						try {
13899 manish.sha 869
							HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/update");
870
							List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
871
							System.out.println("Calling update inventory: Supc: "+inventory.getSupc()+ " to be update stock: "+ sent_inventory);
872
							nameValuePairs.add(new BasicNameValuePair("changedField",
873
									"inventory"));
874
							nameValuePairs.add(new BasicNameValuePair("changedValue",
875
									String.valueOf(sent_inventory)));
876
							nameValuePairs.add(new BasicNameValuePair("supc",
877
									inventory.getSupc()));
878
							post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
879
							HttpResponse response = client.execute(post);
880
							BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
881
							String line = "";
882
							while ((line = rd.readLine()) != null) {
883
								System.out.println("Response of Inventory Update: "+line);
884
							}
13890 manish.sha 885
							Thread.sleep(2000);
10367 vikram.rag 886
						} catch (ClientProtocolException e) {
887
							System.out.println("Could not login and update inventory");
888
							e.printStackTrace();
889
							continue;
890
						} catch (IOException e) {
891
							System.out.println("Could not login and update inventory I/O");
892
							e.printStackTrace();
893
							continue;
13885 manish.sha 894
						} catch (InterruptedException e) {
895
							System.out.println("Could not login and update inventory I/O");
896
							e.printStackTrace();
897
							continue;
10367 vikram.rag 898
						}
899
					}
900
					if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
901
						outOfStockItems.append("<tr>" 
902
								+ "<td>" + inventory.getProductName() +"</td>"
903
								+"<td>" + sku + "</td>"
904
								+"<td>" + inventory.getAvailableInventory() + "</td>"
905
								+"<td>" + sent_inventory + "</td>"
906
								+"</tr>");
907
					}
908
					else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
909
						backInStockItems.append("<tr>" 
910
								+ "<td>" + inventory.getProductName() +"</td>"
911
								+"<td>" + sku + "</td>"
912
								+"<td>" + inventory.getAvailableInventory() + "</td>"
913
								+"<td>" + sent_inventory + "</td>"
914
								+"</tr>");
915
					}
916
					else{
917
						inventoryChangeItems.append("<tr>" 
918
								+ "<td>" + inventory.getProductName() +"</td>"
919
								+"<td>" + sku + "</td>"
920
								+"<td>" + inventory.getAvailableInventory() + "</td>"
921
								+"<td>" + sent_inventory + "</td>"
922
								+"</tr>");
923
					}
924
					iterator++;
925
				}
926
			}
927
			else{
928
				continue;
929
			}
930
		}
931
		if(iterator > 1){
932
			FileOutputStream fileOut = null;
933
			if(!PANEL){
934
				try {
935
					fis.close();
936
				} catch (IOException e2) {
937
					e2.printStackTrace();
938
				}
939
				try {
940
					System.out.println("Before writing file ");
941
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
942
				} catch (FileNotFoundException e) {
943
 
944
					e.printStackTrace();
945
				}
946
				try {
947
 
948
					hwb.write(fileOut);
949
				} catch (IOException e) {
950
 
951
					e.printStackTrace();
952
				}
953
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
954
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
955
				MultipartEntity mpEntity = new MultipartEntity();
956
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
957
				mpEntity.addPart("file", cbFile);
958
				post.setEntity(mpEntity);
959
				System.out.println("Before posting file");
960
				HttpResponse response=null;
961
				try {
962
					response = client.execute(post);
963
				} catch (ClientProtocolException e2) {
964
					System.out.println("Error While Posting Inventory File");
965
					e2.printStackTrace();
966
				} catch (IOException e2) {
967
					System.out.println("I/O Error While Posting Inventory File");
968
					e2.printStackTrace();
969
				}
970
				BufferedReader rd = null;
971
				try {
972
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
973
				} catch (IllegalStateException e1) {
974
 
975
					e1.printStackTrace();
976
				} catch (IOException e1) {
977
 
978
					e1.printStackTrace();
979
				}
980
				String line = "";
981
				String feedresponse = null;
982
				try {
983
					while ((line = rd.readLine()) != null) {
984
						System.out.println(line);
985
						feedresponse = line;
986
					}
987
				} catch (IOException e) {
988
 
989
					e.printStackTrace();
990
				}
991
				System.out.println("posting response" + feedresponse);
992
 
993
			}
994
			int retry = 24;
995
			boolean feedsuccess =false;
996
			while(retry>0){
997
				try {
10501 vikram.rag 998
					Thread.sleep(1*60*1000);
10371 vikram.rag 999
				} catch (InterruptedException e) {
1000
					e.printStackTrace();
1001
				}
1002
				try {
10367 vikram.rag 1003
					lastUpdatedInventoryTime = lastSentInventoryTime; 
1004
					fetchinventoryhistoryfromsnapdeal();
1005
				} catch (UnsupportedEncodingException e1) {
1006
					System.out.println("Error while fetching inventory update result");
1007
					e1.printStackTrace();
10371 vikram.rag 1008
				} catch (TException e) {
1009
					e.printStackTrace();
10367 vikram.rag 1010
				}
1011
				if(inventoryhistoryItemMap.entrySet().size()==iterator -1){
1012
					feedsuccess = true;
1013
					break;
1014
				}
1015
				retry --;
1016
			}
1017
			String PANEL_TEXT_MAIL = "";
1018
			if(PANEL){
1019
				PANEL_TEXT_MAIL = " (Using Panel)";
1020
			}
1021
			String emailSubjectTxt;
1022
			String text;
1023
			String tableHeader;
1024
			if(feedsuccess){
10369 vikram.rag 1025
				in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
1026
				try {
1027
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
1028
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
1029
				} catch (Exception e) {
1030
					try {
1031
						transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
1032
						transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
1033
					} catch (Exception ex) {
1034
						ex.printStackTrace();
1035
					}
1036
				}
10394 vikram.rag 1037
				if(snapdealInventoryItemList.size() > 0){
10450 vikram.rag 1038
					in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = null;
10371 vikram.rag 1039
					try {
10394 vikram.rag 1040
						System.out.println("Before updating to database");
1041
						for(SnapdealInventoryItem item:snapdealInventoryItemList){
1042
							System.out.println("Item ID " + item.getItem_id()); 
1043
							System.out.println("Availability " + item.getAvailability());
1044
							System.out.println("Updated time " + sdf.format(item.getLastUpdatedOnSnapdeal()));
1045
							System.out.println("Pending Orders " + item.getPendingOrders());
1046
						}
1047
						System.out.println("Snapdeal inventory list size" + snapdealInventoryItemList.size());
10450 vikram.rag 1048
						inventoryClient = new InventoryClient().getClient();
10371 vikram.rag 1049
						inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
10394 vikram.rag 1050
					} catch (TException e) {
1051
						e.printStackTrace();
1052
						try {
10450 vikram.rag 1053
							inventoryClient = new InventoryClient().getClient();
1054
						} catch (TTransportException e2) {
1055
							e2.printStackTrace();
1056
						}
1057
						try {
10394 vikram.rag 1058
							inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
1059
						} catch (TException e1) {
1060
							e1.printStackTrace();
1061
						}
10371 vikram.rag 1062
					}
10367 vikram.rag 1063
				}
1064
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1065
				tableHeader = "<tr>" 
1066
					+ "<td>" + "Product Name" +"</td>"
1067
					+"<td>" + "Item ID" + "</td>"
1068
					+"<td>" + "Old Inventory" + "</td>"
1069
					+"<td>" + "New Inventory" + "</td>"
1070
					+"</tr>";
10394 vikram.rag 1071
 
10367 vikram.rag 1072
				if(backInStockItems.length() > 0){
1073
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
1074
					try {
1075
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1076
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1077
					} catch (Exception e) {
10367 vikram.rag 1078
						e.printStackTrace();
1079
					}
1080
				}
1081
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1082
				if(outOfStockItems.length() > 0){
1083
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
1084
					try {
1085
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1086
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
10374 vikram.rag 1087
					} catch (Exception e) {
10367 vikram.rag 1088
						e.printStackTrace();
1089
					}
1090
				}
1091
				emailSubjectTxt = "Snapdeal Inventory Updated for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis())+PANEL_TEXT_MAIL;
1092
				if(inventoryChangeItems.length() > 0){
1093
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
1094
					try {
1095
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
10374 vikram.rag 1096
					} catch (Exception e) {
10367 vikram.rag 1097
						e.printStackTrace();
1098
					}
1099
				}
1100
			}
1101
			else{
1102
				emailSubjectTxt = "Snapdeal Inventory Could not be updated "+PANEL_TEXT_MAIL+" " +sdf.format(System.currentTimeMillis());
10371 vikram.rag 1103
				try {
1104
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password,"Please contact Engg ");
10374 vikram.rag 1105
				} catch (Exception e) {
10371 vikram.rag 1106
					e.printStackTrace();
1107
				}
10367 vikram.rag 1108
			}
1109
			tableHeader = "<tr>" 
1110
				+ "<td>" + "Product Name" +"</td>"
1111
				+"<td>" + "Item ID" + "</td>"
1112
				+"<td>" + "Available - Reserve" + "</td>"
1113
				+"<td>" + "Total Held" + "</td>"
1114
				+"</tr>";
1115
 
1116
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
1117
			if(heldMoreThanAvailable.length() > 0){
1118
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1119
				try {
1120
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1121
					//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 1122
				} catch (Exception e) {
10367 vikram.rag 1123
					e.printStackTrace();
1124
				}
1125
			}
10499 vikram.rag 1126
			try {
1127
				System.out.println("++++++++++++++++++++++++++++++");
1128
				System.out.println("Thread Sleeping for 30 minutes");
1129
				System.out.println("++++++++++++++++++++++++++++++");
1130
				Thread.sleep(30*60*1000);
1131
			} catch (InterruptedException e) {
1132
				e.printStackTrace();
1133
			}
10367 vikram.rag 1134
 
1135
		}
1136
		else{
1137
			try {
1138
				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 1139
			} catch (Exception e) {
10367 vikram.rag 1140
				e.printStackTrace();
1141
			}
10371 vikram.rag 1142
			try {
10398 vikram.rag 1143
				System.out.println("++++++++++++++++++++++++++++++");
1144
				System.out.println("Thread Sleeping for 30 minutes");
1145
				System.out.println("++++++++++++++++++++++++++++++");
10371 vikram.rag 1146
				Thread.sleep(30*60*1000);
1147
			} catch (InterruptedException e) {
1148
				e.printStackTrace();
1149
			}
10367 vikram.rag 1150
		}
1151
		String tableHeader = "<tr>" 
1152
			+ "<td>" + "Product Name" +"</td>"
1153
			+"<td>" + "SKU at Snapdeal" + "</td>"
1154
			+"<td>" + "SUPC" + "</td>"
1155
			+"</tr>";
1156
		String text;
1157
 
1158
		if(notMappedItems.length() >0){
1159
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
10371 vikram.rag 1160
			try {
1161
				mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
10374 vikram.rag 1162
			} catch (Exception e) {
10371 vikram.rag 1163
				e.printStackTrace();
1164
			}
10367 vikram.rag 1165
		}
1166
 
1167
	}
1168
 
10394 vikram.rag 1169
	public static void main(String[] args){
1170
		while(true){
1171
			sendsnapdealinventory();
1172
		}
10367 vikram.rag 1173
 
10394 vikram.rag 1174
	}
1175
 
10367 vikram.rag 1176
}