Subversion Repositories SmartDukaan

Rev

Rev 30043 | Rev 30250 | 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
 
418
		if (priceDropIMEIsMap.size() == 0 && priceDrop.getProcessTimestamp() == null) {
26372 amit.gupta 419
			priceDrop.setProcessTimestamp(LocalDateTime.now());
420
		} else {
421
			priceDropService.priceDropStatus(priceDrop.getId());
422
		}
27071 amit.gupta 423
 
23968 amit.gupta 424
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
27071 amit.gupta 425
		ByteArrayOutputStream baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(),
426
				priceDropIMEIsMap);
23968 amit.gupta 427
		final HttpHeaders headers = new HttpHeaders();
428
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 429
		headers.set("Content-disposition",
430
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
431
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
23968 amit.gupta 432
		byte[] byteArray = baos.toByteArray();
433
		headers.setContentLength(byteArray.length);
434
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 435
 
436
	}
437
 
28568 amit.gupta 438
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
27071 amit.gupta 439
	public String updatePriceDropImeis(HttpServletRequest request, @RequestBody PriceDropImeisModel priceDropImeisModel,
29951 amit.gupta 440
									   Model model) throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 441
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
28889 amit.gupta 442
 
24083 amit.gupta 443
		switch (priceDropImeisModel.getUpdatedStatus()) {
29951 amit.gupta 444
			case "approved": {
445
				status = PriceDropImeiStatus.APPROVED;
446
				break;
447
			}
448
			case "hold": {
449
				status = PriceDropImeiStatus.HOLD;
450
				break;
451
			}
452
			case "rejected": {
453
				status = PriceDropImeiStatus.REJECTED;
454
				break;
455
			}
24083 amit.gupta 456
		}
28889 amit.gupta 457
		PriceDropImeiStatus finalStatus = status;
27071 amit.gupta 458
 
459
		if (PriceDropImeiStatus.PENDING.equals(status)) {
28568 amit.gupta 460
 
461
			List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
28641 amit.gupta 462
			List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
28568 amit.gupta 463
					priceDropImeisModel.getPriceDropId());
464
			LOGGER.info("hello" + priceDropIMEIs);
465
			for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
466
				if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
467
					if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
468
							|| priceDropHoldIMEI.getStatus().equals(status)) {
469
						continue;
470
					}
471
					priceDropIMEIsToHolds.add(priceDropHoldIMEI);
472
					priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
473
					priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
474
				} else {
475
					throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
476
							"Pending Status is allowed  only for Hold IMIEs");
477
				}
478
			}
28889 amit.gupta 479
			model.addAttribute("response", mvcResponseSender.createResponseString(true));
480
			return "response";
27071 amit.gupta 481
		}
482
 
483
		// TODO:PD
24083 amit.gupta 484
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
485
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
486
 
28889 amit.gupta 487
		List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
488
				.filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
29654 tejbeer 489
				.filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
28568 amit.gupta 490
 
28889 amit.gupta 491
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 492
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
24083 amit.gupta 493
		}
28568 amit.gupta 494
 
28889 amit.gupta 495
		if (status.equals(PriceDropImeiStatus.APPROVED)) {
496
			priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
497
					priceDropImeisModel.getUpdatedImeis());
498
		}
499
		for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
500
			if (status.equals(PriceDropImeiStatus.REJECTED)
501
					&& priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
502
				priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
503
				priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
504
			} else if (status.equals(PriceDropImeiStatus.HOLD)) {
505
				if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
506
					priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
507
				} else {
28568 amit.gupta 508
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
509
				}
510
 
511
			}
512
 
513
		}
514
 
24083 amit.gupta 515
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
516
		return "response";
517
 
518
	}
519
 
27071 amit.gupta 520
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
29951 amit.gupta 521
														   Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 522
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
523
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 524
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 525
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 526
			if (priceDropImeis == null) {
26368 amit.gupta 527
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 528
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 529
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
530
			}
23951 amit.gupta 531
		}
27071 amit.gupta 532
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
533
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
534
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 535
	}
24083 amit.gupta 536
 
27071 amit.gupta 537
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
29951 amit.gupta 538
												PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 539
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 540
		row.add(imeiDropSummaryModel.getSerialNumber());
541
		row.add(imeiDropSummaryModel.getStoreName());
542
		row.add(imeiDropSummaryModel.getPartnerCode());
543
		row.add(imeiDropSummaryModel.getItemId());
544
		row.add(imeiDropSummaryModel.getBrand());
545
		row.add(imeiDropSummaryModel.getModelName());
546
		row.add(imeiDropSummaryModel.getModelNumber());
547
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 548
		if (priceDropIMEI != null) {
26368 amit.gupta 549
			row.add(priceDropIMEI.getStatus());
550
			row.add(priceDropIMEI.getRejectionReason());
551
		} else {
552
			row.add(PriceDropImeiStatus.PENDING);
553
			row.add("");
554
		}
26373 amit.gupta 555
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
556
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 557
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 558
		row.add(imeiDropSummaryModel.getActivationTimestamp());
559
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 560
		return row;
561
	}
23819 govind 562
 
23884 amit.gupta 563
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 564
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 565
			return true;
566
		}
567
		return false;
568
	}
23945 amit.gupta 569
 
28102 tejbeer 570
	@RequestMapping(value = "/priceCircular")
571
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
572
		int fofoId = Utils.SYSTEM_PARTNER_ID;
573
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
574
				.collect(Collectors.toSet());
28142 tejbeer 575
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
576
				.collect(Collectors.toSet()));
28102 tejbeer 577
 
578
		model.addAttribute("brands", brands);
29951 amit.gupta 579
		model.addAttribute("isAdmin", true);
29957 amit.gupta 580
		model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
28102 tejbeer 581
 
29951 amit.gupta 582
		return "partner-price-circular";
28102 tejbeer 583
	}
584
 
28142 tejbeer 585
	@RequestMapping(value = "/priceCircularByBrandAndPartnerType")
586
	public String priceCircularByBrandAndPartnerType(HttpServletRequest request, @RequestParam List<String> brands,
29951 amit.gupta 587
													 @RequestParam PartnerType partnerType, Model model) throws ProfitMandiBusinessException {
28142 tejbeer 588
		List<PartnerType> partnerTypes = new ArrayList<>();
589
		partnerTypes.add(partnerType);
590
		partnerTypes.add(PartnerType.ALL);
29788 amit.gupta 591
		List<PriceCircularItemModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
28142 tejbeer 592
				brands, LocalDateTime.now(), LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
30122 amit.gupta 593
		priceCircular = priceCircular.stream().filter(Utils.distinctByKey(PriceCircularItemModel::getCatalogId)).collect(Collectors.toList());
28142 tejbeer 594
 
30122 amit.gupta 595
 
29788 amit.gupta 596
		for (PriceCircularItemModel pc : priceCircular) {
28142 tejbeer 597
 
29646 tejbeer 598
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getUpfrontMargin()
599
					+ pc.getTertiaryPayout() + pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout()
600
					+ pc.getModelSpecfic();
28142 tejbeer 601
			pc.setTotalScheme(totalScheme);
602
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
603
			pc.setNetPrice(netprice);
604
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
605
			pc.setMopdp(mopdpdiff);
606
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
607
			long totalProfit = totalScheme + mopdpdiff;
608
			pc.setTotalProfit((int) totalProfit);
609
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
610
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
611
			pc.setNetMargin(roundOff);
612
 
613
		}
28149 amit.gupta 614
		model.addAttribute("date", LocalDate.now());
28142 tejbeer 615
		model.addAttribute("priceCircular", priceCircular);
616
		return "categorywise-circular";
617
	}
618
 
28102 tejbeer 619
	@RequestMapping(value = "/partnerPriceCircular")
620
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
621
		int fofoId = Utils.SYSTEM_PARTNER_ID;
622
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
623
				.collect(Collectors.toSet());
624
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
625
				.collect(Collectors.toSet()));
626
		model.addAttribute("brands", brands);
29951 amit.gupta 627
		model.addAttribute("isAdmin", false);
28102 tejbeer 628
 
629
		return "partner-price-circular";
630
	}
631
 
29788 amit.gupta 632
	@Autowired
633
	PriceCircularService priceCircularService;
29951 amit.gupta 634
 
28102 tejbeer 635
	@RequestMapping(value = "/priceCircularByBrand")
29951 amit.gupta 636
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
28102 tejbeer 637
			throws ProfitMandiBusinessException {
638
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
29951 amit.gupta 639
		if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
640
		} else {
641
			fofoId = loginDetails.getFofoId();
642
		}
643
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoId, LocalDate.now());
28102 tejbeer 644
		List<PartnerType> partnerTypes = new ArrayList<>();
645
		partnerTypes.add(partnerType);
646
		partnerTypes.add(PartnerType.ALL);
29951 amit.gupta 647
		PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand);
28136 tejbeer 648
 
29951 amit.gupta 649
		FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);
29788 amit.gupta 650
		model.addAttribute("priceCircular", priceCircular.getPriceCircularItemModels());
651
		model.addAttribute("offers", priceCircular.getOffers());
29846 amit.gupta 652
		model.addAttribute("upgradeOffer", priceCircular.isUpgradeOffer());
28136 tejbeer 653
		model.addAttribute("partnerCode", fs.getCode());
28102 tejbeer 654
		return "price-circular-detail";
655
	}
656
 
28568 amit.gupta 657
	@RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
658
	public String selectPriceDropStatus(HttpServletRequest request,
29951 amit.gupta 659
										@RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
660
										Model model) throws Exception {
28568 amit.gupta 661
 
662
		model.addAttribute("selectedStatus", selectedStatus);
663
		return "pricedrop-status-change";
664
	}
665
 
23819 govind 666
}