Subversion Repositories SmartDukaan

Rev

Rev 27876 | Rev 29677 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.gson.Gson;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.CustomRetailer;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.catalog.Offer;
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
import com.spice.profitmandi.dao.enumuration.catalog.ItemCriteriaType;
import com.spice.profitmandi.dao.model.CreateOfferRequest;
import com.spice.profitmandi.dao.model.OfferRowModel;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
import com.spice.profitmandi.service.offers.OfferService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;

@Controller
@Transactional(rollbackOn = Throwable.class)
public class OfferController {
        private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
        @Autowired
        private OfferRepository offerRepository;

        @Autowired
        private OfferMarginRepository offerMarginRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private ResponseSender responseSender;

        @Autowired
        private OfferPartnerRepository offerPartnerRepository;

        @Autowired
        private ItemRepository itemRepository;

        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private Gson gson;

        @Autowired
        private RetailerService retailerService;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private CookiesProcessor cookiesProcessor;

        @Autowired
        private OfferService offerService;

        @Autowired
        private PartnerTypeChangeService partnerTypeChangeService;

        @RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
        public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
                List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
                                .collect(Collectors.toList());

                Set<String> brands = mongoClient.getMongoBrands(loginDetails.getFofoId(), null, 3).stream()
                                .map(x -> (String) x.get("name")).collect(Collectors.toSet());

                Map<Integer, CustomRetailer> customRetailersMap = retailerService.getFofoRetailers(fofoIds);

                model.addAttribute("customRetailersMap", customRetailersMap);
                model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
                model.addAttribute("brands", brands);
                model.addAttribute("partnerCategories", PartnerType.values());
                model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
                return "scheme_offer";

        }

        @RequestMapping(value = "/createOffer", method = RequestMethod.POST)
        public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
                        Model model) throws Exception {
                LOGGER.info("createOfferRequest [{}]", createOfferRequest);
                offerService.addOfferService(createOfferRequest);
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";

        }

        @RequestMapping(value = "/offers/published", method = RequestMethod.GET)
        public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
                        throws Exception {
                LOGGER.info("Published");
                offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
                return "scheme_offer/published";

        }

        @RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
        public String activateOffer(HttpServletRequest request, @PathVariable int offerId, Model model)
                        throws ProfitMandiBusinessException, Exception {
                Offer offer = offerRepository.selectById(offerId);
                offer.setActive(true);
                model.addAttribute("response", mvcResponseSender.createResponseString(true));
                return "response";
        }

        @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
        public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
                        throws ProfitMandiBusinessException {

                List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth);
                model.addAttribute("offers", publishedOffers);
                model.addAttribute("yearMonth", yearMonth);

                return "offer_history";
        }

        @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
        public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
                        throws ProfitMandiBusinessException {
                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                CreateOfferRequest createOfferRequest = offerService.getOffer(offerId);
                int fofoId = loginDetails.getFofoId();
                double 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);
                createOfferRequest.setCurrentTargetSlab(currentSlab);
                createOfferRequest.setEligibleSale((int) amount);

                model.addAttribute("offer", createOfferRequest);
                return "offer-details";
        }

        @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
        public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
                        throws Exception {
                List<List<?>> listOfRows = new ArrayList<>();
                final HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
                CreateOfferRequest createOfferRequest = offerService.getOffer(offerId);
                Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);

                for (OfferRowModel offerRowModel : offerRowModels) {
                        CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
                        listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
                                        createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
                                        createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
                                        createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
                                        createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
                                        createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
                                        customRetailer.getCode(), offerRowModel.getTotalSale(), offerRowModel.getEligibleSale(),
                                        offerRowModel.getAchievedTarget(), offerRowModel.getNextTarget(), offerRowModel.getEligibleSaleDp(),
                                        offerRowModel.getTotalPurchaseValue(), offerRowModel.getCurrentPayoutTarget(),
                                        offerRowModel.getPayoutTargetAchieved(), offerRowModel.getAmountType(),
                                        offerRowModel.getPayoutValue(), offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
                                        String.join(", ", offerRowModel.getPendingImeis())));
                }
                ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
                                Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
                                                "Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
                                                "Total Sale", "Eligible Sale", "Achieved Target", "Next Target", "Eligible Sale DP",
                                                "Total Purchase DP", "Current Payout Target", "Payout Target Achieved", "Payout Amount Type",
                                                "Payout Value", "Payout Value DP", "Amount to be credited", "IMEIs pending for Activation"
                                // "Payout Sale Qty", "Activated Value", "Activated Qty",
                                ), listOfRows);
                final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
                final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
        }
        
        @RequestMapping(value = "/offerById", method = RequestMethod.GET)
        public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
                Offer offer = offerRepository.selectById(offerId);

                model.addAttribute("offer", offer);

                return "offer-edit";

        }

        @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
        public String getOfferMargins(HttpServletRequest request,
                        @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
                Offer offer = offerRepository.selectById(offerId);

                LOGGER.info("offerId" + offer.getId());

                LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);

                CreateOfferRequest createOfferRequest = offerService.getOffer(offerId);
                int fofoId = loginDetails.getFofoId();
                double 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);
                createOfferRequest.setCurrentTargetSlab(currentSlab);
                createOfferRequest.setEligibleSale((int) amount);
                model.addAttribute("offer", createOfferRequest);

                return "offer_margin_detail_partner";

        }

}