Subversion Repositories SmartDukaan

Rev

Rev 28641 | Rev 28889 | 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();
28642 amit.gupta 158
		int processOn =1;
28641 amit.gupta 159
 
28568 amit.gupta 160
 
161
		List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
162
				.collect(Collectors.toList());
163
 
164
		Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
165
				.collect(Collectors.toSet());
166
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
167
		LOGGER.info("catalogIds" + catalogIds);
168
 
169
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
170
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
171
		model.addAttribute("priceDrops", completePriceDrops);
28642 amit.gupta 172
		model.addAttribute("processOn", processOn);
28568 amit.gupta 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;
28641 amit.gupta 411
 
412
		List<PriceDropImeiStatus>priceDropImeiStatuses = new ArrayList<>();
413
 
414
		priceDropImeiStatuses.add(PriceDropImeiStatus.PENDING);
415
		priceDropImeiStatuses.add(PriceDropImeiStatus.HOLD);
416
 
24083 amit.gupta 417
		switch (priceDropImeisModel.getUpdatedStatus()) {
27071 amit.gupta 418
		case "approved": {
28568 amit.gupta 419
			status = PriceDropImeiStatus.APPROVED;
27071 amit.gupta 420
			break;
24083 amit.gupta 421
		}
28568 amit.gupta 422
		case "hold": {
423
			status = PriceDropImeiStatus.HOLD;
424
			break;
425
		}
27071 amit.gupta 426
		case "rejected": {
427
			status = PriceDropImeiStatus.REJECTED;
428
			break;
24083 amit.gupta 429
		}
27071 amit.gupta 430
		}
431
 
432
		if (PriceDropImeiStatus.PENDING.equals(status)) {
28568 amit.gupta 433
 
434
			List<PriceDropIMEI> priceDropIMEIsToHolds = new ArrayList<>();
28641 amit.gupta 435
			List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByIdAndStatus(PriceDropImeiStatus.HOLD,
28568 amit.gupta 436
					priceDropImeisModel.getPriceDropId());
437
			LOGGER.info("hello" + priceDropIMEIs);
438
			for (PriceDropIMEI priceDropHoldIMEI : priceDropIMEIs) {
439
				if (priceDropHoldIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
440
					if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropHoldIMEI.getImei())
441
							|| priceDropHoldIMEI.getStatus().equals(status)) {
442
						continue;
443
					}
444
					priceDropIMEIsToHolds.add(priceDropHoldIMEI);
445
					priceDropHoldIMEI.setStatus(PriceDropImeiStatus.PENDING);
446
					priceDropHoldIMEI.setUpdateTimestamp(LocalDateTime.now());
447
				} else {
448
					throw new ProfitMandiBusinessException("INVALID STATUS", "PENDING",
449
							"Pending Status is allowed  only for Hold IMIEs");
450
				}
451
			}
452
 
27071 amit.gupta 453
		}
454
 
455
		// TODO:PD
24083 amit.gupta 456
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
457
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
458
 
459
		List<PriceDropIMEI> priceDropIMEIsToProcess = new ArrayList<>();
460
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
28568 amit.gupta 461
 
24083 amit.gupta 462
			if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())
463
					|| priceDropIMEI.getStatus().equals(status)) {
464
				continue;
465
			}
28568 amit.gupta 466
 
26368 amit.gupta 467
			priceDropIMEIsToProcess.add(priceDropIMEI);
28568 amit.gupta 468
 
26368 amit.gupta 469
			priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
24083 amit.gupta 470
		}
28568 amit.gupta 471
 
472
		for (PriceDropIMEI PriceDropIMEIByStatus : priceDropIMEIsToProcess) {
473
 
474
			if (status.equals(PriceDropImeiStatus.APPROVED)
475
					&& PriceDropIMEIByStatus.getStatus().equals(PriceDropImeiStatus.PENDING)) {
476
 
477
				PriceDropIMEIByStatus.setStatus(PriceDropImeiStatus.APPROVED);
478
			} else if (status.equals(PriceDropImeiStatus.REJECTED)
479
					&& PriceDropIMEIByStatus.getStatus().equals(PriceDropImeiStatus.PENDING)) {
480
				PriceDropIMEIByStatus.setStatus(PriceDropImeiStatus.REJECTED);
481
				PriceDropIMEIByStatus.setRejectionReason(priceDropImeisModel.getRejectionReason());
482
 
483
			} else {
484
				if (status.equals(PriceDropImeiStatus.HOLD)
485
						&& PriceDropIMEIByStatus.getStatus().equals(PriceDropImeiStatus.PENDING)) {
486
 
487
					PriceDropIMEIByStatus.setStatus(PriceDropImeiStatus.HOLD);
488
				}
489
 
490
				else {
491
					throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
492
				}
493
 
494
			}
495
 
496
		}
497
		List<PriceDropIMEI> priceDropIMEIHoldAndPending = priceDropIMEIRepository
28641 amit.gupta 498
				.selectByIdAndPendingHoldStatus(priceDropImeiStatuses, priceDropImeisModel.getPriceDropId());
28568 amit.gupta 499
 
28641 amit.gupta 500
			LOGGER.info("priceDropIMEIholdandPending" + priceDropIMEIHoldAndPending);
28568 amit.gupta 501
 
502
		if (priceDropIMEIHoldAndPending == null || priceDropIMEIHoldAndPending.isEmpty()) {
503
 
504
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropImeisModel.getPriceDropId());
505
 
506
			LOGGER.info("priceDrop" + priceDrop);
507
 
508
			priceDrop.setCompleteTimestamp(LocalDateTime.now());
509
 
510
			PriceDrop priceDropVal = priceDropRepository.selectById(priceDropImeisModel.getPriceDropId());
511
			LOGGER.info("priceDropsVal" + priceDropVal);
512
		}
27071 amit.gupta 513
		/*
514
		 * if (priceDropIMEIsToProcess.size() > 0) {
515
		 * priceDropService.processManualPriceDrop(priceDropImeisModel.getPriceDropId(),
516
		 * priceDropIMEIsToProcess, status); }
517
		 */
24168 amit.gupta 518
 
24083 amit.gupta 519
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
520
		return "response";
521
 
522
	}
523
 
27071 amit.gupta 524
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
525
			Map<String, PriceDropIMEI> priceDropImeis) throws Exception {
24564 amit.gupta 526
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
527
				.getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId);
25852 amit.gupta 528
		List<List<?>> rows = new ArrayList<>();
23983 amit.gupta 529
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
27071 amit.gupta 530
			if (priceDropImeis == null) {
26368 amit.gupta 531
				rows.add(this.getRow(imeiDropSummaryModel, null));
27071 amit.gupta 532
			} else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
26368 amit.gupta 533
				rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
534
			}
23951 amit.gupta 535
		}
27071 amit.gupta 536
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
537
				"Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
538
				"Grn On", "Activation Timestamp", "Activation Added On"), rows);
23819 govind 539
	}
24083 amit.gupta 540
 
27071 amit.gupta 541
	private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
542
			PriceDropIMEI priceDropIMEI) {
24822 amit.gupta 543
		List<Serializable> row = new ArrayList<>();
23986 amit.gupta 544
		row.add(imeiDropSummaryModel.getSerialNumber());
545
		row.add(imeiDropSummaryModel.getStoreName());
546
		row.add(imeiDropSummaryModel.getPartnerCode());
547
		row.add(imeiDropSummaryModel.getItemId());
548
		row.add(imeiDropSummaryModel.getBrand());
549
		row.add(imeiDropSummaryModel.getModelName());
550
		row.add(imeiDropSummaryModel.getModelNumber());
551
		row.add(imeiDropSummaryModel.getColor());
27071 amit.gupta 552
		if (priceDropIMEI != null) {
26368 amit.gupta 553
			row.add(priceDropIMEI.getStatus());
554
			row.add(priceDropIMEI.getRejectionReason());
555
		} else {
556
			row.add(PriceDropImeiStatus.PENDING);
557
			row.add("");
558
		}
26373 amit.gupta 559
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
560
		row.add(imeiDropSummaryModel.getVendorName());
26420 amit.gupta 561
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
26368 amit.gupta 562
		row.add(imeiDropSummaryModel.getActivationTimestamp());
563
		row.add(imeiDropSummaryModel.getActivationAddedOn());
23986 amit.gupta 564
		return row;
565
	}
23819 govind 566
 
23884 amit.gupta 567
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24564 amit.gupta 568
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
23884 amit.gupta 569
			return true;
570
		}
571
		return false;
572
	}
23945 amit.gupta 573
 
28102 tejbeer 574
	@RequestMapping(value = "/priceCircular")
575
	public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
576
		int fofoId = Utils.SYSTEM_PARTNER_ID;
577
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
578
				.collect(Collectors.toSet());
28142 tejbeer 579
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
580
				.collect(Collectors.toSet()));
28102 tejbeer 581
 
28142 tejbeer 582
		/*
583
		 * Map<Integer, CustomRetailer> customRetailers =
584
		 * retailerService.getFofoRetailers(true); Map<Integer, PartnerType>
585
		 * fofoIdPartnerTypeMap = new HashMap<>();
586
		 * 
587
		 * for (Entry<Integer, CustomRetailer> customRetailer :
588
		 * customRetailers.entrySet()) { PartnerType partnerType =
589
		 * partnerTypeChangeService.getTypeOnDate(customRetailer.getKey(),
590
		 * LocalDate.now()); fofoIdPartnerTypeMap.put(customRetailer.getKey(),
591
		 * partnerType); }
592
		 * 
593
		 * Map<PartnerType, List<Integer>> partnerTypePartnersMap =
594
		 * fofoIdPartnerTypeMap.entrySet().stream().collect( Collectors.groupingBy(x ->
595
		 * x.getValue(), Collectors.mapping(x -> x.getKey(), Collectors.toList())));
596
		 */
28102 tejbeer 597
		model.addAttribute("brands", brands);
28145 tejbeer 598
		model.addAttribute("date", LocalDate.now());
28102 tejbeer 599
 
600
		return "price-circular";
601
	}
602
 
28142 tejbeer 603
	@RequestMapping(value = "/priceCircularByBrandAndPartnerType")
604
	public String priceCircularByBrandAndPartnerType(HttpServletRequest request, @RequestParam List<String> brands,
605
			@RequestParam PartnerType partnerType, Model model) throws ProfitMandiBusinessException {
606
		List<PartnerType> partnerTypes = new ArrayList<>();
607
		partnerTypes.add(partnerType);
608
		partnerTypes.add(PartnerType.ALL);
609
		List<PriceCircularModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
610
				brands, LocalDateTime.now(), LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
611
 
612
		for (PriceCircularModel pc : priceCircular) {
613
 
614
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getTertiaryPayout()
615
					+ pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout() + pc.getModelSpecfic();
616
			pc.setTotalScheme(totalScheme);
617
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
618
			pc.setNetPrice(netprice);
619
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
620
			pc.setMopdp(mopdpdiff);
621
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
622
			long totalProfit = totalScheme + mopdpdiff;
623
			pc.setTotalProfit((int) totalProfit);
624
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
625
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
626
			pc.setNetMargin(roundOff);
627
 
628
		}
28149 amit.gupta 629
		model.addAttribute("date", LocalDate.now());
28142 tejbeer 630
		model.addAttribute("priceCircular", priceCircular);
631
		return "categorywise-circular";
632
	}
633
 
28102 tejbeer 634
	@RequestMapping(value = "/partnerPriceCircular")
635
	public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
636
		int fofoId = Utils.SYSTEM_PARTNER_ID;
637
		Set<String> brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
638
				.collect(Collectors.toSet());
639
		brands.addAll(mongoClient.getMongoBrands(fofoId, null, 6).stream().map(x -> (String) x.get("name"))
640
				.collect(Collectors.toSet()));
641
		model.addAttribute("brands", brands);
642
		model.addAttribute("date", LocalDate.now());
643
 
644
		return "partner-price-circular";
645
	}
646
 
647
	@RequestMapping(value = "/priceCircularByBrand")
648
	public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model)
649
			throws ProfitMandiBusinessException {
650
		LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
651
 
652
		PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(loginDetails.getFofoId(), LocalDate.now());
653
		List<PartnerType> partnerTypes = new ArrayList<>();
654
		partnerTypes.add(partnerType);
655
		partnerTypes.add(PartnerType.ALL);
656
		List<PriceCircularModel> priceCircular = tagListingRepository.getPriceCircularByBrandAndType(partnerTypes,
28142 tejbeer 657
				Arrays.asList(brand), LocalDateTime.now(),
658
				LocalDateTime.now().plusDays(1).toLocalDate().atStartOfDay());
28102 tejbeer 659
 
660
		for (PriceCircularModel pc : priceCircular) {
661
 
662
			Long totalScheme = pc.getBasePayout() + pc.getCashDiscount() + pc.getTertiaryPayout()
663
					+ pc.getHygienePayout() + pc.getCategoryPayout() + pc.getInvestmentPayout() + pc.getModelSpecfic();
664
			pc.setTotalScheme(totalScheme);
665
			long netprice = pc.getSellingPrice() - pc.getTotalScheme();
666
			pc.setNetPrice(netprice);
667
			int mopdpdiff = pc.getMop() - pc.getSellingPrice();
668
			pc.setMopdp(mopdpdiff);
669
			pc.setNetPrice2((int) pc.getNetPrice() - pc.getMopdp());
670
			long totalProfit = totalScheme + mopdpdiff;
28124 tejbeer 671
			pc.setTotalProfit((int) totalProfit);
28102 tejbeer 672
			double rouoff = totalProfit / (pc.getSellingPrice() / 1.18) * 100;
673
			double roundOff = Math.round(rouoff * 100.0) / 100.0;
674
			pc.setNetMargin(roundOff);
675
 
676
		}
28136 tejbeer 677
 
678
		FofoStore fs = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
28102 tejbeer 679
		LOGGER.info("priceCircular" + priceCircular);
680
		model.addAttribute("priceCircular", priceCircular);
28136 tejbeer 681
		model.addAttribute("partnerCode", fs.getCode());
28102 tejbeer 682
		return "price-circular-detail";
683
	}
684
 
28568 amit.gupta 685
	@RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
686
	public String selectPriceDropStatus(HttpServletRequest request,
687
			@RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
688
			Model model) throws Exception {
689
 
690
		model.addAttribute("selectedStatus", selectedStatus);
691
 
692
		return "pricedrop-status-change";
693
 
694
	}
695
 
23819 govind 696
}