Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
10097 kshitij.so 1
package in.shop2020.support.controllers;
2
 
10307 kshitij.so 3
import in.shop2020.config.ConfigException;
10097 kshitij.so 4
import in.shop2020.model.v1.catalog.CatalogService.Client;
5
import in.shop2020.model.v1.catalog.CatalogServiceException;
6
import in.shop2020.model.v1.catalog.FlipkartItem;
7
import in.shop2020.model.v1.catalog.FlipkartItemDetails;
8
import in.shop2020.model.v1.catalog.Item;
9
import in.shop2020.model.v1.catalog.MarketplaceItems;
10
import in.shop2020.model.v1.catalog.MarketplacePercentage;
11
import in.shop2020.model.v1.inventory.InventoryServiceException;
12
import in.shop2020.model.v1.inventory.InventoryType;
13
import in.shop2020.model.v1.inventory.ItemInventory;
14
import in.shop2020.model.v1.inventory.OOSStatus;
15
import in.shop2020.model.v1.inventory.Warehouse;
16
import in.shop2020.model.v1.inventory.WarehouseType;
17
import in.shop2020.support.utils.ReportsUtils;
10268 vikram.rag 18
import in.shop2020.support.utils.UpdateFlipkartPricing;
19
import in.shop2020.support.utils.UpdateSDPricingUsingPanel;
10097 kshitij.so 20
import in.shop2020.thrift.clients.CatalogClient;
21
import in.shop2020.thrift.clients.InventoryClient;
22
import in.shop2020.thrift.clients.TransactionClient;
10307 kshitij.so 23
import in.shop2020.thrift.clients.config.ConfigClient;
10097 kshitij.so 24
import in.shop2020.utils.GmailUtils;
25
import javax.mail.MessagingException;
26
 
27
import java.io.BufferedInputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.FileNotFoundException;
31
import java.io.FileOutputStream;
32
import java.io.FileWriter;
33
import java.io.IOException;
34
import java.io.InputStream;
35
import java.text.DecimalFormat;
36
import java.util.ArrayList;
37
import java.util.Arrays;
38
import java.util.HashMap;
39
import java.util.List;
40
import java.util.Map;
41
 
42
import javax.servlet.ServletContext;
43
import javax.servlet.ServletOutputStream;
44
import javax.servlet.http.HttpServletRequest;
45
import javax.servlet.http.HttpServletResponse;
46
import javax.servlet.http.HttpSession;
47
 
48
import org.apache.commons.io.FileUtils;
49
import org.apache.commons.lang.xwork.StringUtils;
50
import org.apache.poi.hssf.usermodel.HSSFRow;
51
import org.apache.poi.hssf.usermodel.HSSFSheet;
52
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
53
import org.apache.poi.ss.usermodel.Cell;
54
import org.apache.struts2.convention.annotation.InterceptorRef;
55
import org.apache.struts2.convention.annotation.InterceptorRefs;
56
import org.apache.struts2.interceptor.ServletRequestAware;
57
import org.apache.struts2.interceptor.ServletResponseAware;
58
import org.apache.struts2.util.ServletContextAware;
59
import org.apache.thrift.TException;
60
import org.apache.thrift.transport.TTransportException;
61
import org.json.JSONException;
62
import org.json.JSONObject;
63
import org.slf4j.Logger;
64
import org.slf4j.LoggerFactory;
65
 
66
import com.opensymphony.xwork2.ValidationAwareSupport;
67
 
68
@SuppressWarnings({"unused","deprecation"})
69
 
70
@InterceptorRefs({
71
	@InterceptorRef("defaultStack"),
72
	@InterceptorRef("login")
73
})
74
 
75
public class FlipkartListController extends ValidationAwareSupport implements ServletRequestAware ,ServletResponseAware, ServletContextAware{
76
	/**
77
	 * 
78
	 */
79
	private static final long serialVersionUID = 1L;
80
 
81
 
82
	private static Logger logger = LoggerFactory.getLogger(FlipkartListController.class);
83
 
84
 
85
	private HttpServletRequest request;
86
	private HttpServletResponse response;
87
	private HttpSession session;
88
	private ServletContext context;
89
	private String url;
90
	private String itemId;
91
	private String exceptionPrice;
92
	private String warehouseId;
93
	private File file;
94
	private String errMsg;
95
	private String next;
96
	private String id;
97
	private String searchText;
98
	private List<FlipkartItemDetails> flipkartItems;
99
	private long searchCount;
100
	private long totalCount;
101
	private String sellingPrice;
102
	private String transferPrice;
103
	private String webisteMrp;
104
	private String webisteSellingPrice;
105
	private String isListedOnFlipkart;
106
	private String commission;
107
	private String serviceTax;
108
	private String courierCost;
109
	private JSONObject itemObj;
110
	private String isSuppressInventoryFeed;
111
	private String isSuppressPriceFeed;
112
	private String maxNlc;
113
	private String fkItemCode;
114
	private String supc;
115
	private String held;
116
	private String lastUpdatedInventoryTimestamp;
117
	private String lastCheckedTimestamp;
118
	private String otherCost;
119
	private String isAutoIncrement;
120
	private String isAutoDecrement;
121
	private String isManualFavourite;
122
	private String isAutoFavourite;
123
	private String currentSp;
124
	private String currentTp;
125
	private String minPosSp;
126
	private String minPosTp;
127
	private String vat;
128
	private String comparsionResult;
129
	private String maxSp;
130
	private String nDaySale;
131
	private String fkSerialNumber;
10307 kshitij.so 132
	private static String live;
10097 kshitij.so 133
 
134
	public String getFkSerialNumber() {
135
		return fkSerialNumber;
136
	}
137
 
138
	public void setFkSerialNumber(String fkSerialNumber) {
139
		this.fkSerialNumber = fkSerialNumber;
140
	}
141
 
142
	public String getnDaySale() {
143
		return nDaySale;
144
	}
145
 
146
	public void setnDaySale(String nDaySale) {
147
		this.nDaySale = nDaySale;
148
	}
149
 
150
	private String avgSale;
151
 
152
	public String getAvgSale() {
153
		return avgSale;
154
	}
155
 
156
	public void setAvgSale(String avgSale) {
157
		this.avgSale = avgSale;
158
	}
159
 
160
	public String getMaxSp() {
161
		return maxSp;
162
	}
163
 
164
	public void setMaxSp(String maxSp) {
165
		this.maxSp = maxSp;
166
	}
167
 
168
	public String getComparsionResult() {
169
		return comparsionResult;
170
	}
171
 
172
	public void setComparsionResult(String comparsionResult) {
173
		this.comparsionResult = comparsionResult;
174
	}
175
 
176
	private Map<Integer, Long> holdInventoryMap;
177
 
178
	public String getVat() {
179
		return vat;
180
	}
181
 
182
	public void setVat(String vat) {
183
		this.vat = vat;
184
	}
185
 
186
	public String getOtherCost() {
187
		return otherCost;
188
	}
189
 
190
	public void setOtherCost(String otherCost) {
191
		this.otherCost = otherCost;
192
	}
193
 
194
 
195
	public String getCurrentSp() {
196
		return currentSp;
197
	}
198
 
199
	public void setCurrentSp(String currentSp) {
200
		this.currentSp = currentSp;
201
	}
202
 
203
	public String getCurrentTp() {
204
		return currentTp;
205
	}
206
 
207
	public void setCurrentTp(String currentTp) {
208
		this.currentTp = currentTp;
209
	}
210
 
211
 
212
	public String getLastCheckedTimestamp() {
213
		return lastCheckedTimestamp;
214
	}
215
 
216
	public String getLastUpdatedInventoryTimestamp() {
217
		return lastUpdatedInventoryTimestamp;
218
	}
219
 
220
	public void setLastUpdatedInventoryTimestamp(
221
			String lastUpdatedInventoryTimestamp) {
222
		this.lastUpdatedInventoryTimestamp = lastUpdatedInventoryTimestamp;
223
	}
224
 
225
	public void setLastCheckedTimestamp(
226
			String lastCheckedTimestamp) {
227
		this.lastCheckedTimestamp = lastCheckedTimestamp;
228
	}
229
 
230
	public String getIsAutoIncrement() {
231
		return isAutoIncrement;
232
	}
233
 
234
	public void setIsAutoIncrement(String isAutoIncrement) {
235
		this.isAutoIncrement = isAutoIncrement;
236
	}
237
 
238
	public String getIsAutoDecrement() {
239
		return isAutoDecrement;
240
	}
241
 
242
	public void setIsAutoDecrement(String isAutoDecrement) {
243
		this.isAutoDecrement = isAutoDecrement;
244
	}
245
 
246
	public String getIsManualFavourite() {
247
		return isManualFavourite;
248
	}
249
 
250
	public void setIsManualFavourite(String isManualFavourite) {
251
		this.isManualFavourite = isManualFavourite;
252
	}
253
 
254
	public String getIsAutoFavourite() {
255
		return isAutoFavourite;
256
	}
257
 
258
	public void setIsAutoFavourite(String isAutoFavourite) {
259
		this.isAutoFavourite = isAutoFavourite;
260
	}
261
 
262
	public String getMinPosSp() {
263
		return minPosSp;
264
	}
265
 
266
	public void setMinPosSp(String minPosSp) {
267
		this.minPosSp = minPosSp;
268
	}
269
 
270
	public String getMinPosTp() {
271
		return minPosTp;
272
	}
273
 
274
	public void setMinPosTp(String minPosTp) {
275
		this.minPosTp = minPosTp;
276
	}
277
 
278
	public String getHeld() {
279
		return held;
280
	}
281
 
282
	public void setHeld(String held) {
283
		this.held = held;
284
	}
285
 
286
	public String getSupc() {
287
		return supc;
288
	}
289
 
290
	public void setSupc(String supc) {
291
		this.supc = supc;
292
	}
293
 
294
	public String getFkItemCode() {
295
		return fkItemCode;
296
	}
297
 
298
	public void setFkItemCode(String fkItemCode) {
299
		this.fkItemCode = fkItemCode;
300
	}
10307 kshitij.so 301
 
302
	static{
303
		try {
304
			live = ConfigClient.getClient().get("sync_price_on_marketplace");
305
		} catch (ConfigException e) {
306
		    logger.error("Unable to get parameter from the config service", e);
307
		    live = "false";
308
		}
309
	}
10097 kshitij.so 310
 
311
	public String index() {
312
		if (!ReportsUtils.canAccessReport((Long) session.getAttribute(ReportsUtils.ROLE),request.getServletPath())) {
313
			return "authfail";
314
		}
315
		return "index";
316
	}
317
 
318
	public String edit() {
319
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
320
			return "authfail";
321
		}
322
		return "edit";
323
	}
324
 
325
	public String fetchItems() throws TException {
326
		Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
327
		if (searchText.length() == 0) {
328
			flipkartItems = CatalogClient.getFlipkartItems(Long.valueOf(next), 10);
329
			totalCount = CatalogClient.getCountForFlipkartItems();
330
			setSearchCount(totalCount);
331
		} else {
332
			List<String> subString = Arrays.asList(searchText.split(" "));
333
			flipkartItems = CatalogClient.searchFlipkartItems(subString,Long.valueOf(next), 10);
334
			totalCount = CatalogClient.getCountForFlipkartItems();
335
			searchCount = CatalogClient.getFlipkartSearchResultCount(subString);
336
		}
337
		return "flipkart-item-table";
338
	}
339
 
340
	public FlipkartItemDetails fetchItemDetail() throws NumberFormatException, TException {
341
		Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
342
		FlipkartItemDetails fkItemDetails = CatalogClient.getFlipkartItemDetails(Long.valueOf(id));
343
		lastUpdatedInventoryTimeStampForItem(fkItemDetails.getLastUpdatedInventoryTimestamp());
344
		return fkItemDetails;
345
	}
346
 
347
	public MarketplaceItems fetchMarketplaceDetail() throws NumberFormatException, TException {
348
		Client CatalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
349
		MarketplaceItems mpItemDetails = CatalogClient.getMarketplacedetailsForItem(Long.valueOf(id), 8);
350
		lastCheckedTimeStampForItem(mpItemDetails.getLastCheckedTimestamp());
351
		return mpItemDetails;
352
	}
353
 
354
	public void lastUpdatedInventoryTimeStampForItem(long timestamp){
355
		setLastUpdatedInventoryTimestamp(new java.util.Date(timestamp).toLocaleString());
356
	}
357
 
358
	public void lastCheckedTimeStampForItem(long timestamp){
359
		setLastCheckedTimestamp(new java.util.Date(timestamp).toLocaleString());
360
	}
361
 
362
	public String uploadBulkSheet(){
363
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0])) {
364
			logger.info(request.getRequestURI().substring(request.getContextPath().length()).split("/")[1].split("!")[0]);
365
			return "authfail";
366
		}
367
		return "flipkart-bulk-upload";
368
	}
369
 
370
	public String update() throws NumberFormatException, TException, InventoryServiceException, CatalogServiceException, JSONException{
371
		Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
372
		//Client catalogClientProd = new CatalogClient().getClient();
373
		FlipkartItem flipkartItem = catalogClient.getFlipkartItem(Long.valueOf(itemId));
374
		Item item = catalogClient.getItem(Long.valueOf(itemId));
375
		MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
376
		if (mpCosting.getSource()==0){
377
			throw new CatalogServiceException();
378
		}
379
		MarketplaceItems mpItem = catalogClient.getMarketplacedetailsForItem(Long.valueOf(itemId),8);
10307 kshitij.so 380
		boolean toUpdate =false;
381
		if (mpItem.getCurrentSp()!=Double.valueOf(sellingPrice) || flipkartItem.isIsListedOnFlipkart()!=Boolean.valueOf(isListedOnFlipkart) || flipkartItem.isSuppressPriceFeed()!=Boolean.valueOf(isSuppressPriceFeed)){
382
			toUpdate=true;
383
		}
10097 kshitij.so 384
		mpItem.setEmiFee(mpCosting.getEmiFee());
385
		mpItem.setReturnProvision(mpCosting.getReturnProvision());
386
		mpItem.setClosingFee(mpCosting.getClosingFee());
387
		mpItem.setServiceTax(mpCosting.getServiceTax());
388
		mpItem.setCommission(mpCosting.getCommission());
389
		InventoryClient inventoryServiceClient = new InventoryClient();
390
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
391
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
392
		/*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
393
			throw new InventoryServiceException();
394
		}*/
395
		flipkartItem.setWarehouseId(Long.valueOf(warehouseId));
396
		flipkartItem.setIsListedOnFlipkart(Boolean.valueOf(isListedOnFlipkart));
397
		flipkartItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
398
		flipkartItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
399
		flipkartItem.setExceptionPrice(Double.valueOf(exceptionPrice));
400
		flipkartItem.setCommissionValue(Double.valueOf(commission));
401
		flipkartItem.setServiceTaxValue(Double.valueOf(serviceTax));
402
		flipkartItem.setMaxNlc(Double.valueOf(maxNlc));
403
		flipkartItem.setSkuAtFlipkart(fkItemCode);
404
		flipkartItem.setFlipkartSerialNumber(fkSerialNumber);
405
		MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
406
		//double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
407
		//t_mpItem.setVat(vat);
408
		flipkartItem.setUpdatedBy(getUserName());
409
		flipkartItem.setMarketplaceItems(t_mpItem);
410
 
411
		if(!compareParameters(t_mpItem,flipkartItem,warehouse,item.getWeight())){
412
			setComparsionResult("0");
413
			return "flipkart-update-result";
414
		}
415
		else{
416
			setComparsionResult("1");
417
		}
10268 vikram.rag 418
		Long timestamp = System.currentTimeMillis();
10097 kshitij.so 419
		if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
420
			throw new CatalogServiceException();
421
		}
422
 
423
		if (t_mpItem.getCurrentSp()< t_mpItem.getMinimumPossibleSp()){
424
			sendAlert(t_mpItem.getItemId(),t_mpItem.getCurrentSp(),t_mpItem.getMinimumPossibleSp());
425
		}
10156 amar.kumar 426
		logger.info("\nUpdate Method Item Id "+itemId+"\nSelling Price "+sellingPrice+"\nWarehouse Id "+warehouseId+"\nMax Nlc "+maxNlc+"\nUpdated By: "+session.getAttribute(ReportsUtils.USER_NAME).toString());
10307 kshitij.so 427
		if(toUpdate && Boolean.valueOf(live) && Boolean.valueOf(isListedOnFlipkart) && (!Boolean.valueOf(isSuppressPriceFeed))){
10268 vikram.rag 428
			UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,timestamp);
429
			updateFlipkartPricing.start();
430
		}
10097 kshitij.so 431
		return "flipkart-update-result";
432
	}
433
 
434
 
435
	public boolean compareParameters(MarketplaceItems mpItem, FlipkartItem flipkartItem, Warehouse warehouse,double weight) throws TException, JSONException, CatalogServiceException{
436
		double nlc =getNlcForWarehouse(flipkartItem.getWarehouseId(),flipkartItem.getItem_id());
437
		double vat = (mpItem.getCurrentSp()/(1+(mpItem.getVat()/100))-(nlc/(1+(mpItem.getVat()/100))))*(mpItem.getVat()/100);
438
		double inHouseCost = 15+vat+(mpItem.getReturnProvision()/100)*mpItem.getCurrentSp()+mpItem.getOtherCost();
439
		double lowest_possible_tp = nlc+inHouseCost;
440
		double our_tp =  mpItem.getCurrentSp()- mpItem.getCurrentSp()*(mpItem.getCommission()/100+mpItem.getEmiFee()/100)*(1+(mpItem.getServiceTax()/100))-(mpItem.getCourierCost()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100));
441
		double commission =  ((mpItem.getCommission()/100)*mpItem.getCurrentSp());
442
		double service_tax = (mpItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+mpItem.getCourierCost());
443
		double lowest_possible_sp = (nlc+(mpItem.getCourierCost()+mpItem.getClosingFee())*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat()/100))+(15+mpItem.getOtherCost())*(1+(mpItem.getVat())/100))/(1-(mpItem.getCommission()/100+mpItem.getEmiFee()/100)*(1+(mpItem.getServiceTax()/100))*(1+(mpItem.getVat())/100)-(mpItem.getReturnProvision()/100)*(1+(mpItem.getVat())/100));
444
		double vat_rate_prod = getVatRateForItem(warehouse,mpItem.getCurrentSp(),flipkartItem.getItem_id());
445
		JSONObject x = new JSONObject();
446
		x.put("NLC", nlc);
447
		x.put("VAT", vat);
448
		x.put("COURIER COST",getCourierCost(weight));
449
		x.put("LOWEST POS TP", lowest_possible_tp);
450
		x.put("TP", our_tp);
451
		x.put("COMMISSION", commission);
452
		x.put("SERVICE TAX", service_tax);
453
		x.put("LOWEST POS SP", lowest_possible_sp);
454
		x.put("VAT RATE",vat_rate_prod);
455
		logger.info("Flipkart Backend validation "+x.toString());
456
		boolean compare_result=true;
457
 
458
		if(!(getCourierCost(weight)==mpItem.getCourierCost())){
459
			compare_result=false;
460
		}
461
 
462
		if(!(vat_rate_prod==mpItem.getVat())){
463
			compare_result=false;
464
		}
465
 
466
		if(!(nlc==flipkartItem.getMaxNlc())){
467
			compare_result=false;
468
		}
469
		if(!(lowest_possible_tp-mpItem.getMinimumPossibleTp()>-1 && lowest_possible_tp-mpItem.getMinimumPossibleTp()<1)){
470
			compare_result=false;
471
		}
472
		if(!(our_tp-mpItem.getCurrentTp()>-1 && our_tp-mpItem.getCurrentTp()<1)){
473
			compare_result=false;
474
		}
475
		if(!(commission-flipkartItem.getCommissionValue()>-1 && commission-flipkartItem.getCommissionValue()<1)){
476
			compare_result=false;
477
		}
478
		if(!(service_tax-flipkartItem.getServiceTaxValue()>-1 && service_tax-flipkartItem.getServiceTaxValue()<1)){
479
			compare_result=false;
480
		}
481
		if(!(lowest_possible_sp-mpItem.getMinimumPossibleSp()>-1 && lowest_possible_sp-mpItem.getMinimumPossibleSp()<1)){
482
			compare_result=false;
483
		}
484
		return compare_result;
485
 
486
	}
487
 
488
	public double getVatRateForItem(Warehouse warehouse, double sellingPrice,long itemId) throws CatalogServiceException, TException{
489
		Client catalogClientProd = new CatalogClient().getClient();
490
		return catalogClientProd.getVatPercentageForItem(itemId, warehouse.getStateId(), sellingPrice);
491
	}
492
 
493
	public double getNlcForWarehouse(long warehouseId,long item_id) throws TException{
494
		InventoryClient inventoryServiceClient = new InventoryClient();
495
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
496
		return inventoryClient.getNlcForWarehouse(warehouseId, item_id);
497
	}
498
 
499
	public double getCourierCost(double weight){
500
		double cCost = 40.0;
501
		int slabs = (int) ((weight+.05 - .001)/(.5));
502
		for(int i=0;i<slabs;i++){
503
			cCost = cCost + 40;
504
		}
505
		return cCost;
506
	}
507
 
508
	public void getLastNDaySaleForItem(String itemId,String days) {
509
		try{
510
			InventoryClient inventoryServiceClient = new InventoryClient();
511
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
512
			List<OOSStatus> oosStatuses = inventoryClient.getOosStatusesForXDaysForItem(Long.valueOf(itemId), 8, Integer.valueOf(days));
513
			String lastNdaySale="";
514
			double avgSale = 0.0;
515
			long count = 0,sale = 0;
516
			for(OOSStatus oosStatus : oosStatuses){
517
				if(oosStatus.isIs_oos()){
518
					lastNdaySale += "X-";
519
				}else{
520
					lastNdaySale += oosStatus.getNum_orders() + "-";
521
					sale = sale + oosStatus.getNum_orders();
522
					count+=1;
523
				}
524
			}
525
			lastNdaySale = lastNdaySale.substring(0, lastNdaySale.length()-1);
526
			lastNdaySale += "\n";
527
			setnDaySale(lastNdaySale);
528
			if (count!=0){
529
				setAvgSale(String.valueOf(roundTwoDecimals(sale/(double)count)));
530
			}
531
			else{
532
				setAvgSale("0");
533
			}
534
		}
535
		catch (Exception e){
536
			setAvgSale("0");
537
			setnDaySale("Unable to fetch");
538
			logger.error("Unable to get last n day sale",e);
539
		}
540
 
541
	}
542
 
543
 
544
	private MarketplaceItems updateMarketplaceItemDetails(MarketplaceItems mpItem){
545
		mpItem.setItemId(Long.valueOf(itemId));
546
		mpItem.setSource(8);
547
		mpItem.setVat(Double.valueOf(vat));
548
		mpItem.setCourierCost(Double.valueOf(courierCost));
549
		mpItem.setOtherCost(Double.valueOf(otherCost));
550
		mpItem.setCurrentSp(Double.valueOf(sellingPrice));
551
		mpItem.setCurrentTp(Double.valueOf(transferPrice));
552
		mpItem.setAutoDecrement(Boolean.valueOf(isAutoDecrement));
553
		mpItem.setAutoIncrement(Boolean.valueOf(isAutoIncrement));
554
		mpItem.setManualFavourite(Boolean.valueOf(isManualFavourite));
555
		mpItem.setMinimumPossibleSp(Double.valueOf(minPosSp));
556
		mpItem.setMinimumPossibleTp(Double.valueOf(minPosTp));
557
		mpItem.setMaximumSellingPrice(Double.valueOf(maxSp));
558
		return mpItem;
559
	}
560
 
561
	private void sendAlert(long itemId,double sp,double minSp){
562
		Item item;
563
		try{
564
			Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
565
			item= catalogClient.getItem(itemId);
566
		}
567
		catch(Exception e){
568
			e.printStackTrace();
569
			return;
570
		}
571
		String emailSubjectTxt="Flipkart SP is set below Min Possible SP";
572
		String[] sendTo=new String[]{ "kshitij.sood@saholic.com","rajneesh.arora@saholic.com","rajveer.singh@saholic.com","vikram.raghav@saholic.com"};
573
		String text = "Item Details-\nItem Id: "+itemId+"\nProduct Name: "+item.getBrand()+" "+item.getModelName()+" "+item.getModelNumber()+" "+item.getColor()+"\nSellingPrice: "+sp+"\nMinPossibleSp: "+minSp+"\nUpdated By: "+session.getAttribute(ReportsUtils.USER_NAME).toString();
574
		logger.info(text);
575
		String emailFromAddress = "build@shop2020.in";
576
		String password = "cafe@nes";
577
		GmailUtils mailer = new GmailUtils();
578
		try {
579
			mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
580
		}
581
		catch (Exception e) {
582
			logger.info(e.toString());
583
		}
584
	}
585
 
586
	public String addNewItem() throws TException, NumberFormatException, InventoryServiceException, CatalogServiceException, JSONException{
587
		InventoryClient inventoryServiceClient = new InventoryClient();
588
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
589
		Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
590
		Item item = catalogClient.getItem(Long.valueOf(itemId));
591
		//Client catalogClientProd = new CatalogClient().getClient();
592
		MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
593
 
594
		if (mpCosting.getSource()==0){
595
			throw new CatalogServiceException();
596
		}
597
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
598
		/*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
599
			throw new InventoryServiceException();
600
		}*/
601
		FlipkartItem flipkartItem = new FlipkartItem();
602
		flipkartItem.setItem_id(Long.valueOf(itemId));
603
		flipkartItem.setWarehouseId(Long.valueOf(warehouseId));
604
		flipkartItem.setIsListedOnFlipkart(Boolean.valueOf(isListedOnFlipkart));
605
		flipkartItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
606
		flipkartItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
607
		flipkartItem.setExceptionPrice(Double.valueOf(exceptionPrice));
608
		flipkartItem.setCommissionValue(Double.valueOf(commission));
609
		flipkartItem.setServiceTaxValue(Double.valueOf(serviceTax));
610
		flipkartItem.setMaxNlc(Double.valueOf(maxNlc));
611
		flipkartItem.setSkuAtFlipkart(fkItemCode);
612
		flipkartItem.setFlipkartSerialNumber(fkSerialNumber);
613
		flipkartItem.setUpdatedBy(getUserName());
614
 
615
		MarketplaceItems mpItem = new MarketplaceItems();
616
		MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
617
		/*double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
618
		t_mpItem.setVat(vat);*/
619
		t_mpItem.setCommission(mpCosting.getCommission());
620
		t_mpItem.setServiceTax(mpCosting.getServiceTax());
621
		t_mpItem.setReturnProvision(mpCosting.getReturnProvision());
622
		t_mpItem.setEmiFee(mpCosting.getEmiFee());
623
		t_mpItem.setClosingFee(mpCosting.getClosingFee());
624
		if(!compareParameters(t_mpItem,flipkartItem,warehouse,item.getWeight())){
625
			setComparsionResult("0");
626
			return "flipkart-update-result";
627
		}
628
		else{
629
			setComparsionResult("1");
630
		}
631
		flipkartItem.setMarketplaceItems(t_mpItem);
10268 vikram.rag 632
		Long timestamp = System.currentTimeMillis();
10097 kshitij.so 633
		boolean result = catalogClient.addOrUpdateFlipkartItem(flipkartItem);
634
		if(!result){
635
			throw new CatalogServiceException();
636
		}
637
		if (t_mpItem.getCurrentSp()< t_mpItem.getMinimumPossibleSp()){
638
			sendAlert(t_mpItem.getItemId(),t_mpItem.getCurrentSp(),t_mpItem.getMinimumPossibleSp());
639
		}
10307 kshitij.so 640
		if(Boolean.valueOf(isListedOnFlipkart) && Boolean.valueOf(live) && (!Boolean.valueOf(isSuppressPriceFeed))){
10268 vikram.rag 641
			UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,timestamp);
642
			updateFlipkartPricing.start();
643
		}
10097 kshitij.so 644
		return "flipkart-update-result";
645
	}
646
 
647
 
648
	public String getAddNewItemForm(){
649
		return "flipkart-add-item";
650
	}
651
 
652
	public String getItemDetailsInJson() throws NumberFormatException, CatalogServiceException, TException, JSONException, InventoryServiceException{
653
		Client catalogClientProd = new CatalogClient().getClient();
654
		Client catalogClient =new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
655
		FlipkartItem flipkartItem = catalogClient.getFlipkartItem(Long.valueOf(itemId));
656
		MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
657
		if (flipkartItem.getItem_id()!=0){
658
			throw new CatalogServiceException();
659
		}
660
		Item item = catalogClient.getItem(Long.valueOf(itemId));
661
		if (item.getId()==0){
662
			throw new CatalogServiceException();
663
		}
664
		InventoryClient inventoryServiceClient = new InventoryClient();
665
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
666
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
667
		/*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
668
			throw new InventoryServiceException();
669
		}*/
670
		double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
671
		double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
672
		if (maxNLC==0){
673
			throw new InventoryServiceException();
674
		}
675
		itemObj = new JSONObject();
676
		itemObj.put("ItemId", item.getId());
677
		itemObj.put("Brand", item.getBrand());
678
		itemObj.put("ModelName", item.getModelName());
679
		itemObj.put("ModelNumber", item.getModelNumber());
680
		itemObj.put("Color", item.getColor());
681
		itemObj.put("Weight", item.getWeight());
682
		itemObj.put("Risky", item.isRisky());
683
		itemObj.put("Status", item.getItemStatus());
684
		itemObj.put("MRP", item.getMrp());
685
		itemObj.put("SellingPrice", item.getSellingPrice());
686
		itemObj.put("MaxNlc", maxNLC);
687
		itemObj.put("VatRate", vat);
688
		itemObj.put("CommissionRate", mpCosting.getCommission());
689
		itemObj.put("ServiceTaxRate", mpCosting.getServiceTax());
690
		itemObj.put("ReturnProvision", mpCosting.getReturnProvision());
691
		itemObj.put("EmiFee", mpCosting.getEmiFee());
692
		itemObj.put("ClosingFee", mpCosting.getClosingFee());
693
		return "item-details-json";
694
	}
695
 
696
	public String ke$ha() throws NumberFormatException, TException, JSONException, InventoryServiceException, CatalogServiceException{
697
		Client catalogClientProd = new CatalogClient().getClient();
698
		InventoryClient inventoryServiceClient = new InventoryClient();
699
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
700
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
701
		//if (warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD){
702
		double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
703
		double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
704
		itemObj = new JSONObject();
705
		itemObj.put("ItemId", itemId);
706
		itemObj.put("WarehouseId", warehouseId);
707
		itemObj.put("MaxNlc", maxNLC);
708
		itemObj.put("VatRate", vat);
709
		/*}
710
		else{
711
			itemObj = new JSONObject();
712
			throw new InventoryServiceException();
713
		}*/
714
		return "item-details-json";
715
	}
716
 
717
	public ItemInventory getItemInventory(String itemId) throws NumberFormatException, InventoryServiceException, TException{
718
		try{
719
			InventoryClient inventoryServiceClient = new InventoryClient();
720
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
721
			in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(Long.valueOf(itemId));
722
			return thriftItemInventory;
723
		}
724
		catch(Exception e){
725
			logger.error("Unable to get inventory info for item",e);
726
			return null;
727
		}
728
	}
729
 
730
 
731
 
732
	public Warehouse getWarehouse(String warehouseId,String itemId) throws NumberFormatException, TException, InventoryServiceException { 
733
		InventoryClient inventoryServiceClient = new InventoryClient();
734
		holdInventoryMap =inventoryServiceClient.getClient().getHeldInventoryMapForItem(Long.valueOf(itemId), Long.valueOf(warehouseId));
735
		return inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
736
	}
737
 
738
	public Map<Integer, Long> getHoldInventoryMapForItem(){
739
		return holdInventoryMap;
740
	}
741
 
742
	public void changeHeldForSource() throws NumberFormatException, TException, InventoryServiceException{
743
		InventoryClient inventoryServiceClient = new InventoryClient();
744
		Warehouse warehouse = inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
745
		if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
746
			throw new InventoryServiceException();
747
		}
748
		inventoryServiceClient.getClient().addUpdateHoldInventory(Long.valueOf(itemId),Long.valueOf(warehouseId),Long.valueOf(held),8);
749
	}
750
 
751
	public void downloadFlipkartListings() throws IOException, TException{
752
		File file = new File("/tmp/flipkart-bulk-upload-template.xls");
753
		HSSFWorkbook hwb=new HSSFWorkbook();
754
		HSSFSheet sheet =  hwb.createSheet("Flipkart-Listings");
755
		HSSFRow rowhead=   sheet.createRow((short)0);
756
		rowhead.createCell((short) 0).setCellValue("ITEM-ID");
10156 amar.kumar 757
		rowhead.createCell((short) 1).setCellValue("CATEGORY CODE");
758
		rowhead.createCell((short) 2).setCellValue("PRODUCT");
759
		rowhead.createCell((short) 3).setCellValue("WAREHOUSE-ID");
760
		rowhead.createCell((short) 4).setCellValue("EXCEPTIONAL-PRICE");
761
		rowhead.createCell((short) 5).setCellValue("FLIPKART-LISTED");
762
		rowhead.createCell((short) 6).setCellValue("TRANSFER-PRICE");
763
		rowhead.createCell((short) 7).setCellValue("SELLING-PRICE");
764
		rowhead.createCell((short) 8).setCellValue("LOWEST POSSIBLE SP");
765
		rowhead.createCell((short) 9).setCellValue("LOWEST POSSIBLE TP");
10184 kshitij.so 766
		rowhead.createCell((short) 10).setCellValue("MARGIN");
767
		rowhead.createCell((short) 11).setCellValue("MARGING PERCENTAGE");
768
		rowhead.createCell((short) 12).setCellValue("OTHER COST");
769
		rowhead.createCell((short) 13).setCellValue("COURIER-COST");
770
		rowhead.createCell((short) 14).setCellValue("COMMISION PERCENTAGE");
771
		rowhead.createCell((short) 15).setCellValue("COMMISION VALUE");
772
		rowhead.createCell((short) 16).setCellValue("SERVICE TAX RATE");
773
		rowhead.createCell((short) 17).setCellValue("SERVICE-TAX VALUE");
774
		rowhead.createCell((short) 18).setCellValue("VAT PERCENTAGE");
775
		rowhead.createCell((short) 19).setCellValue("Suppress Inventory Feed");
776
		rowhead.createCell((short) 20).setCellValue("Suppress Price Feed");
777
		rowhead.createCell((short) 21).setCellValue("AUTO FAVOURITE");
778
		rowhead.createCell((short) 22).setCellValue("MANUAL FAVOURITE");
779
		rowhead.createCell((short) 23).setCellValue("AUTO INCREMENT");
780
		rowhead.createCell((short) 24).setCellValue("AUTO DECREMENT");
781
		rowhead.createCell((short) 25).setCellValue("Max NLC");
782
		rowhead.createCell((short) 26).setCellValue("SKU @ Flipkart");
783
		rowhead.createCell((short) 27).setCellValue("Flipkart Serial Number");
10097 kshitij.so 784
		Client catalogClient = null;
785
		List<FlipkartItemDetails> flipkartItems = null;
786
		try {
787
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
788
			flipkartItems = catalogClient.getAllFkItems();
789
		} catch (Exception e) {
790
			e.printStackTrace();
791
		}
792
		int iterator=1;
793
		Item item;
794
		MarketplaceItems marketplaceItem;
795
		for(FlipkartItemDetails fkItem:flipkartItems){
796
			marketplaceItem = catalogClient.getMarketplacedetailsForItem(fkItem.getItem_id(), 8);
10184 kshitij.so 797
			//MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, fkItem.getItem_id());
10097 kshitij.so 798
			HSSFRow row = sheet.createRow((short)iterator);
799
			row.createCell((short) 0).setCellValue(fkItem.getItem_id());
10156 amar.kumar 800
			row.createCell((short) 1).setCellValue(fkItem.getCategory());
801
			row.createCell((short) 2).setCellValue(getVaildName(fkItem.getBrand())+" "+getVaildName(fkItem.getModel_name())+" "+getVaildName(fkItem.getModel_number())+" "+getVaildName(fkItem.getColor()));
802
			row.createCell((short) 3).setCellValue(fkItem.getWarehouseId());
803
			row.createCell((short) 4).setCellValue(roundTwoDecimals(fkItem.getExceptionPrice()));
10097 kshitij.so 804
			if(fkItem.isIsListedOnFlipkart()){
10156 amar.kumar 805
				row.createCell((short) 5).setCellValue(1);
10097 kshitij.so 806
			}
807
			else{
10156 amar.kumar 808
				row.createCell((short) 5).setCellValue(0);
10097 kshitij.so 809
			}
10156 amar.kumar 810
			row.createCell((short) 6).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentTp()));
811
			row.createCell((short) 7).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentSp()));
812
			row.createCell((short) 8).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleSp()));
813
			row.createCell((short) 9).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleTp()));
10184 kshitij.so 814
			row.createCell((short) 10).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp()))));
10186 kshitij.so 815
			row.createCell((short) 11).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp())/marketplaceItem.getMinimumPossibleSp())*100));
10184 kshitij.so 816
			row.createCell((short) 12).setCellValue(roundTwoDecimals(marketplaceItem.getOtherCost()));
817
			row.createCell((short) 13).setCellValue(marketplaceItem.getCourierCost());
818
			row.createCell((short) 14).setCellValue(roundTwoDecimals(marketplaceItem.getCommission()));
819
			row.createCell((short) 15).setCellValue(roundTwoDecimals(fkItem.getCommission()));
820
			row.createCell((short) 16).setCellValue(roundTwoDecimals(marketplaceItem.getServiceTax()));
821
			row.createCell((short) 17).setCellValue(roundTwoDecimals(fkItem.getServiceTax()));
822
			row.createCell((short) 18).setCellValue(roundTwoDecimals(marketplaceItem.getVat()));
10097 kshitij.so 823
			if(fkItem.isSuppressInventoryFeed()){
10184 kshitij.so 824
				row.createCell((short) 19).setCellValue(1);
10097 kshitij.so 825
			}
826
			else{
10184 kshitij.so 827
				row.createCell((short) 19).setCellValue(0);
10097 kshitij.so 828
			}
829
			if(fkItem.isSuppressPriceFeed()){
10184 kshitij.so 830
				row.createCell((short) 20).setCellValue(1);
10097 kshitij.so 831
			}
832
			else{
10184 kshitij.so 833
				row.createCell((short) 20).setCellValue(0);
10097 kshitij.so 834
			}
835
			if(marketplaceItem.isAutoFavourite()){
10184 kshitij.so 836
				row.createCell((short) 21).setCellValue(1);
10097 kshitij.so 837
			}
838
			else{
10184 kshitij.so 839
				row.createCell((short) 21).setCellValue(0);
10097 kshitij.so 840
			}
841
			if(marketplaceItem.isManualFavourite()){
10184 kshitij.so 842
				row.createCell((short) 22).setCellValue(1);
10097 kshitij.so 843
			}
844
			else{
10184 kshitij.so 845
				row.createCell((short) 22).setCellValue(0);
10097 kshitij.so 846
			}
847
			if(marketplaceItem.isAutoIncrement()){
10184 kshitij.so 848
				row.createCell((short) 23).setCellValue(1);
10097 kshitij.so 849
			}
850
			else{
10184 kshitij.so 851
				row.createCell((short) 23).setCellValue(0);
10097 kshitij.so 852
			}
853
			if(marketplaceItem.isAutoDecrement()){
10184 kshitij.so 854
				row.createCell((short) 24).setCellValue(1);
10097 kshitij.so 855
			}
856
			else{
10184 kshitij.so 857
				row.createCell((short) 24).setCellValue(0);
10097 kshitij.so 858
			}
10184 kshitij.so 859
			row.createCell((short) 25).setCellValue(fkItem.getMaxNlc());
860
			row.createCell((short) 26).setCellValue(fkItem.getSkuAtFlipkart());
861
			row.createCell((short) 27).setCellValue(fkItem.getFlipkartSerialNumber());
10097 kshitij.so 862
			iterator++;
863
		}
864
 
865
		FileOutputStream fileOut = null;
866
		try {
867
			fileOut = new FileOutputStream(file);
868
		} catch (FileNotFoundException e) {
869
			// TODO Auto-generated catch block
870
			e.printStackTrace();
871
		}
872
		try {
873
			hwb.write(fileOut);
874
		} catch (IOException e) {
875
			// TODO Auto-generated catch block
876
			e.printStackTrace();
877
		}
878
		try {
879
			fileOut.close();
880
		} catch (IOException e) {
881
			// TODO Auto-generated catch block
882
			e.printStackTrace();
883
		}
884
		byte[] buffer = new byte[(int)file.length()];
885
		InputStream input = null;
886
		try {
887
			int totalBytesRead = 0;
888
			input = new BufferedInputStream(new FileInputStream(file));
889
			while(totalBytesRead < buffer.length){
890
				int bytesRemaining = buffer.length - totalBytesRead;
891
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
892
				if (bytesRead > 0){
893
					totalBytesRead = totalBytesRead + bytesRead;
894
				}
895
			}
896
		}
897
		finally {
898
			input.close();
899
			file.delete();
900
		}
901
 
902
		response.setHeader("Content-Disposition", "attachment; filename=\"Flipkart-Bulk-Listings.xls\"");
903
		response.setContentType("application/octet-stream");
904
		ServletOutputStream sos;
905
		try {
906
			sos = response.getOutputStream();
907
			sos.write(buffer);
908
			sos.flush();
909
		} catch (IOException e) {
910
			System.out.println("Unable to stream the manifest file");
911
		}   
912
 
913
 
914
	}
915
 
916
 
917
	public void uploadflipkartBulkSheet() throws IOException, TException, NumberFormatException, InventoryServiceException, CatalogServiceException{
918
		File fileToCreate = new File("/tmp/", "flipkart-bulk-upload.xls");
919
		FileUtils.copyFile(this.file, fileToCreate);
920
		FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
921
		HSSFWorkbook workbook = new HSSFWorkbook(iFile);
922
		HSSFSheet sheet = workbook.getSheetAt(0);
923
		String updatedBy = getUserName();
924
		Client catalogClient=null;
925
		Client catalogClientProd=null;
926
		StringBuilder sb = new StringBuilder();
927
		try {
928
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
929
			catalogClientProd = new CatalogClient().getClient();
930
		} catch (TTransportException e) {
931
			e.printStackTrace();
932
		}
933
		InventoryClient inventoryServiceClient = new InventoryClient();
934
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
935
 
936
		for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
937
			if (sheet.getLastRowNum()-1>100){
938
				sb.append("Number of items to update can't be greater than 100");
939
				break;
940
			}
941
			FlipkartItem flipkartItem = null;
942
			MarketplaceItems marketplaceItem = null;
943
			MarketplacePercentage mpCosting = null;
944
			Warehouse warehouse = null;
945
			Item item = null;
946
			Long sku;
947
			boolean new_item = false;
948
			if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
949
				continue;
950
			}
951
			else {
952
				sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
953
				flipkartItem = catalogClient.getFlipkartItem(sku);
954
				mpCosting = catalogClient.getCostingForMarketplace(8, sku);
955
				marketplaceItem  = catalogClient.getMarketplacedetailsForItem(sku, 8);
956
				marketplaceItem.setItemId(sku);
957
				marketplaceItem.setSource(8);
958
				marketplaceItem.setCommission(mpCosting.getCommission());
959
				marketplaceItem.setServiceTax(mpCosting.getServiceTax());
960
				marketplaceItem.setReturnProvision(mpCosting.getReturnProvision());
961
				marketplaceItem.setEmiFee(mpCosting.getEmiFee());
962
				marketplaceItem.setClosingFee(mpCosting.getClosingFee());
963
 
964
				try {
965
					item = catalogClient.getItem(sku);
966
					if (item.getId()==0){
967
						sb.append(sku + " Item not valid"+"\n");
968
						continue;
969
					}
970
				} catch (CatalogServiceException e) {
971
					sb.append(sku + " Item not valid"+"\n");
972
					continue;
973
				}
974
				if(flipkartItem.getItem_id()==0){
975
					new_item = true;
976
					flipkartItem = new FlipkartItem();
977
					flipkartItem.setItem_id(sku); 
978
				}
979
			}
10111 kshitij.so 980
 
981
 
10097 kshitij.so 982
			if (checkEmptyString(sheet.getRow(iterator).getCell(1)) && new_item){
983
				sb.append(sku + " New Listing - Warehouse Id not Present"+"\n");
984
				continue;
985
			}
10111 kshitij.so 986
 
987
 
10097 kshitij.so 988
 
989
			if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
990
				/*Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
991
				if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
992
					sb.append(sku + "Not acceptable warehouse"+"\n");
993
					continue;
994
				}*/
995
				long warehouseId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
996
				double maxNLC = inventoryClient.getNlcForWarehouse(warehouseId, item.getId());
997
				if (maxNLC==0){
10114 kshitij.so 998
					sb.append(sku + " Max Nlc can't be 0"+"\n");
10097 kshitij.so 999
					continue;
1000
				}
1001
				flipkartItem.setWarehouseId(warehouseId);
1002
				flipkartItem.setMaxNlc(maxNLC);
1003
			}
1004
 
1005
			if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
1006
				double exceptionPrice = sheet.getRow(iterator).getCell(2).getNumericCellValue();
1007
				flipkartItem.setExceptionPrice(exceptionPrice);
1008
			}
1009
 
1010
			if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
1011
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==1){
1012
					flipkartItem.setIsListedOnFlipkart(true);
1013
				}
1014
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==0){
1015
					flipkartItem.setIsListedOnFlipkart(false);
1016
				}
1017
			}
1018
 
1019
			double transferPrice = 0,sellingPrice,commission,courierCost =40,serviceTax,otherCost;
1020
			if (checkEmptyString(sheet.getRow(iterator).getCell(4))&& new_item){
1021
				sb.append(sku + "New Item -  Selling Price cannot be empty"+"\n");
1022
				continue;
1023
			}
1024
			if (!checkEmptyString(sheet.getRow(iterator).getCell(4))){
1025
				sellingPrice = sheet.getRow(iterator).getCell(4).getNumericCellValue();
1026
				if(sellingPrice==0){
1027
					sb.append(sku + " Selling Price cannot be zero"+"\n");
1028
					continue;
1029
				}
1030
				marketplaceItem.setCurrentSp(sellingPrice);
1031
			}
1032
 
1033
			if (!checkEmptyString(sheet.getRow(iterator).getCell(5))){
1034
				otherCost = sheet.getRow(iterator).getCell(5).getNumericCellValue();
1035
				marketplaceItem.setOtherCost(otherCost);
1036
			}
1037
 
1038
 
1039
			if (!checkEmptyString(sheet.getRow(iterator).getCell(6))){
1040
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==1){
1041
					flipkartItem.setSuppressPriceFeed(true);
1042
				}
1043
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
1044
					flipkartItem.setSuppressPriceFeed(false);
1045
				}
1046
			}
1047
 
1048
			if (!checkEmptyString(sheet.getRow(iterator).getCell(7))){
1049
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==1){
1050
					flipkartItem.setSuppressInventoryFeed(true);
1051
				}
1052
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==0){
1053
					flipkartItem.setSuppressInventoryFeed(false);
1054
				}
1055
			}
1056
 
1057
			if (checkEmptyString(sheet.getRow(iterator).getCell(8)) && new_item){
1058
				sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1059
				continue;
1060
			}
1061
 
1062
			if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
1063
				sheet.getRow(iterator).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
1064
				String flipkartItemCode = sheet.getRow(iterator).getCell(8).getStringCellValue();
1065
				if (flipkartItemCode.length()==0 && new_item){
1066
					sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1067
					continue;
1068
				}
1069
				flipkartItem.setSkuAtFlipkart(flipkartItemCode);
1070
			}
1071
 
1072
			if (checkEmptyString(sheet.getRow(iterator).getCell(9)) && new_item){
1073
				sb.append(sku + " New Item -  Flipkart serial number cannot be empty"+"\n");
1074
				continue;
1075
			}
1076
 
1077
			if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
1078
				sheet.getRow(iterator).getCell(9).setCellType(Cell.CELL_TYPE_STRING);
1079
				String flipkartSerialNumber = sheet.getRow(iterator).getCell(9).getStringCellValue();
1080
				if (flipkartSerialNumber.length()==0 && new_item){
1081
					sb.append(sku + "  New Item -  Flipkart serial number cannot be empty"+"\n");
1082
					continue;
1083
				}
1084
				flipkartItem.setFlipkartSerialNumber(flipkartSerialNumber);
1085
			}
1086
 
1087
			double weight = item.getWeight();
1088
 
1089
 
1090
			if(weight==0){
1091
				sb.append(sku + " Please add weight"+"\n");
1092
				continue;
1093
			}
1094
			if (weight!=0){
1095
				weight = weight+.05;
1096
				int slabs = (int) ((weight - .001)/(.5));
1097
 
1098
				for(int i=0;i<slabs;i++){
1099
					courierCost = courierCost + 40;
1100
				}
1101
			}
10108 kshitij.so 1102
			warehouse = inventoryClient.getWarehouse(flipkartItem.getWarehouseId());
10097 kshitij.so 1103
			marketplaceItem.setCourierCost(courierCost);
1104
			transferPrice = roundTwoDecimals(marketplaceItem.getCurrentSp()- marketplaceItem.getCurrentSp()*(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))-(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+(marketplaceItem.getServiceTax()/100)));
1105
			marketplaceItem.setCurrentTp(transferPrice);
1106
			commission = roundTwoDecimals(((marketplaceItem.getCommission()/100)*marketplaceItem.getCurrentSp()));
1107
			flipkartItem.setCommissionValue(commission);
1108
			serviceTax = roundTwoDecimals((marketplaceItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+marketplaceItem.getCourierCost())); 
1109
			flipkartItem.setServiceTaxValue(serviceTax);
1110
			double vatRate = catalogClientProd.getVatPercentageForItem(flipkartItem.getItem_id(),warehouse.getStateId(),marketplaceItem.getCurrentSp());
1111
			marketplaceItem.setVat(vatRate);
1112
			double vat = roundTwoDecimals((marketplaceItem.getCurrentSp()/(1+(marketplaceItem.getVat()/100))-(flipkartItem.getMaxNlc()/(1+(marketplaceItem.getVat()/100))))*(marketplaceItem.getVat()/100));
1113
			double inHouseCost = roundTwoDecimals(15+vat+(marketplaceItem.getReturnProvision()/100)*marketplaceItem.getCurrentSp()+marketplaceItem.getOtherCost());
1114
			double lowest_possible_tp = roundTwoDecimals(flipkartItem.getMaxNlc()+inHouseCost);
1115
			marketplaceItem.setMinimumPossibleTp(lowest_possible_tp);
1116
			double lowest_possible_sp = roundTwoDecimals((flipkartItem.getMaxNlc()+(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+marketplaceItem.getServiceTax()/100)*(1+(marketplaceItem.getVat()/100))+(15+marketplaceItem.getOtherCost())*(1+(marketplaceItem.getVat())/100))/(1-(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))*(1+(marketplaceItem.getVat())/100)-(marketplaceItem.getReturnProvision()/100)*(1+(marketplaceItem.getVat())/100)));
1117
			marketplaceItem.setMinimumPossibleSp(lowest_possible_sp);
1118
			flipkartItem.setUpdatedBy(updatedBy);
1119
			flipkartItem.setMarketplaceItems(marketplaceItem);
1120
			if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
1121
				sb.append(sku + " Service Error\n");
1122
			}	
1123
		}
1124
		File file = new File("/tmp/flipkartbulk");
1125
		FileWriter writer = new FileWriter(file);
1126
		writer.append(sb.toString());
1127
		writer.close();
1128
		byte[] buffer = new byte[(int)file.length()];
1129
		InputStream input = null;
1130
		try {
1131
			int totalBytesRead = 0;
1132
			input = new BufferedInputStream(new FileInputStream(file));
1133
			while(totalBytesRead < buffer.length){
1134
				int bytesRemaining = buffer.length - totalBytesRead;
1135
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
1136
				if (bytesRead > 0){
1137
					totalBytesRead = totalBytesRead + bytesRead;
1138
				}
1139
			}
1140
		}
1141
		finally {
1142
			input.close();
1143
			file.delete();
1144
		}
1145
 
1146
		response.setHeader("Content-Type", "text/javascript");
1147
 
1148
		ServletOutputStream sos;
1149
		try {
1150
			sos = response.getOutputStream();
1151
			sos.write(buffer);
1152
			sos.flush();
1153
		} catch (IOException e) {
1154
			System.out.println("Unable to stream the manifest file");
1155
		}   
1156
	}
1157
 
1158
	public boolean checkEmptyString(Cell cell){
10114 kshitij.so 1159
		if (cell==null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
10097 kshitij.so 1160
			return true;
1161
		}
1162
		return false;
1163
	}
1164
 
1165
	double roundTwoDecimals(double d) {
1166
		DecimalFormat twoPlaces = new DecimalFormat("#.##");
1167
		return Double.valueOf(twoPlaces.format(d));
1168
	}
1169
 
1170
	/*String getLocation(String location){
1171
		logger.info("Inside trim"+location);
1172
		int loc = location.lastIndexOf(',');
1173
		logger.info("end result "+location.substring(loc+1));
1174
		return location.substring(loc+1);
1175
	}*/
1176
 
1177
 
1178
	public String show() {
1179
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
1180
			return "authfail";
1181
		}
1182
 
1183
		if (StringUtils.equals(id, "flipkart-list-options")){
1184
			return "flipkart-list-options";
1185
		}
1186
		if (StringUtils.equals(id, "item-table")){
1187
			return "flipkart-item-table";
1188
		}
1189
 
1190
		return "id";
1191
	}
1192
 
1193
	public void setId(String id) {
1194
		this.id = id;
1195
	}
1196
 
1197
	public String getUserName(){
1198
		return session.getAttribute(ReportsUtils.USER_NAME).toString();
1199
	}
1200
 
1201
	public HttpServletRequest getRequest() {
1202
		logger.info("set request"+request.toString());
1203
		return request;
1204
	}
1205
 
1206
	public void setRequest(HttpServletRequest request) {
1207
		this.request = request;
1208
	}
1209
 
1210
	public HttpServletResponse getResponse() {
1211
		return response;
1212
	}
1213
 
1214
	public void setResponse(HttpServletResponse response) {
1215
		this.response = response;
1216
	}
1217
 
1218
	public HttpSession getSession() {
1219
		return session;
1220
	}
1221
 
1222
	public void setSession(HttpSession session) {
1223
		this.session = session;
1224
	}
1225
 
1226
	public ServletContext getContext() {
1227
		return context;
1228
	}
1229
 
1230
	public void setContext(ServletContext context) {
1231
		this.context = context;
1232
	}
1233
 
1234
	public String getUrl() {
1235
		return url;
1236
	}
1237
 
1238
	public void setUrl(String url) {
1239
		this.url = url;
1240
	}
1241
 
1242
	public String getItemId() {
1243
		return itemId;
1244
	}
1245
 
1246
	public void setItemId(String itemId) {
1247
		this.itemId = itemId;
1248
	}
1249
 
1250
	public String getExceptionPrice() {
1251
		return exceptionPrice;
1252
	}
1253
 
1254
	public void setExceptionPrice(String exceptionPrice) {
1255
		this.exceptionPrice = exceptionPrice;
1256
	}
1257
 
1258
	public String getWarehouseId() {
1259
		return warehouseId;
1260
	}
1261
 
1262
	public void setWarehouseId(String warehouseId) {
1263
		this.warehouseId = warehouseId;
1264
	}
1265
 
1266
	public File getFile() {
1267
		return file;
1268
	}
1269
 
1270
	public void setFile(File file) {
1271
		this.file = file;
1272
	}
1273
 
1274
	public String getErrMsg() {
1275
		return errMsg;
1276
	}
1277
 
1278
	public void setErrMsg(String errMsg) {
1279
		this.errMsg = errMsg;
1280
	}
1281
 
1282
	public String getNext() {
1283
		return next;
1284
	}
1285
 
1286
	public void setNext(String next) {
1287
		this.next = next;
1288
	}
1289
 
1290
	public String getId() {
1291
		return id;
1292
	}
1293
 
1294
	public void setServletRequest(HttpServletRequest req) {
1295
		this.request = req;
1296
		this.session = req.getSession();        
1297
	}
1298
 
1299
	public void setServletContext(ServletContext arg0) {
1300
		// TODO Auto-generated method stub
1301
 
1302
	}
1303
 
1304
	public void setServletResponse(HttpServletResponse response) {
1305
		this.response = response;
1306
	}
1307
 
1308
	public void setSearchText(String searchText) {
1309
		this.searchText = searchText;
1310
	}
1311
 
1312
	public String getSearchText() {
1313
		return searchText;
1314
	}
1315
 
1316
	public long getSearchCount() {
1317
		return searchCount;
1318
	}
1319
 
1320
	public long getTotalCount() {
1321
		return totalCount;
1322
	}
1323
 
1324
	public void setSearchCount(long count) {
1325
		this.searchCount = count;
1326
	}
1327
 
1328
	public List<FlipkartItemDetails> getFlipkartItems(){
1329
		return flipkartItems;
1330
	}
1331
 
1332
	public void setSellingPrice(String sellingPrice) {
1333
		this.sellingPrice = sellingPrice;
1334
	}
1335
 
1336
	public String getSellingPrice() {
1337
		return sellingPrice;
1338
	}
1339
 
1340
	public void setTransferPrice(String transferPrice) {
1341
		this.transferPrice = transferPrice;
1342
	}
1343
 
1344
	public String getTransferPrice() {
1345
		return transferPrice;
1346
	}
1347
 
1348
	public void setWebisteMrp(String webisteMrp) {
1349
		this.webisteMrp = webisteMrp;
1350
	}
1351
 
1352
	public String getWebisteMrp() {
1353
		return webisteMrp;
1354
	}
1355
 
1356
	public void setWebisteSellingPrice(String webisteSellingPrice) {
1357
		this.webisteSellingPrice = webisteSellingPrice;
1358
	}
1359
 
1360
	public String getWebisteSellingPrice() {
1361
		return webisteSellingPrice;
1362
	}
1363
 
1364
	public void setIsListedOnFlipkart(String isListedOnFlipkart) {
1365
		this.isListedOnFlipkart = isListedOnFlipkart;
1366
	}
1367
 
1368
	public String getIsSuppressInventoryFeed() {
1369
		return isSuppressInventoryFeed;
1370
	}
1371
 
1372
	public void setIsSuppressInventoryFeed(String isSuppressInventoryFeed) {
1373
		this.isSuppressInventoryFeed = isSuppressInventoryFeed;
1374
	}
1375
 
1376
	public String getIsSuppressPriceFeed() {
1377
		return isSuppressPriceFeed;
1378
	}
1379
 
1380
	public void setIsSuppressPriceFeed(String isSuppressPriceFeed) {
1381
		this.isSuppressPriceFeed = isSuppressPriceFeed;
1382
	}
1383
 
1384
	public String getIsListedOnFlipkart() {
1385
		return isListedOnFlipkart;
1386
	}
1387
 
1388
	public void setCommission(String commission) {
1389
		this.commission = commission;
1390
	}
1391
 
1392
	public String getCommission() {
1393
		return commission;
1394
	}
1395
 
1396
	public void setServiceTax(String serviceTax) {
1397
		this.serviceTax = serviceTax;
1398
	}
1399
 
1400
	public String getServiceTax() {
1401
		return serviceTax;
1402
	}
1403
 
1404
	public void setCourierCost(String courierCost) {
1405
		this.courierCost = courierCost;
1406
	}
1407
 
1408
	public String getCourierCost() {
1409
		return courierCost;
1410
	}
1411
 
1412
	public void setMaxNlc(String maxNlc) {
1413
		this.maxNlc = maxNlc;
1414
	}
1415
 
1416
	public String getMaxNlc() {
1417
		return maxNlc;
1418
	}
1419
 
1420
	public String getItemDetails(){
1421
		return itemObj.toString();
1422
	}
1423
 
1424
	public double getRoundOfValue(String val){
1425
		return roundTwoDecimals(Double.valueOf(val));
1426
	}
1427
 
1428
	public String getVaildName(String name){
1429
		return name!=null?name:"";
1430
	}
1431
 
1432
 
1433
 
1434
}