Subversion Repositories SmartDukaan

Rev

Rev 31650 | Rev 31903 | 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
 
31852 amit.gupta 147
	private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin", "Modelwise");
30471 amit.gupta 148
	private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
149
	private static final List<String> ALL_MARGINS = Arrays.asList(SELLINS, SELLOUTS).stream().flatMap(x -> x.stream()).collect(Collectors.toList());
150
 
23819 govind 151
	@RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
23945 amit.gupta 152
	public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
28568 amit.gupta 153
		List<PriceDrop> priceDrops = priceDropRepository.selectAllIncomplete();
24191 amit.gupta 154
		Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
29654 tejbeer 155
 
24180 amit.gupta 156
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
24191 amit.gupta 157
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
158
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
23819 govind 159
		model.addAttribute("priceDrops", priceDrops);
23968 amit.gupta 160
		model.addAttribute("catalogDescription", catalogDescription);
23819 govind 161
		return "price-drop";
162
	}
24083 amit.gupta 163
 
28568 amit.gupta 164
	@RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
165
	public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
166
		List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
28889 amit.gupta 167
		int processOn = 1;
28568 amit.gupta 168
 
169
		List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
170
				.collect(Collectors.toList());
171
 
172
		Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
173
				.collect(Collectors.toSet());
174
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
175
		LOGGER.info("catalogIds" + catalogIds);
176
 
177
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
178
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
179
		model.addAttribute("priceDrops", completePriceDrops);
28642 amit.gupta 180
		model.addAttribute("processOn", processOn);
28568 amit.gupta 181
		model.addAttribute("catalogDescription", catalogDescription);
182
		return "price-drop";
183
	}
184
 
24049 amit.gupta 185
	@RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
186
	public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
24083 amit.gupta 187
 
24063 amit.gupta 188
		TagListing tagListing;
24049 amit.gupta 189
		PriceDropModel pm = new PriceDropModel();
24063 amit.gupta 190
		try {
191
			tagListing = tagListingRepository.selectByItemId(itemId);
24083 amit.gupta 192
			if (tagListing != null) {
24063 amit.gupta 193
				pm.setMop(tagListing.getMop());
194
				pm.setDp(tagListing.getSellingPrice());
195
				pm.setMrp(tagListing.getMrp());
196
				List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
24083 amit.gupta 197
				if (vips.size() > 0) {
24063 amit.gupta 198
					VendorItemPricing vip = vips.get(0);
199
					pm.setNlc(vip.getNlc());
200
					pm.setTp(vip.getTp());
201
				} else {
202
					throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
203
				}
204
			}
24083 amit.gupta 205
		} catch (Exception e) {
24063 amit.gupta 206
			LOGGER.info("Chose item that doesn't exist");
24049 amit.gupta 207
		}
31238 amit.gupta 208
		model.addAttribute("response1", mvcResponseSender.createResponseString(pm));
24049 amit.gupta 209
		return "response";
210
	}
24083 amit.gupta 211
 
24168 amit.gupta 212
	@RequestMapping(value = "/item", method = RequestMethod.GET)
28102 tejbeer 213
	public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
29951 amit.gupta 214
								 @RequestParam boolean anyColor) throws Throwable {
24383 amit.gupta 215
		String query1 = query.toLowerCase();
28102 tejbeer 216
 
217
		List<ItemDescriptionModel> partnersItemDescription = inventoryService
218
				.getAllPartnerItemStringDescription(anyColor).parallelStream()
219
				.filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
24564 amit.gupta 220
				.collect(Collectors.toList());
28102 tejbeer 221
		LOGGER.info("partnersItemDescription" + partnersItemDescription);
24168 amit.gupta 222
 
31238 amit.gupta 223
		model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
24168 amit.gupta 224
		return "response";
225
	}
226
 
23951 amit.gupta 227
	@RequestMapping(value = "/price-drop/imes/download")
228
	public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
29951 amit.gupta 229
																	@RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
23951 amit.gupta 230
		Item item = itemRepository.selectById(itemId);
26368 amit.gupta 231
		ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null);
23951 amit.gupta 232
		final HttpHeaders headers = new HttpHeaders();
233
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
25408 amit.gupta 234
		headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
23951 amit.gupta 235
		byte[] byteArray = baos.toByteArray();
236
		headers.setContentLength(byteArray.length);
237
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
238
	}
239
 
24083 amit.gupta 240
	@RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
241
	public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
29951 amit.gupta 242
								  Model model) throws Exception {
24083 amit.gupta 243
		boolean response = false;
244
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
245
		if (priceDrop.getProcessTimestamp() == null) {
246
			priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
247
			priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
248
			// priceDrop.setProcessTimestamp(LocalDateTime.now());
249
			priceDropRepository.persist(priceDrop);
250
			response = true;
251
		}
31238 amit.gupta 252
		model.addAttribute("response1", mvcResponseSender.createResponseString(response));
24083 amit.gupta 253
		return "response";
254
	}
255
 
256
	@RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
257
	public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
258
			throws Exception {
259
 
260
		PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
24564 amit.gupta 261
 
262
		// This call is used to persit imeis to pricedrop imeis in case its not there.
27071 amit.gupta 263
		// This should be called while creating price drop.
264
		// priceDropService.priceDropStatus(priceDropId);
24564 amit.gupta 265
 
24083 amit.gupta 266
		List<String> pendingImeis = new ArrayList<>();
267
		List<String> approvedImeis = new ArrayList<>();
268
		List<String> rejectedImeis = new ArrayList<>();
28568 amit.gupta 269
		List<String> holdImeis = new ArrayList<>();
24083 amit.gupta 270
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
271
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
272
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
273
				pendingImeis.add(priceDropIMEI.getImei());
274
			} else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
275
				approvedImeis.add(priceDropIMEI.getImei());
276
			}
277
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
278
				rejectedImeis.add(priceDropIMEI.getImei());
28568 amit.gupta 279
			} else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
280
				holdImeis.add(priceDropIMEI.getImei());
281
 
24083 amit.gupta 282
			}
283
		}
28568 amit.gupta 284
		LOGGER.info("pendingImeis" + pendingImeis);
285
		LOGGER.info("approvedImeis" + approvedImeis);
286
		LOGGER.info("rejectedImeis" + rejectedImeis);
287
		LOGGER.info("priceDropImeis" + priceDropImeis);
288
 
24083 amit.gupta 289
		priceDropImeisModel.setPendingImeis(pendingImeis);
290
		priceDropImeisModel.setPriceDropId(priceDropId);
291
		priceDropImeisModel.setApprovedImeis(approvedImeis);
28568 amit.gupta 292
		priceDropImeisModel.setHoldImeis(holdImeis);
24083 amit.gupta 293
		priceDropImeisModel.setRejectedImeis(rejectedImeis);
31238 amit.gupta 294
		model.addAttribute("response1", mvcResponseSender.createResponseString(priceDropImeisModel));
24083 amit.gupta 295
		return "response";
296
	}
297
 
23968 amit.gupta 298
	@RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
27071 amit.gupta 299
	public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
29951 amit.gupta 300
								   Model model) throws Exception {
27071 amit.gupta 301
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
23968 amit.gupta 302
		boolean response = false;
28102 tejbeer 303
		if (priceDrop.getPartnerPayout() == 0) {
27071 amit.gupta 304
			priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
305
		}
306
		priceDrop.setProcessTimestamp(LocalDateTime.now());
307
		priceDropRepository.persist(priceDrop);
308
		priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
28102 tejbeer 309
		response = true;
31238 amit.gupta 310
		model.addAttribute("response1", mvcResponseSender.createResponseString(response));
23968 amit.gupta 311
		return "response";
23819 govind 312
	}
24083 amit.gupta 313
 
23884 amit.gupta 314
	@RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
23945 amit.gupta 315
	public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
316
			throws Exception {
23884 amit.gupta 317
		boolean response = false;
23968 amit.gupta 318
		priceDropModel.setAllColors(true);
23945 amit.gupta 319
		if (this.validatePriceDrop(priceDropModel)) {
23884 amit.gupta 320
			TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
24409 amit.gupta 321
			float oldDp = tagListing.getSellingPrice();
24410 amit.gupta 322
			float oldMop = tagListing.getMop();
323
			float oldTp = 0;
24409 amit.gupta 324
			float newDp = priceDropModel.getDp();
24564 amit.gupta 325
 
24410 amit.gupta 326
			if (newDp != oldDp) {
23884 amit.gupta 327
				List<Item> allItems = null;
328
				Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
23945 amit.gupta 329
				if (priceDropModel.isAllColors()) {
23884 amit.gupta 330
					allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
23945 amit.gupta 331
 
23884 amit.gupta 332
				} else {
23945 amit.gupta 333
					allItems = Arrays.asList(currentItem);
23884 amit.gupta 334
				}
23945 amit.gupta 335
				for (Item item : allItems) {
23884 amit.gupta 336
					TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
23945 amit.gupta 337
					if (itemTagListing == null)
338
						continue;
23884 amit.gupta 339
					itemTagListing.setSellingPrice(newDp);
340
					itemTagListing.setMop(priceDropModel.getMop());
341
					List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
23945 amit.gupta 342
					for (VendorItemPricing vip : vipList) {
24410 amit.gupta 343
						oldTp = vip.getNlc();
23884 amit.gupta 344
						vip.setDp(newDp);
345
						vip.setMop(priceDropModel.getMop());
31650 amit.gupta 346
						//Lets not update NLC/TP as it has to be managed by Category Tea,
347
						//vip.setNlc(priceDropModel.getTp());
348
						//vip.setTp(priceDropModel.getTp());
23884 amit.gupta 349
						vendorItemPricingRepository.persist(vip);
350
					}
351
					transactionService.updatePriceDrop(item.getId(), newDp);
352
				}
27071 amit.gupta 353
 
354
				// Add to itemPricing history
24822 amit.gupta 355
				ItemPricingHistory iph = new ItemPricingHistory();
356
				iph.setCatalogId(currentItem.getCatalogItemId());
357
				iph.setTp(priceDropModel.getTp());
358
				iph.setDp(priceDropModel.getDp());
359
				iph.setMop(priceDropModel.getMop());
27071 amit.gupta 360
				// TODO: changedBy
24822 amit.gupta 361
				iph.setChangedBy("me");
362
				iph.setCreateTimestamp(LocalDateTime.now());
363
				itemPricingHistoryRepository.persist(iph);
27071 amit.gupta 364
 
23951 amit.gupta 365
				PriceDrop priceDrop = new PriceDrop();
366
				priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
24410 amit.gupta 367
				priceDrop.setTp(oldTp);
368
				priceDrop.setNlc(oldTp);
369
				priceDrop.setMop(oldMop);
24409 amit.gupta 370
				priceDrop.setOldDp(oldDp);
371
				priceDrop.setAmount(oldDp - newDp);
23968 amit.gupta 372
				priceDrop.setNewDp(newDp);
23951 amit.gupta 373
				priceDrop.setCreatedOn(LocalDateTime.now());
374
				priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
375
				priceDropRepository.persist(priceDrop);
26116 amit.gupta 376
				priceDropService.priceDropStatus(priceDrop.getId());
23884 amit.gupta 377
				response = true;
29926 amit.gupta 378
 
379
				this.sendPriceChangeNotification(priceDrop);
23884 amit.gupta 380
			} else {
23945 amit.gupta 381
				throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
24409 amit.gupta 382
						"Price Drop Should be greater than 0");
23884 amit.gupta 383
			}
384
		}
31238 amit.gupta 385
		model.addAttribute("response1", mvcResponseSender.createResponseString(response));
23884 amit.gupta 386
		return "response";
387
	}
29951 amit.gupta 388
 
29926 amit.gupta 389
	private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
390
		List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
391
		String title = "Price has been %s for %s";
23945 amit.gupta 392
 
29926 amit.gupta 393
 
394
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
395
		sendNotificationModel.setCampaignName("pricechange");
396
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
397
		sendNotificationModel.setTitle("");
398
		StringBuffer sb = new StringBuffer();
399
		String message = null;
29951 amit.gupta 400
		if (priceDrop.getDropAmount() > 0) {
29926 amit.gupta 401
			title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
30032 amit.gupta 402
			message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
403
					FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
29926 amit.gupta 404
		} else {
405
			title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
30032 amit.gupta 406
			message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
407
					FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
29926 amit.gupta 408
		}
409
		sendNotificationModel.setTitle(title);
410
		sendNotificationModel.setMessage(message);
411
		sendNotificationModel.setMessageType(MessageType.pricechange);
29927 amit.gupta 412
		notificationService.sendNotificationToAll(sendNotificationModel);
29926 amit.gupta 413
	}
414
 
23819 govind 415
	@RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
416
	public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
29951 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));
30638 amit.gupta 422
		LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
23968 amit.gupta 423
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
424
		final HttpHeaders headers = new HttpHeaders();
425
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 426
		headers.set("Content-disposition",
427
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
428
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
30385 amit.gupta 429
		ByteArrayOutputStream baos = null;
30386 amit.gupta 430
		if (priceDropIMEIsMap.size() == 0) {
30385 amit.gupta 431
			priceDropService.priceDropStatus(priceDrop.getId());
432
			baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
433
					"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
434
					"Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
435
		} else {
30638 amit.gupta 436
 
437
			LOGGER.info("In else block");
30385 amit.gupta 438
			baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
439
					priceDropIMEIsMap);
440
		}
23968 amit.gupta 441
		byte[] byteArray = baos.toByteArray();
442
		headers.setContentLength(byteArray.length);
443
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 444
 
445
	}
446
 
28568 amit.gupta 447
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
27071 amit.gupta 448
	public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
29951 amit.gupta 449
									   Model model) throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 450
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
28889 amit.gupta 451
 
24083 amit.gupta 452
		switch (priceDropImeisModel.getUpdatedStatus()) {
29951 amit.gupta 453
			case "approved": {
454
				status = PriceDropImeiStatus.APPROVED;
455
				break;
456
			}
457
			case "hold": {
458
				status = PriceDropImeiStatus.HOLD;
459
				break;
460
			}
461
			case "rejected": {
462
				status = PriceDropImeiStatus.REJECTED;
463
				break;
464
			}
24083 amit.gupta 465
		}
28889 amit.gupta 466
		PriceDropImeiStatus finalStatus = status;
27071 amit.gupta 467
 
468
		if (PriceDropImeiStatus.PENDING.equals(status)) {
28568 amit.gupta 469
 
470
			List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
28641 amit.gupta 471
			List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
28568 amit.gupta 472
					priceDropImeisModel.getPriceDropId());
473
			LOGGER.info("hello" + priceDropIMEIs);
474
			for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
475
				if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
476
					if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
477
							|| priceDropHoldIMEI.getStatus().equals(status)) {
478
						continue;
479
					}
480
					priceDropIMEIsToHolds.add(priceDropHoldIMEI);
481
					priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
31009 amit.gupta 482
					//priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
28568 amit.gupta 483
				} else {
484
					throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
485
							"Pending Status is allowed  only for Hold IMIEs");
486
				}
487
			}
31238 amit.gupta 488
			model.addAttribute("response1", mvcResponseSender.createResponseString(true));
28889 amit.gupta 489
			return "response";
27071 amit.gupta 490
		}
491
 
492
		// TODO:PD
24083 amit.gupta 493
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
494
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
495
 
28889 amit.gupta 496
		List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
497
				.filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
29654 tejbeer 498
				.filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
28568 amit.gupta 499
 
31852 amit.gupta 500
        /*for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 501
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
31009 amit.gupta 502
		}*/
28568 amit.gupta 503
 
28889 amit.gupta 504
		if (status.equals(PriceDropImeiStatus.APPROVED)) {
505
			priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
506
					priceDropImeisModel.getUpdatedImeis());
507
		}
508
		for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
509
			if (status.equals(PriceDropImeiStatus.REJECTED)
510
					&& priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
511
				priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
512
				priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
31009 amit.gupta 513
				priceDropImei.setRejectTimestamp(LocalDateTime.now());
28889 amit.gupta 514
			} else if (status.equals(PriceDropImeiStatus.HOLD)) {
515
				if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
516
					priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
517
				} else {
28568 amit.gupta 518
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
519
				}
520
 
521
			}
522
 
523
		}
524
 
31238 amit.gupta 525
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
24083 amit.gupta 526
		return "response";
527
 
528
	}
529
 
27071 amit.gupta 530
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
29951 amit.gupta 531
														   Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 532
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
533
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 534
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 535
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 536
			if (priceDropImeis == null) {
26368 amit.gupta 537
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 538
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 539
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
540
			}
23951 amit.gupta 541
		}
27071 amit.gupta 542
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
543
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
544
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 545
	}
24083 amit.gupta 546
 
27071 amit.gupta 547
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
29951 amit.gupta 548
												PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 549
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 550
		row.add(imeiDropSummaryModel.getSerialNumber());
551
		row.add(imeiDropSummaryModel.getStoreName());
552
		row.add(imeiDropSummaryModel.getPartnerCode());
553
		row.add(imeiDropSummaryModel.getItemId());
554
		row.add(imeiDropSummaryModel.getBrand());
555
		row.add(imeiDropSummaryModel.getModelName());
556
		row.add(imeiDropSummaryModel.getModelNumber());
557
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 558
		if (priceDropIMEI != null) {
26368 amit.gupta 559
			row.add(priceDropIMEI.getStatus());
560
			row.add(priceDropIMEI.getRejectionReason());
561
		} else {
562
			row.add(PriceDropImeiStatus.PENDING);
563
			row.add("");
564
		}
26373 amit.gupta 565
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
566
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 567
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 568
		row.add(imeiDropSummaryModel.getActivationTimestamp());
569
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 570
		return row;
571
	}
23819 govind 572
 
23884 amit.gupta 573
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 574
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 575
			return true;
576
		}
577
		return false;
578
	}
23945 amit.gupta 579
 
28102 tejbeer 580
	@RequestMapping(value = "/priceCircular")
581
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
582
		int fofoId = Utils.SYSTEM_PARTNER_ID;
583
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
584
				.collect(Collectors.toSet());
28142 tejbeer 585
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
586
				.collect(Collectors.toSet()));
28102 tejbeer 587
 
588
		model.addAttribute("brands", brands);
29951 amit.gupta 589
		model.addAttribute("isAdmin", true);
29957 amit.gupta 590
		model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 591
 
29951 amit.gupta 592
		return "partner-price-circular";
28102 tejbeer 593
	}
594
 
595
	@RequestMapping(value = "/partnerPriceCircular")
596
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
597
		int fofoId = Utils.SYSTEM_PARTNER_ID;
598
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
599
				.collect(Collectors.toSet());
600
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
601
				.collect(Collectors.toSet()));
602
		model.addAttribute("brands", brands);
29951 amit.gupta 603
		model.addAttribute("isAdmin", false);
28102 tejbeer 604
 
605
		return "partner-price-circular";
606
	}
607
 
29788 amit.gupta 608
	@Autowired
609
	PriceCircularService priceCircularService;
29951 amit.gupta 610
 
28102 tejbeer 611
	@RequestMapping(value = "/priceCircularByBrand")
29951 amit.gupta 612
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
28102 tejbeer 613
			throws ProfitMandiBusinessException {
614
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29951 amit.gupta 615
		if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
616
		} else {
617
			fofoId = loginDetails.getFofoId();
618
		}
619
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
28102 tejbeer 620
		List<PartnerType> partnerTypes = new ArrayList<>();
621
		partnerTypes.add(partnerType);
622
		partnerTypes.add(PartnerType.ALL);
29951 amit.gupta 623
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand);
30471 amit.gupta 624
		PriceCircularItemModel summaryModel = this.getSummaryModel(priceCircular);
625
		List<String> allMargins = ALL_MARGINS.stream().filter(payoutType -> summaryModel.getByPayoutType(payoutType) > 0).collect(Collectors.toList());
626
		List<String> sellins = SELLINS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
627
		List<String> sellouts = SELLOUTS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
628
		LOGGER.info("All margins - {}", allMargins);
629
		LOGGER.info("Sellins - {}", sellins);
630
		LOGGER.info("Sellouts - {}", sellouts);
29951 amit.gupta 631
		FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
29788 amit.gupta 632
		model.addAttribute("priceCircular", priceCircular.getPriceCircularItemModels());
30471 amit.gupta 633
		model.addAttribute("allMargins", allMargins);
634
		model.addAttribute("sellins", sellins);
635
		model.addAttribute("sellouts", sellouts);
29788 amit.gupta 636
		model.addAttribute("offers", priceCircular.getOffers());
29846 amit.gupta 637
		model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
28136 tejbeer 638
		model.addAttribute("partnerCode", fs.getCode());
28102 tejbeer 639
		return "price-circular-detail";
640
	}
641
 
30472 amit.gupta 642
	//private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
643
	//private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 644
	private PriceCircularItemModel getSummaryModel(PriceCircularModel priceCircular) {
30250 amit.gupta 645
 
30471 amit.gupta 646
		PriceCircularItemModel summaryModel = new PriceCircularItemModel();
647
		priceCircular.getPriceCircularItemModels().stream().forEach(x -> {
648
			if (summaryModel.getBasePayout() == 0 && x.getBasePayout() > 0) {
649
				summaryModel.setBasePayout(1);
650
			}
30472 amit.gupta 651
			if (summaryModel.getCashDiscount() == 0 && x.getCashDiscount() > 0) {
652
				summaryModel.setCashDiscount(1);
653
			}
30471 amit.gupta 654
			if (summaryModel.getSpecialSupport() == 0 && x.getSpecialSupport() > 0) {
655
				summaryModel.setSpecialSupport(1);
656
			}
657
			if (summaryModel.getCategoryPayout() == 0 && x.getCategoryPayout() > 0) {
30472 amit.gupta 658
				summaryModel.setCategoryPayout(1);
30471 amit.gupta 659
			}
660
			if (summaryModel.getTertiaryPayout() == 0 && x.getTertiaryPayout() > 0) {
661
				summaryModel.setTertiaryPayout(1);
662
			}
663
			if (summaryModel.getModelSpecfic() == 0 && x.getModelSpecfic() > 0) {
664
				summaryModel.setModelSpecfic(1);
665
			}
666
			if (summaryModel.getUpfrontMargin() == 0 && x.getUpfrontMargin() > 0) {
667
				summaryModel.setUpfrontMargin(1);
668
			}
669
			if (summaryModel.getHygienePayout() == 0 && x.getHygienePayout() > 0) {
670
				summaryModel.setHygienePayout(1);
671
			}
672
			if (summaryModel.getInvestmentPayout() == 0 && x.getInvestmentPayout() > 0) {
673
				summaryModel.setInvestmentPayout(1);
674
			}
31852 amit.gupta 675
			if (summaryModel.getModelWise() == 0 && x.getModelWise() > 0) {
676
				summaryModel.setModelWise(1);
677
			}
30471 amit.gupta 678
		});
679
 
30562 amit.gupta 680
		LOGGER.info("Summary Model {}", summaryModel);
681
 
30471 amit.gupta 682
		return summaryModel;
683
	}
684
 
685
 
30250 amit.gupta 686
	@RequestMapping(value = "/downloadNlcByBrand")
687
	public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
688
																@RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
689
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
690
		if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
691
		} else {
692
			fofoId = loginDetails.getFofoId();
693
		}
694
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
695
		List<PartnerType> partnerTypes = new ArrayList<>();
696
		partnerTypes.add(partnerType);
697
		partnerTypes.add(PartnerType.ALL);
698
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand);
699
		ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
700
		final HttpHeaders headers = new HttpHeaders();
701
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
702
		headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
703
		byte[] byteArray = baos.toByteArray();
704
		headers.setContentLength(byteArray.length);
705
		return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
706
	}
707
 
708
	private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
709
		List<List<?>> rows = new ArrayList<>();
710
		for (PriceCircularItemModel priceCircularItemModel : priceCircular.getPriceCircularItemModels()) {
711
			List<Serializable> row = new ArrayList<>();
712
			row.add(priceCircularItemModel.getCatalogId());
713
			row.add(brand);
714
			row.add(priceCircularItemModel.getModelName());
715
			row.add(priceCircularItemModel.getModelNumber());
716
			row.add(priceCircularItemModel.getNetPrice());
717
			rows.add(row);
718
		}
719
		return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
720
	}
721
 
28568 amit.gupta 722
	@RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
723
	public String selectPriceDropStatus(HttpServletRequest request,
29951 amit.gupta 724
										@RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
725
										Model model) throws Exception {
28568 amit.gupta 726
 
727
		model.addAttribute("selectedStatus", selectedStatus);
728
		return "pricedrop-status-change";
729
	}
730
 
23819 govind 731
}