Subversion Repositories SmartDukaan

Rev

Rev 15439 | 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";
15734 kshitij.so 583
		String[] sendTo=new String[]{ "kshitij.sood@saholic.com","rajneesh.arora@saholic.com","khushal.bhatia@saholic.com","yukti.jain@saholic.com","yatin.singh@saholic.com","chandan.kumar@saholic.com"};
10097 kshitij.so 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;
15439 kshitij.so 796
		List<FlipkartItem> flipkartItems = null;
10097 kshitij.so 797
		try {
798
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
15439 kshitij.so 799
			flipkartItems = catalogClient.getAllFlipkartMarketplaceItem();
10097 kshitij.so 800
		} catch (Exception e) {
801
			e.printStackTrace();
802
		}
803
		int iterator=1;
804
		Item item;
805
		MarketplaceItems marketplaceItem;
15439 kshitij.so 806
		for(FlipkartItem fkItem:flipkartItems){
807
			marketplaceItem = fkItem.getMarketplaceItems();
808
			item = fkItem.getItem();
10184 kshitij.so 809
			//MarketplacePercentage mpCosting = catalogClient.getCostingForMarketplace(8, fkItem.getItem_id());
10097 kshitij.so 810
			HSSFRow row = sheet.createRow((short)iterator);
811
			row.createCell((short) 0).setCellValue(fkItem.getItem_id());
15439 kshitij.so 812
			row.createCell((short) 1).setCellValue(item.getCategory());
813
			row.createCell((short) 2).setCellValue(getVaildName(item.getBrand())+" "+getVaildName(item.getModelName())+" "+getVaildName(item.getModelNumber())+" "+getVaildName(item.getColor()));
10156 amar.kumar 814
			row.createCell((short) 3).setCellValue(fkItem.getWarehouseId());
815
			row.createCell((short) 4).setCellValue(roundTwoDecimals(fkItem.getExceptionPrice()));
10097 kshitij.so 816
			if(fkItem.isIsListedOnFlipkart()){
10156 amar.kumar 817
				row.createCell((short) 5).setCellValue(1);
10097 kshitij.so 818
			}
819
			else{
10156 amar.kumar 820
				row.createCell((short) 5).setCellValue(0);
10097 kshitij.so 821
			}
10156 amar.kumar 822
			row.createCell((short) 6).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentTp()));
823
			row.createCell((short) 7).setCellValue(roundTwoDecimals(marketplaceItem.getCurrentSp()));
824
			row.createCell((short) 8).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleSp()));
825
			row.createCell((short) 9).setCellValue(roundTwoDecimals(marketplaceItem.getMinimumPossibleTp()));
10184 kshitij.so 826
			row.createCell((short) 10).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp()))));
10186 kshitij.so 827
			row.createCell((short) 11).setCellValue(roundTwoDecimals(roundTwoDecimals((marketplaceItem.getCurrentTp()-marketplaceItem.getMinimumPossibleTp())/marketplaceItem.getMinimumPossibleSp())*100));
10184 kshitij.so 828
			row.createCell((short) 12).setCellValue(roundTwoDecimals(marketplaceItem.getOtherCost()));
829
			row.createCell((short) 13).setCellValue(marketplaceItem.getCourierCost());
830
			row.createCell((short) 14).setCellValue(roundTwoDecimals(marketplaceItem.getCommission()));
15439 kshitij.so 831
			row.createCell((short) 15).setCellValue(roundTwoDecimals(fkItem.getCommissionValue()));
10184 kshitij.so 832
			row.createCell((short) 16).setCellValue(roundTwoDecimals(marketplaceItem.getServiceTax()));
15439 kshitij.so 833
			row.createCell((short) 17).setCellValue(roundTwoDecimals(fkItem.getServiceTaxValue()));
10184 kshitij.so 834
			row.createCell((short) 18).setCellValue(roundTwoDecimals(marketplaceItem.getVat()));
10097 kshitij.so 835
			if(fkItem.isSuppressInventoryFeed()){
10184 kshitij.so 836
				row.createCell((short) 19).setCellValue(1);
10097 kshitij.so 837
			}
838
			else{
10184 kshitij.so 839
				row.createCell((short) 19).setCellValue(0);
10097 kshitij.so 840
			}
841
			if(fkItem.isSuppressPriceFeed()){
10184 kshitij.so 842
				row.createCell((short) 20).setCellValue(1);
10097 kshitij.so 843
			}
844
			else{
10184 kshitij.so 845
				row.createCell((short) 20).setCellValue(0);
10097 kshitij.so 846
			}
847
			if(marketplaceItem.isAutoFavourite()){
10184 kshitij.so 848
				row.createCell((short) 21).setCellValue(1);
10097 kshitij.so 849
			}
850
			else{
10184 kshitij.so 851
				row.createCell((short) 21).setCellValue(0);
10097 kshitij.so 852
			}
853
			if(marketplaceItem.isManualFavourite()){
10184 kshitij.so 854
				row.createCell((short) 22).setCellValue(1);
10097 kshitij.so 855
			}
856
			else{
10184 kshitij.so 857
				row.createCell((short) 22).setCellValue(0);
10097 kshitij.so 858
			}
859
			if(marketplaceItem.isAutoIncrement()){
10184 kshitij.so 860
				row.createCell((short) 23).setCellValue(1);
10097 kshitij.so 861
			}
862
			else{
10184 kshitij.so 863
				row.createCell((short) 23).setCellValue(0);
10097 kshitij.so 864
			}
865
			if(marketplaceItem.isAutoDecrement()){
10184 kshitij.so 866
				row.createCell((short) 24).setCellValue(1);
10097 kshitij.so 867
			}
868
			else{
10184 kshitij.so 869
				row.createCell((short) 24).setCellValue(0);
10097 kshitij.so 870
			}
10184 kshitij.so 871
			row.createCell((short) 25).setCellValue(fkItem.getMaxNlc());
872
			row.createCell((short) 26).setCellValue(fkItem.getSkuAtFlipkart());
873
			row.createCell((short) 27).setCellValue(fkItem.getFlipkartSerialNumber());
10097 kshitij.so 874
			iterator++;
875
		}
876
 
877
		FileOutputStream fileOut = null;
878
		try {
879
			fileOut = new FileOutputStream(file);
880
		} catch (FileNotFoundException e) {
881
			// TODO Auto-generated catch block
882
			e.printStackTrace();
883
		}
884
		try {
885
			hwb.write(fileOut);
886
		} catch (IOException e) {
887
			// TODO Auto-generated catch block
888
			e.printStackTrace();
889
		}
890
		try {
891
			fileOut.close();
892
		} catch (IOException e) {
893
			// TODO Auto-generated catch block
894
			e.printStackTrace();
895
		}
896
		byte[] buffer = new byte[(int)file.length()];
897
		InputStream input = null;
898
		try {
899
			int totalBytesRead = 0;
900
			input = new BufferedInputStream(new FileInputStream(file));
901
			while(totalBytesRead < buffer.length){
902
				int bytesRemaining = buffer.length - totalBytesRead;
903
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
904
				if (bytesRead > 0){
905
					totalBytesRead = totalBytesRead + bytesRead;
906
				}
907
			}
908
		}
909
		finally {
910
			input.close();
911
			file.delete();
912
		}
913
 
914
		response.setHeader("Content-Disposition", "attachment; filename=\"Flipkart-Bulk-Listings.xls\"");
915
		response.setContentType("application/octet-stream");
916
		ServletOutputStream sos;
917
		try {
918
			sos = response.getOutputStream();
919
			sos.write(buffer);
920
			sos.flush();
921
		} catch (IOException e) {
922
			System.out.println("Unable to stream the manifest file");
923
		}   
924
 
925
 
926
	}
927
 
928
 
929
	public void uploadflipkartBulkSheet() throws IOException, TException, NumberFormatException, InventoryServiceException, CatalogServiceException{
930
		File fileToCreate = new File("/tmp/", "flipkart-bulk-upload.xls");
931
		FileUtils.copyFile(this.file, fileToCreate);
932
		FileInputStream iFile = new FileInputStream(new File(file.getAbsolutePath()));
933
		HSSFWorkbook workbook = new HSSFWorkbook(iFile);
934
		HSSFSheet sheet = workbook.getSheetAt(0);
935
		String updatedBy = getUserName();
936
		Client catalogClient=null;
937
		Client catalogClientProd=null;
938
		StringBuilder sb = new StringBuilder();
939
		try {
940
			catalogClient = new CatalogClient("catalog_service_server_host_amazon","catalog_service_server_port").getClient();
941
			catalogClientProd = new CatalogClient().getClient();
942
		} catch (TTransportException e) {
943
			e.printStackTrace();
944
		}
945
		InventoryClient inventoryServiceClient = new InventoryClient();
946
		in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = inventoryServiceClient.getClient();
947
 
948
		for (int iterator=(sheet.getFirstRowNum()+1);iterator<=sheet.getLastRowNum();iterator++){
15434 kshitij.so 949
			if (sheet.getLastRowNum()-1>300){
10097 kshitij.so 950
				sb.append("Number of items to update can't be greater than 100");
951
				break;
952
			}
953
			FlipkartItem flipkartItem = null;
954
			MarketplaceItems marketplaceItem = null;
955
			MarketplacePercentage mpCosting = null;
956
			Warehouse warehouse = null;
957
			Item item = null;
958
			Long sku;
959
			boolean new_item = false;
960
			if (checkEmptyString(sheet.getRow(iterator).getCell(0))){
961
				continue;
962
			}
963
			else {
964
				sku=(long) sheet.getRow(iterator).getCell(0).getNumericCellValue();
965
				flipkartItem = catalogClient.getFlipkartItem(sku);
966
				mpCosting = catalogClient.getCostingForMarketplace(8, sku);
967
				marketplaceItem  = catalogClient.getMarketplacedetailsForItem(sku, 8);
968
				marketplaceItem.setItemId(sku);
969
				marketplaceItem.setSource(8);
970
				marketplaceItem.setCommission(mpCosting.getCommission());
971
				marketplaceItem.setServiceTax(mpCosting.getServiceTax());
972
				marketplaceItem.setReturnProvision(mpCosting.getReturnProvision());
973
				marketplaceItem.setEmiFee(mpCosting.getEmiFee());
974
				marketplaceItem.setClosingFee(mpCosting.getClosingFee());
975
 
976
				try {
977
					item = catalogClient.getItem(sku);
978
					if (item.getId()==0){
979
						sb.append(sku + " Item not valid"+"\n");
980
						continue;
981
					}
982
				} catch (CatalogServiceException e) {
983
					sb.append(sku + " Item not valid"+"\n");
984
					continue;
985
				}
986
				if(flipkartItem.getItem_id()==0){
987
					new_item = true;
988
					flipkartItem = new FlipkartItem();
989
					flipkartItem.setItem_id(sku); 
990
				}
991
			}
10111 kshitij.so 992
 
993
 
10097 kshitij.so 994
			if (checkEmptyString(sheet.getRow(iterator).getCell(1)) && new_item){
995
				sb.append(sku + " New Listing - Warehouse Id not Present"+"\n");
996
				continue;
997
			}
10111 kshitij.so 998
 
999
 
10097 kshitij.so 1000
 
1001
			if (!checkEmptyString(sheet.getRow(iterator).getCell(1))){
1002
				/*Warehouse warehouse = inventoryClient.getWarehouse(Long.valueOf(warehouseId));
1003
				if (!(warehouse.getWarehouseType()==WarehouseType.OURS && warehouse.getInventoryType() == InventoryType.GOOD)){
1004
					sb.append(sku + "Not acceptable warehouse"+"\n");
1005
					continue;
1006
				}*/
1007
				long warehouseId = (long) sheet.getRow(iterator).getCell(1).getNumericCellValue();
1008
				double maxNLC = inventoryClient.getNlcForWarehouse(warehouseId, item.getId());
1009
				if (maxNLC==0){
10114 kshitij.so 1010
					sb.append(sku + " Max Nlc can't be 0"+"\n");
10097 kshitij.so 1011
					continue;
1012
				}
1013
				flipkartItem.setWarehouseId(warehouseId);
1014
				flipkartItem.setMaxNlc(maxNLC);
1015
			}
1016
 
1017
			if (!checkEmptyString(sheet.getRow(iterator).getCell(2))){
1018
				double exceptionPrice = sheet.getRow(iterator).getCell(2).getNumericCellValue();
1019
				flipkartItem.setExceptionPrice(exceptionPrice);
1020
			}
1021
 
1022
			if (!checkEmptyString(sheet.getRow(iterator).getCell(3))){
1023
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==1){
1024
					flipkartItem.setIsListedOnFlipkart(true);
1025
				}
1026
				if ((long)sheet.getRow(iterator).getCell(3).getNumericCellValue()==0){
1027
					flipkartItem.setIsListedOnFlipkart(false);
1028
				}
1029
			}
1030
 
13473 kshitij.so 1031
			double transferPrice = 0,sellingPrice,commission,courierCost =55,serviceTax,otherCost;
10097 kshitij.so 1032
			if (checkEmptyString(sheet.getRow(iterator).getCell(4))&& new_item){
1033
				sb.append(sku + "New Item -  Selling Price cannot be empty"+"\n");
1034
				continue;
1035
			}
1036
			if (!checkEmptyString(sheet.getRow(iterator).getCell(4))){
1037
				sellingPrice = sheet.getRow(iterator).getCell(4).getNumericCellValue();
1038
				if(sellingPrice==0){
1039
					sb.append(sku + " Selling Price cannot be zero"+"\n");
1040
					continue;
1041
				}
1042
				marketplaceItem.setCurrentSp(sellingPrice);
1043
			}
1044
 
1045
			if (!checkEmptyString(sheet.getRow(iterator).getCell(5))){
1046
				otherCost = sheet.getRow(iterator).getCell(5).getNumericCellValue();
1047
				marketplaceItem.setOtherCost(otherCost);
1048
			}
1049
 
1050
 
1051
			if (!checkEmptyString(sheet.getRow(iterator).getCell(6))){
1052
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==1){
1053
					flipkartItem.setSuppressPriceFeed(true);
1054
				}
1055
				if ((long)sheet.getRow(iterator).getCell(6).getNumericCellValue()==0){
1056
					flipkartItem.setSuppressPriceFeed(false);
1057
				}
1058
			}
1059
 
1060
			if (!checkEmptyString(sheet.getRow(iterator).getCell(7))){
1061
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==1){
1062
					flipkartItem.setSuppressInventoryFeed(true);
1063
				}
1064
				if ((long)sheet.getRow(iterator).getCell(7).getNumericCellValue()==0){
1065
					flipkartItem.setSuppressInventoryFeed(false);
1066
				}
1067
			}
1068
 
1069
			if (checkEmptyString(sheet.getRow(iterator).getCell(8)) && new_item){
1070
				sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1071
				continue;
1072
			}
1073
 
1074
			if (!checkEmptyString(sheet.getRow(iterator).getCell(8))){
1075
				sheet.getRow(iterator).getCell(8).setCellType(Cell.CELL_TYPE_STRING);
1076
				String flipkartItemCode = sheet.getRow(iterator).getCell(8).getStringCellValue();
1077
				if (flipkartItemCode.length()==0 && new_item){
1078
					sb.append(sku + " New Item -  SKU@Flipkart cannot be empty"+"\n");
1079
					continue;
1080
				}
1081
				flipkartItem.setSkuAtFlipkart(flipkartItemCode);
1082
			}
1083
 
1084
			if (checkEmptyString(sheet.getRow(iterator).getCell(9)) && new_item){
1085
				sb.append(sku + " New Item -  Flipkart serial number cannot be empty"+"\n");
1086
				continue;
1087
			}
1088
 
1089
			if (!checkEmptyString(sheet.getRow(iterator).getCell(9))){
1090
				sheet.getRow(iterator).getCell(9).setCellType(Cell.CELL_TYPE_STRING);
1091
				String flipkartSerialNumber = sheet.getRow(iterator).getCell(9).getStringCellValue();
1092
				if (flipkartSerialNumber.length()==0 && new_item){
1093
					sb.append(sku + "  New Item -  Flipkart serial number cannot be empty"+"\n");
1094
					continue;
1095
				}
1096
				flipkartItem.setFlipkartSerialNumber(flipkartSerialNumber);
1097
			}
1098
 
1099
			double weight = item.getWeight();
1100
 
1101
 
1102
			if(weight==0){
1103
				sb.append(sku + " Please add weight"+"\n");
1104
				continue;
1105
			}
1106
			if (weight!=0){
1107
				weight = weight+.05;
1108
				int slabs = (int) ((weight - .001)/(.5));
1109
 
1110
				for(int i=0;i<slabs;i++){
1111
					courierCost = courierCost + 40;
1112
				}
1113
			}
10108 kshitij.so 1114
			warehouse = inventoryClient.getWarehouse(flipkartItem.getWarehouseId());
10097 kshitij.so 1115
			marketplaceItem.setCourierCost(courierCost);
1116
			transferPrice = roundTwoDecimals(marketplaceItem.getCurrentSp()- marketplaceItem.getCurrentSp()*(marketplaceItem.getCommission()/100+marketplaceItem.getEmiFee()/100)*(1+(marketplaceItem.getServiceTax()/100))-(marketplaceItem.getCourierCost()+marketplaceItem.getClosingFee())*(1+(marketplaceItem.getServiceTax()/100)));
1117
			marketplaceItem.setCurrentTp(transferPrice);
1118
			commission = roundTwoDecimals(((marketplaceItem.getCommission()/100)*marketplaceItem.getCurrentSp()));
1119
			flipkartItem.setCommissionValue(commission);
1120
			serviceTax = roundTwoDecimals((marketplaceItem.getServiceTax()/100)*(flipkartItem.getCommissionValue()+marketplaceItem.getCourierCost())); 
1121
			flipkartItem.setServiceTaxValue(serviceTax);
1122
			double vatRate = catalogClientProd.getVatPercentageForItem(flipkartItem.getItem_id(),warehouse.getStateId(),marketplaceItem.getCurrentSp());
1123
			marketplaceItem.setVat(vatRate);
1124
			double vat = roundTwoDecimals((marketplaceItem.getCurrentSp()/(1+(marketplaceItem.getVat()/100))-(flipkartItem.getMaxNlc()/(1+(marketplaceItem.getVat()/100))))*(marketplaceItem.getVat()/100));
1125
			double inHouseCost = roundTwoDecimals(15+vat+(marketplaceItem.getReturnProvision()/100)*marketplaceItem.getCurrentSp()+marketplaceItem.getOtherCost());
1126
			double lowest_possible_tp = roundTwoDecimals(flipkartItem.getMaxNlc()+inHouseCost);
1127
			marketplaceItem.setMinimumPossibleTp(lowest_possible_tp);
1128
			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)));
1129
			marketplaceItem.setMinimumPossibleSp(lowest_possible_sp);
1130
			flipkartItem.setUpdatedBy(updatedBy);
1131
			flipkartItem.setMarketplaceItems(marketplaceItem);
1132
			if(!catalogClient.addOrUpdateFlipkartItem(flipkartItem)){
1133
				sb.append(sku + " Service Error\n");
1134
			}	
1135
		}
1136
		File file = new File("/tmp/flipkartbulk");
1137
		FileWriter writer = new FileWriter(file);
1138
		writer.append(sb.toString());
1139
		writer.close();
1140
		byte[] buffer = new byte[(int)file.length()];
1141
		InputStream input = null;
1142
		try {
1143
			int totalBytesRead = 0;
1144
			input = new BufferedInputStream(new FileInputStream(file));
1145
			while(totalBytesRead < buffer.length){
1146
				int bytesRemaining = buffer.length - totalBytesRead;
1147
				int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
1148
				if (bytesRead > 0){
1149
					totalBytesRead = totalBytesRead + bytesRead;
1150
				}
1151
			}
1152
		}
1153
		finally {
1154
			input.close();
1155
			file.delete();
1156
		}
1157
 
1158
		response.setHeader("Content-Type", "text/javascript");
1159
 
1160
		ServletOutputStream sos;
1161
		try {
1162
			sos = response.getOutputStream();
1163
			sos.write(buffer);
1164
			sos.flush();
1165
		} catch (IOException e) {
1166
			System.out.println("Unable to stream the manifest file");
1167
		}   
1168
	}
1169
 
1170
	public boolean checkEmptyString(Cell cell){
10114 kshitij.so 1171
		if (cell==null || cell.getCellType() == Cell.CELL_TYPE_BLANK){
10097 kshitij.so 1172
			return true;
1173
		}
1174
		return false;
1175
	}
1176
 
1177
	double roundTwoDecimals(double d) {
1178
		DecimalFormat twoPlaces = new DecimalFormat("#.##");
1179
		return Double.valueOf(twoPlaces.format(d));
1180
	}
1181
 
1182
	/*String getLocation(String location){
1183
		logger.info("Inside trim"+location);
1184
		int loc = location.lastIndexOf(',');
1185
		logger.info("end result "+location.substring(loc+1));
1186
		return location.substring(loc+1);
1187
	}*/
1188
 
1189
 
1190
	public String show() {
1191
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getRequestURI().substring(request.getContextPath().length()).split("/")[1])) {
1192
			return "authfail";
1193
		}
1194
 
1195
		if (StringUtils.equals(id, "flipkart-list-options")){
1196
			return "flipkart-list-options";
1197
		}
1198
		if (StringUtils.equals(id, "item-table")){
1199
			return "flipkart-item-table";
1200
		}
1201
 
1202
		return "id";
1203
	}
1204
 
1205
	public void setId(String id) {
1206
		this.id = id;
1207
	}
1208
 
1209
	public String getUserName(){
1210
		return session.getAttribute(ReportsUtils.USER_NAME).toString();
1211
	}
1212
 
1213
	public HttpServletRequest getRequest() {
1214
		logger.info("set request"+request.toString());
1215
		return request;
1216
	}
1217
 
1218
	public void setRequest(HttpServletRequest request) {
1219
		this.request = request;
1220
	}
1221
 
1222
	public HttpServletResponse getResponse() {
1223
		return response;
1224
	}
1225
 
1226
	public void setResponse(HttpServletResponse response) {
1227
		this.response = response;
1228
	}
1229
 
1230
	public HttpSession getSession() {
1231
		return session;
1232
	}
1233
 
1234
	public void setSession(HttpSession session) {
1235
		this.session = session;
1236
	}
1237
 
1238
	public ServletContext getContext() {
1239
		return context;
1240
	}
1241
 
1242
	public void setContext(ServletContext context) {
1243
		this.context = context;
1244
	}
1245
 
1246
	public String getUrl() {
1247
		return url;
1248
	}
1249
 
1250
	public void setUrl(String url) {
1251
		this.url = url;
1252
	}
1253
 
1254
	public String getItemId() {
1255
		return itemId;
1256
	}
1257
 
1258
	public void setItemId(String itemId) {
1259
		this.itemId = itemId;
1260
	}
1261
 
1262
	public String getExceptionPrice() {
1263
		return exceptionPrice;
1264
	}
1265
 
1266
	public void setExceptionPrice(String exceptionPrice) {
1267
		this.exceptionPrice = exceptionPrice;
1268
	}
1269
 
1270
	public String getWarehouseId() {
1271
		return warehouseId;
1272
	}
1273
 
1274
	public void setWarehouseId(String warehouseId) {
1275
		this.warehouseId = warehouseId;
1276
	}
1277
 
1278
	public File getFile() {
1279
		return file;
1280
	}
1281
 
1282
	public void setFile(File file) {
1283
		this.file = file;
1284
	}
1285
 
1286
	public String getErrMsg() {
1287
		return errMsg;
1288
	}
1289
 
1290
	public void setErrMsg(String errMsg) {
1291
		this.errMsg = errMsg;
1292
	}
1293
 
1294
	public String getNext() {
1295
		return next;
1296
	}
1297
 
1298
	public void setNext(String next) {
1299
		this.next = next;
1300
	}
1301
 
1302
	public String getId() {
1303
		return id;
1304
	}
1305
 
1306
	public void setServletRequest(HttpServletRequest req) {
1307
		this.request = req;
1308
		this.session = req.getSession();        
1309
	}
1310
 
1311
	public void setServletContext(ServletContext arg0) {
1312
		// TODO Auto-generated method stub
1313
 
1314
	}
1315
 
1316
	public void setServletResponse(HttpServletResponse response) {
1317
		this.response = response;
1318
	}
1319
 
1320
	public void setSearchText(String searchText) {
1321
		this.searchText = searchText;
1322
	}
1323
 
1324
	public String getSearchText() {
1325
		return searchText;
1326
	}
1327
 
1328
	public long getSearchCount() {
1329
		return searchCount;
1330
	}
1331
 
1332
	public long getTotalCount() {
1333
		return totalCount;
1334
	}
1335
 
1336
	public void setSearchCount(long count) {
1337
		this.searchCount = count;
1338
	}
1339
 
1340
	public List<FlipkartItemDetails> getFlipkartItems(){
1341
		return flipkartItems;
1342
	}
1343
 
1344
	public void setSellingPrice(String sellingPrice) {
1345
		this.sellingPrice = sellingPrice;
1346
	}
1347
 
1348
	public String getSellingPrice() {
1349
		return sellingPrice;
1350
	}
1351
 
1352
	public void setTransferPrice(String transferPrice) {
1353
		this.transferPrice = transferPrice;
1354
	}
1355
 
1356
	public String getTransferPrice() {
1357
		return transferPrice;
1358
	}
1359
 
1360
	public void setWebisteMrp(String webisteMrp) {
1361
		this.webisteMrp = webisteMrp;
1362
	}
1363
 
1364
	public String getWebisteMrp() {
1365
		return webisteMrp;
1366
	}
1367
 
1368
	public void setWebisteSellingPrice(String webisteSellingPrice) {
1369
		this.webisteSellingPrice = webisteSellingPrice;
1370
	}
1371
 
1372
	public String getWebisteSellingPrice() {
1373
		return webisteSellingPrice;
1374
	}
1375
 
1376
	public void setIsListedOnFlipkart(String isListedOnFlipkart) {
1377
		this.isListedOnFlipkart = isListedOnFlipkart;
1378
	}
1379
 
1380
	public String getIsSuppressInventoryFeed() {
1381
		return isSuppressInventoryFeed;
1382
	}
1383
 
1384
	public void setIsSuppressInventoryFeed(String isSuppressInventoryFeed) {
1385
		this.isSuppressInventoryFeed = isSuppressInventoryFeed;
1386
	}
1387
 
1388
	public String getIsSuppressPriceFeed() {
1389
		return isSuppressPriceFeed;
1390
	}
1391
 
1392
	public void setIsSuppressPriceFeed(String isSuppressPriceFeed) {
1393
		this.isSuppressPriceFeed = isSuppressPriceFeed;
1394
	}
1395
 
1396
	public String getIsListedOnFlipkart() {
1397
		return isListedOnFlipkart;
1398
	}
1399
 
1400
	public void setCommission(String commission) {
1401
		this.commission = commission;
1402
	}
1403
 
1404
	public String getCommission() {
1405
		return commission;
1406
	}
1407
 
1408
	public void setServiceTax(String serviceTax) {
1409
		this.serviceTax = serviceTax;
1410
	}
1411
 
1412
	public String getServiceTax() {
1413
		return serviceTax;
1414
	}
1415
 
1416
	public void setCourierCost(String courierCost) {
1417
		this.courierCost = courierCost;
1418
	}
1419
 
1420
	public String getCourierCost() {
1421
		return courierCost;
1422
	}
1423
 
1424
	public void setMaxNlc(String maxNlc) {
1425
		this.maxNlc = maxNlc;
1426
	}
1427
 
1428
	public String getMaxNlc() {
1429
		return maxNlc;
1430
	}
1431
 
1432
	public String getItemDetails(){
1433
		return itemObj.toString();
1434
	}
1435
 
1436
	public double getRoundOfValue(String val){
1437
		return roundTwoDecimals(Double.valueOf(val));
1438
	}
1439
 
1440
	public String getVaildName(String name){
1441
		return name!=null?name:"";
1442
	}
1443
 
14780 manish.sha 1444
	public String getIsFaListedOnFlipkart() {
1445
		return isFaListedOnFlipkart;
1446
	}
10097 kshitij.so 1447
 
14780 manish.sha 1448
	public void setIsFaListedOnFlipkart(String isFaListedOnFlipkart) {
1449
		this.isFaListedOnFlipkart = isFaListedOnFlipkart;
1450
	}
10097 kshitij.so 1451
 
1452
}