Subversion Repositories SmartDukaan

Rev

Rev 29646 | Rev 29788 | 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());
29654 tejbeer 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()))
29654 tejbeer 457
				.filter(x -> !x.getStatus().equals(finalStatus)).collect(Collectors.toList());
28568 amit.gupta 458
 
28889 amit.gupta 459
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIsToProcess) {
26368 amit.gupta 460
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
24083 amit.gupta 461
		}
28568 amit.gupta 462
 
28889 amit.gupta 463
		if (status.equals(PriceDropImeiStatus.APPROVED)) {
464
			priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
465
					priceDropImeisModel.getUpdatedImeis());
466
		}
467
		for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
468
			if (status.equals(PriceDropImeiStatus.REJECTED)
469
					&& priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
470
				priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
471
				priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
472
			} else if (status.equals(PriceDropImeiStatus.HOLD)) {
473
				if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
474
					priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
475
				} else {
28568 amit.gupta 476
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
477
				}
478
 
479
			}
480
 
481
		}
482
 
24083 amit.gupta 483
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
484
		return "response";
485
 
486
	}
487
 
27071 amit.gupta 488
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
489
			Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 490
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
491
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 492
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 493
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 494
			if (priceDropImeis == null) {
26368 amit.gupta 495
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 496
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 497
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
498
			}
23951 amit.gupta 499
		}
27071 amit.gupta 500
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
501
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
502
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 503
	}
24083 amit.gupta 504
 
27071 amit.gupta 505
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
506
			PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 507
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 508
		row.add(imeiDropSummaryModel.getSerialNumber());
509
		row.add(imeiDropSummaryModel.getStoreName());
510
		row.add(imeiDropSummaryModel.getPartnerCode());
511
		row.add(imeiDropSummaryModel.getItemId());
512
		row.add(imeiDropSummaryModel.getBrand());
513
		row.add(imeiDropSummaryModel.getModelName());
514
		row.add(imeiDropSummaryModel.getModelNumber());
515
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 516
		if (priceDropIMEI != null) {
26368 amit.gupta 517
			row.add(priceDropIMEI.getStatus());
518
			row.add(priceDropIMEI.getRejectionReason());
519
		} else {
520
			row.add(PriceDropImeiStatus.PENDING);
521
			row.add("");
522
		}
26373 amit.gupta 523
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
524
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 525
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 526
		row.add(imeiDropSummaryModel.getActivationTimestamp());
527
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 528
		return row;
529
	}
23819 govind 530
 
23884 amit.gupta 531
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 532
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 533
			return true;
534
		}
535
		return false;
536
	}
23945 amit.gupta 537
 
28102 tejbeer 538
	@RequestMapping(value = "/priceCircular")
539
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
540
		int fofoId = Utils.SYSTEM_PARTNER_ID;
541
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
542
				.collect(Collectors.toSet());
28142 tejbeer 543
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
544
				.collect(Collectors.toSet()));
28102 tejbeer 545
 
28142 tejbeer 546
		/*
547
		 * Map<Integer, CustomRetailer> customRetailers =
548
		 * retailerService.getFofoRetailers(true); Map<Integer, PartnerType>
549
		 * fofoIdPartnerTypeMap = new HashMap<>();
550
		 * 
551
		 * for (Entry<Integer, CustomRetailer> customRetailer :
552
		 * customRetailers.entrySet()) { PartnerType partnerType =
553
		 * partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
554
		 * LocalDate.now()); fofoIdPartnerTypeMap.put(customRetailer.getKey(),
555
		 * partnerType); }
556
		 * 
557
		 * Map<PartnerType, List<Integer>> partnerTypePartnersMap =
558
		 * fofoIdPartnerTypeMap.entrySet().stream().collect( Collectors.groupingBy(x ->
559
		 * x.getValue(), Collectors.mapping(x -> x.getKey(), Collectors.toList())));
560
		 */
28102 tejbeer 561
		model.addAttribute("brands", brands);
28145 tejbeer 562
		model.addAttribute("date", LocalDate.now());
28102 tejbeer 563
 
564
		return "price-circular";
565
	}
566
 
28142 tejbeer 567
	@RequestMapping(value = "/priceCircularByBrandAndPartnerType")
568
	public String priceCircularByBrandAndPartnerType(HttpServletRequest request, @RequestParam List<String> brands,
569
			@RequestParam PartnerType partnerType, Model model) throws ProfitMandiBusinessException {
570
		List<PartnerType> partnerTypes = new ArrayList<>();
571
		partnerTypes.add(partnerType);
572
		partnerTypes.add(PartnerType.ALL);
573
		List<PriceCircularModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
574
				brands, LocalDateTime.now(), LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
575
 
576
		for (PriceCircularModel pc : priceCircular) {
577
 
29646 tejbeer 578
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getUpfrontMargin()
579
					+ pc.getTertiaryPayout() + pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout()
580
					+ pc.getModelSpecfic();
28142 tejbeer 581
			pc.setTotalScheme(totalScheme);
582
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
583
			pc.setNetPrice(netprice);
584
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
585
			pc.setMopdp(mopdpdiff);
586
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
587
			long totalProfit = totalScheme + mopdpdiff;
588
			pc.setTotalProfit((int) totalProfit);
589
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
590
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
591
			pc.setNetMargin(roundOff);
592
 
593
		}
28149 amit.gupta 594
		model.addAttribute("date", LocalDate.now());
28142 tejbeer 595
		model.addAttribute("priceCircular", priceCircular);
596
		return "categorywise-circular";
597
	}
598
 
28102 tejbeer 599
	@RequestMapping(value = "/partnerPriceCircular")
600
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
601
		int fofoId = Utils.SYSTEM_PARTNER_ID;
602
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
603
				.collect(Collectors.toSet());
604
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
605
				.collect(Collectors.toSet()));
606
		model.addAttribute("brands", brands);
607
		model.addAttribute("date", LocalDate.now());
608
 
609
		return "partner-price-circular";
610
	}
611
 
612
	@RequestMapping(value = "/priceCircularByBrand")
613
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model)
614
			throws ProfitMandiBusinessException {
615
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
616
 
617
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), LocalDate.now());
618
		List<PartnerType> partnerTypes = new ArrayList<>();
619
		partnerTypes.add(partnerType);
620
		partnerTypes.add(PartnerType.ALL);
621
		List<PriceCircularModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
28142 tejbeer 622
				Arrays.asList(brand), LocalDateTime.now(),
623
				LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
28102 tejbeer 624
 
625
		for (PriceCircularModel pc : priceCircular) {
626
 
29654 tejbeer 627
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getUpfrontMargin()
628
					+ pc.getTertiaryPayout() + pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout()
629
					+ pc.getModelSpecfic();
28102 tejbeer 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
}