Subversion Repositories SmartDukaan

Rev

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

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