Subversion Repositories SmartDukaan

Rev

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