Subversion Repositories SmartDukaan

Rev

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