Subversion Repositories SmartDukaan

Rev

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