Subversion Repositories SmartDukaan

Rev

Rev 31170 | Rev 31650 | 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
 
30471 amit.gupta 147
	private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
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());
24409 amit.gupta 346
						vip.setNlc(priceDropModel.getTp());
23884 amit.gupta 347
						vip.setTp(priceDropModel.getTp());
348
						vendorItemPricingRepository.persist(vip);
349
					}
350
					transactionService.updatePriceDrop(item.getId(), newDp);
351
				}
27071 amit.gupta 352
 
353
				// Add to itemPricing history
24822 amit.gupta 354
				ItemPricingHistory iph = new ItemPricingHistory();
355
				iph.setCatalogId(currentItem.getCatalogItemId());
356
				iph.setTp(priceDropModel.getTp());
357
				iph.setDp(priceDropModel.getDp());
358
				iph.setMop(priceDropModel.getMop());
27071 amit.gupta 359
				// TODO: changedBy
24822 amit.gupta 360
				iph.setChangedBy("me");
361
				iph.setCreateTimestamp(LocalDateTime.now());
362
				itemPricingHistoryRepository.persist(iph);
27071 amit.gupta 363
 
23951 amit.gupta 364
				PriceDrop priceDrop = new PriceDrop();
365
				priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
24410 amit.gupta 366
				priceDrop.setTp(oldTp);
367
				priceDrop.setNlc(oldTp);
368
				priceDrop.setMop(oldMop);
24409 amit.gupta 369
				priceDrop.setOldDp(oldDp);
370
				priceDrop.setAmount(oldDp - newDp);
23968 amit.gupta 371
				priceDrop.setNewDp(newDp);
23951 amit.gupta 372
				priceDrop.setCreatedOn(LocalDateTime.now());
373
				priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
374
				priceDropRepository.persist(priceDrop);
26116 amit.gupta 375
				priceDropService.priceDropStatus(priceDrop.getId());
23884 amit.gupta 376
				response = true;
29926 amit.gupta 377
 
378
				this.sendPriceChangeNotification(priceDrop);
23884 amit.gupta 379
			} else {
23945 amit.gupta 380
				throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
24409 amit.gupta 381
						"Price Drop Should be greater than 0");
23884 amit.gupta 382
			}
383
		}
31238 amit.gupta 384
		model.addAttribute("response1", mvcResponseSender.createResponseString(response));
23884 amit.gupta 385
		return "response";
386
	}
29951 amit.gupta 387
 
29926 amit.gupta 388
	private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
389
		List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
390
		String title = "Price has been %s for %s";
23945 amit.gupta 391
 
29926 amit.gupta 392
 
393
		SendNotificationModel sendNotificationModel = new SendNotificationModel();
394
		sendNotificationModel.setCampaignName("pricechange");
395
		sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
396
		sendNotificationModel.setTitle("");
397
		StringBuffer sb = new StringBuffer();
398
		String message = null;
29951 amit.gupta 399
		if (priceDrop.getDropAmount() > 0) {
29926 amit.gupta 400
			title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
30032 amit.gupta 401
			message = String.format("Price has been dropped 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
		} else {
404
			title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
30032 amit.gupta 405
			message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
406
					FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
29926 amit.gupta 407
		}
408
		sendNotificationModel.setTitle(title);
409
		sendNotificationModel.setMessage(message);
410
		sendNotificationModel.setMessageType(MessageType.pricechange);
29927 amit.gupta 411
		notificationService.sendNotificationToAll(sendNotificationModel);
29926 amit.gupta 412
	}
413
 
23819 govind 414
	@RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
415
	public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
29951 amit.gupta 416
														Model model) throws ProfitMandiBusinessException, Exception {
23819 govind 417
 
418
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
27071 amit.gupta 419
		Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
420
				.collect(Collectors.toMap(x -> x.getImei(), x -> x));
30638 amit.gupta 421
		LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
23968 amit.gupta 422
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
423
		final HttpHeaders headers = new HttpHeaders();
424
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 425
		headers.set("Content-disposition",
426
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
427
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
30385 amit.gupta 428
		ByteArrayOutputStream baos = null;
30386 amit.gupta 429
		if (priceDropIMEIsMap.size() == 0) {
30385 amit.gupta 430
			priceDropService.priceDropStatus(priceDrop.getId());
431
			baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
432
					"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
433
					"Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
434
		} else {
30638 amit.gupta 435
 
436
			LOGGER.info("In else block");
30385 amit.gupta 437
			baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
438
					priceDropIMEIsMap);
439
		}
23968 amit.gupta 440
		byte[] byteArray = baos.toByteArray();
441
		headers.setContentLength(byteArray.length);
442
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 443
 
444
	}
445
 
28568 amit.gupta 446
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
27071 amit.gupta 447
	public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
29951 amit.gupta 448
									   Model model) throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 449
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
28889 amit.gupta 450
 
24083 amit.gupta 451
		switch (priceDropImeisModel.getUpdatedStatus()) {
29951 amit.gupta 452
			case "approved": {
453
				status = PriceDropImeiStatus.APPROVED;
454
				break;
455
			}
456
			case "hold": {
457
				status = PriceDropImeiStatus.HOLD;
458
				break;
459
			}
460
			case "rejected": {
461
				status = PriceDropImeiStatus.REJECTED;
462
				break;
463
			}
24083 amit.gupta 464
		}
28889 amit.gupta 465
		PriceDropImeiStatus finalStatus = status;
27071 amit.gupta 466
 
467
		if (PriceDropImeiStatus.PENDING.equals(status)) {
28568 amit.gupta 468
 
469
			List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
28641 amit.gupta 470
			List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
28568 amit.gupta 471
					priceDropImeisModel.getPriceDropId());
472
			LOGGER.info("hello" + priceDropIMEIs);
473
			for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
474
				if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
475
					if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
476
							|| priceDropHoldIMEI.getStatus().equals(status)) {
477
						continue;
478
					}
479
					priceDropIMEIsToHolds.add(priceDropHoldIMEI);
480
					priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
31009 amit.gupta 481
					//priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
28568 amit.gupta 482
				} else {
483
					throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
484
							"Pending Status is allowed  only for Hold IMIEs");
485
				}
486
			}
31238 amit.gupta 487
			model.addAttribute("response1", mvcResponseSender.createResponseString(true));
28889 amit.gupta 488
			return "response";
27071 amit.gupta 489
		}
490
 
491
		// TODO:PD
24083 amit.gupta 492
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
493
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
494
 
28889 amit.gupta 495
		List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
496
				.filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
29654 tejbeer 497
				.filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
28568 amit.gupta 498
 
31009 amit.gupta 499
		/*for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 500
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
31009 amit.gupta 501
		}*/
28568 amit.gupta 502
 
28889 amit.gupta 503
		if (status.equals(PriceDropImeiStatus.APPROVED)) {
504
			priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
505
					priceDropImeisModel.getUpdatedImeis());
506
		}
507
		for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
508
			if (status.equals(PriceDropImeiStatus.REJECTED)
509
					&& priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
510
				priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
511
				priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
31009 amit.gupta 512
				priceDropImei.setRejectTimestamp(LocalDateTime.now());
28889 amit.gupta 513
			} else if (status.equals(PriceDropImeiStatus.HOLD)) {
514
				if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
515
					priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
516
				} else {
28568 amit.gupta 517
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
518
				}
519
 
520
			}
521
 
522
		}
523
 
31238 amit.gupta 524
		model.addAttribute("response1", mvcResponseSender.createResponseString(true));
24083 amit.gupta 525
		return "response";
526
 
527
	}
528
 
27071 amit.gupta 529
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
29951 amit.gupta 530
														   Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 531
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
532
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 533
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 534
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 535
			if (priceDropImeis == null) {
26368 amit.gupta 536
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 537
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 538
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
539
			}
23951 amit.gupta 540
		}
27071 amit.gupta 541
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
542
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
543
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 544
	}
24083 amit.gupta 545
 
27071 amit.gupta 546
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
29951 amit.gupta 547
												PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 548
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 549
		row.add(imeiDropSummaryModel.getSerialNumber());
550
		row.add(imeiDropSummaryModel.getStoreName());
551
		row.add(imeiDropSummaryModel.getPartnerCode());
552
		row.add(imeiDropSummaryModel.getItemId());
553
		row.add(imeiDropSummaryModel.getBrand());
554
		row.add(imeiDropSummaryModel.getModelName());
555
		row.add(imeiDropSummaryModel.getModelNumber());
556
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 557
		if (priceDropIMEI != null) {
26368 amit.gupta 558
			row.add(priceDropIMEI.getStatus());
559
			row.add(priceDropIMEI.getRejectionReason());
560
		} else {
561
			row.add(PriceDropImeiStatus.PENDING);
562
			row.add("");
563
		}
26373 amit.gupta 564
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
565
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 566
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 567
		row.add(imeiDropSummaryModel.getActivationTimestamp());
568
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 569
		return row;
570
	}
23819 govind 571
 
23884 amit.gupta 572
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 573
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 574
			return true;
575
		}
576
		return false;
577
	}
23945 amit.gupta 578
 
28102 tejbeer 579
	@RequestMapping(value = "/priceCircular")
580
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
581
		int fofoId = Utils.SYSTEM_PARTNER_ID;
582
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
583
				.collect(Collectors.toSet());
28142 tejbeer 584
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
585
				.collect(Collectors.toSet()));
28102 tejbeer 586
 
587
		model.addAttribute("brands", brands);
29951 amit.gupta 588
		model.addAttribute("isAdmin", true);
29957 amit.gupta 589
		model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 590
 
29951 amit.gupta 591
		return "partner-price-circular";
28102 tejbeer 592
	}
593
 
594
	@RequestMapping(value = "/partnerPriceCircular")
595
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
596
		int fofoId = Utils.SYSTEM_PARTNER_ID;
597
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
598
				.collect(Collectors.toSet());
599
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
600
				.collect(Collectors.toSet()));
601
		model.addAttribute("brands", brands);
29951 amit.gupta 602
		model.addAttribute("isAdmin", false);
28102 tejbeer 603
 
604
		return "partner-price-circular";
605
	}
606
 
29788 amit.gupta 607
	@Autowired
608
	PriceCircularService priceCircularService;
29951 amit.gupta 609
 
28102 tejbeer 610
	@RequestMapping(value = "/priceCircularByBrand")
29951 amit.gupta 611
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
28102 tejbeer 612
			throws ProfitMandiBusinessException {
613
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29951 amit.gupta 614
		if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
615
		} else {
616
			fofoId = loginDetails.getFofoId();
617
		}
618
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
28102 tejbeer 619
		List<PartnerType> partnerTypes = new ArrayList<>();
620
		partnerTypes.add(partnerType);
621
		partnerTypes.add(PartnerType.ALL);
29951 amit.gupta 622
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand);
30471 amit.gupta 623
		PriceCircularItemModel summaryModel = this.getSummaryModel(priceCircular);
624
		List<String> allMargins = ALL_MARGINS.stream().filter(payoutType -> summaryModel.getByPayoutType(payoutType) > 0).collect(Collectors.toList());
625
		List<String> sellins = SELLINS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
626
		List<String> sellouts = SELLOUTS.stream().filter(x -> allMargins.contains(x)).collect(Collectors.toList());
627
		LOGGER.info("All margins - {}", allMargins);
628
		LOGGER.info("Sellins - {}", sellins);
629
		LOGGER.info("Sellouts - {}", sellouts);
29951 amit.gupta 630
		FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
29788 amit.gupta 631
		model.addAttribute("priceCircular", priceCircular.getPriceCircularItemModels());
30471 amit.gupta 632
		model.addAttribute("allMargins", allMargins);
633
		model.addAttribute("sellins", sellins);
634
		model.addAttribute("sellouts", sellouts);
29788 amit.gupta 635
		model.addAttribute("offers", priceCircular.getOffers());
29846 amit.gupta 636
		model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
28136 tejbeer 637
		model.addAttribute("partnerCode", fs.getCode());
28102 tejbeer 638
		return "price-circular-detail";
639
	}
640
 
30472 amit.gupta 641
	//private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
642
	//private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");
30471 amit.gupta 643
	private PriceCircularItemModel getSummaryModel(PriceCircularModel priceCircular) {
30250 amit.gupta 644
 
30471 amit.gupta 645
		PriceCircularItemModel summaryModel = new PriceCircularItemModel();
646
		priceCircular.getPriceCircularItemModels().stream().forEach(x -> {
647
			if (summaryModel.getBasePayout() == 0 && x.getBasePayout() > 0) {
648
				summaryModel.setBasePayout(1);
649
			}
30472 amit.gupta 650
			if (summaryModel.getCashDiscount() == 0 && x.getCashDiscount() > 0) {
651
				summaryModel.setCashDiscount(1);
652
			}
30471 amit.gupta 653
			if (summaryModel.getSpecialSupport() == 0 && x.getSpecialSupport() > 0) {
654
				summaryModel.setSpecialSupport(1);
655
			}
656
			if (summaryModel.getCategoryPayout() == 0 && x.getCategoryPayout() > 0) {
30472 amit.gupta 657
				summaryModel.setCategoryPayout(1);
30471 amit.gupta 658
			}
659
			if (summaryModel.getTertiaryPayout() == 0 && x.getTertiaryPayout() > 0) {
660
				summaryModel.setTertiaryPayout(1);
661
			}
662
			if (summaryModel.getModelSpecfic() == 0 && x.getModelSpecfic() > 0) {
663
				summaryModel.setModelSpecfic(1);
664
			}
665
			if (summaryModel.getUpfrontMargin() == 0 && x.getUpfrontMargin() > 0) {
666
				summaryModel.setUpfrontMargin(1);
667
			}
668
			if (summaryModel.getHygienePayout() == 0 && x.getHygienePayout() > 0) {
669
				summaryModel.setHygienePayout(1);
670
			}
671
			if (summaryModel.getInvestmentPayout() == 0 && x.getInvestmentPayout() > 0) {
672
				summaryModel.setInvestmentPayout(1);
673
			}
674
		});
675
 
30562 amit.gupta 676
		LOGGER.info("Summary Model {}", summaryModel);
677
 
30471 amit.gupta 678
		return summaryModel;
679
	}
680
 
681
 
30250 amit.gupta 682
	@RequestMapping(value = "/downloadNlcByBrand")
683
	public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
684
																@RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
685
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
686
		if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
687
		} else {
688
			fofoId = loginDetails.getFofoId();
689
		}
690
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
691
		List<PartnerType> partnerTypes = new ArrayList<>();
692
		partnerTypes.add(partnerType);
693
		partnerTypes.add(PartnerType.ALL);
694
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand);
695
		ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
696
		final HttpHeaders headers = new HttpHeaders();
697
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
698
		headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
699
		byte[] byteArray = baos.toByteArray();
700
		headers.setContentLength(byteArray.length);
701
		return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
702
	}
703
 
704
	private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
705
		List<List<?>> rows = new ArrayList<>();
706
		for (PriceCircularItemModel priceCircularItemModel : priceCircular.getPriceCircularItemModels()) {
707
			List<Serializable> row = new ArrayList<>();
708
			row.add(priceCircularItemModel.getCatalogId());
709
			row.add(brand);
710
			row.add(priceCircularItemModel.getModelName());
711
			row.add(priceCircularItemModel.getModelNumber());
712
			row.add(priceCircularItemModel.getNetPrice());
713
			rows.add(row);
714
		}
715
		return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
716
	}
717
 
28568 amit.gupta 718
	@RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
719
	public String selectPriceDropStatus(HttpServletRequest request,
29951 amit.gupta 720
										@RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
721
										Model model) throws Exception {
28568 amit.gupta 722
 
723
		model.addAttribute("selectedStatus", selectedStatus);
724
		return "pricedrop-status-change";
725
	}
726
 
23819 govind 727
}