Rev 29683 | Rev 29783 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.spice.profitmandi.service.offers;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.time.LocalDate;import java.time.YearMonth;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellType;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.google.gson.Gson;import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;import com.spice.profitmandi.common.model.PartnerTargetModel;import com.spice.profitmandi.common.model.ProfitMandiConstants;import com.spice.profitmandi.dao.entity.catalog.ItemCriteria;import com.spice.profitmandi.dao.entity.catalog.Offer;import com.spice.profitmandi.dao.entity.catalog.TargetSlab;import com.spice.profitmandi.dao.enumuration.catalog.OfferSchemeType;import com.spice.profitmandi.dao.model.CreateOfferRequest;import com.spice.profitmandi.dao.model.ItemCriteriaPayout;import com.spice.profitmandi.dao.repository.catalog.ItemCriteriaRepository;import com.spice.profitmandi.dao.repository.catalog.ItemRepository;import com.spice.profitmandi.dao.repository.catalog.OfferRepository;import com.spice.profitmandi.dao.repository.catalog.OfferTargetSlabRepository;import com.spice.profitmandi.service.user.RetailerService;@Componentpublic class OfferServiceImpl implements OfferService {private static final List<String> targets = Arrays.asList("Target 1", "Target 2", "Target 3", "Target 4","Target 5");@Autowiredprivate Gson gson;@Autowiredprivate OfferRepository offerRepository;@Autowiredprivate RetailerService retailerService;@Autowiredprivate ItemCriteriaRepository itemCriteriaRepository;@Autowiredprivate ItemRepository itemRepository;@Autowiredprivate OfferTargetSlabRepository targetSlabRepository;private static final Logger LOGGER = LogManager.getLogger(OfferServiceImpl.class);@Overridepublic void addOfferService(CreateOfferRequest createOfferRequest) throws ProfitMandiBusinessException {LOGGER.info("createOfferRequest -- {}", createOfferRequest);this.createOffer(createOfferRequest);this.createTargetSlabs(createOfferRequest);}private void createOffer(CreateOfferRequest createOfferRequest) {Offer offer = new Offer();offer.setName(createOfferRequest.getName());offer.setTargetType(createOfferRequest.getTargetType());offer.setPayoutType(createOfferRequest.getPayoutType());offer.setSchemeType(createOfferRequest.getSchemeType());offer.setIncrementalTarget(createOfferRequest.isIncrementalTarget());offer.setEndDate(createOfferRequest.getEndDate());offer.setStartDate(createOfferRequest.getStartDate());offer.setBrandSharePercentage(createOfferRequest.getBrandShareTerms());offer.setSellinPercentage(createOfferRequest.getSellinPercentage());offer.setOfferNotes(createOfferRequest.getOfferNotes());offer.setActivationBrands(createOfferRequest.getActivationBrands());offer.setTerms(createOfferRequest.getTerms());offer.setItemCriteria(gson.toJson(createOfferRequest.getItemCriteria()));offer.setPartnerCriteria(gson.toJson(createOfferRequest.getPartnerCriteria()));offerRepository.persist(offer);createOfferRequest.setId(offer.getId());}@Overridepublic List<CreateOfferRequest> getPublishedOffers(int fofoId, YearMonth yearMonth) {List<Offer> publishedOffers = offerRepository.selectAllPublishedMapByPartner(yearMonth).get(fofoId);List<CreateOfferRequest> createOfferRequests = new ArrayList<>();if (publishedOffers != null) {for (Offer offer : publishedOffers) {List<com.spice.profitmandi.dao.model.TargetSlab> targetSlabs = targetSlabRepository.getByOfferId(offer.getId());CreateOfferRequest createOfferRequest = this.getCreateOfferRequest(offer);createOfferRequest.getItemCriteria();createOfferRequest.setTargetSlabs(targetSlabs);createOfferRequests.add(createOfferRequest);}for (CreateOfferRequest createOfferRequest : createOfferRequests) {if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {} else {long amount = offerRepository.getPartnerWiseSalesSum(createOfferRequest).get(fofoId) == null ? 0: offerRepository.getPartnerWiseSalesSum(createOfferRequest).get(fofoId);com.spice.profitmandi.dao.model.TargetSlab currentSlab = createOfferRequest.getTargetSlabs().stream().filter(x -> x.getOnwardsAmount() <= amount).max(Comparator.comparing(x -> x.getOnwardsAmount())).orElse(null);com.spice.profitmandi.dao.model.TargetSlab nextSlab = createOfferRequest.getTargetSlabs().stream().filter(x -> x.getOnwardsAmount() > amount).min(Comparator.comparing(x -> x.getOnwardsAmount())).orElse(null);createOfferRequest.setNextTargetSlab(nextSlab);if (nextSlab != null) {createOfferRequest.setNextTarget(targets.get(createOfferRequest.getTargetSlabs().indexOf(nextSlab)));}createOfferRequest.setCurrentTargetSlab(currentSlab);if (currentSlab != null) {createOfferRequest.setCurrentTarget(targets.get(createOfferRequest.getTargetSlabs().indexOf(currentSlab)));}createOfferRequest.setEligibleSale((int) amount);}}}return createOfferRequests;}@Overridepublic List<CreateOfferRequest> getAllOffers(YearMonth yearMonth) {List<Offer> allOffers = offerRepository.selectAll(yearMonth, false);List<CreateOfferRequest> createOfferRequests = new ArrayList<>();for (Offer offer : allOffers) {CreateOfferRequest createOfferRequest = this.getCreateOfferRequest(offer);createOfferRequests.add(createOfferRequest);}return createOfferRequests;}@Overridepublic CreateOfferRequest getOffer(int offerId) {Offer offer = offerRepository.selectById(offerId);CreateOfferRequest createOfferRequest = this.getCreateOfferRequest(offer);return createOfferRequest;}private CreateOfferRequest getCreateOfferRequest(Offer fromOffer) {CreateOfferRequest createOfferRequest = new CreateOfferRequest();createOfferRequest.setName(fromOffer.getName());createOfferRequest.setTargetType(fromOffer.getTargetType());createOfferRequest.setPayoutType(fromOffer.getPayoutType());createOfferRequest.setSchemeType(fromOffer.getSchemeType());createOfferRequest.setActivationBrands(fromOffer.getActivationBrands());createOfferRequest.setEndDate(fromOffer.getEndDate());createOfferRequest.setStartDate(fromOffer.getStartDate());createOfferRequest.setActive(fromOffer.isActive());createOfferRequest.setSellinPercentage(fromOffer.getSellinPercentage());createOfferRequest.setBrandShareTerms(fromOffer.getBrandSharePercentage());createOfferRequest.setOfferNotes(fromOffer.getOfferNotes());createOfferRequest.setTerms(fromOffer.getTerms());createOfferRequest.setItemCriteria(gson.fromJson(fromOffer.getItemCriteria(), com.spice.profitmandi.service.offers.ItemCriteria.class));createOfferRequest.setPartnerCriteria(gson.fromJson(fromOffer.getPartnerCriteria(), PartnerCriteria.class));createOfferRequest.setId(fromOffer.getId());createOfferRequest.setCreatedOn(fromOffer.getCreatedTimestamp());createOfferRequest.setItemCriteriaString(itemCriteriaRepository.getItemCriteriaDescription(createOfferRequest.getItemCriteria()));List<com.spice.profitmandi.dao.model.TargetSlab> targetSlabs = targetSlabRepository.getByOfferId(fromOffer.getId());createOfferRequest.setPartnerCriteriaString(retailerService.getPartnerCriteriaString(createOfferRequest.getPartnerCriteria()));createOfferRequest.setTargetSlabs(targetSlabs);LOGGER.info("createOfferRequest {}", createOfferRequest);return createOfferRequest;}private void createTargetSlabs(CreateOfferRequest createOfferRequest) throws ProfitMandiBusinessException {List<com.spice.profitmandi.dao.model.TargetSlab> targetSlabs = createOfferRequest.getTargetSlabs().stream().filter(x -> x.validate()).collect(Collectors.toList());if (targetSlabs.size() >= 0) {Collections.sort(targetSlabs);for (com.spice.profitmandi.dao.model.TargetSlab targetSlab : targetSlabs) {if (targetSlab.validate()) {List<ItemCriteriaPayout> itemCriteriaPayouts = targetSlab.getItemCriteriaPayouts();for (ItemCriteriaPayout itemCriteriaPayout : itemCriteriaPayouts) {String itemCriteriaJson = gson.toJson(itemCriteriaPayout.getItemCriteria());ItemCriteria itemCriteria = itemCriteriaRepository.selectByCriteria(itemCriteriaJson);// ItemCriteria Only onceif (itemCriteria == null) {itemCriteria = new ItemCriteria();itemCriteria.setCriteria(gson.toJson(itemCriteriaPayout.getItemCriteria()));itemCriteriaRepository.persist(itemCriteria);}for (PayoutSlab payoutSlab : itemCriteriaPayout.getPayoutSlabs()) {TargetSlab targetSlab1 = new TargetSlab();targetSlab1.setOfferId(createOfferRequest.getId());targetSlab1.setOnwardsTarget(targetSlab.getOnwardsAmount());targetSlab1.setTargetDescription(targetSlab.getTargetDescription());targetSlab1.setPayoutTarget(payoutSlab.getOnwardsAmount());targetSlab1.setPayoutValue(payoutSlab.getPayoutAmount());targetSlab1.setItemCriteriaId(itemCriteria.getId());targetSlab1.setAmountType(itemCriteriaPayout.getAmountType());targetSlabRepository.persist(targetSlab1);}}}}} else {throw new ProfitMandiBusinessException("Invalid Target Slabs", "Invalid Target", "");}}@Overridepublic List<CreateOfferRequest> getPublishedOffers(LocalDate date, int fofoId, int itemId) {List<Offer> publishedOffers = offerRepository.selectAllPublishedMapByPartner(YearMonth.from(date)).get(fofoId);List<CreateOfferRequest> createOfferRequests = new ArrayList<>();if (publishedOffers != null) {for (Offer offer : publishedOffers) {boolean found = false;List<com.spice.profitmandi.dao.model.TargetSlab> targetSlabs = targetSlabRepository.getByOfferId(offer.getId());CreateOfferRequest createOfferRequest = this.getCreateOfferRequest(offer);createOfferRequest.setTargetSlabs(targetSlabs);Set<com.spice.profitmandi.service.offers.ItemCriteria> itemCriteriaSet = targetSlabs.stream().flatMap(x -> x.getItemCriteriaPayouts().stream()).map(x -> x.getItemCriteria()).distinct().filter(x -> itemRepository.containsItem(x, itemId)).collect(Collectors.toSet());for (com.spice.profitmandi.dao.model.TargetSlab targetSlab : targetSlabs) {targetSlab.setItemCriteriaPayouts(targetSlab.getItemCriteriaPayouts().stream().filter(x -> itemCriteriaSet.contains(x.getItemCriteria())).collect(Collectors.toList()));if (targetSlab.getItemCriteriaPayouts().size() > 0) {found = true;}}if (found) {createOfferRequests.add(createOfferRequest);}}}return createOfferRequests;}@Overridepublic void createOffers(InputStream fileInputStream) throws Exception {Map<CreateOfferRequest, List<PartnerTargetModel>> offerPartnerTargetMap = this.parseFromExcel(fileInputStream);for(Map.Entry<CreateOfferRequest, List<PartnerTargetModel>> partnerTargetEntry: offerPartnerTargetMap.entrySet()) {CreateOfferRequest createOfferRequest = partnerTargetEntry.getKey();Map<List<Integer>, List<Integer>> targetPartnerMap = partnerTargetEntry.getValue().stream().collect(Collectors.groupingBy(PartnerTargetModel::getTargets, Collectors.mapping(PartnerTargetModel::getFofoId, Collectors.toList())));for (Map.Entry<List<Integer>, List<Integer>> targetPartnersEntry : targetPartnerMap.entrySet()) {List<Integer> fofoIds = createOfferRequest.getPartnerCriteria().getFofoIds();List<Integer> filterFofoIds = targetPartnersEntry.getValue().stream().filter(x->!fofoIds.contains(x)).collect(Collectors.toList());List<Integer> targets = targetPartnersEntry.getKey();createOfferRequest.getPartnerCriteria().setFofoIds(filterFofoIds);int counter = 0;for (com.spice.profitmandi.dao.model.TargetSlab targetSlab : createOfferRequest.getTargetSlabs()) {targetSlab.setOnwardsAmount(targets.get(counter));counter++;}this.addOfferService(createOfferRequest);}}}private Map<CreateOfferRequest, List<PartnerTargetModel>> parseFromExcel(InputStream inputStream) throws ProfitMandiBusinessException {Map<CreateOfferRequest, List<PartnerTargetModel>> offerPartnerTargetMap = new HashMap<>();XSSFWorkbook myWorkBook = null;try {myWorkBook = new XSSFWorkbook(inputStream);myWorkBook.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL);for(int i=0; i< myWorkBook.getNumberOfSheets();i++) {XSSFSheet mySheet = myWorkBook.getSheetAt(i);int offerId = Integer.parseInt(mySheet.getSheetName());CreateOfferRequest existingOffer = this.getOffer(offerId);List<PartnerTargetModel> partnerTargetModels = new ArrayList<>();offerPartnerTargetMap.put(existingOffer, partnerTargetModels);this.printIterator(mySheet);LOGGER.info("rowCellNum {}", mySheet.getLastRowNum());for (int rowNumber = 1; rowNumber <= mySheet.getLastRowNum(); rowNumber++) {XSSFRow row = mySheet.getRow(rowNumber);LOGGER.info("row {}", row);PartnerTargetModel partnerTargetModel = new PartnerTargetModel();if (row.getCell(0) != null && row.getCell(0).getCellTypeEnum() == CellType.NUMERIC) {partnerTargetModel.setFofoId((int) row.getCell(0).getNumericCellValue());} else {ProfitMandiBusinessException profitMandiBusinessException = new ProfitMandiBusinessException("FOFO ID", row.getCell(0).toString(), "TGLSTNG_VE_1010");LOGGER.error("Excel file parse error : ", profitMandiBusinessException);throw profitMandiBusinessException;}List<Integer> targets = new ArrayList<>();for (int cellNumber = 1; cellNumber <= existingOffer.getTargetSlabs().size(); cellNumber++) {if (row.getCell(cellNumber) != null&& row.getCell(cellNumber).getCellTypeEnum() == CellType.NUMERIC) {targets.add((int) row.getCell(cellNumber).getNumericCellValue());} else {ProfitMandiBusinessException profitMandiBusinessException = new ProfitMandiBusinessException("Target Column issue at " + rowNumber + ", " + cellNumber, row.getCell(cellNumber),"Invalid target");LOGGER.error("Excel file parse error : ", profitMandiBusinessException);throw profitMandiBusinessException;}}partnerTargetModel.setTargets(targets);partnerTargetModels.add(partnerTargetModel);}}myWorkBook.close();} catch ( ProfitMandiBusinessException pbse) {throw pbse;} catch (IOException ioException) {ioException.printStackTrace();throw new ProfitMandiBusinessException(ProfitMandiConstants.EXCEL_FILE, ioException.getMessage(),"EXL_VE_1000");} finally {if (myWorkBook != null) {try {myWorkBook.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}LOGGER.info("offerPartnerTargetMap {}", offerPartnerTargetMap);return offerPartnerTargetMap;}private void printIterator (XSSFSheet sheet) {Iterator<Row> rowIterator = sheet.iterator();while (rowIterator.hasNext()){Row row = rowIterator.next();//For each row, iterate through all the columnsIterator<Cell> cellIterator = row.cellIterator();while (cellIterator.hasNext()){Cell cell = cellIterator.next();//Check the cell type and format accordinglyswitch (cell.getCellType()){case Cell.CELL_TYPE_NUMERIC:System.out.print(cell.getNumericCellValue() + "t");break;case Cell.CELL_TYPE_STRING:System.out.print(cell.getStringCellValue() + "t");break;}}System.out.println("");}}}