Subversion Repositories SmartDukaan

Rev

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