Subversion Repositories SmartDukaan

Rev

Rev 24176 | Rev 24191 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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