Subversion Repositories SmartDukaan

Rev

Rev 10307 | Rev 12327 | 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
	}
12323 kshitij.so 433
 
434
	public void updateForAutoPricing() throws NumberFormatException, CatalogServiceException, TException{
435
        logger.info("Calling Method to update price at snapdeal for auto pricing");
436
        Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
437
        Item item = catalogClient.getItem(Long.valueOf(itemId));
438
        UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,System.currentTimeMillis());
439
        updateFlipkartPricing.start();
440
    }
10097 kshitij.so 441
 
442
 
12323 kshitij.so 443
 
10097 kshitij.so 444
	public boolean compareParameters(MarketplaceItems mpItem, FlipkartItem flipkartItem, Warehouse warehouse,double weight) throws TException, JSONException, CatalogServiceException{
445
		double nlc =getNlcForWarehouse(flipkartItem.getWarehouseId(),flipkartItem.getItem_id());
446
		double vat = (mpItem.getCurrentSp()/(1+(mpItem.getVat()/100))-(nlc/(1+(mpItem.getVat()/100))))*(mpItem.getVat()/100);
447
		double inHouseCost = 15+vat+(mpItem.getReturnProvision()/100)*mpItem.getCurrentSp()+mpItem.getOtherCost();
448
		double lowest_possible_tp = nlc+inHouseCost;
449
		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));
450
		double commission =  ((mpItem.getCommission()/100)*mpItem.getCurrentSp());
451
		double service_tax = (mpItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+mpItem.getCourierCost());
452
		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));
453
		double vat_rate_prod = getVatRateForItem(warehouse,mpItem.getCurrentSp(),flipkartItem.getItem_id());
454
		JSONObject x = new JSONObject();
455
		x.put("NLC", nlc);
456
		x.put("VAT", vat);
457
		x.put("COURIER COST",getCourierCost(weight));
458
		x.put("LOWEST POS TP", lowest_possible_tp);
459
		x.put("TP", our_tp);
460
		x.put("COMMISSION", commission);
461
		x.put("SERVICE TAX", service_tax);
462
		x.put("LOWEST POS SP", lowest_possible_sp);
463
		x.put("VAT RATE",vat_rate_prod);
464
		logger.info("Flipkart Backend validation "+x.toString());
465
		boolean compare_result=true;
466
 
467
		if(!(getCourierCost(weight)==mpItem.getCourierCost())){
468
			compare_result=false;
469
		}
470
 
471
		if(!(vat_rate_prod==mpItem.getVat())){
472
			compare_result=false;
473
		}
474
 
475
		if(!(nlc==flipkartItem.getMaxNlc())){
476
			compare_result=false;
477
		}
478
		if(!(lowest_possible_tp-mpItem.getMinimumPossibleTp()>-1 && lowest_possible_tp-mpItem.getMinimumPossibleTp()<1)){
479
			compare_result=false;
480
		}
481
		if(!(our_tp-mpItem.getCurrentTp()>-1 && our_tp-mpItem.getCurrentTp()<1)){
482
			compare_result=false;
483
		}
484
		if(!(commission-flipkartItem.getCommissionValue()>-1 && commission-flipkartItem.getCommissionValue()<1)){
485
			compare_result=false;
486
		}
487
		if(!(service_tax-flipkartItem.getServiceTaxValue()>-1 && service_tax-flipkartItem.getServiceTaxValue()<1)){
488
			compare_result=false;
489
		}
490
		if(!(lowest_possible_sp-mpItem.getMinimumPossibleSp()>-1 && lowest_possible_sp-mpItem.getMinimumPossibleSp()<1)){
491
			compare_result=false;
492
		}
493
		return compare_result;
494
 
495
	}
496
 
497
	public double getVatRateForItem(Warehouse warehouse, double sellingPrice,long itemId) throws CatalogServiceException, TException{
498
		Client catalogClientProd = new CatalogClient().getClient();
499
		return catalogClientProd.getVatPercentageForItem(itemId, warehouse.getStateId(), sellingPrice);
500
	}
501
 
502
	public double getNlcForWarehouse(long warehouseId,long item_id) throws TException{
503
		InventoryClient inventoryServiceClient = new InventoryClient();
504
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
505
		return inventoryClient.getNlcForWarehouse(warehouseId, item_id);
506
	}
507
 
508
	public double getCourierCost(double weight){
509
		double cCost = 40.0;
510
		int slabs = (int) ((weight+.05 - .001)/(.5));
511
		for(int i=0;i<slabs;i++){
512
			cCost = cCost + 40;
513
		}
514
		return cCost;
515
	}
516
 
517
	public void getLastNDaySaleForItem(String itemId,String days) {
518
		try{
519
			InventoryClient inventoryServiceClient = new InventoryClient();
520
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
521
			List<OOSStatus> oosStatuses = inventoryClient.getOosStatusesForXDaysForItem(Long.valueOf(itemId), 8, Integer.valueOf(days));
522
			String lastNdaySale="";
523
			double avgSale = 0.0;
524
			long count = 0,sale = 0;
525
			for(OOSStatus oosStatus : oosStatuses){
526
				if(oosStatus.isIs_oos()){
527
					lastNdaySale += "X-";
528
				}else{
529
					lastNdaySale += oosStatus.getNum_orders() + "-";
530
					sale = sale + oosStatus.getNum_orders();
531
					count+=1;
532
				}
533
			}
534
			lastNdaySale = lastNdaySale.substring(0, lastNdaySale.length()-1);
535
			lastNdaySale += "\n";
536
			setnDaySale(lastNdaySale);
537
			if (count!=0){
538
				setAvgSale(String.valueOf(roundTwoDecimals(sale/(double)count)));
539
			}
540
			else{
541
				setAvgSale("0");
542
			}
543
		}
544
		catch (Exception e){
545
			setAvgSale("0");
546
			setnDaySale("Unable to fetch");
547
			logger.error("Unable to get last n day sale",e);
548
		}
549
 
550
	}
551
 
552
 
553
	private MarketplaceItems updateMarketplaceItemDetails(MarketplaceItems mpItem){
554
		mpItem.setItemId(Long.valueOf(itemId));
555
		mpItem.setSource(8);
556
		mpItem.setVat(Double.valueOf(vat));
557
		mpItem.setCourierCost(Double.valueOf(courierCost));
558
		mpItem.setOtherCost(Double.valueOf(otherCost));
559
		mpItem.setCurrentSp(Double.valueOf(sellingPrice));
560
		mpItem.setCurrentTp(Double.valueOf(transferPrice));
561
		mpItem.setAutoDecrement(Boolean.valueOf(isAutoDecrement));
562
		mpItem.setAutoIncrement(Boolean.valueOf(isAutoIncrement));
563
		mpItem.setManualFavourite(Boolean.valueOf(isManualFavourite));
564
		mpItem.setMinimumPossibleSp(Double.valueOf(minPosSp));
565
		mpItem.setMinimumPossibleTp(Double.valueOf(minPosTp));
566
		mpItem.setMaximumSellingPrice(Double.valueOf(maxSp));
567
		return mpItem;
568
	}
569
 
570
	private void sendAlert(long itemId,double sp,double minSp){
571
		Item item;
572
		try{
573
			Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
574
			item= catalogClient.getItem(itemId);
575
		}
576
		catch(Exception e){
577
			e.printStackTrace();
578
			return;
579
		}
580
		String emailSubjectTxt="Flipkart SP is set below Min Possible SP";
581
		String[] sendTo=new String[]{ "kshitij.sood@saholic.com","rajneesh.arora@saholic.com","rajveer.singh@saholic.com","vikram.raghav@saholic.com"};
582
		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();
583
		logger.info(text);
584
		String emailFromAddress = "build@shop2020.in";
585
		String password = "cafe@nes";
586
		GmailUtils mailer = new GmailUtils();
587
		try {
588
			mailer.sendSSLMessage(sendTo, emailSubjectTxt, text, emailFromAddress, password, new ArrayList<File>());
589
		}
590
		catch (Exception e) {
591
			logger.info(e.toString());
592
		}
593
	}
594
 
595
	public String addNewItem() throws TException, NumberFormatException, InventoryServiceException, CatalogServiceException, JSONException{
596
		InventoryClient inventoryServiceClient = new InventoryClient();
597
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
598
		Client catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
599
		Item item = catalogClient.getItem(Long.valueOf(itemId));
600
		//Client catalogClientProd = new CatalogClient().getClient();
601
		MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
602
 
603
		if (mpCosting.getSource()==0){
604
			throw new CatalogServiceException();
605
		}
606
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
607
		/*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
608
			throw new InventoryServiceException();
609
		}*/
610
		FlipkartItem flipkartItem = new FlipkartItem();
611
		flipkartItem.setItem_id(Long.valueOf(itemId));
612
		flipkartItem.setWarehouseId(Long.valueOf(warehouseId));
613
		flipkartItem.setIsListedOnFlipkart(Boolean.valueOf(isListedOnFlipkart));
614
		flipkartItem.setSuppressInventoryFeed(Boolean.valueOf(isSuppressInventoryFeed));
615
		flipkartItem.setSuppressPriceFeed(Boolean.valueOf(isSuppressPriceFeed));
616
		flipkartItem.setExceptionPrice(Double.valueOf(exceptionPrice));
617
		flipkartItem.setCommissionValue(Double.valueOf(commission));
618
		flipkartItem.setServiceTaxValue(Double.valueOf(serviceTax));
619
		flipkartItem.setMaxNlc(Double.valueOf(maxNlc));
620
		flipkartItem.setSkuAtFlipkart(fkItemCode);
621
		flipkartItem.setFlipkartSerialNumber(fkSerialNumber);
622
		flipkartItem.setUpdatedBy(getUserName());
623
 
624
		MarketplaceItems mpItem = new MarketplaceItems();
625
		MarketplaceItems t_mpItem = updateMarketplaceItemDetails(mpItem);
626
		/*double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
627
		t_mpItem.setVat(vat);*/
628
		t_mpItem.setCommission(mpCosting.getCommission());
629
		t_mpItem.setServiceTax(mpCosting.getServiceTax());
630
		t_mpItem.setReturnProvision(mpCosting.getReturnProvision());
631
		t_mpItem.setEmiFee(mpCosting.getEmiFee());
632
		t_mpItem.setClosingFee(mpCosting.getClosingFee());
633
		if(!compareParameters(t_mpItem,flipkartItem,warehouse,item.getWeight())){
634
			setComparsionResult("0");
635
			return "flipkart-update-result";
636
		}
637
		else{
638
			setComparsionResult("1");
639
		}
640
		flipkartItem.setMarketplaceItems(t_mpItem);
10268 vikram.rag 641
		Long timestamp = System.currentTimeMillis();
10097 kshitij.so 642
		boolean result = catalogClient.addOrUpdateFlipkartItem(flipkartItem);
643
		if(!result){
644
			throw new CatalogServiceException();
645
		}
646
		if (t_mpItem.getCurrentSp()< t_mpItem.getMinimumPossibleSp()){
647
			sendAlert(t_mpItem.getItemId(),t_mpItem.getCurrentSp(),t_mpItem.getMinimumPossibleSp());
648
		}
10307 kshitij.so 649
		if(Boolean.valueOf(isListedOnFlipkart) && Boolean.valueOf(live) && (!Boolean.valueOf(isSuppressPriceFeed))){
10268 vikram.rag 650
			UpdateFlipkartPricing updateFlipkartPricing = new UpdateFlipkartPricing(Float.valueOf(sellingPrice),fkItemCode,item,timestamp);
651
			updateFlipkartPricing.start();
652
		}
10097 kshitij.so 653
		return "flipkart-update-result";
654
	}
655
 
656
 
657
	public String getAddNewItemForm(){
658
		return "flipkart-add-item";
659
	}
660
 
661
	public String getItemDetailsInJson() throws NumberFormatException, CatalogServiceException, TException, JSONException, InventoryServiceException{
662
		Client catalogClientProd = new CatalogClient().getClient();
663
		Client catalogClient =new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
664
		FlipkartItem flipkartItem = catalogClient.getFlipkartItem(Long.valueOf(itemId));
665
		MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, Long.valueOf(itemId));
666
		if (flipkartItem.getItem_id()!=0){
667
			throw new CatalogServiceException();
668
		}
669
		Item item = catalogClient.getItem(Long.valueOf(itemId));
670
		if (item.getId()==0){
671
			throw new CatalogServiceException();
672
		}
673
		InventoryClient inventoryServiceClient = new InventoryClient();
674
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
675
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
676
		/*if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
677
			throw new InventoryServiceException();
678
		}*/
679
		double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
680
		double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
681
		if (maxNLC==0){
682
			throw new InventoryServiceException();
683
		}
684
		itemObj = new JSONObject();
685
		itemObj.put("ItemId", item.getId());
686
		itemObj.put("Brand", item.getBrand());
687
		itemObj.put("ModelName", item.getModelName());
688
		itemObj.put("ModelNumber", item.getModelNumber());
689
		itemObj.put("Color", item.getColor());
690
		itemObj.put("Weight", item.getWeight());
691
		itemObj.put("Risky", item.isRisky());
692
		itemObj.put("Status", item.getItemStatus());
693
		itemObj.put("MRP", item.getMrp());
694
		itemObj.put("SellingPrice", item.getSellingPrice());
695
		itemObj.put("MaxNlc", maxNLC);
696
		itemObj.put("VatRate", vat);
697
		itemObj.put("CommissionRate", mpCosting.getCommission());
698
		itemObj.put("ServiceTaxRate", mpCosting.getServiceTax());
699
		itemObj.put("ReturnProvision", mpCosting.getReturnProvision());
700
		itemObj.put("EmiFee", mpCosting.getEmiFee());
701
		itemObj.put("ClosingFee", mpCosting.getClosingFee());
702
		return "item-details-json";
703
	}
704
 
705
	public String ke$ha() throws NumberFormatException, TException, JSONException, InventoryServiceException, CatalogServiceException{
706
		Client catalogClientProd = new CatalogClient().getClient();
707
		InventoryClient inventoryServiceClient = new InventoryClient();
708
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
709
		Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
710
		//if (warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD){
711
		double maxNLC = inventoryClient.getNlcForWarehouse(Long.valueOf(warehouseId), Long.valueOf(itemId));
712
		double vat = catalogClientProd.getVatPercentageForItem(Long.valueOf(itemId), warehouse.getStateId(), Double.valueOf(sellingPrice));
713
		itemObj = new JSONObject();
714
		itemObj.put("ItemId", itemId);
715
		itemObj.put("WarehouseId", warehouseId);
716
		itemObj.put("MaxNlc", maxNLC);
717
		itemObj.put("VatRate", vat);
718
		/*}
719
		else{
720
			itemObj = new JSONObject();
721
			throw new InventoryServiceException();
722
		}*/
723
		return "item-details-json";
724
	}
725
 
726
	public ItemInventory getItemInventory(String itemId) throws NumberFormatException, InventoryServiceException, TException{
727
		try{
728
			InventoryClient inventoryServiceClient = new InventoryClient();
729
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
730
			in.shop2020.model.v1.inventory.ItemInventory thriftItemInventory = inventoryClient.getItemInventoryByItemId(Long.valueOf(itemId));
731
			return thriftItemInventory;
732
		}
733
		catch(Exception e){
734
			logger.error("Unable to get inventory info for item",e);
735
			return null;
736
		}
737
	}
738
 
739
 
740
 
741
	public Warehouse getWarehouse(String warehouseId,String itemId) throws NumberFormatException, TException, InventoryServiceException { 
742
		InventoryClient inventoryServiceClient = new InventoryClient();
743
		holdInventoryMap =inventoryServiceClient.getClient().getHeldInventoryMapForItem(Long.valueOf(itemId), Long.valueOf(warehouseId));
744
		return inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
745
	}
746
 
747
	public Map<Integer, Long> getHoldInventoryMapForItem(){
748
		return holdInventoryMap;
749
	}
750
 
751
	public void changeHeldForSource() throws NumberFormatException, TException, InventoryServiceException{
752
		InventoryClient inventoryServiceClient = new InventoryClient();
753
		Warehouse warehouse = inventoryServiceClient.getClient().getWarehouse(Long.valueOf(warehouseId));
754
		if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
755
			throw new InventoryServiceException();
756
		}
757
		inventoryServiceClient.getClient().addUpdateHoldInventory(Long.valueOf(itemId),Long.valueOf(warehouseId),Long.valueOf(held),8);
758
	}
759
 
760
	public void downloadFlipkartListings() throws IOException, TException{
761
		File file = new File("/tmp/flipkart-bulk-upload-template.xls");
762
		HSSFWorkbook hwb=new HSSFWorkbook();
763
		HSSFSheet sheet =  hwb.createSheet("Flipkart-Listings");
764
		HSSFRow rowhead=   sheet.createRow((short)0);
765
		rowhead.createCell((short) 0).setCellValue("ITEM-ID");
10156 amar.kumar 766
		rowhead.createCell((short) 1).setCellValue("CATEGORY CODE");
767
		rowhead.createCell((short) 2).setCellValue("PRODUCT");
768
		rowhead.createCell((short) 3).setCellValue("WAREHOUSE-ID");
769
		rowhead.createCell((short) 4).setCellValue("EXCEPTIONAL-PRICE");
770
		rowhead.createCell((short) 5).setCellValue("FLIPKART-LISTED");
771
		rowhead.createCell((short) 6).setCellValue("TRANSFER-PRICE");
772
		rowhead.createCell((short) 7).setCellValue("SELLING-PRICE");
773
		rowhead.createCell((short) 8).setCellValue("LOWEST POSSIBLE SP");
774
		rowhead.createCell((short) 9).setCellValue("LOWEST POSSIBLE TP");
10184 kshitij.so 775
		rowhead.createCell((short) 10).setCellValue("MARGIN");
776
		rowhead.createCell((short) 11).setCellValue("MARGING PERCENTAGE");
777
		rowhead.createCell((short) 12).setCellValue("OTHER COST");
778
		rowhead.createCell((short) 13).setCellValue("COURIER-COST");
779
		rowhead.createCell((short) 14).setCellValue("COMMISION PERCENTAGE");
780
		rowhead.createCell((short) 15).setCellValue("COMMISION VALUE");
781
		rowhead.createCell((short) 16).setCellValue("SERVICE TAX RATE");
782
		rowhead.createCell((short) 17).setCellValue("SERVICE-TAX VALUE");
783
		rowhead.createCell((short) 18).setCellValue("VAT PERCENTAGE");
784
		rowhead.createCell((short) 19).setCellValue("Suppress Inventory Feed");
785
		rowhead.createCell((short) 20).setCellValue("Suppress Price Feed");
786
		rowhead.createCell((short) 21).setCellValue("AUTO FAVOURITE");
787
		rowhead.createCell((short) 22).setCellValue("MANUAL FAVOURITE");
788
		rowhead.createCell((short) 23).setCellValue("AUTO INCREMENT");
789
		rowhead.createCell((short) 24).setCellValue("AUTO DECREMENT");
790
		rowhead.createCell((short) 25).setCellValue("Max NLC");
791
		rowhead.createCell((short) 26).setCellValue("SKU @ Flipkart");
792
		rowhead.createCell((short) 27).setCellValue("Flipkart Serial Number");
10097 kshitij.so 793
		Client catalogClient = null;
794
		List<FlipkartItemDetails> flipkartItems = null;
795
		try {
796
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
797
			flipkartItems = catalogClient.getAllFkItems();
798
		} catch (Exception e) {
799
			e.printStackTrace();
800
		}
801
		int iterator=1;
802
		Item item;
803
		MarketplaceItems marketplaceItem;
804
		for(FlipkartItemDetails fkItem:flipkartItems){
805
			marketplaceItem = catalogClient.getMarketplacedetailsForItem(fkItem.getItem_id(), 8);
10184 kshitij.so 806
			//MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, fkItem.getItem_id());
10097 kshitij.so 807
			HSSFRow row = sheet.createRow((short)iterator);
808
			row.createCell((short) 0).setCellValue(fkItem.getItem_id());
10156 amar.kumar 809
			row.createCell((short) 1).setCellValue(fkItem.getCategory());
810
			row.createCell((short) 2).setCellValue(getVaildName(fkItem.getBrand())+" "+getVaildName(fkItem.getModel_name())+" "+getVaildName(fkItem.getModel_number())+" "+getVaildName(fkItem.getColor()));
811
			row.createCell((short) 3).setCellValue(fkItem.getWarehouseId());
812
			row.createCell((short) 4).setCellValue(roundTwoDecimals(fkItem.getExceptionPrice()));
10097 kshitij.so 813
			if(fkItem.isIsListedOnFlipkart()){
10156 amar.kumar 814
				row.createCell((short) 5).setCellValue(1);
10097 kshitij.so 815
			}
816
			else{
10156 amar.kumar 817
				row.createCell((short) 5).setCellValue(0);
10097 kshitij.so 818
			}
10156 amar.kumar 819
			row.createCell((short) 6).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentTp()));
820
			row.createCell((short) 7).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentSp()));
821
			row.createCell((short) 8).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleSp()));
822
			row.createCell((short) 9).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleTp()));
10184 kshitij.so 823
			row.createCell((short) 10).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp()))));
10186 kshitij.so 824
			row.createCell((short) 11).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp())/marketplaceItem.getMinimumPossibleSp())*100));
10184 kshitij.so 825
			row.createCell((short) 12).setCellValue(roundTwoDecimals(marketplaceItem.getOtherCost()));
826
			row.createCell((short) 13).setCellValue(marketplaceItem.getCourierCost());
827
			row.createCell((short) 14).setCellValue(roundTwoDecimals(marketplaceItem.getCommission()));
828
			row.createCell((short) 15).setCellValue(roundTwoDecimals(fkItem.getCommission()));
829
			row.createCell((short) 16).setCellValue(roundTwoDecimals(marketplaceItem.getServiceTax()));
830
			row.createCell((short) 17).setCellValue(roundTwoDecimals(fkItem.getServiceTax()));
831
			row.createCell((short) 18).setCellValue(roundTwoDecimals(marketplaceItem.getVat()));
10097 kshitij.so 832
			if(fkItem.isSuppressInventoryFeed()){
10184 kshitij.so 833
				row.createCell((short) 19).setCellValue(1);
10097 kshitij.so 834
			}
835
			else{
10184 kshitij.so 836
				row.createCell((short) 19).setCellValue(0);
10097 kshitij.so 837
			}
838
			if(fkItem.isSuppressPriceFeed()){
10184 kshitij.so 839
				row.createCell((short) 20).setCellValue(1);
10097 kshitij.so 840
			}
841
			else{
10184 kshitij.so 842
				row.createCell((short) 20).setCellValue(0);
10097 kshitij.so 843
			}
844
			if(marketplaceItem.isAutoFavourite()){
10184 kshitij.so 845
				row.createCell((short) 21).setCellValue(1);
10097 kshitij.so 846
			}
847
			else{
10184 kshitij.so 848
				row.createCell((short) 21).setCellValue(0);
10097 kshitij.so 849
			}
850
			if(marketplaceItem.isManualFavourite()){
10184 kshitij.so 851
				row.createCell((short) 22).setCellValue(1);
10097 kshitij.so 852
			}
853
			else{
10184 kshitij.so 854
				row.createCell((short) 22).setCellValue(0);
10097 kshitij.so 855
			}
856
			if(marketplaceItem.isAutoIncrement()){
10184 kshitij.so 857
				row.createCell((short) 23).setCellValue(1);
10097 kshitij.so 858
			}
859
			else{
10184 kshitij.so 860
				row.createCell((short) 23).setCellValue(0);
10097 kshitij.so 861
			}
862
			if(marketplaceItem.isAutoDecrement()){
10184 kshitij.so 863
				row.createCell((short) 24).setCellValue(1);
10097 kshitij.so 864
			}
865
			else{
10184 kshitij.so 866
				row.createCell((short) 24).setCellValue(0);
10097 kshitij.so 867
			}
10184 kshitij.so 868
			row.createCell((short) 25).setCellValue(fkItem.getMaxNlc());
869
			row.createCell((short) 26).setCellValue(fkItem.getSkuAtFlipkart());
870
			row.createCell((short) 27).setCellValue(fkItem.getFlipkartSerialNumber());
10097 kshitij.so 871
			iterator++;
872
		}
873
 
874
		FileOutputStream fileOut = null;
875
		try {
876
			fileOut = new FileOutputStream(file);
877
		} catch (FileNotFoundException e) {
878
			// TODO Auto-generated catch block
879
			e.printStackTrace();
880
		}
881
		try {
882
			hwb.write(fileOut);
883
		} catch (IOException e) {
884
			// TODO Auto-generated catch block
885
			e.printStackTrace();
886
		}
887
		try {
888
			fileOut.close();
889
		} catch (IOException e) {
890
			// TODO Auto-generated catch block
891
			e.printStackTrace();
892
		}
893
		byte[] buffer = new byte[(int)file.length()];
894
		InputStream input = null;
895
		try {
896
			int totalBytesRead = 0;
897
			input = new BufferedInputStream(new FileInputStream(file));
898
			while(totalBytesRead < buffer.length){
899
				int bytesRemaining = buffer.length - totalBytesRead;
900
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
901
				if (bytesRead > 0){
902
					totalBytesRead = totalBytesRead + bytesRead;
903
				}
904
			}
905
		}
906
		finally {
907
			input.close();
908
			file.delete();
909
		}
910
 
911
		response.setHeader("Content-Disposition", "attachment; filename=\"Flipkart-Bulk-Listings.xls\"");
912
		response.setContentType("application/octet-stream");
913
		ServletOutputStream sos;
914
		try {
915
			sos = response.getOutputStream();
916
			sos.write(buffer);
917
			sos.flush();
918
		} catch (IOException e) {
919
			System.out.println("Unable to stream the manifest file");
920
		}   
921
 
922
 
923
	}
924
 
925
 
926
	public void uploadflipkartBulkSheet() throws IOException, TException, NumberFormatException, InventoryServiceException, CatalogServiceException{
927
		File fileToCreate = new File("/tmp/", "flipkart-bulk-upload.xls");
928
		FileUtils.copyFile(this.file, fileToCreate);
929
		FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
930
		HSSFWorkbook workbook = new HSSFWorkbook(iFile);
931
		HSSFSheet sheet = workbook.getSheetAt(0);
932
		String updatedBy = getUserName();
933
		Client catalogClient=null;
934
		Client catalogClientProd=null;
935
		StringBuilder sb = new StringBuilder();
936
		try {
937
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
938
			catalogClientProd = new CatalogClient().getClient();
939
		} catch (TTransportException e) {
940
			e.printStackTrace();
941
		}
942
		InventoryClient inventoryServiceClient = new InventoryClient();
943
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
944
 
945
		for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
946
			if (sheet.getLastRowNum()-1>100){
947
				sb.append("Number of items to update can't be greater than 100");
948
				break;
949
			}
950
			FlipkartItem flipkartItem = null;
951
			MarketplaceItems marketplaceItem = null;
952
			MarketplacePercentage mpCosting = null;
953
			Warehouse warehouse = null;
954
			Item item = null;
955
			Long sku;
956
			boolean new_item = false;
957
			if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
958
				continue;
959
			}
960
			else {
961
				sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
962
				flipkartItem = catalogClient.getFlipkartItem(sku);
963
				mpCosting = catalogClient.getCostingForMarketplace(8, sku);
964
				marketplaceItem  = catalogClient.getMarketplacedetailsForItem(sku, 8);
965
				marketplaceItem.setItemId(sku);
966
				marketplaceItem.setSource(8);
967
				marketplaceItem.setCommission(mpCosting.getCommission());
968
				marketplaceItem.setServiceTax(mpCosting.getServiceTax());
969
				marketplaceItem.setReturnProvision(mpCosting.getReturnProvision());
970
				marketplaceItem.setEmiFee(mpCosting.getEmiFee());
971
				marketplaceItem.setClosingFee(mpCosting.getClosingFee());
972
 
973
				try {
974
					item = catalogClient.getItem(sku);
975
					if (item.getId()==0){
976
						sb.append(sku + " Item not valid"+"\n");
977
						continue;
978
					}
979
				} catch (CatalogServiceException e) {
980
					sb.append(sku + " Item not valid"+"\n");
981
					continue;
982
				}
983
				if(flipkartItem.getItem_id()==0){
984
					new_item = true;
985
					flipkartItem = new FlipkartItem();
986
					flipkartItem.setItem_id(sku); 
987
				}
988
			}
10111 kshitij.so 989
 
990
 
10097 kshitij.so 991
			if (checkEmptyString(sheet.getRow(iterator).getCell(1)) && new_item){
992
				sb.append(sku + " New Listing - Warehouse Id not Present"+"\n");
993
				continue;
994
			}
10111 kshitij.so 995
 
996
 
10097 kshitij.so 997
 
998
			if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
999
				/*Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
1000
				if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
1001
					sb.append(sku + "Not acceptable warehouse"+"\n");
1002
					continue;
1003
				}*/
1004
				long warehouseId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
1005
				double maxNLC = inventoryClient.getNlcForWarehouse(warehouseId, item.getId());
1006
				if (maxNLC==0){
10114 kshitij.so 1007
					sb.append(sku + " Max Nlc can't be 0"+"\n");
10097 kshitij.so 1008
					continue;
1009
				}
1010
				flipkartItem.setWarehouseId(warehouseId);
1011
				flipkartItem.setMaxNlc(maxNLC);
1012
			}
1013
 
1014
			if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
1015
				double exceptionPrice = sheet.getRow(iterator).getCell(2).getNumericCellValue();
1016
				flipkartItem.setExceptionPrice(exceptionPrice);
1017
			}
1018
 
1019
			if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
1020
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==1){
1021
					flipkartItem.setIsListedOnFlipkart(true);
1022
				}
1023
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==0){
1024
					flipkartItem.setIsListedOnFlipkart(false);
1025
				}
1026
			}
1027
 
1028
			double transferPrice = 0,sellingPrice,commission,courierCost =40,serviceTax,otherCost;
1029
			if (checkEmptyString(sheet.getRow(iterator).getCell(4))&& new_item){
1030
				sb.append(sku + "New Item -  Selling Price cannot be empty"+"\n");
1031
				continue;
1032
			}
1033
			if (!checkEmptyString(sheet.getRow(iterator).getCell(4))){
1034
				sellingPrice = sheet.getRow(iterator).getCell(4).getNumericCellValue();
1035
				if(sellingPrice==0){
1036
					sb.append(sku + " Selling Price cannot be zero"+"\n");
1037
					continue;
1038
				}
1039
				marketplaceItem.setCurrentSp(sellingPrice);
1040
			}
1041
 
1042
			if (!checkEmptyString(sheet.getRow(iterator).getCell(5))){
1043
				otherCost = sheet.getRow(iterator).getCell(5).getNumericCellValue();
1044
				marketplaceItem.setOtherCost(otherCost);
1045
			}
1046
 
1047
 
1048
			if (!checkEmptyString(sheet.getRow(iterator).getCell(6))){
1049
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==1){
1050
					flipkartItem.setSuppressPriceFeed(true);
1051
				}
1052
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
1053
					flipkartItem.setSuppressPriceFeed(false);
1054
				}
1055
			}
1056
 
1057
			if (!checkEmptyString(sheet.getRow(iterator).getCell(7))){
1058
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==1){
1059
					flipkartItem.setSuppressInventoryFeed(true);
1060
				}
1061
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==0){
1062
					flipkartItem.setSuppressInventoryFeed(false);
1063
				}
1064
			}
1065
 
1066
			if (checkEmptyString(sheet.getRow(iterator).getCell(8)) && new_item){
1067
				sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1068
				continue;
1069
			}
1070
 
1071
			if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
1072
				sheet.getRow(iterator).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
1073
				String flipkartItemCode = sheet.getRow(iterator).getCell(8).getStringCellValue();
1074
				if (flipkartItemCode.length()==0 && new_item){
1075
					sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1076
					continue;
1077
				}
1078
				flipkartItem.setSkuAtFlipkart(flipkartItemCode);
1079
			}
1080
 
1081
			if (checkEmptyString(sheet.getRow(iterator).getCell(9)) && new_item){
1082
				sb.append(sku + " New Item -  Flipkart serial number cannot be empty"+"\n");
1083
				continue;
1084
			}
1085
 
1086
			if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
1087
				sheet.getRow(iterator).getCell(9).setCellType(Cell.CELL_TYPE_STRING);
1088
				String flipkartSerialNumber = sheet.getRow(iterator).getCell(9).getStringCellValue();
1089
				if (flipkartSerialNumber.length()==0 && new_item){
1090
					sb.append(sku + "  New Item -  Flipkart serial number cannot be empty"+"\n");
1091
					continue;
1092
				}
1093
				flipkartItem.setFlipkartSerialNumber(flipkartSerialNumber);
1094
			}
1095
 
1096
			double weight = item.getWeight();
1097
 
1098
 
1099
			if(weight==0){
1100
				sb.append(sku + " Please add weight"+"\n");
1101
				continue;
1102
			}
1103
			if (weight!=0){
1104
				weight = weight+.05;
1105
				int slabs = (int) ((weight - .001)/(.5));
1106
 
1107
				for(int i=0;i<slabs;i++){
1108
					courierCost = courierCost + 40;
1109
				}
1110
			}
10108 kshitij.so 1111
			warehouse = inventoryClient.getWarehouse(flipkartItem.getWarehouseId());
10097 kshitij.so 1112
			marketplaceItem.setCourierCost(courierCost);
1113
			transferPrice = roundTwoDecimals(marketplaceItem.getCurrentSp()- marketplaceItem.getCurrentSp()*(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))-(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+(marketplaceItem.getServiceTax()/100)));
1114
			marketplaceItem.setCurrentTp(transferPrice);
1115
			commission = roundTwoDecimals(((marketplaceItem.getCommission()/100)*marketplaceItem.getCurrentSp()));
1116
			flipkartItem.setCommissionValue(commission);
1117
			serviceTax = roundTwoDecimals((marketplaceItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+marketplaceItem.getCourierCost())); 
1118
			flipkartItem.setServiceTaxValue(serviceTax);
1119
			double vatRate = catalogClientProd.getVatPercentageForItem(flipkartItem.getItem_id(),warehouse.getStateId(),marketplaceItem.getCurrentSp());
1120
			marketplaceItem.setVat(vatRate);
1121
			double vat = roundTwoDecimals((marketplaceItem.getCurrentSp()/(1+(marketplaceItem.getVat()/100))-(flipkartItem.getMaxNlc()/(1+(marketplaceItem.getVat()/100))))*(marketplaceItem.getVat()/100));
1122
			double inHouseCost = roundTwoDecimals(15+vat+(marketplaceItem.getReturnProvision()/100)*marketplaceItem.getCurrentSp()+marketplaceItem.getOtherCost());
1123
			double lowest_possible_tp = roundTwoDecimals(flipkartItem.getMaxNlc()+inHouseCost);
1124
			marketplaceItem.setMinimumPossibleTp(lowest_possible_tp);
1125
			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)));
1126
			marketplaceItem.setMinimumPossibleSp(lowest_possible_sp);
1127
			flipkartItem.setUpdatedBy(updatedBy);
1128
			flipkartItem.setMarketplaceItems(marketplaceItem);
1129
			if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
1130
				sb.append(sku + " Service Error\n");
1131
			}	
1132
		}
1133
		File file = new File("/tmp/flipkartbulk");
1134
		FileWriter writer = new FileWriter(file);
1135
		writer.append(sb.toString());
1136
		writer.close();
1137
		byte[] buffer = new byte[(int)file.length()];
1138
		InputStream input = null;
1139
		try {
1140
			int totalBytesRead = 0;
1141
			input = new BufferedInputStream(new FileInputStream(file));
1142
			while(totalBytesRead < buffer.length){
1143
				int bytesRemaining = buffer.length - totalBytesRead;
1144
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
1145
				if (bytesRead > 0){
1146
					totalBytesRead = totalBytesRead + bytesRead;
1147
				}
1148
			}
1149
		}
1150
		finally {
1151
			input.close();
1152
			file.delete();
1153
		}
1154
 
1155
		response.setHeader("Content-Type", "text/javascript");
1156
 
1157
		ServletOutputStream sos;
1158
		try {
1159
			sos = response.getOutputStream();
1160
			sos.write(buffer);
1161
			sos.flush();
1162
		} catch (IOException e) {
1163
			System.out.println("Unable to stream the manifest file");
1164
		}   
1165
	}
1166
 
1167
	public boolean checkEmptyString(Cell cell){
10114 kshitij.so 1168
		if (cell==null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
10097 kshitij.so 1169
			return true;
1170
		}
1171
		return false;
1172
	}
1173
 
1174
	double roundTwoDecimals(double d) {
1175
		DecimalFormat twoPlaces = new DecimalFormat("#.##");
1176
		return Double.valueOf(twoPlaces.format(d));
1177
	}
1178
 
1179
	/*String getLocation(String location){
1180
		logger.info("Inside trim"+location);
1181
		int loc = location.lastIndexOf(',');
1182
		logger.info("end result "+location.substring(loc+1));
1183
		return location.substring(loc+1);
1184
	}*/
1185
 
1186
 
1187
	public String show() {
1188
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
1189
			return "authfail";
1190
		}
1191
 
1192
		if (StringUtils.equals(id, "flipkart-list-options")){
1193
			return "flipkart-list-options";
1194
		}
1195
		if (StringUtils.equals(id, "item-table")){
1196
			return "flipkart-item-table";
1197
		}
1198
 
1199
		return "id";
1200
	}
1201
 
1202
	public void setId(String id) {
1203
		this.id = id;
1204
	}
1205
 
1206
	public String getUserName(){
1207
		return session.getAttribute(ReportsUtils.USER_NAME).toString();
1208
	}
1209
 
1210
	public HttpServletRequest getRequest() {
1211
		logger.info("set request"+request.toString());
1212
		return request;
1213
	}
1214
 
1215
	public void setRequest(HttpServletRequest request) {
1216
		this.request = request;
1217
	}
1218
 
1219
	public HttpServletResponse getResponse() {
1220
		return response;
1221
	}
1222
 
1223
	public void setResponse(HttpServletResponse response) {
1224
		this.response = response;
1225
	}
1226
 
1227
	public HttpSession getSession() {
1228
		return session;
1229
	}
1230
 
1231
	public void setSession(HttpSession session) {
1232
		this.session = session;
1233
	}
1234
 
1235
	public ServletContext getContext() {
1236
		return context;
1237
	}
1238
 
1239
	public void setContext(ServletContext context) {
1240
		this.context = context;
1241
	}
1242
 
1243
	public String getUrl() {
1244
		return url;
1245
	}
1246
 
1247
	public void setUrl(String url) {
1248
		this.url = url;
1249
	}
1250
 
1251
	public String getItemId() {
1252
		return itemId;
1253
	}
1254
 
1255
	public void setItemId(String itemId) {
1256
		this.itemId = itemId;
1257
	}
1258
 
1259
	public String getExceptionPrice() {
1260
		return exceptionPrice;
1261
	}
1262
 
1263
	public void setExceptionPrice(String exceptionPrice) {
1264
		this.exceptionPrice = exceptionPrice;
1265
	}
1266
 
1267
	public String getWarehouseId() {
1268
		return warehouseId;
1269
	}
1270
 
1271
	public void setWarehouseId(String warehouseId) {
1272
		this.warehouseId = warehouseId;
1273
	}
1274
 
1275
	public File getFile() {
1276
		return file;
1277
	}
1278
 
1279
	public void setFile(File file) {
1280
		this.file = file;
1281
	}
1282
 
1283
	public String getErrMsg() {
1284
		return errMsg;
1285
	}
1286
 
1287
	public void setErrMsg(String errMsg) {
1288
		this.errMsg = errMsg;
1289
	}
1290
 
1291
	public String getNext() {
1292
		return next;
1293
	}
1294
 
1295
	public void setNext(String next) {
1296
		this.next = next;
1297
	}
1298
 
1299
	public String getId() {
1300
		return id;
1301
	}
1302
 
1303
	public void setServletRequest(HttpServletRequest req) {
1304
		this.request = req;
1305
		this.session = req.getSession();        
1306
	}
1307
 
1308
	public void setServletContext(ServletContext arg0) {
1309
		// TODO Auto-generated method stub
1310
 
1311
	}
1312
 
1313
	public void setServletResponse(HttpServletResponse response) {
1314
		this.response = response;
1315
	}
1316
 
1317
	public void setSearchText(String searchText) {
1318
		this.searchText = searchText;
1319
	}
1320
 
1321
	public String getSearchText() {
1322
		return searchText;
1323
	}
1324
 
1325
	public long getSearchCount() {
1326
		return searchCount;
1327
	}
1328
 
1329
	public long getTotalCount() {
1330
		return totalCount;
1331
	}
1332
 
1333
	public void setSearchCount(long count) {
1334
		this.searchCount = count;
1335
	}
1336
 
1337
	public List<FlipkartItemDetails> getFlipkartItems(){
1338
		return flipkartItems;
1339
	}
1340
 
1341
	public void setSellingPrice(String sellingPrice) {
1342
		this.sellingPrice = sellingPrice;
1343
	}
1344
 
1345
	public String getSellingPrice() {
1346
		return sellingPrice;
1347
	}
1348
 
1349
	public void setTransferPrice(String transferPrice) {
1350
		this.transferPrice = transferPrice;
1351
	}
1352
 
1353
	public String getTransferPrice() {
1354
		return transferPrice;
1355
	}
1356
 
1357
	public void setWebisteMrp(String webisteMrp) {
1358
		this.webisteMrp = webisteMrp;
1359
	}
1360
 
1361
	public String getWebisteMrp() {
1362
		return webisteMrp;
1363
	}
1364
 
1365
	public void setWebisteSellingPrice(String webisteSellingPrice) {
1366
		this.webisteSellingPrice = webisteSellingPrice;
1367
	}
1368
 
1369
	public String getWebisteSellingPrice() {
1370
		return webisteSellingPrice;
1371
	}
1372
 
1373
	public void setIsListedOnFlipkart(String isListedOnFlipkart) {
1374
		this.isListedOnFlipkart = isListedOnFlipkart;
1375
	}
1376
 
1377
	public String getIsSuppressInventoryFeed() {
1378
		return isSuppressInventoryFeed;
1379
	}
1380
 
1381
	public void setIsSuppressInventoryFeed(String isSuppressInventoryFeed) {
1382
		this.isSuppressInventoryFeed = isSuppressInventoryFeed;
1383
	}
1384
 
1385
	public String getIsSuppressPriceFeed() {
1386
		return isSuppressPriceFeed;
1387
	}
1388
 
1389
	public void setIsSuppressPriceFeed(String isSuppressPriceFeed) {
1390
		this.isSuppressPriceFeed = isSuppressPriceFeed;
1391
	}
1392
 
1393
	public String getIsListedOnFlipkart() {
1394
		return isListedOnFlipkart;
1395
	}
1396
 
1397
	public void setCommission(String commission) {
1398
		this.commission = commission;
1399
	}
1400
 
1401
	public String getCommission() {
1402
		return commission;
1403
	}
1404
 
1405
	public void setServiceTax(String serviceTax) {
1406
		this.serviceTax = serviceTax;
1407
	}
1408
 
1409
	public String getServiceTax() {
1410
		return serviceTax;
1411
	}
1412
 
1413
	public void setCourierCost(String courierCost) {
1414
		this.courierCost = courierCost;
1415
	}
1416
 
1417
	public String getCourierCost() {
1418
		return courierCost;
1419
	}
1420
 
1421
	public void setMaxNlc(String maxNlc) {
1422
		this.maxNlc = maxNlc;
1423
	}
1424
 
1425
	public String getMaxNlc() {
1426
		return maxNlc;
1427
	}
1428
 
1429
	public String getItemDetails(){
1430
		return itemObj.toString();
1431
	}
1432
 
1433
	public double getRoundOfValue(String val){
1434
		return roundTwoDecimals(Double.valueOf(val));
1435
	}
1436
 
1437
	public String getVaildName(String name){
1438
		return name!=null?name:"";
1439
	}
1440
 
1441
 
1442
 
1443
}