Subversion Repositories SmartDukaan

Rev

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