Subversion Repositories SmartDukaan

Rev

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){
12793 kshitij.so 206
						System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());						
10138 vikram.rag 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){
12792 kshitij.so 210
						    System.out.println("Warehouse is "+warehouse.getId());
10138 vikram.rag 211
							if(warehouse.getBillingWarehouseId()!=7){
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) {
10162 vikram.rag 371
 
10138 vikram.rag 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) {
10162 vikram.rag 392
 
10138 vikram.rag 393
				e.printStackTrace();
394
			} catch (IOException e) {
10162 vikram.rag 395
 
10138 vikram.rag 396
				e.printStackTrace();
397
			}
398
 
399
			try {
400
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
401
 
402
			} catch (IllegalStateException e) {
10162 vikram.rag 403
 
10138 vikram.rag 404
				e.printStackTrace();
405
			} catch (IOException e) {
10162 vikram.rag 406
 
10138 vikram.rag 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()){
10162 vikram.rag 413
					//System.out.println("Inventory History " + inventoryhistory.getSellerSku() +" "+ inventoryhistory.getSupc());
10138 vikram.rag 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
		}
434
		InventoryClient inventoryServiceClient = new InventoryClient();
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
		}
448
		PendingOrderInventoryHistory  pendingOrdersInventoryHistory;
449
		for(Entry<String, InventoryHistory> inventoryHistoryItem :inventoryhistoryItemMap.entrySet()){
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
			}
463
		}
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 ");
476
		while(true){
477
			//System.out.println("Fetching current inventory page " +i);
478
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=normal&_search=false&nd="+time+"&rows="+30+"&page="+i+"&sidx=&sord=asc");
479
			try {
480
				response = client.execute(get);
481
			} catch (ClientProtocolException e) {
10162 vikram.rag 482
 
10138 vikram.rag 483
				e.printStackTrace();
484
			} catch (IOException e) {
10162 vikram.rag 485
 
10138 vikram.rag 486
				e.printStackTrace();
487
			}
488
			try {
489
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
490
			} catch (IllegalStateException e) {
10162 vikram.rag 491
 
10138 vikram.rag 492
				e.printStackTrace();
493
			} catch (IOException e) {
10162 vikram.rag 494
 
10138 vikram.rag 495
				e.printStackTrace();
496
			}
497
			InventoryItems inventoryitems = (InventoryItems) gson.fromJson(rd, InventoryItems.class);
498
			if(inventoryitems.getRows().size()!=0){
499
				for(Inventory inventory : inventoryitems.getRows()){
500
					if(snapdealItemMap.containsKey(inventory.getSellerSku())){
501
						currentInventoryItemList.add(inventory);
502
					}
503
 
504
					else{
505
						notMappedItems.append("<tr>" 
506
								+ "<td>" + inventory.getProductName() +"</td>"
507
								+"<td>" + inventory.getSellerSku() + "</td>"
508
								+"<td>" + inventory.getSupc() + "</td>"
509
								+"</tr>");
510
					}
511
					items++;
512
				}
513
			}
514
			else{
515
				System.out.println("Fetched  " + items);
516
				break;
517
			}
518
			i++;
519
		}
10974 vikram.rag 520
		System.out.println("Current inventory list size  " + currentInventoryItemList.size());
10969 vikram.rag 521
		if(currentInventoryItemList.size()==0){
522
			try {
523
				mailer.sendSSLMessage(sendTo,"Unable to fetch current inventory "+ sdf.format(System.currentTimeMillis()),"Error : Unable to fetch current inventory ", emailFromAddress, password, new ArrayList<File>());
524
			} catch (MessagingException e) {
525
				e.printStackTrace();
526
			}
527
			System.exit(0);
528
		}
10138 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) {
10162 vikram.rag 543
 
10138 vikram.rag 544
			e1.printStackTrace();
545
		}
546
		try {
547
			catalogServiceClient = new CatalogClient().getClient();
548
		} catch (TTransportException e1) {
10162 vikram.rag 549
 
10138 vikram.rag 550
			e1.printStackTrace();
551
		}
552
		List<String> notMappedItems = new ArrayList<String>();
553
 
554
		for(Inventory inventory:currentInventoryItemList){
555
			created_orders = 0;
556
			pending_orders = 0;
557
			snapdealitem = snapdealItemMap.get(inventory.getSellerSku());
558
			if(snapdealitem==null){
559
				notMappedItems.add(inventory.getSellerSku()+" "+inventory.getProductName());
560
				System.out.println("Not Mapped  " + inventory.getSellerSku());
561
				continue;
562
			}
563
			sku = snapdealitem.getItem_id();
564
			if(sku!=0){
565
				if(itemIdCreatedOrdersMap!=null && itemIdCreatedOrdersMap.containsKey(sku)){
566
					created_orders = itemIdCreatedOrdersMap.get(sku);
567
				}
568
				System.out.println("Created orders for " + sku +" " + created_orders);
569
			}
570
			else{
571
				continue;
572
			}
573
			if(PendingOrdersInventoryHistoryMap.containsKey(inventory.getSellerSku())){
574
				System.out.println("Calculating Pending Orders for " + inventory.getSellerSku());
575
				System.out.println("Current Inventory "+inventory.getAvailableInventory());
576
				System.out.println("History Inventory "+PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory());
577
				System.out.println("Created Orders "+created_orders);
578
				System.out.println("Old Pending Orders "+ PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders());
579
				if(PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getLastUpdatedTimestamp() > lastUpdatedInventoryTime){
580
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() + PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getInventoryHistory() - inventory.getAvailableInventory() - created_orders;
581
				}
582
				else{
583
					pending_orders = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku()).getPendingOrders() - created_orders;
584
				}
585
				if(pending_orders < 0){
586
					pending_orders = 0;
587
				}
588
				System.out.println("New Pending Orders "+pending_orders);
589
				PendingOrderInventoryHistory pendingOrderInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventory.getSellerSku());
590
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
591
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
592
			}
593
			else{
594
				System.out.print("Could not calculate pending orders " + inventory.getSellerSku() +"\n");
595
				PendingOrderInventoryHistory pendingOrderInventoryHistory = new PendingOrderInventoryHistory();
596
				pendingOrderInventoryHistory.setPendingOrders(pending_orders);
597
				pendingOrderInventoryHistory.setInventoryHistory(inventory.getAvailableInventory());
598
				pendingOrderInventoryHistory.setLastUpdatedTimestamp(System.currentTimeMillis());
599
				PendingOrdersInventoryHistoryMap.put(inventory.getSellerSku(),pendingOrderInventoryHistory);
600
			}
601
			itemIdpendingOrdersMap.put(sku, pending_orders);
602
 
603
		}
604
		List<SnapdealInventoryItem> snapdealInventoryItemList = new ArrayList<SnapdealInventoryItem>();
605
		SnapdealInventoryItem snapdealInventoryItem;
606
		for(Entry<String, PendingOrderInventoryHistory> pendingOrderInventoryHistory:PendingOrdersInventoryHistoryMap.entrySet()){
607
			snapdealInventoryItem = new SnapdealInventoryItem();
608
			if(snapdealItemMap.containsKey(pendingOrderInventoryHistory.getKey())){
609
				snapdealInventoryItem.setItem_id(snapdealItemMap.get(pendingOrderInventoryHistory.getKey()).getItem_id());
610
				snapdealInventoryItem.setPendingOrders(pendingOrderInventoryHistory.getValue().getPendingOrders());
611
				snapdealInventoryItem.setAvailability(pendingOrderInventoryHistory.getValue().getInventoryHistory());
612
				snapdealInventoryItem.setLastUpdatedOnSnapdeal(pendingOrderInventoryHistory.getValue().getLastUpdatedTimestamp());
613
				snapdealInventoryItemList.add(snapdealInventoryItem);
614
			}
615
		}
616
		InventoryClient inventoryServiceClient = new InventoryClient();
617
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
618
		try {
619
			inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
620
		} catch (TException e) {
10162 vikram.rag 621
 
10138 vikram.rag 622
			e.printStackTrace();
623
			inventoryClient = inventoryServiceClient.getClient();
624
			inventoryClient.addOrUpdateAllSnapdealInventory(snapdealInventoryItemList);
625
		}
626
 
627
	}
628
 
629
	public static void handleLogin() throws ClientProtocolException, IOException{
630
		HttpGet get = new HttpGet("http://selleraccounts.snapdeal.com/keymaker/login");
631
		HttpResponse response = null;
632
		try {
633
			response = client.execute(get);
634
		} catch (ClientProtocolException e) {
10162 vikram.rag 635
 
10138 vikram.rag 636
			e.printStackTrace();
637
		} catch (IOException e) {
10162 vikram.rag 638
 
10138 vikram.rag 639
			e.printStackTrace();
640
		}
641
		BufferedReader rd = null;
642
		try {
643
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
644
		} catch (IllegalStateException e1) {
10162 vikram.rag 645
 
10138 vikram.rag 646
			e1.printStackTrace();
647
		} catch (IOException e1) {
10162 vikram.rag 648
 
10138 vikram.rag 649
			e1.printStackTrace();
650
		}
651
		String line = "";
652
		StringBuffer sb = new StringBuffer();
653
		try {
654
			while ((line = rd.readLine()) != null) {
655
				sb.append(line);
656
				//System.out.println(line);
657
			}
658
		} catch (IOException e) {
10162 vikram.rag 659
 
10138 vikram.rag 660
			e.printStackTrace();
661
		}
662
		int i= sb.toString().indexOf("name=\"lt\" value=");
663
		char[] charArray = sb.toString().toCharArray();
664
		String lt = "";
665
		int j=0;
666
		for(j=i+16;j<=charArray.length;j++){
667
 
668
			if(charArray[j]==' '){
669
				break;
670
			}
671
		}
672
		lt = sb.substring(i+17,j-1);
673
		System.out.println("LT VALUE " + lt);
674
		i= sb.toString().indexOf("name=\"execution\" value=");
675
		charArray = sb.toString().toCharArray();
676
		String ex = "";
677
		j=0;
678
		for(j=i+24;j<=charArray.length;j++){
679
			if(charArray[j]==' '){
680
				break;
681
			}
682
		}
683
		ex = sb.substring(i+24,j-1);
684
		System.out.println("EXECUTION VALUE " + ex);
685
		HttpPost post = new HttpPost("http://selleraccounts.snapdeal.com/login?service=http%3A%2F%2Fseller.snapdeal.com%2Fj_spring_cas_security_check");
686
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
687
		//nameValuePairs.add(new BasicNameValuePair("username",
688
		//"khushal.bhatia@saholic.com"));
689
		nameValuePairs.add(new BasicNameValuePair("username",
690
		"saholic-snapdeal@saholic.com"));
691
		//nameValuePairs.add(new BasicNameValuePair("password",
692
		//"sonline"));
693
		nameValuePairs.add(new BasicNameValuePair("password",
11266 vikram.rag 694
		"snapsaholic"));
10138 vikram.rag 695
		nameValuePairs.add(new BasicNameValuePair("_eventId","submit"));
696
		nameValuePairs.add(new BasicNameValuePair("execution",ex));
697
		nameValuePairs.add(new BasicNameValuePair("lt",lt));
698
		nameValuePairs.add(new BasicNameValuePair("submit","LOGIN"));
699
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));
700
		response = client.execute(post);
701
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
702
		line = "";
703
		while ((line = rd.readLine()) != null) {
704
			System.out.println(line);
705
		}
706
		get = new HttpGet("http://seller.snapdeal.com/inventory/");
707
		response = client.execute(get);
708
		rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
709
		while ((line = rd.readLine()) != null) {
710
			//System.out.println(line);
711
		}
712
	}
713
 
714
 
10162 vikram.rag 715
 
716
 
10138 vikram.rag 717
	@SuppressWarnings("deprecation")
10167 vikram.rag 718
	public static void main(String[] args) throws NumberFormatException, TException,MessagingException, InterruptedException {
10164 vikram.rag 719
		try {
720
			handleLogin();
721
		} catch (ClientProtocolException e2) {
722
			System.out.println("Handle login failed");
723
			e2.printStackTrace();
724
		} catch (IOException e2) {
725
			System.out.println("Handle login failed");
726
			e2.printStackTrace();
727
		}
728
		try {
729
			fetchinventoryhistoryfromsnapdeal();
730
		} catch (UnsupportedEncodingException e2) {
731
			System.out.println("History Inventory Fetch failed");
732
			e2.printStackTrace();
733
		}
734
		try {
735
			fetchcurrentinventoryfromsnapdeal();
736
		} catch (UnsupportedEncodingException e2) {
737
			System.out.println("Current Inventory Fetch failed");
738
			e2.printStackTrace();
739
		}
10138 vikram.rag 740
		calculateinventory();
741
		in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
742
		try {
743
			catalogServiceClient = new CatalogClient().getClient();
744
		} catch (TTransportException e) {
10162 vikram.rag 745
 
10138 vikram.rag 746
			e.printStackTrace();
747
		}
10162 vikram.rag 748
		FileInputStream fis = null;
749
		Workbook hwb = null;
750
		Sheet sheet = null;
751
		if(!PANEL){
10164 vikram.rag 752
			try {
753
				fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
754
			} catch (FileNotFoundException e) {
755
				System.out.println("Template File not found");
756
				e.printStackTrace();
757
			}
758
			try {
759
				hwb = new HSSFWorkbook(fis);
760
			} catch (IOException e) {
761
				System.out.println("Could not created workbook I/O Problem");
762
				e.printStackTrace();
763
			}
10162 vikram.rag 764
			sheet = hwb.getSheetAt(0);
765
		}
766
		Row row = null;
10138 vikram.rag 767
		int iterator=1;
768
		long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
769
		SnapdealItemForInventory  inventoryItem;
770
		StringBuffer outOfStockItems =new StringBuffer();
771
		StringBuffer backInStockItems =new StringBuffer();
772
		StringBuffer inventoryChangeItems =new StringBuffer();
773
		StringBuffer heldMoreThanAvailable =new StringBuffer();
774
		long sku = 0;
775
		SnapdealItemDetails snapdealitem;
10365 vikram.rag 776
		long lastSentInventoryTime = System.currentTimeMillis();
10138 vikram.rag 777
		for(Inventory inventory:currentInventoryItemList){
778
			//System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
779
			if(snapdealItemMap.containsKey(inventory.getSellerSku())){
780
				snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
781
				sku =  snapdealitem.getItem_id();
782
			}
783
			else{
784
				continue;
785
			}
786
			if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
787
				inventoryItem = allItemsInventoryMap.get(sku);
788
				if(inventoryItem==null){
789
					continue;
790
				}
791
				available = inventoryItem.getAvailability(); 
792
				reserve = inventoryItem.getReserve();
793
				defaultinventory = inventoryItem.getDefaultInventory();
794
				holdinventory = inventoryItem.getHoldInventory();
795
				totalheld = inventoryItem.getTotalHeldInventory();
796
				heldforsource = inventoryItem.getHeldForSource();
797
				if(itemIdpendingOrdersMap.containsKey(sku)){
798
					heldorders = itemIdpendingOrdersMap.get(sku);
799
					if(heldorders < 0){
800
						heldorders = 0;
801
					}
802
				}
803
				System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
804
						"\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
805
						"\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
806
						+ defaultinventory + "\theldorders " + heldorders);
10162 vikram.rag 807
				if(!PANEL){
808
					row =   sheet.getRow((short) iterator);
809
				}
10138 vikram.rag 810
				if(!inventoryItem.getStatus().equals(status.PAUSED)){
811
					if(inventoryItem.getRisky()){
812
						if((available - reserve) < totalheld && totalheld!=0){
813
							sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
814
							heldMoreThanAvailable.append("<tr>" 
815
									+ "<td>" + inventory.getProductName() +"</td>"
816
									+"<td>" + sku + "</td>"
817
									+"<td>" + (available - reserve) +  "</td>"
818
									+"<td>" + totalheld + "</td>"
819
									+"</tr>");
820
						}
821
						else{
822
							allocable = available - reserve - totalheld - holdinventory;
823
							if(allocable < 0){
824
								allocable = 0;
825
							}
826
							sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
827
						}
828
						if(sent_inventory < 0){
829
							sent_inventory = 0;
830
						}
831
					}
832
					else{
833
						allocable = available - reserve - totalheld;
834
						if(allocable < 0){
835
							allocable = 0;
836
						}
837
						if((allocable + heldforsource ) > defaultinventory){
838
							sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
839
							//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));
840
							if(sent_inventory < 0){
841
								sent_inventory = 0;							
842
							}
843
						}
844
						else{
845
							if(defaultinventory > heldorders){
846
								sent_inventory = defaultinventory - heldorders;
847
							}
848
							else{
849
								sent_inventory = 0;
850
							}
851
						}
852
					}
853
				}
854
				else{
855
					sent_inventory = 0;
856
				}
857
				if(inventory.getAvailableInventory()!= sent_inventory){
10162 vikram.rag 858
					if(!PANEL){
10138 vikram.rag 859
						row.getCell((short) 0).setCellValue(inventory.getSupc());
860
						row.getCell((short) 1).setCellValue(inventory.getSellerSku());
861
						row.getCell((short) 2).setCellValue(inventory.getProductName());
862
						row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
863
						row.getCell((short) 4).setCellValue(sent_inventory);
864
						if(inventory.isLive()){
865
							row.getCell((short) 5).setCellValue("Yes");
866
						}
867
						else{
868
							row.getCell((short) 5).setCellValue("No");
869
						}
870
					}
10162 vikram.rag 871
					else{
872
						UpdateSDIUsingPanel UDSI = new UpdateSDIUsingPanel();
10164 vikram.rag 873
						try {
10166 vikram.rag 874
							UDSI.handleLogin();
10164 vikram.rag 875
							UDSI.updateInventory(sent_inventory,inventory.getSupc());
876
						} catch (ClientProtocolException e) {
877
							System.out.println("Could not login and update inventory");
878
							e.printStackTrace();
10167 vikram.rag 879
							continue;
10164 vikram.rag 880
						} catch (IOException e) {
881
							System.out.println("Could not login and update inventory I/O");
882
							e.printStackTrace();
10167 vikram.rag 883
							continue;
10164 vikram.rag 884
						}
10162 vikram.rag 885
					}
10164 vikram.rag 886
					if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
887
						outOfStockItems.append("<tr>" 
888
								+ "<td>" + inventory.getProductName() +"</td>"
889
								+"<td>" + sku + "</td>"
890
								+"<td>" + inventory.getAvailableInventory() + "</td>"
891
								+"<td>" + sent_inventory + "</td>"
892
								+"</tr>");
893
					}
894
					else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
895
						backInStockItems.append("<tr>" 
896
								+ "<td>" + inventory.getProductName() +"</td>"
897
								+"<td>" + sku + "</td>"
898
								+"<td>" + inventory.getAvailableInventory() + "</td>"
899
								+"<td>" + sent_inventory + "</td>"
900
								+"</tr>");
901
					}
902
					else{
903
						inventoryChangeItems.append("<tr>" 
904
								+ "<td>" + inventory.getProductName() +"</td>"
905
								+"<td>" + sku + "</td>"
906
								+"<td>" + inventory.getAvailableInventory() + "</td>"
907
								+"<td>" + sent_inventory + "</td>"
908
								+"</tr>");
909
					}
10138 vikram.rag 910
					iterator++;
911
				}
912
			}
913
			else{
914
				continue;
915
			}
916
		}
10151 vikram.rag 917
		if(iterator > 1){
10162 vikram.rag 918
			FileOutputStream fileOut = null;
919
			if(!PANEL){
10138 vikram.rag 920
				try {
10164 vikram.rag 921
					fis.close();
922
				} catch (IOException e2) {
923
					e2.printStackTrace();
924
				}
925
				try {
10138 vikram.rag 926
					System.out.println("Before writing file ");
927
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
928
				} catch (FileNotFoundException e) {
10162 vikram.rag 929
 
10138 vikram.rag 930
					e.printStackTrace();
931
				}
932
				try {
933
 
934
					hwb.write(fileOut);
935
				} catch (IOException e) {
10162 vikram.rag 936
 
10138 vikram.rag 937
					e.printStackTrace();
938
				}
939
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
940
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
941
				MultipartEntity mpEntity = new MultipartEntity();
942
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
943
				mpEntity.addPart("file", cbFile);
944
				post.setEntity(mpEntity);
945
				System.out.println("Before posting file");
10165 vikram.rag 946
				HttpResponse response=null;
10164 vikram.rag 947
				try {
948
					response = client.execute(post);
949
				} catch (ClientProtocolException e2) {
950
					System.out.println("Error While Posting Inventory File");
951
					e2.printStackTrace();
952
				} catch (IOException e2) {
953
					System.out.println("I/O Error While Posting Inventory File");
954
					e2.printStackTrace();
955
				}
10138 vikram.rag 956
				BufferedReader rd = null;
957
				try {
958
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
959
				} catch (IllegalStateException e1) {
10162 vikram.rag 960
 
10138 vikram.rag 961
					e1.printStackTrace();
962
				} catch (IOException e1) {
10162 vikram.rag 963
 
10138 vikram.rag 964
					e1.printStackTrace();
965
				}
966
				String line = "";
967
				String feedresponse = null;
968
				try {
969
					while ((line = rd.readLine()) != null) {
970
						System.out.println(line);
971
						feedresponse = line;
972
					}
973
				} catch (IOException e) {
10162 vikram.rag 974
 
10138 vikram.rag 975
					e.printStackTrace();
976
				}
977
				System.out.println("posting response" + feedresponse);
10162 vikram.rag 978
 
10151 vikram.rag 979
			}
10162 vikram.rag 980
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
10138 vikram.rag 981
			try {
982
				transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
983
				transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
10162 vikram.rag 984
			} catch (Exception e) {
985
				try {
986
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
987
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
988
				} catch (Exception ex) {
989
					ex.printStackTrace();
990
				}
10138 vikram.rag 991
			}
10209 vikram.rag 992
			int retry = 5;
10167 vikram.rag 993
			boolean feedsuccess =false;
994
			while(retry>0){
10366 vikram.rag 995
				Thread.sleep(5*60*1000);
10167 vikram.rag 996
				try {
997
					lastUpdatedInventoryTime = lastSentInventoryTime; 
998
					fetchinventoryhistoryfromsnapdeal();
999
				} catch (UnsupportedEncodingException e1) {
1000
					System.out.println("Error while fetching inventory update result");
1001
					e1.printStackTrace();
1002
				}
1003
				if(inventoryhistoryItemMap.entrySet().size()==iterator -1){
1004
					feedsuccess = true;
1005
					break;
1006
				}
1007
				retry --;
1008
			}
10164 vikram.rag 1009
			String PANEL_TEXT_MAIL = "";
1010
			if(PANEL){
1011
				PANEL_TEXT_MAIL = " (Using Panel)";
1012
			}
10167 vikram.rag 1013
			String emailSubjectTxt;
10162 vikram.rag 1014
			String text;
10167 vikram.rag 1015
			String tableHeader;
1016
			if(feedsuccess){
1017
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1018
				tableHeader = "<tr>" 
1019
					+ "<td>" + "Product Name" +"</td>"
1020
					+"<td>" + "Item ID" + "</td>"
1021
					+"<td>" + "Old Inventory" + "</td>"
1022
					+"<td>" + "New Inventory" + "</td>"
1023
					+"</tr>";
1024
 
1025
				if(backInStockItems.length() > 0){
1026
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
1027
					try {
1028
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1029
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
1030
					} catch (MessagingException e) {
1031
						e.printStackTrace();
1032
					}
10162 vikram.rag 1033
				}
10167 vikram.rag 1034
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime) + PANEL_TEXT_MAIL;
1035
				if(outOfStockItems.length() > 0){
1036
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
1037
					try {
1038
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1039
						//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
1040
					} catch (MessagingException e) {
1041
						e.printStackTrace();
1042
					}
10162 vikram.rag 1043
				}
10167 vikram.rag 1044
				emailSubjectTxt = "Snapdeal Inventory Updated for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis())+PANEL_TEXT_MAIL;
1045
				if(inventoryChangeItems.length() > 0){
1046
					text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
1047
					try {
1048
						mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1049
					} catch (MessagingException e) {
1050
						e.printStackTrace();
1051
					}
10162 vikram.rag 1052
				}
10138 vikram.rag 1053
			}
10167 vikram.rag 1054
			else{
1055
				emailSubjectTxt = "Snapdeal Inventory Could not be updated "+PANEL_TEXT_MAIL+" " +sdf.format(System.currentTimeMillis());
1056
				mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password,"Please contact Engg ");
1057
			}
10162 vikram.rag 1058
			tableHeader = "<tr>" 
1059
				+ "<td>" + "Product Name" +"</td>"
1060
				+"<td>" + "Item ID" + "</td>"
1061
				+"<td>" + "Available - Reserve" + "</td>"
1062
				+"<td>" + "Total Held" + "</td>"
1063
				+"</tr>";
10138 vikram.rag 1064
 
10162 vikram.rag 1065
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
1066
			if(heldMoreThanAvailable.length() > 0){
1067
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1068
				try {
1069
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1070
					//mailer.sendSSLMessage(sendTo,"Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis()),inventoryChangeItems.toString(), emailFromAddress, password, new ArrayList<File>());
1071
				} catch (MessagingException e) {
1072
					e.printStackTrace();
1073
				}
1074
			}
1075
 
1076
		}
1077
		else{
10138 vikram.rag 1078
			try {
10162 vikram.rag 1079
				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 1080
			} catch (MessagingException e) {
1081
				e.printStackTrace();
1082
			}
1083
		}
10162 vikram.rag 1084
		String tableHeader = "<tr>" 
10138 vikram.rag 1085
			+ "<td>" + "Product Name" +"</td>"
1086
			+"<td>" + "SKU at Snapdeal" + "</td>"
1087
			+"<td>" + "SUPC" + "</td>"
1088
			+"</tr>";
10162 vikram.rag 1089
		String text;
1090
 
10138 vikram.rag 1091
		if(notMappedItems.length() >0){
1092
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
1093
			mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
1094
		}
10162 vikram.rag 1095
 
10138 vikram.rag 1096
	}
10162 vikram.rag 1097
 
10149 vikram.rag 1098
}