Subversion Repositories SmartDukaan

Rev

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