Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
23819 govind 1
package com.spice.profitmandi.web.controller;
2
 
23945 amit.gupta 3
import com.fasterxml.jackson.databind.ObjectMapper;
29926 amit.gupta 4
import com.spice.profitmandi.common.enumuration.MessageType;
23819 govind 5
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29926 amit.gupta 6
import com.spice.profitmandi.common.model.*;
23945 amit.gupta 7
import com.spice.profitmandi.common.services.ReporticoService;
23951 amit.gupta 8
import com.spice.profitmandi.common.util.FileUtil;
23945 amit.gupta 9
import com.spice.profitmandi.common.util.FormattingUtils;
28102 tejbeer 10
import com.spice.profitmandi.common.util.Utils;
23819 govind 11
import com.spice.profitmandi.dao.entity.catalog.Item;
23884 amit.gupta 12
import com.spice.profitmandi.dao.entity.catalog.TagListing;
28136 tejbeer 13
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
28102 tejbeer 14
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
24822 amit.gupta 15
import com.spice.profitmandi.dao.entity.inventory.ItemPricingHistory;
23884 amit.gupta 16
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
23819 govind 17
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
24083 amit.gupta 18
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
19
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
23819 govind 20
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23884 amit.gupta 21
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
29926 amit.gupta 22
import com.spice.profitmandi.dao.repository.cs.CsService;
28136 tejbeer 23
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28102 tejbeer 24
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29926 amit.gupta 25
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
28102 tejbeer 26
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
24822 amit.gupta 27
import com.spice.profitmandi.dao.repository.inventory.ItemPricingHistoryRepository;
23884 amit.gupta 28
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
23983 amit.gupta 29
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
24083 amit.gupta 30
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
23819 govind 31
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
29926 amit.gupta 32
import com.spice.profitmandi.service.NotificationService;
23819 govind 33
import com.spice.profitmandi.service.inventory.InventoryService;
29788 amit.gupta 34
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModel;
35
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
36
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
23983 amit.gupta 37
import com.spice.profitmandi.service.pricing.PriceDropService;
23968 amit.gupta 38
import com.spice.profitmandi.service.scheme.SchemeService;
23884 amit.gupta 39
import com.spice.profitmandi.service.transaction.TransactionService;
28102 tejbeer 40
import com.spice.profitmandi.service.user.RetailerService;
23819 govind 41
import com.spice.profitmandi.service.wallet.WalletService;
28102 tejbeer 42
import com.spice.profitmandi.web.model.LoginDetails;
43
import com.spice.profitmandi.web.util.CookiesProcessor;
23819 govind 44
import com.spice.profitmandi.web.util.MVCResponseSender;
29926 amit.gupta 45
import org.apache.commons.io.output.ByteArrayOutputStream;
46
import org.apache.logging.log4j.LogManager;
47
import org.apache.logging.log4j.Logger;
48
import org.springframework.beans.factory.annotation.Autowired;
49
import org.springframework.beans.factory.annotation.Qualifier;
50
import org.springframework.core.io.ByteArrayResource;
51
import org.springframework.http.HttpHeaders;
52
import org.springframework.http.HttpStatus;
53
import org.springframework.http.ResponseEntity;
54
import org.springframework.stereotype.Controller;
55
import org.springframework.transaction.annotation.Transactional;
56
import org.springframework.ui.Model;
57
import org.springframework.web.bind.annotation.*;
23819 govind 58
 
29926 amit.gupta 59
import javax.servlet.http.HttpServletRequest;
60
import java.io.Serializable;
61
import java.time.LocalDate;
62
import java.time.LocalDateTime;
63
import java.util.*;
64
import java.util.stream.Collectors;
65
 
23819 govind 66
@Controller
27071 amit.gupta 67
@Transactional(rollbackFor = Throwable.class)
23819 govind 68
public class PriceDropController {
69
 
70
	private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);
71
 
72
	@Autowired
29926 amit.gupta 73
	private CsService csService;
74
 
75
	@Autowired
76
	private UserRepository dtrUserRepository;
77
 
78
	@Autowired
23819 govind 79
	private PriceDropRepository priceDropRepository;
80
 
23951 amit.gupta 81
	@Autowired
82
	private ObjectMapper objectMapper;
23945 amit.gupta 83
 
23819 govind 84
	@Autowired
23884 amit.gupta 85
	private VendorItemPricingRepository vendorItemPricingRepository;
23819 govind 86
 
87
	@Autowired
23884 amit.gupta 88
	@Qualifier("fofoInventoryService")
89
	private InventoryService inventoryService;
23945 amit.gupta 90
 
23884 amit.gupta 91
	@Autowired
23819 govind 92
	private MVCResponseSender mvcResponseSender;
93
 
94
	@Autowired
23983 amit.gupta 95
	private PriceDropService priceDropService;
27071 amit.gupta 96
 
24822 amit.gupta 97
	@Autowired
98
	private ItemPricingHistoryRepository itemPricingHistoryRepository;
24083 amit.gupta 99
 
23983 amit.gupta 100
	@Autowired
23819 govind 101
	private WalletService walletService;
102
 
103
	@Autowired
23884 amit.gupta 104
	private TagListingRepository tagListingRepository;
23945 amit.gupta 105
 
23884 amit.gupta 106
	@Autowired
107
	private TransactionService transactionService;
23819 govind 108
 
109
	@Autowired
24083 amit.gupta 110
	private PriceDropIMEIRepository priceDropIMEIRepository;
111
 
112
	@Autowired
23819 govind 113
	@Qualifier("catalogItemRepository")
114
	private ItemRepository itemRepository;
115
 
23945 amit.gupta 116
	@Autowired
23968 amit.gupta 117
	private SchemeService schemeService;
24083 amit.gupta 118
 
23986 amit.gupta 119
	@Autowired
23945 amit.gupta 120
	ReporticoService reporticoService;
24083 amit.gupta 121
 
23983 amit.gupta 122
	@Autowired
123
	LineItemImeisRepository lineItemImeisRepository;
23945 amit.gupta 124
 
28102 tejbeer 125
	@Autowired
126
	private Mongo mongoClient;
127
 
128
	@Autowired
129
	private CookiesProcessor cookiesProcessor;
130
 
131
	@Autowired
132
	private PartnerTypeChangeService partnerTypeChangeService;
133
 
134
	@Autowired
135
	private RetailerService retailerService;
136
 
28136 tejbeer 137
	@Autowired
29926 amit.gupta 138
	private NotificationService notificationService;
139
 
140
	@Autowired
28136 tejbeer 141
	private FofoStoreRepository fofoStoreRepository;
142
 
23819 govind 143
	@RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
23945 amit.gupta 144
	public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
28568 amit.gupta 145
		List<PriceDrop> priceDrops = priceDropRepository.selectAllIncomplete();
24191 amit.gupta 146
		Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
29654 tejbeer 147
 
24180 amit.gupta 148
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
24191 amit.gupta 149
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
150
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
23819 govind 151
		model.addAttribute("priceDrops", priceDrops);
23968 amit.gupta 152
		model.addAttribute("catalogDescription", catalogDescription);
23819 govind 153
		return "price-drop";
154
	}
24083 amit.gupta 155
 
28568 amit.gupta 156
	@RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
157
	public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
158
		List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
28889 amit.gupta 159
		int processOn = 1;
28568 amit.gupta 160
 
161
		List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
162
				.collect(Collectors.toList());
163
 
164
		Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
165
				.collect(Collectors.toSet());
166
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
167
		LOGGER.info("catalogIds" + catalogIds);
168
 
169
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
170
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
171
		model.addAttribute("priceDrops", completePriceDrops);
28642 amit.gupta 172
		model.addAttribute("processOn", processOn);
28568 amit.gupta 173
		model.addAttribute("catalogDescription", catalogDescription);
174
		return "price-drop";
175
	}
176
 
24049 amit.gupta 177
	@RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
178
	public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
24083 amit.gupta 179
 
24063 amit.gupta 180
		TagListing tagListing;
24049 amit.gupta 181
		PriceDropModel pm = new PriceDropModel();
24063 amit.gupta 182
		try {
183
			tagListing = tagListingRepository.selectByItemId(itemId);
24083 amit.gupta 184
			if (tagListing != null) {
24063 amit.gupta 185
				pm.setMop(tagListing.getMop());
186
				pm.setDp(tagListing.getSellingPrice());
187
				pm.setMrp(tagListing.getMrp());
188
				List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
24083 amit.gupta 189
				if (vips.size() > 0) {
24063 amit.gupta 190
					VendorItemPricing vip = vips.get(0);
191
					pm.setNlc(vip.getNlc());
192
					pm.setTp(vip.getTp());
193
				} else {
194
					throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
195
				}
196
			}
24083 amit.gupta 197
		} catch (Exception e) {
24063 amit.gupta 198
			LOGGER.info("Chose item that doesn't exist");
24049 amit.gupta 199
		}
200
		model.addAttribute("response", mvcResponseSender.createResponseString(pm));
201
		return "response";
202
	}
24083 amit.gupta 203
 
24168 amit.gupta 204
	@RequestMapping(value = "/item", method = RequestMethod.GET)
28102 tejbeer 205
	public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
206
			@RequestParam boolean anyColor) throws Throwable {
24383 amit.gupta 207
		String query1 = query.toLowerCase();
28102 tejbeer 208
 
209
		List<ItemDescriptionModel> partnersItemDescription = inventoryService
210
				.getAllPartnerItemStringDescription(anyColor).parallelStream()
211
				.filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
24564 amit.gupta 212
				.collect(Collectors.toList());
28102 tejbeer 213
		LOGGER.info("partnersItemDescription" + partnersItemDescription);
24168 amit.gupta 214
 
24191 amit.gupta 215
		model.addAttribute("response", mvcResponseSender.createResponseString(partnersItemDescription));
24168 amit.gupta 216
		return "response";
217
	}
218
 
23951 amit.gupta 219
	@RequestMapping(value = "/price-drop/imes/download")
220
	public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
221
			@RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
222
		Item item = itemRepository.selectById(itemId);
26368 amit.gupta 223
		ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null);
23951 amit.gupta 224
		final HttpHeaders headers = new HttpHeaders();
225
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
25408 amit.gupta 226
		headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
23951 amit.gupta 227
		byte[] byteArray = baos.toByteArray();
228
		headers.setContentLength(byteArray.length);
229
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
230
	}
231
 
24083 amit.gupta 232
	@RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
233
	public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
234
			Model model) throws Exception {
235
		boolean response = false;
236
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
237
		if (priceDrop.getProcessTimestamp() == null) {
238
			priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
239
			priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
240
			// priceDrop.setProcessTimestamp(LocalDateTime.now());
241
			priceDropRepository.persist(priceDrop);
242
			response = true;
243
		}
244
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
245
		return "response";
246
	}
247
 
248
	@RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
249
	public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
250
			throws Exception {
251
 
252
		PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
24564 amit.gupta 253
 
254
		// This call is used to persit imeis to pricedrop imeis in case its not there.
27071 amit.gupta 255
		// This should be called while creating price drop.
256
		// priceDropService.priceDropStatus(priceDropId);
24564 amit.gupta 257
 
24083 amit.gupta 258
		List<String> pendingImeis = new ArrayList<>();
259
		List<String> approvedImeis = new ArrayList<>();
260
		List<String> rejectedImeis = new ArrayList<>();
28568 amit.gupta 261
		List<String> holdImeis = new ArrayList<>();
24083 amit.gupta 262
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
263
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
264
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
265
				pendingImeis.add(priceDropIMEI.getImei());
266
			} else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
267
				approvedImeis.add(priceDropIMEI.getImei());
268
			}
269
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
270
				rejectedImeis.add(priceDropIMEI.getImei());
28568 amit.gupta 271
			} else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
272
				holdImeis.add(priceDropIMEI.getImei());
273
 
24083 amit.gupta 274
			}
275
		}
28568 amit.gupta 276
		LOGGER.info("pendingImeis" + pendingImeis);
277
		LOGGER.info("approvedImeis" + approvedImeis);
278
		LOGGER.info("rejectedImeis" + rejectedImeis);
279
		LOGGER.info("priceDropImeis" + priceDropImeis);
280
 
24083 amit.gupta 281
		priceDropImeisModel.setPendingImeis(pendingImeis);
282
		priceDropImeisModel.setPriceDropId(priceDropId);
283
		priceDropImeisModel.setApprovedImeis(approvedImeis);
28568 amit.gupta 284
		priceDropImeisModel.setHoldImeis(holdImeis);
24083 amit.gupta 285
		priceDropImeisModel.setRejectedImeis(rejectedImeis);
286
		model.addAttribute("response", mvcResponseSender.createResponseString(priceDropImeisModel));
287
		return "response";
288
	}
289
 
23968 amit.gupta 290
	@RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
27071 amit.gupta 291
	public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
23968 amit.gupta 292
			Model model) throws Exception {
27071 amit.gupta 293
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
23968 amit.gupta 294
		boolean response = false;
28102 tejbeer 295
		if (priceDrop.getPartnerPayout() == 0) {
27071 amit.gupta 296
			priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
297
		}
298
		priceDrop.setProcessTimestamp(LocalDateTime.now());
299
		priceDropRepository.persist(priceDrop);
300
		priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
28102 tejbeer 301
		response = true;
23968 amit.gupta 302
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
303
		return "response";
23819 govind 304
	}
24083 amit.gupta 305
 
23884 amit.gupta 306
	@RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
23945 amit.gupta 307
	public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
308
			throws Exception {
23884 amit.gupta 309
		boolean response = false;
23968 amit.gupta 310
		priceDropModel.setAllColors(true);
23945 amit.gupta 311
		if (this.validatePriceDrop(priceDropModel)) {
23884 amit.gupta 312
			TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
24409 amit.gupta 313
			float oldDp = tagListing.getSellingPrice();
24410 amit.gupta 314
			float oldMop = tagListing.getMop();
315
			float oldTp = 0;
24409 amit.gupta 316
			float newDp = priceDropModel.getDp();
24564 amit.gupta 317
 
24410 amit.gupta 318
			if (newDp != oldDp) {
23884 amit.gupta 319
				List<Item> allItems = null;
320
				Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
23945 amit.gupta 321
				if (priceDropModel.isAllColors()) {
23884 amit.gupta 322
					allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
23945 amit.gupta 323
 
23884 amit.gupta 324
				} else {
23945 amit.gupta 325
					allItems = Arrays.asList(currentItem);
23884 amit.gupta 326
				}
23945 amit.gupta 327
				for (Item item : allItems) {
23884 amit.gupta 328
					TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
23945 amit.gupta 329
					if (itemTagListing == null)
330
						continue;
23884 amit.gupta 331
					itemTagListing.setSellingPrice(newDp);
332
					itemTagListing.setMop(priceDropModel.getMop());
333
					tagListingRepository.persist(tagListing);
334
					List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
23945 amit.gupta 335
					for (VendorItemPricing vip : vipList) {
24410 amit.gupta 336
						oldTp = vip.getNlc();
23884 amit.gupta 337
						vip.setDp(newDp);
338
						vip.setMop(priceDropModel.getMop());
24409 amit.gupta 339
						vip.setNlc(priceDropModel.getTp());
23884 amit.gupta 340
						vip.setTp(priceDropModel.getTp());
341
						vendorItemPricingRepository.persist(vip);
342
					}
343
					transactionService.updatePriceDrop(item.getId(), newDp);
344
				}
27071 amit.gupta 345
 
346
				// Add to itemPricing history
24822 amit.gupta 347
				ItemPricingHistory iph = new ItemPricingHistory();
348
				iph.setCatalogId(currentItem.getCatalogItemId());
349
				iph.setTp(priceDropModel.getTp());
350
				iph.setDp(priceDropModel.getDp());
351
				iph.setMop(priceDropModel.getMop());
27071 amit.gupta 352
				// TODO: changedBy
24822 amit.gupta 353
				iph.setChangedBy("me");
354
				iph.setCreateTimestamp(LocalDateTime.now());
355
				itemPricingHistoryRepository.persist(iph);
27071 amit.gupta 356
 
23951 amit.gupta 357
				PriceDrop priceDrop = new PriceDrop();
358
				priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
24410 amit.gupta 359
				priceDrop.setTp(oldTp);
360
				priceDrop.setNlc(oldTp);
361
				priceDrop.setMop(oldMop);
24409 amit.gupta 362
				priceDrop.setOldDp(oldDp);
363
				priceDrop.setAmount(oldDp - newDp);
23968 amit.gupta 364
				priceDrop.setNewDp(newDp);
23951 amit.gupta 365
				priceDrop.setCreatedOn(LocalDateTime.now());
366
				priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
367
				priceDropRepository.persist(priceDrop);
26116 amit.gupta 368
				priceDropService.priceDropStatus(priceDrop.getId());
23884 amit.gupta 369
				response = true;
29926 amit.gupta 370
 
371
				this.sendPriceChangeNotification(priceDrop);
23884 amit.gupta 372
			} else {
23945 amit.gupta 373
				throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
24409 amit.gupta 374
						"Price Drop Should be greater than 0");
23884 amit.gupta 375
			}
376
		}
377
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
378
		return "response";
379
	}
29926 amit.gupta 380
	private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
381
		List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
382
		String title = "Price has been %s for %s";
23945 amit.gupta 383
 
29926 amit.gupta 384
 
385
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
386
		sendNotificationModel.setCampaignName("pricechange");
387
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
388
		sendNotificationModel.setTitle("");
389
		StringBuffer sb = new StringBuffer();
390
		String message = null;
391
		if(priceDrop.getDropAmount() > 0) {
392
			title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
393
			message = String.format("Price has been dropped from Rs.%d. Old DP - Rs.%d, New DP - Rs.%d", priceDrop.getDropAmount(),
394
					priceDrop.getOldDp(), priceDrop.getNewDp());
395
		} else {
396
			title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
397
			message = String.format("Price has been increased from Rs.%d. Old DP - Rs.%d, New DP - Rs.%d", -priceDrop.getDropAmount(),
398
					priceDrop.getOldDp(), priceDrop.getNewDp());
399
		}
400
		sendNotificationModel.setTitle(title);
401
		sendNotificationModel.setMessage(message);
402
		sendNotificationModel.setMessageType(MessageType.pricechange);
29927 amit.gupta 403
		notificationService.sendNotificationToAll(sendNotificationModel);
29926 amit.gupta 404
	}
405
 
23819 govind 406
	@RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
407
	public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
23945 amit.gupta 408
			Model model) throws ProfitMandiBusinessException, Exception {
23819 govind 409
 
410
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
27071 amit.gupta 411
		Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
412
				.collect(Collectors.toMap(x -> x.getImei(), x -> x));
413
 
414
		if (priceDropIMEIsMap.size() == 0 && priceDrop.getProcessTimestamp() == null) {
26372 amit.gupta 415
			priceDrop.setProcessTimestamp(LocalDateTime.now());
416
		} else {
417
			priceDropService.priceDropStatus(priceDrop.getId());
418
		}
27071 amit.gupta 419
 
23968 amit.gupta 420
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
27071 amit.gupta 421
		ByteArrayOutputStream baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
422
				priceDropIMEIsMap);
23968 amit.gupta 423
		final HttpHeaders headers = new HttpHeaders();
424
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 425
		headers.set("Content-disposition",
426
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
427
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
23968 amit.gupta 428
		byte[] byteArray = baos.toByteArray();
429
		headers.setContentLength(byteArray.length);
430
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 431
 
432
	}
433
 
28568 amit.gupta 434
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
27071 amit.gupta 435
	public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
436
			Model model) throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 437
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
28889 amit.gupta 438
 
24083 amit.gupta 439
		switch (priceDropImeisModel.getUpdatedStatus()) {
27071 amit.gupta 440
		case "approved": {
28568 amit.gupta 441
			status = PriceDropImeiStatus.APPROVED;
27071 amit.gupta 442
			break;
24083 amit.gupta 443
		}
28568 amit.gupta 444
		case "hold": {
445
			status = PriceDropImeiStatus.HOLD;
446
			break;
447
		}
27071 amit.gupta 448
		case "rejected": {
449
			status = PriceDropImeiStatus.REJECTED;
450
			break;
24083 amit.gupta 451
		}
27071 amit.gupta 452
		}
28889 amit.gupta 453
		PriceDropImeiStatus finalStatus = status;
27071 amit.gupta 454
 
455
		if (PriceDropImeiStatus.PENDING.equals(status)) {
28568 amit.gupta 456
 
457
			List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
28641 amit.gupta 458
			List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
28568 amit.gupta 459
					priceDropImeisModel.getPriceDropId());
460
			LOGGER.info("hello" + priceDropIMEIs);
461
			for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
462
				if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
463
					if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
464
							|| priceDropHoldIMEI.getStatus().equals(status)) {
465
						continue;
466
					}
467
					priceDropIMEIsToHolds.add(priceDropHoldIMEI);
468
					priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
469
					priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
470
				} else {
471
					throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
472
							"Pending Status is allowed  only for Hold IMIEs");
473
				}
474
			}
28889 amit.gupta 475
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
476
			return "response";
27071 amit.gupta 477
		}
478
 
479
		// TODO:PD
24083 amit.gupta 480
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
481
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
482
 
28889 amit.gupta 483
		List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
484
				.filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
29654 tejbeer 485
				.filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
28568 amit.gupta 486
 
28889 amit.gupta 487
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 488
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
24083 amit.gupta 489
		}
28568 amit.gupta 490
 
28889 amit.gupta 491
		if (status.equals(PriceDropImeiStatus.APPROVED)) {
492
			priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
493
					priceDropImeisModel.getUpdatedImeis());
494
		}
495
		for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
496
			if (status.equals(PriceDropImeiStatus.REJECTED)
497
					&& priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
498
				priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
499
				priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
500
			} else if (status.equals(PriceDropImeiStatus.HOLD)) {
501
				if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
502
					priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
503
				} else {
28568 amit.gupta 504
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
505
				}
506
 
507
			}
508
 
509
		}
510
 
24083 amit.gupta 511
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
512
		return "response";
513
 
514
	}
515
 
27071 amit.gupta 516
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
517
			Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 518
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
519
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 520
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 521
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 522
			if (priceDropImeis == null) {
26368 amit.gupta 523
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 524
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 525
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
526
			}
23951 amit.gupta 527
		}
27071 amit.gupta 528
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
529
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
530
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 531
	}
24083 amit.gupta 532
 
27071 amit.gupta 533
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
534
			PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 535
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 536
		row.add(imeiDropSummaryModel.getSerialNumber());
537
		row.add(imeiDropSummaryModel.getStoreName());
538
		row.add(imeiDropSummaryModel.getPartnerCode());
539
		row.add(imeiDropSummaryModel.getItemId());
540
		row.add(imeiDropSummaryModel.getBrand());
541
		row.add(imeiDropSummaryModel.getModelName());
542
		row.add(imeiDropSummaryModel.getModelNumber());
543
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 544
		if (priceDropIMEI != null) {
26368 amit.gupta 545
			row.add(priceDropIMEI.getStatus());
546
			row.add(priceDropIMEI.getRejectionReason());
547
		} else {
548
			row.add(PriceDropImeiStatus.PENDING);
549
			row.add("");
550
		}
26373 amit.gupta 551
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
552
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 553
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 554
		row.add(imeiDropSummaryModel.getActivationTimestamp());
555
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 556
		return row;
557
	}
23819 govind 558
 
23884 amit.gupta 559
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 560
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 561
			return true;
562
		}
563
		return false;
564
	}
23945 amit.gupta 565
 
28102 tejbeer 566
	@RequestMapping(value = "/priceCircular")
567
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
568
		int fofoId = Utils.SYSTEM_PARTNER_ID;
569
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
570
				.collect(Collectors.toSet());
28142 tejbeer 571
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
572
				.collect(Collectors.toSet()));
28102 tejbeer 573
 
28142 tejbeer 574
		/*
575
		 * Map<Integer, CustomRetailer> customRetailers =
576
		 * retailerService.getFofoRetailers(true); Map<Integer, PartnerType>
577
		 * fofoIdPartnerTypeMap = new HashMap<>();
578
		 * 
579
		 * for (Entry<Integer, CustomRetailer> customRetailer :
580
		 * customRetailers.entrySet()) { PartnerType partnerType =
581
		 * partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
582
		 * LocalDate.now()); fofoIdPartnerTypeMap.put(customRetailer.getKey(),
583
		 * partnerType); }
584
		 * 
585
		 * Map<PartnerType, List<Integer>> partnerTypePartnersMap =
586
		 * fofoIdPartnerTypeMap.entrySet().stream().collect( Collectors.groupingBy(x ->
587
		 * x.getValue(), Collectors.mapping(x -> x.getKey(), Collectors.toList())));
588
		 */
28102 tejbeer 589
		model.addAttribute("brands", brands);
28145 tejbeer 590
		model.addAttribute("date", LocalDate.now());
28102 tejbeer 591
 
592
		return "price-circular";
593
	}
594
 
28142 tejbeer 595
	@RequestMapping(value = "/priceCircularByBrandAndPartnerType")
596
	public String priceCircularByBrandAndPartnerType(HttpServletRequest request, @RequestParam List<String> brands,
597
			@RequestParam PartnerType partnerType, Model model) throws ProfitMandiBusinessException {
598
		List<PartnerType> partnerTypes = new ArrayList<>();
599
		partnerTypes.add(partnerType);
600
		partnerTypes.add(PartnerType.ALL);
29788 amit.gupta 601
		List<PriceCircularItemModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
28142 tejbeer 602
				brands, LocalDateTime.now(), LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
603
 
29788 amit.gupta 604
		for (PriceCircularItemModel pc : priceCircular) {
28142 tejbeer 605
 
29646 tejbeer 606
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getUpfrontMargin()
607
					+ pc.getTertiaryPayout() + pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout()
608
					+ pc.getModelSpecfic();
28142 tejbeer 609
			pc.setTotalScheme(totalScheme);
610
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
611
			pc.setNetPrice(netprice);
612
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
613
			pc.setMopdp(mopdpdiff);
614
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
615
			long totalProfit = totalScheme + mopdpdiff;
616
			pc.setTotalProfit((int) totalProfit);
617
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
618
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
619
			pc.setNetMargin(roundOff);
620
 
621
		}
28149 amit.gupta 622
		model.addAttribute("date", LocalDate.now());
28142 tejbeer 623
		model.addAttribute("priceCircular", priceCircular);
624
		return "categorywise-circular";
625
	}
626
 
28102 tejbeer 627
	@RequestMapping(value = "/partnerPriceCircular")
628
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
629
		int fofoId = Utils.SYSTEM_PARTNER_ID;
630
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
631
				.collect(Collectors.toSet());
632
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
633
				.collect(Collectors.toSet()));
634
		model.addAttribute("brands", brands);
635
		model.addAttribute("date", LocalDate.now());
636
 
637
		return "partner-price-circular";
638
	}
639
 
29788 amit.gupta 640
	@Autowired
641
	PriceCircularService priceCircularService;
28102 tejbeer 642
	@RequestMapping(value = "/priceCircularByBrand")
643
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model)
644
			throws ProfitMandiBusinessException {
645
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
646
 
647
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), LocalDate.now());
648
		List<PartnerType> partnerTypes = new ArrayList<>();
649
		partnerTypes.add(partnerType);
650
		partnerTypes.add(PartnerType.ALL);
29788 amit.gupta 651
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(loginDetails.getFofoId(), brand);
652
		for (PriceCircularItemModel pc : priceCircular.getPriceCircularItemModels()) {
653
			LOGGER.info("Slabs {}", pc.getSlabPayouts());
29793 amit.gupta 654
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() 
655
					+  pc.getUpfrontMargin()
656
					+  pc.getTertiaryPayout()
29846 amit.gupta 657
					+ pc.getUpgradeOffer()
29788 amit.gupta 658
					+ pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout() + pc.getModelSpecfic()
659
					+ (pc.getSlabPayouts()==null ? 0l:pc.getSlabPayouts().stream().filter(x->x!=null).collect(Collectors.summingLong(x->x.entrySet().stream().findFirst().get().getValue())));
28102 tejbeer 660
			pc.setTotalScheme(totalScheme);
661
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
662
			pc.setNetPrice(netprice);
663
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
664
			pc.setMopdp(mopdpdiff);
665
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
666
			long totalProfit = totalScheme + mopdpdiff;
28124 tejbeer 667
			pc.setTotalProfit((int) totalProfit);
28102 tejbeer 668
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
669
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
670
			pc.setNetMargin(roundOff);
671
		}
28136 tejbeer 672
 
673
		FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
29788 amit.gupta 674
		model.addAttribute("priceCircular", priceCircular.getPriceCircularItemModels());
675
		model.addAttribute("offers", priceCircular.getOffers());
29846 amit.gupta 676
		model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
28136 tejbeer 677
		model.addAttribute("partnerCode", fs.getCode());
28102 tejbeer 678
		return "price-circular-detail";
679
	}
680
 
28568 amit.gupta 681
	@RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
682
	public String selectPriceDropStatus(HttpServletRequest request,
683
			@RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
684
			Model model) throws Exception {
685
 
686
		model.addAttribute("selectedStatus", selectedStatus);
687
		return "pricedrop-status-change";
688
	}
689
 
23819 govind 690
}