Subversion Repositories SmartDukaan

Rev

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

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