Subversion Repositories SmartDukaan

Rev

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