Subversion Repositories SmartDukaan

Rev

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