Subversion Repositories SmartDukaan

Rev

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