Subversion Repositories SmartDukaan

Rev

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

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