Subversion Repositories SmartDukaan

Rev

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

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