Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
10125 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
 
65
public class UpdateSnapdealInventoryUsingPanel {
66
	private static long time = System.currentTimeMillis();
67
	private static String SNAPDEAL_INVENTORY_SHEET;
68
	private static Map<Long, SnapdealItemForInventory> allItemsInventoryMap = new HashMap<Long, SnapdealItemForInventory>();
69
	private static ArrayList<Inventory> currentInventoryItemList;
70
	static Map<Long,Long> itemIdpendingOrdersMap;
71
	private static Map<String,InventoryHistory> inventoryhistoryItemMap;
72
	private static DefaultHttpClient client = new DefaultHttpClient();
73
	static Map<String,SnapdealItemDetails> snapdealItemMap = new HashMap<String,SnapdealItemDetails>();
74
	static Map<Long,SnapdealItemDetails> itemSnapdealMap = new HashMap<Long,SnapdealItemDetails>();
75
	static Map<String,PendingOrderInventoryHistory> PendingOrdersInventoryHistoryMap = new HashMap<String,PendingOrderInventoryHistory>();
76
	static long lastUpdatedInventoryTime = 0;
77
	static java.text.SimpleDateFormat sdf;
78
	static String emailFromAddress;
79
	static String password;
80
	static GmailUtils mailer;
81
	static String sendTo[];
82
	static StringBuffer notMappedItems =new StringBuffer();
83
	private static boolean UPDATEUSINGPANEL;
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",
92
				"yukti.jain@shop2020.in","manisha.sharma@shop2020.in","chandan.kumar@shop2020.in","ankush.dhingra@shop2020.in","amar.kumar@shop2020.in"};
93
		itemIdpendingOrdersMap = new HashMap<Long,Long>();
94
		CatalogClient catalogServiceClient = null;
95
		try {
96
			catalogServiceClient = new CatalogClient();
97
		} catch (TTransportException e1) {
98
			// TODO Auto-generated catch block
99
			e1.printStackTrace();
100
		}
101
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
102
		List<SnapdealItemDetails> allSnapdealItems = null;
103
		try {
104
			allSnapdealItems = catalogClient.getAllSnapdealItems();
105
		} catch (TException e) {
106
			// TODO Auto-generated catch block
107
			e.printStackTrace();
108
		}
109
		for(SnapdealItemDetails snapdealItem:allSnapdealItems){
110
			snapdealItemMap.put(snapdealItem.getSkuAtSnapdeal(),snapdealItem);
111
			itemSnapdealMap.put(snapdealItem.getItem_id(), snapdealItem);
112
			//System.out.println("Creating Item and Snapdeal Map " + snapdealItem.getItem_id() + " " + snapdealItem.getSkuAtSnapdeal());
113
		}
114
		in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
115
		try {
116
			transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
117
			lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
118
			//System.out.println("Time is " + lastUpdatedInventoryTime);
119
		} catch (Exception e) {
120
			try {
121
				transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
122
				lastUpdatedInventoryTime = transactionClient.getSourceDetail(7).getLastUpdatedOn();
123
			} catch (Exception ex) {
124
				ex.printStackTrace();
125
			}
126
		}
127
 
128
	}
129
 
130
	private static void calculateinventory(){
131
		CatalogClient catalogServiceClient = null;
132
		Map<Long,ItemInventory> availability= new HashMap<Long,ItemInventory>();
133
		try {
134
			catalogServiceClient = new CatalogClient();
135
		} catch (TTransportException e) {
136
			// TODO Auto-generated catch block
137
			e.printStackTrace();
138
		}
139
		in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = catalogServiceClient.getClient();
140
		try {
141
			List<Item> aliveItems = catalogClient.getAllAliveItems();
142
			Map<Long,Item> aliveItemsMap = new HashMap<Long,Item>(); 
143
			for(in.shop2020.model.v1.catalog.Item thriftItem:aliveItems){
144
				aliveItemsMap.put(thriftItem.getId(), thriftItem);
145
 
146
			}
147
			InventoryClient inventoryServiceClient = new InventoryClient();
148
			try {
149
				inventoryServiceClient = new InventoryClient();
150
			} catch (TTransportException e) {
151
				e.printStackTrace();
152
			}
153
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
154
			List<in.shop2020.model.v1.inventory.IgnoredInventoryUpdateItems> ignoreItems = inventoryClient.getIgnoredWarehouseidsAndItemids();
155
			SNAPDEAL_INVENTORY_SHEET = "/home/snapdeal/snapdeal-inventory-"+time+".xls";
156
			availability = inventoryClient.getInventorySnapshot(0);
157
			List<Warehouse> allwarehouses = inventoryClient.getWarehouses(null,null,0,0,0);
158
			Map<Long,Warehouse> allWarehousesMap = new HashMap<Long,Warehouse>();
159
			for(Warehouse warehouse:allwarehouses){
160
				allWarehousesMap.put(warehouse.getId(),warehouse);
161
			}
162
			List<Warehouse> warehouses = inventoryClient.getWarehouses(WarehouseType.OURS_THIRDPARTY,null,0,0,0);
163
			List<Warehouse> ours_warehouses = inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, 0, 0);
164
			List<Long> thirdpartywarehouseids = new ArrayList<Long>();
165
			List<Long> oursGoodWarehouse = new ArrayList<Long>();
166
			for(Warehouse warehouse:warehouses){
167
				thirdpartywarehouseids.add(warehouse.getId());
168
			}
169
			for (Warehouse warehouse:ours_warehouses){
170
				oursGoodWarehouse.add(warehouse.getId());
171
			}
172
			long available=0;
173
			long reserve=0;
174
			long total_warehouse_held=0;
175
			long heldForSource=0;
176
			long total_held=0;
177
			double nlc=0;
178
			double maxnlc=0;
179
			Item thriftItem;
180
			long sku = 0;
181
			for(Inventory inventoryItem:currentInventoryItemList){
182
				if(snapdealItemMap.containsKey(inventoryItem.getSellerSku())){
183
					sku = snapdealItemMap.get(inventoryItem.getSellerSku()).getItem_id();
184
				}
185
				else{
186
					continue;
187
				}
188
				if(aliveItemsMap.get(sku) != null){
189
					thriftItem = aliveItemsMap.get(sku);	
190
				}
191
				else{
192
					continue;
193
				}
194
				available=0;
195
				reserve=0;
196
				total_warehouse_held=0;
197
				heldForSource=0;
198
				total_held=0;
199
				nlc=0;
200
				List<Warehouse> vendor_warehouses=null;
201
				SnapdealItemForInventory item;
202
				if(availability.get(thriftItem.getId())!=null){ 
203
					ItemInventory iteminventory = availability.get(thriftItem.getId());
204
					Map<Long,Long> itemavailability = new HashMap<Long,Long>();
205
					itemavailability = iteminventory.getAvailability();
206
					if (thriftItem.isIsWarehousePreferenceSticky() && thriftItem.getPreferredVendor()!=0){
207
						//System.out.println("Item id "+thriftItem.getId()+".Found prefered vendor and warehouse is marked sticky (Calculating availability)"+thriftItem.getPreferredVendor());						
208
						vendor_warehouses = inventoryClient.getWarehouses(WarehouseType.THIRD_PARTY,InventoryType.GOOD , thriftItem.getPreferredVendor(), 0, 0);
209
						vendor_warehouses.addAll(ours_warehouses);
210
						for (Warehouse warehouse:vendor_warehouses){
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) {
371
			// TODO Auto-generated catch block
372
			e.printStackTrace();
373
		}
374
 
375
	}
376
	private static void fetchinventoryhistoryfromsnapdeal() throws UnsupportedEncodingException, TException{
377
		int i = 1;
378
		Gson gson = new Gson();
379
		inventoryhistoryItemMap = new HashMap<String,InventoryHistory>();
380
		boolean exitfetchinghistory = true;
381
		System.out.println("Fetching history inventory");
382
		HttpGet get;
383
		HttpResponse response = null;
384
		BufferedReader rd = null;
385
		while(exitfetchinghistory){
386
			System.out.println("Fetching inventory history page " +i);
387
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=history&_search=false&nd="+time+"&rows=30&page="+i+"&sidx=&sord=dsc");
388
 
389
			try {
390
				response = client.execute(get);
391
			} catch (ClientProtocolException e) {
392
				// TODO Auto-generated catch block
393
				e.printStackTrace();
394
			} catch (IOException e) {
395
				// TODO Auto-generated catch block
396
				e.printStackTrace();
397
			}
398
 
399
			try {
400
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
401
 
402
			} catch (IllegalStateException e) {
403
				// TODO Auto-generated catch block
404
				e.printStackTrace();
405
			} catch (IOException e) {
406
				// TODO Auto-generated catch block
407
				e.printStackTrace();
408
			}
409
			InventoryHistoryItems inventoryhistoryitems = (InventoryHistoryItems) gson.fromJson(rd, InventoryHistoryItems.class);
410
			if(inventoryhistoryitems.getRows().size()!=0){
411
				//System.out.println("Parsing page " + i);
412
				for(InventoryHistory inventoryhistory : inventoryhistoryitems.getRows()){
413
					System.out.println("Inventory History " + inventoryhistory.getSellerSku() +" "+ inventoryhistory.getSupc()+" "+inventoryhistory.getNewValue());
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
		if(inventoryhistoryItemMap.entrySet().size()==0){
435
			try {
436
				mailer.sendSSLMessage(sendTo,"Error : Last Inventory Sent still not updated"+ sdf.format(System.currentTimeMillis()),"This e-mail is sent when there is some time lag on inventory updation on snapdeal ", emailFromAddress, password, new ArrayList<File>());
437
			} catch (MessagingException e) {
438
				// TODO Auto-generated catch block
439
				e.printStackTrace();
440
			}
441
		}
442
		InventoryClient inventoryServiceClient = new InventoryClient();
443
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
444
		List<SnapdealInventoryItem> snapdealInventoryItemHistoryList = inventoryClient.getSnapdealInventorySnapshot();
445
		if(snapdealInventoryItemHistoryList.size()>0){
446
			for(SnapdealInventoryItem snapdealInventoryItem:snapdealInventoryItemHistoryList){
447
				if(itemSnapdealMap.containsKey(snapdealInventoryItem.getItem_id())){
448
					PendingOrderInventoryHistory pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
449
					pendingOrdersInventoryHistory.setPendingOrders(snapdealInventoryItem.getPendingOrders());
450
					pendingOrdersInventoryHistory.setInventoryHistory(snapdealInventoryItem.getAvailability());
451
					pendingOrdersInventoryHistory.setLastUpdatedTimestamp(snapdealInventoryItem.getLastUpdatedOnSnapdeal());
452
					PendingOrdersInventoryHistoryMap.put(itemSnapdealMap.get(snapdealInventoryItem.getItem_id()).getSkuAtSnapdeal(), pendingOrdersInventoryHistory);
453
				}
454
			}
455
		}
456
		PendingOrderInventoryHistory  pendingOrdersInventoryHistory;
457
		for(Entry<String, InventoryHistory> inventoryHistoryItem :inventoryhistoryItemMap.entrySet()){
458
			if(PendingOrdersInventoryHistoryMap.containsKey(inventoryHistoryItem.getValue().getSellerSku())){
459
				pendingOrdersInventoryHistory = PendingOrdersInventoryHistoryMap.get(inventoryHistoryItem.getValue().getSellerSku());
460
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
461
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
462
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
463
			}
464
			else{
465
				pendingOrdersInventoryHistory = new PendingOrderInventoryHistory();
466
				pendingOrdersInventoryHistory.setInventoryHistory(Long.parseLong(inventoryHistoryItem.getValue().getNewValue()));
467
				pendingOrdersInventoryHistory.setLastUpdatedTimestamp(inventoryHistoryItem.getValue().getUpdateTime());
468
				pendingOrdersInventoryHistory.setPendingOrders(0);
469
				PendingOrdersInventoryHistoryMap.put(inventoryHistoryItem.getValue().getSellerSku(),pendingOrdersInventoryHistory);
470
			}
471
		}
472
	}
473
 
474
	private static void fetchcurrentinventoryfromsnapdeal() throws UnsupportedEncodingException, TException{
475
		int i = 1;
476
		int items=0;
477
		Gson gson = new Gson();
478
		in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
479
		currentInventoryItemList = new ArrayList<Inventory>();
480
		HttpGet get;
481
		HttpResponse response = null;
482
		BufferedReader rd= null;
483
		System.out.println("Fetching current inventory ");
484
		while(true){
485
			//System.out.println("Fetching current inventory page " +i);
486
			get = new HttpGet("http://seller.snapdeal.com/inventory/search?gridType=normal&_search=false&nd="+time+"&rows="+30+"&page="+i+"&sidx=&sord=asc");
487
			try {
488
				response = client.execute(get);
489
			} catch (ClientProtocolException e) {
490
				// TODO Auto-generated catch block
491
				e.printStackTrace();
492
			} catch (IOException e) {
493
				// TODO Auto-generated catch block
494
				e.printStackTrace();
495
			}
496
			try {
497
				rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
498
			} catch (IllegalStateException e) {
499
				// TODO Auto-generated catch block
500
				e.printStackTrace();
501
			} catch (IOException e) {
502
				// TODO Auto-generated catch block
503
				e.printStackTrace();
504
			}
505
			InventoryItems inventoryitems = (InventoryItems) gson.fromJson(rd, InventoryItems.class);
506
			if(inventoryitems.getRows().size()!=0){
507
				for(Inventory inventory : inventoryitems.getRows()){
508
					if(snapdealItemMap.containsKey(inventory.getSellerSku())){
509
						currentInventoryItemList.add(inventory);
510
					}
511
 
512
					else{
513
						notMappedItems.append("<tr>" 
514
								+ "<td>" + inventory.getProductName() +"</td>"
515
								+"<td>" + inventory.getSellerSku() + "</td>"
516
								+"<td>" + inventory.getSupc() + "</td>"
517
								+"</tr>");
518
					}
519
					items++;
520
				}
521
			}
522
			else{
523
				System.out.println("Fetched  " + items);
524
				break;
525
			}
526
			i++;
527
		}
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) {
542
			// TODO Auto-generated catch block
543
			e1.printStackTrace();
544
		}
545
		try {
546
			catalogServiceClient = new CatalogClient().getClient();
547
		} catch (TTransportException e1) {
548
			// TODO Auto-generated catch block
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) {
620
			// TODO Auto-generated catch block
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) {
634
			// TODO Auto-generated catch block
635
			e.printStackTrace();
636
		} catch (IOException e) {
637
			// TODO Auto-generated catch block
638
			e.printStackTrace();
639
		}
640
		BufferedReader rd = null;
641
		try {
642
			rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
643
		} catch (IllegalStateException e1) {
644
			// TODO Auto-generated catch block
645
			e1.printStackTrace();
646
		} catch (IOException e1) {
647
			// TODO Auto-generated catch block
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) {
658
			// TODO Auto-generated catch block
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",
693
		"bc452ce4"));
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
 
714
	@SuppressWarnings("deprecation")
715
	public static void main(String[] args) throws NumberFormatException, TException, ClientProtocolException, IOException, MessagingException {
716
		handleLogin();
717
		fetchinventoryhistoryfromsnapdeal();
718
		fetchcurrentinventoryfromsnapdeal();
719
		calculateinventory();
720
		in.shop2020.model.v1.catalog.CatalogService.Client catalogServiceClient = null;
721
		try {
722
			catalogServiceClient = new CatalogClient().getClient();
723
		} catch (TTransportException e) {
724
			// TODO Auto-generated catch block
725
			e.printStackTrace();
726
		}
727
		FileInputStream fis = new FileInputStream("/root/code/trunk/SnapDealFeeds/SellerInventory.xls");
728
		Workbook hwb = new HSSFWorkbook(fis);
729
		Sheet sheet = hwb.getSheetAt(0);
730
		Row row;
731
		int iterator=1;
732
		long available,reserve,defaultinventory,holdinventory,heldorders=0,sent_inventory = 0,totalheld,heldforsource,allocable;
733
		SnapdealItemForInventory  inventoryItem;
734
		StringBuffer outOfStockItems =new StringBuffer();
735
		StringBuffer backInStockItems =new StringBuffer();
736
		StringBuffer inventoryChangeItems =new StringBuffer();
737
		StringBuffer heldMoreThanAvailable =new StringBuffer();
738
		long sku = 0;
739
		SnapdealItemDetails snapdealitem;
740
		for(Inventory inventory:currentInventoryItemList){
741
			//System.out.println(inventory.getSupc()+" "+inventory.getSellerSku()+ " " +inventory.getProductName()+" "+inventory.getAvailableInventory()+" "+inventory.isLive()+" "+itemIdpendingOrdersMap.get(Long.parseLong(inventory.getSellerSku())));
742
			if(snapdealItemMap.containsKey(inventory.getSellerSku())){
743
				snapdealitem = snapdealItemMap.get(inventory.getSellerSku()); 
744
				sku =  snapdealitem.getItem_id();
745
			}
746
			else{
747
				continue;
748
			}
749
			if(snapdealitem.getItem_id()!=0 && snapdealitem.isIsListedOnSnapdeal() && !snapdealitem.isSuppressInventoryFeed()){
750
				inventoryItem = allItemsInventoryMap.get(sku);
751
				if(inventoryItem==null){
752
					continue;
753
				}
754
				available = inventoryItem.getAvailability(); 
755
				reserve = inventoryItem.getReserve();
756
				defaultinventory = inventoryItem.getDefaultInventory();
757
				holdinventory = inventoryItem.getHoldInventory();
758
				totalheld = inventoryItem.getTotalHeldInventory();
759
				heldforsource = inventoryItem.getHeldForSource();
760
				if(itemIdpendingOrdersMap.containsKey(sku)){
761
					heldorders = itemIdpendingOrdersMap.get(sku);
762
					if(heldorders < 0){
763
						heldorders = 0;
764
					}
765
				}
766
				System.out.println("itemId: " + inventoryItem.getId() + "\trisky: " + inventoryItem.getRisky()+ 
767
						"\tavailable: " + available + "\treserve: " + reserve + "\theldForSource:" + heldforsource +
768
						"\twebsite_hold: " + holdinventory + "\ttotal_held: " +totalheld +"\tdefault_inv: "
769
						+ defaultinventory + "\theldorders " + heldorders);
770
				row =   sheet.getRow((short) iterator);
771
				if(!inventoryItem.getStatus().equals(status.PAUSED)){
772
					if(inventoryItem.getRisky()){
773
						if((available - reserve) < totalheld && totalheld!=0){
774
							sent_inventory = (long) Math.floor(((available - reserve)*heldforsource/totalheld)) - heldorders;
775
							heldMoreThanAvailable.append("<tr>" 
776
									+ "<td>" + inventory.getProductName() +"</td>"
777
									+"<td>" + sku + "</td>"
778
									+"<td>" + (available - reserve) +  "</td>"
779
									+"<td>" + totalheld + "</td>"
780
									+"</tr>");
781
						}
782
						else{
783
							allocable = available - reserve - totalheld - holdinventory;
784
							if(allocable < 0){
785
								allocable = 0;
786
							}
787
							sent_inventory = Math.round(allocable*2/3) + heldforsource - heldorders ;
788
						}
789
						if(sent_inventory < 0){
790
							sent_inventory = 0;
791
						}
792
					}
793
					else{
794
						allocable = available - reserve - totalheld;
795
						if(allocable < 0){
796
							allocable = 0;
797
						}
798
						if((allocable + heldforsource ) > defaultinventory){
799
							sent_inventory = Math.round(allocable*2/3) +  heldforsource - heldorders;
800
							//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));
801
							if(sent_inventory < 0){
802
								sent_inventory = 0;							
803
							}
804
						}
805
						else{
806
							if(defaultinventory > heldorders){
807
								sent_inventory = defaultinventory - heldorders;
808
							}
809
							else{
810
								sent_inventory = 0;
811
							}
812
						}
813
					}
814
				}
815
				else{
816
					sent_inventory = 0;
817
				}
818
				if(inventory.getAvailableInventory()!= sent_inventory){
819
 
820
					if(UPDATEUSINGPANEL){
821
						UpdateSDIUsingPanel.updateInventory(sent_inventory,inventory.getSupc());	
822
					}
823
					else{
824
						row.getCell((short) 0).setCellValue(inventory.getSupc());
825
						row.getCell((short) 1).setCellValue(inventory.getSellerSku());
826
						row.getCell((short) 2).setCellValue(inventory.getProductName());
827
						row.getCell((short) 3).setCellValue(inventory.getAvailableInventory());
828
						row.getCell((short) 4).setCellValue(sent_inventory);
829
						if(inventory.getAvailableInventory()!=0 && sent_inventory==0){
830
							outOfStockItems.append("<tr>" 
831
									+ "<td>" + inventory.getProductName() +"</td>"
832
									+"<td>" + sku + "</td>"
833
									+"<td>" + inventory.getAvailableInventory() + "</td>"
834
									+"<td>" + sent_inventory + "</td>"
835
									+"</tr>");
836
						}
837
						else if(inventory.getAvailableInventory()==0 && sent_inventory!=0){
838
							backInStockItems.append("<tr>" 
839
									+ "<td>" + inventory.getProductName() +"</td>"
840
									+"<td>" + sku + "</td>"
841
									+"<td>" + inventory.getAvailableInventory() + "</td>"
842
									+"<td>" + sent_inventory + "</td>"
843
									+"</tr>");
844
						}
845
						else{
846
							inventoryChangeItems.append("<tr>" 
847
									+ "<td>" + inventory.getProductName() +"</td>"
848
									+"<td>" + sku + "</td>"
849
									+"<td>" + inventory.getAvailableInventory() + "</td>"
850
									+"<td>" + sent_inventory + "</td>"
851
									+"</tr>");
852
						}
853
						if(inventory.isLive()){
854
							row.getCell((short) 5).setCellValue("Yes");
855
						}
856
						else{
857
							row.getCell((short) 5).setCellValue("No");
858
						}
859
					}
860
					iterator++;
861
				}
862
			}
863
			else{
864
				continue;
865
			}
866
		}
867
		if(!UPDATEUSINGPANEL){
868
			if(iterator > 1){
869
				FileOutputStream fileOut = null;
870
				fis.close();
871
				try {
872
					System.out.println("Before writing file ");
873
					fileOut = new FileOutputStream(SNAPDEAL_INVENTORY_SHEET);
874
				} catch (FileNotFoundException e) {
875
					// TODO Auto-generated catch block
876
					e.printStackTrace();
877
				}
878
				try {
879
 
880
					hwb.write(fileOut);
881
				} catch (IOException e) {
882
					// TODO Auto-generated catch block
883
					e.printStackTrace();
884
				}
885
				HttpPost post = new HttpPost("http://seller.snapdeal.com/inventory/upload");
886
				File file = new File(SNAPDEAL_INVENTORY_SHEET);
887
				MultipartEntity mpEntity = new MultipartEntity();
888
				ContentBody cbFile = new FileBody(file,"application/vnd.ms-excel");
889
				mpEntity.addPart("file", cbFile);
890
				post.setEntity(mpEntity);
891
				System.out.println("Before posting file");
892
				HttpResponse response = client.execute(post);
893
				BufferedReader rd = null;
894
				try {
895
					rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
896
				} catch (IllegalStateException e1) {
897
					// TODO Auto-generated catch block
898
					e1.printStackTrace();
899
				} catch (IOException e1) {
900
					// TODO Auto-generated catch block
901
					e1.printStackTrace();
902
				}
903
				String line = "";
904
				String feedresponse = null;
905
				try {
906
					while ((line = rd.readLine()) != null) {
907
						System.out.println(line);
908
						feedresponse = line;
909
					}
910
				} catch (IOException e) {
911
					// TODO Auto-generated catch block
912
					e.printStackTrace();
913
				}
914
				System.out.println("posting response" + feedresponse);
915
			}	
916
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = null;
917
			long lastSentInventoryTime = System.currentTimeMillis();
918
			try {
919
				transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
920
				transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
921
			} catch (Exception e) {
922
				try {
923
					transactionClient = new TransactionClient("support_transaction_service_server_host","transaction_service_server_port").getClient();
924
					transactionClient.updateSourceDetailTimestamp(7, lastSentInventoryTime);
925
				} catch (Exception ex) {
926
					ex.printStackTrace();
927
				}
928
			}
929
			String emailSubjectTxt;
930
			if(UPDATEUSINGPANEL){
931
				emailSubjectTxt = "Products back in stock on Snapdeal (Using Panel) "+sdf.format(lastSentInventoryTime);
932
			}
933
			else{
934
				emailSubjectTxt = "Products back in stock on Snapdeal "+sdf.format(lastSentInventoryTime);
935
			}
936
 
937
			String text;
938
			String tableHeader = "<tr>" 
939
				+ "<td>" + "Product Name" +"</td>"
940
				+"<td>" + "Item ID" + "</td>"
941
				+"<td>" + "Old Inventory" + "</td>"
942
				+"<td>" + "New Inventory" + "</td>"
943
				+"</tr>";
944
			if(backInStockItems.length() > 0){
945
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+backInStockItems.toString()+"</table></html>";
946
				try {
947
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
948
					//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
949
				} catch (MessagingException e) {
950
					e.printStackTrace();
951
				}
952
			}
953
			if(UPDATEUSINGPANEL){
954
				emailSubjectTxt = "Products back in stock on Snapdeal (Using Panel) "+sdf.format(lastSentInventoryTime);
955
			}
956
			else{
957
				emailSubjectTxt = "Products out of stock on Snapdeal "+sdf.format(lastSentInventoryTime);
958
			}
959
			if(outOfStockItems.length() > 0){
960
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+outOfStockItems.toString()+"</table></html>";
961
				try {
962
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
963
					//mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
964
				} catch (MessagingException e) {
965
					e.printStackTrace();
966
				}
967
			}
968
			/*			List<File> files = new ArrayList<File>();
969
			files.add(new File(SNAPDEAL_INVENTORY_SHEET));
970
			try {
971
				mailer.sendSSLMessage(sendTo,"Inventory File",feedresponse, emailFromAddress, password, files);
972
			} catch (MessagingException e) {
973
				e.printStackTrace();
974
			}
975
			 */
976
			if(UPDATEUSINGPANEL){
977
				emailSubjectTxt = "Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis() +" "+"(Using Panel)");
978
			}
979
			else{
980
				emailSubjectTxt = "Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis());
981
			}
982
			if(inventoryChangeItems.length() > 0){
983
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+inventoryChangeItems.toString()+"</table></html>";
984
				try {
985
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
986
				} catch (MessagingException e) {
987
					e.printStackTrace();
988
				}
989
			}
990
 
991
			tableHeader = "<tr>" 
992
				+ "<td>" + "Product Name" +"</td>"
993
				+"<td>" + "Item ID" + "</td>"
994
				+"<td>" + "Available - Reserve" + "</td>"
995
				+"<td>" + "Total Held" + "</td>"
996
				+"</tr>";
997
 
998
			emailSubjectTxt = "Items with (Total Held > Net Available) Inventory "+ sdf.format(System.currentTimeMillis());
999
			if(heldMoreThanAvailable.length() > 0){
1000
				text = "<html><table border=\"1\" align=\"center\">"+tableHeader+heldMoreThanAvailable.toString()+"</table></html>";
1001
				try {
1002
					mailer.sendSSLMessage(sendTo,emailSubjectTxt, emailFromAddress, password, text);
1003
					//mailer.sendSSLMessage(sendTo,"Snapdeal Inventory Updates sent for " +(iterator-1)+" items "+ sdf.format(System.currentTimeMillis()),inventoryChangeItems.toString(), emailFromAddress, password, new ArrayList<File>());
1004
				} catch (MessagingException e) {
1005
					e.printStackTrace();
1006
				}
1007
			}
1008
 
1009
		}
1010
		else{
1011
			try {
1012
				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>());
1013
			} catch (MessagingException e) {
1014
				e.printStackTrace();
1015
			}
1016
		}
1017
		String tableHeader = "<tr>" 
1018
			+ "<td>" + "Product Name" +"</td>"
1019
			+"<td>" + "SKU at Snapdeal" + "</td>"
1020
			+"<td>" + "SUPC" + "</td>"
1021
			+"</tr>";
1022
		String text;
1023
 
1024
		if(notMappedItems.length() >0){
1025
			text = "<html><table border=\"1\" align=\"center\">"+tableHeader+notMappedItems.toString()+"</table></html>";
1026
			mailer.sendSSLMessage(sendTo,"Please create Warehouse ID and Item ID mapping", emailFromAddress, password, text);
1027
		}
1028
	}
1029
}