Subversion Repositories SmartDukaan

Rev

Rev 24406 | Rev 24410 | 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());
24409 amit.gupta 325
			float oldDp = tagListing.getSellingPrice();
326
			float newDp = priceDropModel.getDp();
327
			if (newDp == oldDp) {
23884 amit.gupta 328
				List<Item> allItems = null;
329
				Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
23945 amit.gupta 330
				if (priceDropModel.isAllColors()) {
23884 amit.gupta 331
					allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
23945 amit.gupta 332
 
23884 amit.gupta 333
				} else {
23945 amit.gupta 334
					allItems = Arrays.asList(currentItem);
23884 amit.gupta 335
				}
23945 amit.gupta 336
				for (Item item : allItems) {
23884 amit.gupta 337
					TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
23945 amit.gupta 338
					if (itemTagListing == null)
339
						continue;
23884 amit.gupta 340
					itemTagListing.setSellingPrice(newDp);
341
					itemTagListing.setMop(priceDropModel.getMop());
342
					tagListingRepository.persist(tagListing);
343
					List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
23945 amit.gupta 344
					for (VendorItemPricing vip : vipList) {
23884 amit.gupta 345
						vip.setDp(newDp);
346
						vip.setMop(priceDropModel.getMop());
24409 amit.gupta 347
						vip.setNlc(priceDropModel.getTp());
23884 amit.gupta 348
						vip.setTp(priceDropModel.getTp());
349
						vendorItemPricingRepository.persist(vip);
350
					}
351
					transactionService.updatePriceDrop(item.getId(), newDp);
352
				}
23951 amit.gupta 353
				PriceDrop priceDrop = new PriceDrop();
354
				priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
24409 amit.gupta 355
				priceDrop.setOldDp(oldDp);
356
				priceDrop.setAmount(oldDp - newDp);
23968 amit.gupta 357
				priceDrop.setNewDp(newDp);
24409 amit.gupta 358
				priceDrop.setNlc(priceDropModel.getTp());
24049 amit.gupta 359
				priceDrop.setMop(priceDropModel.getMop());
23968 amit.gupta 360
				priceDrop.setTp(priceDropModel.getTp());
23951 amit.gupta 361
				priceDrop.setCreatedOn(LocalDateTime.now());
362
				priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
363
				priceDropRepository.persist(priceDrop);
23884 amit.gupta 364
				response = true;
365
			} else {
23945 amit.gupta 366
				throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
24409 amit.gupta 367
						"Price Drop Should be greater than 0");
23884 amit.gupta 368
			}
369
		}
370
		model.addAttribute("response", mvcResponseSender.createResponseString(response));
371
		return "response";
372
	}
23945 amit.gupta 373
 
23819 govind 374
	@RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
375
	public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
23945 amit.gupta 376
			Model model) throws ProfitMandiBusinessException, Exception {
23819 govind 377
 
378
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
23968 amit.gupta 379
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
380
		ByteArrayOutputStream baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId());
381
		final HttpHeaders headers = new HttpHeaders();
382
		headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
23983 amit.gupta 383
		headers.set("Content-disposition",
384
				"inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
385
						+ FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
23968 amit.gupta 386
		byte[] byteArray = baos.toByteArray();
387
		headers.setContentLength(byteArray.length);
388
		return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
23951 amit.gupta 389
 
390
	}
391
 
24083 amit.gupta 392
	@RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
393
	public String downloadTotalPriceDropIMEI(HttpServletRequest request,
394
			@RequestBody PriceDropImeisModel priceDropImeisModel, Model model)
395
			throws ProfitMandiBusinessException, Exception {
24168 amit.gupta 396
		PriceDropImeiStatus status = PriceDropImeiStatus.PENDING;
397
		;
24083 amit.gupta 398
 
399
		switch (priceDropImeisModel.getUpdatedStatus()) {
400
		case "pending": {
401
			status = PriceDropImeiStatus.PENDING;
402
			break;
403
		}
404
		case "approved": {
405
			status = PriceDropImeiStatus.APPROVED;
406
			break;
407
		}
408
		case "rejected": {
409
			status = PriceDropImeiStatus.REJECTED;
410
			break;
411
		}
412
 
413
		}
414
		List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
415
				.selectByPriceDropId(priceDropImeisModel.getPriceDropId());
416
 
417
		List<PriceDropIMEI> priceDropIMEIsToProcess = new ArrayList<>();
418
		for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
419
			if (!priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())
420
					|| priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)
421
					|| priceDropIMEI.getStatus().equals(status)) {
422
				continue;
423
			} else {
24168 amit.gupta 424
				if (status.equals(PriceDropImeiStatus.APPROVED)) {
24083 amit.gupta 425
					priceDropIMEIsToProcess.add(priceDropIMEI);
426
				}
427
				priceDropIMEI.setStatus(status);
428
				priceDropIMEI.setUpdateTimestamp(LocalDateTime.now());
429
				priceDropIMEIRepository.persist(priceDropIMEI);
430
			}
431
		}
432
		PriceDrop priceDrop = priceDropRepository.selectById(priceDropImeisModel.getPriceDropId());
433
		Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
434
		String description = item.getItemDescriptionNoColor();
435
		if (priceDropIMEIsToProcess.size() > 0) {
436
			List<String> serialNumbers = priceDropIMEIsToProcess.stream().map(x -> x.getImei())
437
					.collect(Collectors.toList());
438
			List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByIMEI(serialNumbers);
439
			Map<Integer, List<InventoryItem>> pendingPartnerInventoryMap = priceDropService
440
					.getInventoryForPriceDrop(lineItemImeis, priceDrop).stream()
441
					.collect(Collectors.groupingBy(InventoryItem::getFofoId));
442
 
443
			for (Map.Entry<Integer, List<InventoryItem>> pendingPartnerInventory : pendingPartnerInventoryMap
444
					.entrySet()) {
445
				List<InventoryItem> fofoInventoryList = pendingPartnerInventory.getValue();
446
				int fofoId = pendingPartnerInventory.getKey();
447
 
448
				String reversalReason = MessageFormat.format(
449
						"Scheme  differential for Price Drop of Rs.{0} on {1}, on {3}. Total {2} item(s)",
450
						priceDrop.getAmount(), description, fofoInventoryList.size(),
451
						FormattingUtils.formatDate(priceDrop.getAffectedOn()));
452
				String aReason = MessageFormat.format(
453
						"Payout of Rs.{4} per unit for Price Drop of Rs.{0} on {1}, on {3}. Total {2} item(s)",
454
						priceDrop.getAmount(), description, fofoInventoryList.size(),
455
						FormattingUtils.formatDate(priceDrop.getAffectedOn()), priceDrop.getPartnerPayout());
456
				inventoryService.updatePriceDrop(fofoInventoryList, priceDrop.getAmount());
457
				if (item.getBrand().equals("Samsung")) {
24168 amit.gupta 458
					schemeService.reverseSchemes(fofoInventoryList, priceDrop.getId(), reversalReason);
24083 amit.gupta 459
				}
460
				walletService.addAmountToWallet(fofoId, priceDrop.getId(), WalletReferenceType.PRICE_DROP, aReason,
461
						priceDrop.getPartnerPayout() * fofoInventoryList.size());
462
			}
463
 
464
		}
24168 amit.gupta 465
 
24083 amit.gupta 466
		model.addAttribute("response", mvcResponseSender.createResponseString(true));
467
		return "response";
468
 
469
	}
470
 
23983 amit.gupta 471
	private List<ImeiDropSummaryModel> getAllSerialNumbersByAffectedDate(LocalDateTime affectedOn,
472
			Integer catalogItemId) throws Exception {
23951 amit.gupta 473
		List<Item> items = itemRepository.selectAllByCatalogItemId(catalogItemId);
474
		List<String> itemIds = items.stream().map(x -> String.valueOf(x.getId())).collect(Collectors.toList());
23945 amit.gupta 475
 
23968 amit.gupta 476
		Map<String, String> params = new HashMap<>();
24088 amit.gupta 477
		params.put("MANUAL_criteria1_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23968 amit.gupta 478
		params.put("MANUAL_itemId", StringUtils.join(itemIds, ","));
479
 
480
		Map<String, String> params1 = new HashMap<>();
23979 amit.gupta 481
		params1.put("MANUAL_criteriaDate_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23968 amit.gupta 482
		params1.put("MANUAL_criteriaItemId", StringUtils.join(itemIds, ","));
483
 
23970 amit.gupta 484
		Map<String, String> params2 = new HashMap<>();
23981 amit.gupta 485
		params2.put("MANUAL_Criteria2_FROMDATE", FormattingUtils.formatReporitcoDate(affectedOn.minusDays(1)));
23970 amit.gupta 486
		params2.put("MANUAL_Criteria1", StringUtils.join(itemIds, ","));
487
 
23968 amit.gupta 488
		List<? extends ImeiDropSummaryModel> grnPendingList = getReports(GrnPendingDataModel.class,
489
				ReporticoProject.FOCO, "imeispendinggrn.xml", params);
490
		List<? extends ImeiDropSummaryModel> partnerImeiNotSoldList = getReports(PartnerImeiNotSold.class,
491
				ReporticoProject.FOCO, "PartnerIMEINotSold.xml", params1);
23970 amit.gupta 492
		List<? extends ImeiDropSummaryModel> itemStockOnDateList = getReports(ClosingStockOnDate.class,
493
				ReporticoProject.WAREHOUSENEW, "itemstockondate.xml", params2);
23983 amit.gupta 494
 
23968 amit.gupta 495
		List<ImeiDropSummaryModel> mergedImeis = new ArrayList<>();
496
		mergedImeis.addAll(grnPendingList);
497
		mergedImeis.addAll(partnerImeiNotSoldList);
23970 amit.gupta 498
		mergedImeis.addAll(itemStockOnDateList);
23983 amit.gupta 499
		return mergedImeis;
500
	}
23968 amit.gupta 501
 
23983 amit.gupta 502
	private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId)
503
			throws Exception {
24083 amit.gupta 504
		List<ImeiDropSummaryModel> imeiDropSummaryModelList = this.getAllSerialNumbersByAffectedDate(affectedOn,
505
				catalogItemId);
23951 amit.gupta 506
		List<List<Object>> rows = new ArrayList<>();
23983 amit.gupta 507
		for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
23986 amit.gupta 508
			rows.add(this.getRow(imeiDropSummaryModel));
23951 amit.gupta 509
		}
510
		return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
511
				"Model Name", "Model Number", "Color", "Last Scanned"), rows);
23819 govind 512
	}
24083 amit.gupta 513
 
23986 amit.gupta 514
	private List<Object> getRow(ImeiDropSummaryModel imeiDropSummaryModel) {
515
		List<Object> row = new ArrayList<>();
516
		row.add(imeiDropSummaryModel.getSerialNumber());
517
		row.add(imeiDropSummaryModel.getStoreName());
518
		row.add(imeiDropSummaryModel.getPartnerCode());
519
		row.add(imeiDropSummaryModel.getItemId());
520
		row.add(imeiDropSummaryModel.getBrand());
521
		row.add(imeiDropSummaryModel.getModelName());
522
		row.add(imeiDropSummaryModel.getModelNumber());
523
		row.add(imeiDropSummaryModel.getColor());
524
		row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
525
		return row;
526
	}
23819 govind 527
 
23945 amit.gupta 528
	private <T> List<T> getReports(Class<T> className, ReporticoProject project, String reportName,
529
			Map<String, String> params) throws Exception {
530
		HttpResponse reportResponse = reporticoService.getJsonFile(project, reportName, params);
23951 amit.gupta 531
		JavaType type = objectMapper.getTypeFactory().constructParametricType(ReporticoResponseModel.class, className);
532
		ObjectReader or = objectMapper.readerFor(type);
23945 amit.gupta 533
		ReporticoResponseModel<T> responseObj = or.readValue(reportResponse.getEntity().getContent());
534
		return responseObj.getData();
535
	}
536
 
23884 amit.gupta 537
	private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
24409 amit.gupta 538
		if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0
23945 amit.gupta 539
				&& priceDropModel.getTp() > 0 && priceDropModel.getNlc() > 0) {
23884 amit.gupta 540
			return true;
541
		}
542
		return false;
543
	}
23945 amit.gupta 544
 
23819 govind 545
}