Subversion Repositories SmartDukaan

Rev

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