Subversion Repositories SmartDukaan

Rev

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