Subversion Repositories SmartDukaan

Rev

Rev 24180 | Rev 24349 | 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
 
23968 amit.gupta 3
import java.text.MessageFormat;
24019 amit.gupta 4
import java.time.LocalDate;
23819 govind 5
import java.time.LocalDateTime;
24019 amit.gupta 6
import java.time.LocalTime;
23819 govind 7
import java.util.ArrayList;
23884 amit.gupta 8
import java.util.Arrays;
23819 govind 9
import java.util.HashMap;
10
import java.util.List;
11
import java.util.Map;
24063 amit.gupta 12
import java.util.Set;
23819 govind 13
import java.util.stream.Collectors;
14
 
15
import javax.servlet.http.HttpServletRequest;
16
import javax.transaction.Transactional;
17
 
23951 amit.gupta 18
import org.apache.commons.io.output.ByteArrayOutputStream;
19
import org.apache.commons.lang.StringUtils;
23945 amit.gupta 20
import org.apache.http.HttpResponse;
23819 govind 21
import org.apache.logging.log4j.LogManager;
22
import org.apache.logging.log4j.Logger;
23
import org.springframework.beans.factory.annotation.Autowired;
24
import org.springframework.beans.factory.annotation.Qualifier;
24191 amit.gupta 25
import org.springframework.cache.annotation.Cacheable;
23951 amit.gupta 26
import org.springframework.core.io.ByteArrayResource;
27
import org.springframework.http.HttpHeaders;
23819 govind 28
import org.springframework.http.HttpStatus;
29
import org.springframework.http.ResponseEntity;
30
import org.springframework.stereotype.Controller;
31
import org.springframework.ui.Model;
32
import org.springframework.web.bind.annotation.PathVariable;
23884 amit.gupta 33
import org.springframework.web.bind.annotation.RequestBody;
23819 govind 34
import org.springframework.web.bind.annotation.RequestMapping;
35
import org.springframework.web.bind.annotation.RequestMethod;
23951 amit.gupta 36
import org.springframework.web.bind.annotation.RequestParam;
23819 govind 37
 
23951 amit.gupta 38
import com.fasterxml.jackson.databind.JavaType;
23945 amit.gupta 39
import com.fasterxml.jackson.databind.ObjectMapper;
40
import com.fasterxml.jackson.databind.ObjectReader;
41
import com.spice.profitmandi.common.enumuration.ReporticoProject;
23819 govind 42
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23945 amit.gupta 43
import com.spice.profitmandi.common.model.ClosingStockOnDate;
44
import com.spice.profitmandi.common.model.GrnPendingDataModel;
23951 amit.gupta 45
import com.spice.profitmandi.common.model.ImeiDropSummaryModel;
23884 amit.gupta 46
import com.spice.profitmandi.common.model.ItemDescriptionModel;
23945 amit.gupta 47
import com.spice.profitmandi.common.model.PartnerImeiNotSold;
24083 amit.gupta 48
import com.spice.profitmandi.common.model.PriceDropImeisModel;
23884 amit.gupta 49
import com.spice.profitmandi.common.model.PriceDropModel;
23968 amit.gupta 50
import com.spice.profitmandi.common.model.PriceDropProcessModel;
23945 amit.gupta 51
import com.spice.profitmandi.common.model.ReporticoResponseModel;
52
import com.spice.profitmandi.common.services.ReporticoService;
23951 amit.gupta 53
import com.spice.profitmandi.common.util.FileUtil;
23945 amit.gupta 54
import com.spice.profitmandi.common.util.FormattingUtils;
23819 govind 55
import com.spice.profitmandi.dao.entity.catalog.Item;
23884 amit.gupta 56
import com.spice.profitmandi.dao.entity.catalog.TagListing;
23968 amit.gupta 57
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
23884 amit.gupta 58
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
23983 amit.gupta 59
import com.spice.profitmandi.dao.entity.transaction.LineItemImei;
23819 govind 60
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
24083 amit.gupta 61
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
62
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
23819 govind 63
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
23884 amit.gupta 64
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
23986 amit.gupta 65
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
66
import com.spice.profitmandi.dao.repository.fofo.SchemeInOutRepository;
23884 amit.gupta 67
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
23983 amit.gupta 68
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
24083 amit.gupta 69
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
23819 govind 70
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
71
import com.spice.profitmandi.service.inventory.InventoryService;
23983 amit.gupta 72
import com.spice.profitmandi.service.pricing.PriceDropService;
23968 amit.gupta 73
import com.spice.profitmandi.service.scheme.SchemeService;
23884 amit.gupta 74
import com.spice.profitmandi.service.transaction.TransactionService;
23819 govind 75
import com.spice.profitmandi.service.wallet.WalletService;
76
import com.spice.profitmandi.web.util.MVCResponseSender;
77
 
23968 amit.gupta 78
import in.shop2020.model.v1.order.WalletReferenceType;
79
 
23819 govind 80
@Controller
81
@Transactional
82
public class PriceDropController {
83
 
84
	private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);
85
 
86
	@Autowired
87
	private PriceDropRepository priceDropRepository;
88
 
23951 amit.gupta 89
	@Autowired
90
	private ObjectMapper objectMapper;
23945 amit.gupta 91
 
23819 govind 92
	@Autowired
23884 amit.gupta 93
	private VendorItemPricingRepository vendorItemPricingRepository;
23819 govind 94
 
95
	@Autowired
23884 amit.gupta 96
	@Qualifier("fofoInventoryService")
97
	private InventoryService inventoryService;
23945 amit.gupta 98
 
23884 amit.gupta 99
	@Autowired
23819 govind 100
	private MVCResponseSender mvcResponseSender;
101
 
102
	@Autowired
23983 amit.gupta 103
	private PriceDropService priceDropService;
24083 amit.gupta 104
 
23983 amit.gupta 105
	@Autowired
23986 amit.gupta 106
	private InventoryItemRepository inventoryItemRepository;
24083 amit.gupta 107
 
23986 amit.gupta 108
	@Autowired
23819 govind 109
	private WalletService walletService;
110
 
111
	@Autowired
23884 amit.gupta 112
	private TagListingRepository tagListingRepository;
23945 amit.gupta 113
 
23884 amit.gupta 114
	@Autowired
115
	private TransactionService transactionService;
23819 govind 116
 
117
	@Autowired
24083 amit.gupta 118
	private PriceDropIMEIRepository priceDropIMEIRepository;
119
 
120
	@Autowired
23819 govind 121
	@Qualifier("catalogItemRepository")
122
	private ItemRepository itemRepository;
123
 
23945 amit.gupta 124
	@Autowired
23968 amit.gupta 125
	private SchemeService schemeService;
24083 amit.gupta 126
 
23986 amit.gupta 127
	@Autowired
128
	private SchemeInOutRepository schemeInOutRepository;
23968 amit.gupta 129
 
130
	@Autowired
23945 amit.gupta 131
	ReporticoService reporticoService;
24083 amit.gupta 132
 
23983 amit.gupta 133
	@Autowired
134
	LineItemImeisRepository lineItemImeisRepository;
23945 amit.gupta 135
 
23819 govind 136
	@RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
23945 amit.gupta 137
	public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
23819 govind 138
		List<PriceDrop> priceDrops = priceDropRepository.selectAll();
24191 amit.gupta 139
		Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
24180 amit.gupta 140
		List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
24191 amit.gupta 141
		Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
142
				x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
23819 govind 143
		model.addAttribute("priceDrops", priceDrops);
23968 amit.gupta 144
		model.addAttribute("catalogDescription", catalogDescription);
23819 govind 145
		return "price-drop";
146
	}
24083 amit.gupta 147
 
24049 amit.gupta 148
	@RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
149
	public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {
24083 amit.gupta 150
 
24063 amit.gupta 151
		TagListing tagListing;
24049 amit.gupta 152
		PriceDropModel pm = new PriceDropModel();
24063 amit.gupta 153
		try {
154
			tagListing = tagListingRepository.selectByItemId(itemId);
24083 amit.gupta 155
			if (tagListing != null) {
24063 amit.gupta 156
				pm.setMop(tagListing.getMop());
157
				pm.setDp(tagListing.getSellingPrice());
158
				pm.setMrp(tagListing.getMrp());
159
				List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
24083 amit.gupta 160
				if (vips.size() > 0) {
24063 amit.gupta 161
					VendorItemPricing vip = vips.get(0);
162
					pm.setNlc(vip.getNlc());
163
					pm.setTp(vip.getTp());
164
				} else {
165
					throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
166
				}
167
			}
24083 amit.gupta 168
		} catch (Exception e) {
24063 amit.gupta 169
			LOGGER.info("Chose item that doesn't exist");
24049 amit.gupta 170
		}
171
		model.addAttribute("response", mvcResponseSender.createResponseString(pm));
172
		return "response";
173
	}
24083 amit.gupta 174
 
24168 amit.gupta 175
	@RequestMapping(value = "/item", method = RequestMethod.GET)
176
	public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query) throws Throwable {
24191 amit.gupta 177
		List<ItemDescriptionModel> partnersItemDescription = this.getAllPartnerItemStringDescription()
178
				.parallelStream().filter(x -> !x.getItemDescription().matches(query)).collect(Collectors.toList());
24168 amit.gupta 179
 
24191 amit.gupta 180
		model.addAttribute("response", mvcResponseSender.createResponseString(partnersItemDescription));
24168 amit.gupta 181
		return "response";
182
	}
183
 
24191 amit.gupta 184
	@Cacheable(value = "fofoItems", cacheManager = "thirtyMinsTimeOutCacheManager")
185
	private List<ItemDescriptionModel> getAllPartnerItemStringDescription() {
186
		return itemRepository.selectPartnerItems(0).stream().map(x -> {
187
			String itemDescription = x.getItemDescription() + "(" + x.getId() + ")";
188
			ItemDescriptionModel itemDescriptionModel = new ItemDescriptionModel();
189
			itemDescriptionModel.setItemDescription(itemDescription);
190
			itemDescriptionModel.setItemId(x.getId());
191
			return itemDescriptionModel;
192
		}).collect(Collectors.toList());
193
	}
194
 
24083 amit.gupta 195
	/*
24191 amit.gupta 196
	 * IN-Request-20181101-0125
197
	 * 
24083 amit.gupta 198
	 * @RequestMapping(value = "/price-drop/imes1/download") public
199
	 * ResponseEntity<ByteArrayResource> downloadPriceDropImeis1(HttpServletRequest
200
	 * request,
201
	 * 
202
	 * @RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws
203
	 * Exception { Item item = itemRepository.selectById(itemId);
204
	 * List<ImeiDropSummaryModel> imeiDropSummaryModelList =
205
	 * this.getAllSerialNumbersByAffectedDate(affectedDate,
206
	 * item.getCatalogItemId()); List<String> imeis =
207
	 * imeiDropSummaryModelList.stream().map(x->x.getSerialNumber()).collect(
208
	 * Collectors.toList()); Map<String, ImeiDropSummaryModel> imeisDropMap =
209
	 * imeiDropSummaryModelList.stream().collect(Collectors.toMap(
210
	 * ImeiDropSummaryModel::getSerialNumber, x->x)); List<InventoryItem>
211
	 * inventoryItems = inventoryItemRepository.selectBySerialNumbers(new
212
	 * HashSet<>(imeis)); List<Integer> inventoryItemIds =
213
	 * inventoryItems.stream().map(InventoryItem::getId).collect(Collectors.toList()
214
	 * );
215
	 * 
216
	 * List<SchemeInOut> schemeInOuts =
217
	 * schemeInOutRepository.selectByInventoryItemIds(new
218
	 * HashSet<>(inventoryItemIds));
219
	 * 
220
	 * Set<ItemQuantity> itemSchemes = new HashSet<>(); Map<ItemQuantity,
221
	 * SchemeInOut> itemSchemeInOutMap = new HashMap<>(); for(SchemeInOut
222
	 * schemeInOut : schemeInOuts) { } List<List<Object>> rows = new ArrayList<>();
223
	 * for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
224
	 * List<Object> row = this.getRow(imeiDropSummaryModel);
225
	 * 
226
	 * rows.add(this.getRow(imeiDropSummaryModel)); }
227
	 * 
228
	 * FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name",
229
	 * "Store Code", "Item ID", "Brand", "Model Name", "Model Number", "Color",
230
	 * "Last Scanned"), rows); final HttpHeaders headers = new HttpHeaders();
231
	 * headers.set("Content-Type",
232
	 * "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
233
	 * headers.set("Content-disposition", "inline; filename=imei-" +
234
	 * item.getItemDescriptionNoColor() + ".csv"); return new
235
	 * ResponseEntity<ByteArrayResource>(null, headers, HttpStatus.OK);
236
	 * 
237
	 * }
238
	 */
23951 amit.gupta 239
	@RequestMapping(value = "/price-drop/imes/download")
240
	public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
241
			@RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
242
		Item item = itemRepository.selectById(itemId);
23968 amit.gupta 243
		ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId());
23951 amit.gupta 244
		final HttpHeaders headers = new HttpHeaders();
245
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
246
		headers.set("Content-disposition", "inline; filename=imei-" + item.getItemDescriptionNoColor() + ".csv");
247
		byte[] byteArray = baos.toByteArray();
248
		headers.setContentLength(byteArray.length);
249
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
250
	}
251
 
24083 amit.gupta 252
	@RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
253
	public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
254
			Model model) throws Exception {
255
		boolean response = false;
256
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
257
		if (priceDrop.getProcessTimestamp() == null) {
258
			priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
259
			priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
260
			// priceDrop.setProcessTimestamp(LocalDateTime.now());
261
			priceDropRepository.persist(priceDrop);
262
			response = true;
263
		}
264
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
265
		return "response";
266
	}
267
 
268
	@RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
269
	public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
270
			throws Exception {
271
 
272
		PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();
273
		List<String> pendingImeis = new ArrayList<>();
274
		List<String> approvedImeis = new ArrayList<>();
275
		List<String> rejectedImeis = new ArrayList<>();
276
		List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
277
		if (priceDropImeis.size() == 0) {
278
			PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
279
			List<ImeiDropSummaryModel> imeis = this.getAllSerialNumbersByAffectedDate(priceDrop.getAffectedOn(),
280
					priceDrop.getCatalogItemId());
281
			for (ImeiDropSummaryModel imei : imeis) {
282
				PriceDropIMEI priceDropIMEI = new PriceDropIMEI();
283
				priceDropIMEI.setImei(imei.getSerialNumber());
284
				priceDropIMEI.setPriceDropId(priceDropId);
285
				priceDropIMEI.setPartnerId(imei.getRetailerId());
286
				priceDropIMEIRepository.persist(priceDropIMEI);
287
			}
288
			priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
289
		}
290
 
291
		for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
292
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
293
				pendingImeis.add(priceDropIMEI.getImei());
294
			} else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
295
				approvedImeis.add(priceDropIMEI.getImei());
296
			}
297
			if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
298
				rejectedImeis.add(priceDropIMEI.getImei());
299
			}
300
		}
301
		priceDropImeisModel.setPendingImeis(pendingImeis);
302
		priceDropImeisModel.setPriceDropId(priceDropId);
303
		priceDropImeisModel.setApprovedImeis(approvedImeis);
304
		priceDropImeisModel.setRejectedImeis(rejectedImeis);
305
		model.addAttribute("response", mvcResponseSender.createResponseString(priceDropImeisModel));
306
		return "response";
307
	}
308
 
23968 amit.gupta 309
	@RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
310
	public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcess,
311
			Model model) throws Exception {
312
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcess.getPriceDropId());
313
		boolean response = false;
314
		if (priceDrop.getProcessTimestamp() == null) {
315
			priceDrop.setProcessTimestamp(LocalDateTime.now());
316
			priceDropRepository.persist(priceDrop);
317
			response = true;
23819 govind 318
		}
23968 amit.gupta 319
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
320
		return "response";
23819 govind 321
	}
24083 amit.gupta 322
 
24019 amit.gupta 323
	@RequestMapping(value = "/updateMop", method = RequestMethod.POST)
24083 amit.gupta 324
	public String addMop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
325
			throws Exception {
24019 amit.gupta 326
		boolean response = false;
327
		priceDropModel.setAllColors(true);
328
		TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
329
		float newDp = tagListing.getSellingPrice() - priceDropModel.getPd();
330
		List<Item> allItems = null;
331
		Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
332
		if (priceDropModel.isAllColors()) {
333
			allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
23819 govind 334
 
24019 amit.gupta 335
		} else {
336
			allItems = Arrays.asList(currentItem);
337
		}
338
		for (Item item : allItems) {
339
			TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
340
			if (itemTagListing == null)
341
				continue;
342
			itemTagListing.setMop(priceDropModel.getMop());
343
			tagListingRepository.persist(tagListing);
344
			List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
345
			for (VendorItemPricing vip : vipList) {
346
				vip.setDp(newDp);
347
				vip.setMop(priceDropModel.getMop());
348
				vendorItemPricingRepository.persist(vip);
349
			}
350
			transactionService.updatePriceDrop(item.getId(), newDp);
351
		}
352
		PriceDrop priceDrop = new PriceDrop();
24083 amit.gupta 353
		priceDrop.setAffectedOn(LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT));
24019 amit.gupta 354
		priceDrop.setOldDp(tagListing.getSellingPrice());
355
		priceDrop.setAmount(priceDropModel.getPd());
356
		priceDrop.setNewDp(tagListing.getSellingPrice());
357
		priceDrop.setNlc(priceDropModel.getNlc());
358
		priceDrop.setTp(priceDropModel.getTp());
359
		priceDrop.setCreatedOn(LocalDateTime.now());
360
		priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
361
		priceDrop.setProcessTimestamp(LocalDateTime.now());
362
		priceDrop.setPartnerPayout(0);
363
		priceDrop.setPriceDropIn(0);
364
		priceDropRepository.persist(priceDrop);
365
		response = true;
366
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
367
		return "response";
368
	}
369
 
23884 amit.gupta 370
	@RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
23945 amit.gupta 371
	public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
372
			throws Exception {
23884 amit.gupta 373
		boolean response = false;
23968 amit.gupta 374
		priceDropModel.setAllColors(true);
23945 amit.gupta 375
		if (this.validatePriceDrop(priceDropModel)) {
23884 amit.gupta 376
			TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
377
			float newDp = tagListing.getSellingPrice() - priceDropModel.getPd();
23945 amit.gupta 378
			if (newDp > 0) {
23884 amit.gupta 379
				List<Item> allItems = null;
380
				Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
23945 amit.gupta 381
				if (priceDropModel.isAllColors()) {
23884 amit.gupta 382
					allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
23945 amit.gupta 383
 
23884 amit.gupta 384
				} else {
23945 amit.gupta 385
					allItems = Arrays.asList(currentItem);
23884 amit.gupta 386
				}
23945 amit.gupta 387
				for (Item item : allItems) {
23884 amit.gupta 388
					TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
23945 amit.gupta 389
					if (itemTagListing == null)
390
						continue;
23884 amit.gupta 391
					itemTagListing.setSellingPrice(newDp);
392
					itemTagListing.setMop(priceDropModel.getMop());
393
					tagListingRepository.persist(tagListing);
394
					List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
23945 amit.gupta 395
					for (VendorItemPricing vip : vipList) {
23884 amit.gupta 396
						vip.setDp(newDp);
397
						vip.setMop(priceDropModel.getMop());
398
						vip.setNlc(priceDropModel.getNlc());
399
						vip.setTp(priceDropModel.getTp());
400
						vendorItemPricingRepository.persist(vip);
401
					}
402
					transactionService.updatePriceDrop(item.getId(), newDp);
403
				}
23951 amit.gupta 404
				PriceDrop priceDrop = new PriceDrop();
405
				priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
23968 amit.gupta 406
				priceDrop.setOldDp(newDp + priceDropModel.getPd());
23951 amit.gupta 407
				priceDrop.setAmount(priceDropModel.getPd());
23968 amit.gupta 408
				priceDrop.setNewDp(newDp);
409
				priceDrop.setNlc(priceDropModel.getNlc());
24049 amit.gupta 410
				priceDrop.setMop(priceDropModel.getMop());
23968 amit.gupta 411
				priceDrop.setTp(priceDropModel.getTp());
23951 amit.gupta 412
				priceDrop.setCreatedOn(LocalDateTime.now());
413
				priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
414
				priceDropRepository.persist(priceDrop);
23884 amit.gupta 415
				response = true;
416
			} else {
23945 amit.gupta 417
				throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
418
						"Price Drop Cannot be more than Current DP");
23884 amit.gupta 419
			}
420
		}
421
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
422
		return "response";
423
	}
23945 amit.gupta 424
 
23819 govind 425
	@RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
426
	public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
23945 amit.gupta 427
			Model model) throws ProfitMandiBusinessException, Exception {
23819 govind 428
 
429
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
23968 amit.gupta 430
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
431
		ByteArrayOutputStream baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId());
432
		final HttpHeaders headers = new HttpHeaders();
433
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 434
		headers.set("Content-disposition",
435
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
436
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
23968 amit.gupta 437
		byte[] byteArray = baos.toByteArray();
438
		headers.setContentLength(byteArray.length);
439
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 440
 
441
	}
442
 
24083 amit.gupta 443
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
444
	public String downloadTotalPriceDropIMEI(HttpServletRequest request,
445
			@RequestBody PriceDropImeisModel priceDropImeisModel, Model model)
446
			throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 447
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
448
		;
24083 amit.gupta 449
 
450
		switch (priceDropImeisModel.getUpdatedStatus()) {
451
		case "pending": {
452
			status = PriceDropImeiStatus.PENDING;
453
			break;
454
		}
455
		case "approved": {
456
			status = PriceDropImeiStatus.APPROVED;
457
			break;
458
		}
459
		case "rejected": {
460
			status = PriceDropImeiStatus.REJECTED;
461
			break;
462
		}
463
 
464
		}
465
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
466
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
467
 
468
		List<PriceDropIMEI> priceDropIMEIsToProcess = new ArrayList<>();
469
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
470
			if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())
471
					|| priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)
472
					|| priceDropIMEI.getStatus().equals(status)) {
473
				continue;
474
			} else {
24168 amit.gupta 475
				if (status.equals(PriceDropImeiStatus.APPROVED)) {
24083 amit.gupta 476
					priceDropIMEIsToProcess.add(priceDropIMEI);
477
				}
478
				priceDropIMEI.setStatus(status);
479
				priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
480
				priceDropIMEIRepository.persist(priceDropIMEI);
481
			}
482
		}
483
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropImeisModel.getPriceDropId());
484
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
485
		String description = item.getItemDescriptionNoColor();
486
		if (priceDropIMEIsToProcess.size() > 0) {
487
			List<String> serialNumbers = priceDropIMEIsToProcess.stream().map(x -> x.getImei())
488
					.collect(Collectors.toList());
489
			List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByIMEI(serialNumbers);
490
			Map<Integer, List<InventoryItem>> pendingPartnerInventoryMap = priceDropService
491
					.getInventoryForPriceDrop(lineItemImeis, priceDrop).stream()
492
					.collect(Collectors.groupingBy(InventoryItem::getFofoId));
493
 
494
			for (Map.Entry<Integer, List<InventoryItem>> pendingPartnerInventory : pendingPartnerInventoryMap
495
					.entrySet()) {
496
				List<InventoryItem> fofoInventoryList = pendingPartnerInventory.getValue();
497
				int fofoId = pendingPartnerInventory.getKey();
498
 
499
				String reversalReason = MessageFormat.format(
500
						"Scheme  differential for Price Drop of Rs.{0} on {1}, on {3}. Total {2} item(s)",
501
						priceDrop.getAmount(), description, fofoInventoryList.size(),
502
						FormattingUtils.formatDate(priceDrop.getAffectedOn()));
503
				String aReason = MessageFormat.format(
504
						"Payout of Rs.{4} per unit for Price Drop of Rs.{0} on {1}, on {3}. Total {2} item(s)",
505
						priceDrop.getAmount(), description, fofoInventoryList.size(),
506
						FormattingUtils.formatDate(priceDrop.getAffectedOn()), priceDrop.getPartnerPayout());
507
				inventoryService.updatePriceDrop(fofoInventoryList, priceDrop.getAmount());
508
				if (item.getBrand().equals("Samsung")) {
24168 amit.gupta 509
					schemeService.reverseSchemes(fofoInventoryList, priceDrop.getId(), reversalReason);
24083 amit.gupta 510
				}
511
				walletService.addAmountToWallet(fofoId, priceDrop.getId(), WalletReferenceType.PRICE_DROP, aReason,
512
						priceDrop.getPartnerPayout() * fofoInventoryList.size());
513
			}
514
 
515
		}
24168 amit.gupta 516
 
24083 amit.gupta 517
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
518
		return "response";
519
 
520
	}
521
 
23983 amit.gupta 522
	private List<ImeiDropSummaryModel> getAllSerialNumbersByAffectedDate(LocalDateTime affectedOn,
523
			Integer catalogItemId) throws Exception {
23951 amit.gupta 524
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogItemId);
525
		List<String> itemIds = items.stream().map(x -> String.valueOf(x.getId())).collect(Collectors.toList());
23945 amit.gupta 526
 
23968 amit.gupta 527
		Map<String, String> params = new HashMap<>();
24088 amit.gupta 528
		params.put("MANUAL_criteria1_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23968 amit.gupta 529
		params.put("MANUAL_itemId", StringUtils.join(itemIds, ","));
530
 
531
		Map<String, String> params1 = new HashMap<>();
23979 amit.gupta 532
		params1.put("MANUAL_criteriaDate_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23968 amit.gupta 533
		params1.put("MANUAL_criteriaItemId", StringUtils.join(itemIds, ","));
534
 
23970 amit.gupta 535
		Map<String, String> params2 = new HashMap<>();
23981 amit.gupta 536
		params2.put("MANUAL_Criteria2_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23970 amit.gupta 537
		params2.put("MANUAL_Criteria1", StringUtils.join(itemIds, ","));
538
 
23968 amit.gupta 539
		List<? extends ImeiDropSummaryModel> grnPendingList = getReports(GrnPendingDataModel.class,
540
				ReporticoProject.FOCO, "imeispendinggrn.xml", params);
541
		List<? extends ImeiDropSummaryModel> partnerImeiNotSoldList = getReports(PartnerImeiNotSold.class,
542
				ReporticoProject.FOCO, "PartnerIMEINotSold.xml", params1);
23970 amit.gupta 543
		List<? extends ImeiDropSummaryModel> itemStockOnDateList = getReports(ClosingStockOnDate.class,
544
				ReporticoProject.WAREHOUSENEW, "itemstockondate.xml", params2);
23983 amit.gupta 545
 
23968 amit.gupta 546
		List<ImeiDropSummaryModel> mergedImeis = new ArrayList<>();
547
		mergedImeis.addAll(grnPendingList);
548
		mergedImeis.addAll(partnerImeiNotSoldList);
23970 amit.gupta 549
		mergedImeis.addAll(itemStockOnDateList);
23983 amit.gupta 550
		return mergedImeis;
551
	}
23968 amit.gupta 552
 
23983 amit.gupta 553
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId)
554
			throws Exception {
24083 amit.gupta 555
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = this.getAllSerialNumbersByAffectedDate(affectedOn,
556
				catalogItemId);
23951 amit.gupta 557
		List<List<Object>> rows = new ArrayList<>();
23983 amit.gupta 558
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
23986 amit.gupta 559
			rows.add(this.getRow(imeiDropSummaryModel));
23951 amit.gupta 560
		}
561
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
562
				"Model Name", "Model Number", "Color", "Last Scanned"), rows);
23819 govind 563
	}
24083 amit.gupta 564
 
23986 amit.gupta 565
	private List<Object> getRow(ImeiDropSummaryModel imeiDropSummaryModel) {
566
		List<Object> row = new ArrayList<>();
567
		row.add(imeiDropSummaryModel.getSerialNumber());
568
		row.add(imeiDropSummaryModel.getStoreName());
569
		row.add(imeiDropSummaryModel.getPartnerCode());
570
		row.add(imeiDropSummaryModel.getItemId());
571
		row.add(imeiDropSummaryModel.getBrand());
572
		row.add(imeiDropSummaryModel.getModelName());
573
		row.add(imeiDropSummaryModel.getModelNumber());
574
		row.add(imeiDropSummaryModel.getColor());
575
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
576
		return row;
577
	}
23819 govind 578
 
23945 amit.gupta 579
	private <T> List<T> getReports(Class<T> className, ReporticoProject project, String reportName,
580
			Map<String, String> params) throws Exception {
581
		HttpResponse reportResponse = reporticoService.getJsonFile(project, reportName, params);
23951 amit.gupta 582
		JavaType type = objectMapper.getTypeFactory().constructParametricType(ReporticoResponseModel.class, className);
583
		ObjectReader or = objectMapper.readerFor(type);
23945 amit.gupta 584
		ReporticoResponseModel<T> responseObj = or.readValue(reportResponse.getEntity().getContent());
585
		return responseObj.getData();
586
	}
587
 
23884 amit.gupta 588
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
23945 amit.gupta 589
		if (priceDropModel.getMop() > 0 && priceDropModel.getMop() > 0 && priceDropModel.getNlc() > 0
590
				&& priceDropModel.getTp() > 0 && priceDropModel.getNlc() > 0) {
23884 amit.gupta 591
			return true;
592
		}
593
		return false;
594
	}
23945 amit.gupta 595
 
23819 govind 596
}