Subversion Repositories SmartDukaan

Rev

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