Subversion Repositories SmartDukaan

Rev

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