Subversion Repositories SmartDukaan

Rev

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