Subversion Repositories SmartDukaan

Rev

Rev 34720 | 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 com.fasterxml.jackson.databind.ObjectMapper;
import com.spice.profitmandi.common.enumuration.MessageType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.*;
import com.spice.profitmandi.common.services.ReporticoService;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.common.util.FormattingUtils;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.inventory.ItemPricingHistory;
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
import com.spice.profitmandi.dao.enumuration.catalog.SchemeType;
import com.spice.profitmandi.dao.enumuration.transaction.PriceDropImeiStatus;
import com.spice.profitmandi.dao.model.AmountModel;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.Mongo;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
import com.spice.profitmandi.dao.repository.inventory.ItemPricingHistoryRepository;
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
import com.spice.profitmandi.service.NotificationService;
import com.spice.profitmandi.service.authentication.RoleManager;
import com.spice.profitmandi.service.catalog.BrandsService;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.order.OrderService;
import com.spice.profitmandi.service.pricecircular.PriceCircularItemModelNew;
import com.spice.profitmandi.service.pricecircular.PriceCircularModel;
import com.spice.profitmandi.service.pricecircular.PriceCircularService;
import com.spice.profitmandi.service.pricing.PriceDropService;
import com.spice.profitmandi.service.scheme.SchemeService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.user.RetailerService;
import com.spice.profitmandi.service.wallet.WalletService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
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.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class PriceDropController {

    private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);
    /*private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin", "Modelwise");
    private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support", "Sellout Support");
    private static final List<String> ALL_MARGINS = Arrays.asList(SELLINS, SELLOUTS).stream().flatMap(x -> x.stream()).collect(Collectors.toList());*/
    @Autowired
    ReporticoService reporticoService;
    @Autowired
    LineItemImeisRepository lineItemImeisRepository;
    @Autowired
    PriceCircularService priceCircularService;
    @Autowired
    private CsService csService;
    @Autowired
    private UserRepository dtrUserRepository;
    @Autowired
    private PriceDropRepository priceDropRepository;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private VendorItemPricingRepository vendorItemPricingRepository;
    @Autowired
    @Qualifier("fofoInventoryService")
    private InventoryService inventoryService;
    @Autowired
    private MVCResponseSender mvcResponseSender;
    @Autowired
    private PriceDropService priceDropService;
    @Autowired
    private ItemPricingHistoryRepository itemPricingHistoryRepository;
    @Autowired
    private WalletService walletService;
    @Autowired
    private TagListingRepository tagListingRepository;
    @Autowired
    private TransactionService transactionService;
    @Autowired
    private PriceDropIMEIRepository priceDropIMEIRepository;
    @Autowired
    private RoleManager roleManager;
    @Autowired
    @Qualifier("catalogItemRepository")
    private ItemRepository itemRepository;
    @Autowired
    private SchemeService schemeService;
    @Autowired
    private Mongo mongoClient;
    @Autowired
    private CookiesProcessor cookiesProcessor;
    @Autowired
    private PartnerTypeChangeService partnerTypeChangeService;
    @Autowired
    private RetailerService retailerService;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private FofoStoreRepository fofoStoreRepository;

    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
    public String getItemDescription(HttpServletRequest request, Model model) throws Throwable {
        List<PriceDrop> priceDrops = priceDropRepository.selectAllIncomplete();
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());

        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
        model.addAttribute("priceDrops", priceDrops);
        model.addAttribute("catalogDescription", catalogDescription);
        return "price-drop";
    }

    @RequestMapping(value = "/getPricedropByDate", method = RequestMethod.GET)
    public String getItemDescriptionByDate(
            HttpServletRequest request,
            @RequestParam LocalDateTime startDate,
            @RequestParam LocalDateTime endDate,
            Model model) throws Throwable {
        if (endDate.isAfter(LocalDateTime.now().plusDays(1)) || startDate.isAfter(LocalDateTime.now().plusDays(1))) {
            throw new ProfitMandiBusinessException("startData and end data must if before the today date ", "", "");
        }
        try {
            List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetweenSortByDate(startDate, endDate);

            Set<Integer> catalogIds = priceDrops.stream()
                    .map(PriceDrop::getCatalogItemId)
                    .collect(Collectors.toSet());

            List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
            Map<Integer, String> catalogDescription = items.stream()
                    .collect(Collectors.toMap(
                            Item::getCatalogItemId,
                            Item::getItemDescriptionNoColor,
                            (description1, description2) -> description1));

            model.addAttribute("priceDrops", priceDrops);
            model.addAttribute("catalogDescription", catalogDescription);

            return "price-drop-table";

        } catch (Exception e) {
            e.printStackTrace();
            return "price-drop";
        }
    }
    @RequestMapping(value = "/pricedropByDate/download", method = RequestMethod.GET)
    public ResponseEntity<?> dowloadItems(HttpServletRequest request, @PathVariable(name = "tagId") @RequestParam LocalDateTime startDate, @RequestParam LocalDateTime endDate)
            throws Throwable {
        List<PriceDrop> priceDrops = priceDropRepository.selectAllByDatesBetweenSortByDate(startDate, endDate);
        Set<Integer> catalogIds = priceDrops.stream().map(x -> x.getCatalogItemId()).collect(Collectors.toSet());
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));

        List<List<?>> rows = new ArrayList<>();
        for (PriceDrop priceDrop : priceDrops) {
            rows.add(Arrays.asList(priceDrop.getId(), priceDrop.getCatalogItemId(), catalogDescription.get(priceDrop.getCatalogItemId()), priceDrop.getTp(), priceDrop.getOldDp(), priceDrop.getMop(),
                    priceDrop.getAmount(), priceDrop.getNewDp(), FormattingUtils.formatDate(priceDrop.getAffectedOn()), FormattingUtils.formatDate(priceDrop.getCreatedOn())
            ));

        }
        org.apache.commons.io.output.ByteArrayOutputStream baos = FileUtil.getCSVByteStream(
                Arrays.asList("Drop Id", "Catalog Id", "Item Name", "TP", "DP", "Mop", "Price Drop",
                        "New DP", "Affected On", "Created On"),
                rows);
        ResponseEntity<?> responseEntity = orderService.downloadReportInCsv(baos, rows, "Price Drop ");
        return responseEntity;
    }

    @RequestMapping(value = "/getClosedPricedropItemDescription", method = RequestMethod.GET)
    public String getClosedPricedropItemDescription(HttpServletRequest request, Model model) throws Throwable {
        List<PriceDrop> priceDrops = priceDropRepository.selectAllComplete();
        int processOn = 1;

        List<PriceDrop> completePriceDrops = priceDrops.stream().filter(x -> x.getCompleteTimestamp() != null)
                .collect(Collectors.toList());

        Set<Integer> catalogIds = completePriceDrops.stream().map(x -> x.getCatalogItemId())
                .collect(Collectors.toSet());
        List<Item> items = itemRepository.selectAllByCatalogIds(catalogIds);
        LOGGER.info("catalogIds" + catalogIds);

        Map<Integer, String> catalogDescription = items.stream().collect(Collectors.toMap(x -> x.getCatalogItemId(),
                x -> x.getItemDescriptionNoColor(), (description1, description2) -> description1));
        model.addAttribute("priceDrops", completePriceDrops);
        model.addAttribute("processOn", processOn);
        model.addAttribute("catalogDescription", catalogDescription);
        return "price-drop";
    }

    @RequestMapping(value = "/item-pricing/{itemId}", method = RequestMethod.GET)
    public String getItemPricing(HttpServletRequest request, Model model, @PathVariable int itemId) throws Throwable {

        TagListing tagListing;
        PriceDropModel pm = new PriceDropModel();
        try {
            tagListing = tagListingRepository.selectByItemId(itemId);
            if (tagListing != null) {
                pm.setMop(tagListing.getMop());
                pm.setDp(tagListing.getSellingPrice());
                pm.setMrp(tagListing.getMrp());
                List<VendorItemPricing> vips = vendorItemPricingRepository.selectAll(itemId);
                if (vips.size() > 0) {
                    VendorItemPricing vip = vips.get(0);
                    pm.setNlc(vip.getNlc());
                    pm.setTp(vip.getTp());
                } else {
                    throw new ProfitMandiBusinessException("Item Id", itemId, "Vendor item pricing does not exist");
                }
            }
        } catch (Exception e) {
            LOGGER.info("Chose item that doesn't exist");
        }
        model.addAttribute("response1", mvcResponseSender.createResponseString(pm));
        return "response";
    }

    @RequestMapping(value = "/item", method = RequestMethod.GET)
    public String getItemPricing(HttpServletRequest request, Model model, @RequestParam String query,
                                 @RequestParam boolean anyColor) throws Throwable {
        String query1 = query.toLowerCase();

        List<ItemDescriptionModel> partnersItemDescription = inventoryService
                .getAllPartnerItemStringDescription(anyColor).parallelStream()
                .filter(x -> x.getItemDescription().toLowerCase().matches(".*?" + query1 + ".*?"))
                .collect(Collectors.toList());
        LOGGER.info("partnersItemDescription" + partnersItemDescription);

        model.addAttribute("response1", mvcResponseSender.createResponseString(partnersItemDescription));
        return "response";
    }

    @RequestMapping(value = "/price-drop/imes/download")
    public ResponseEntity<ByteArrayResource> downloadPriceDropImeis(HttpServletRequest request,
                                                                    @RequestParam LocalDateTime affectedDate, @RequestParam int itemId) throws Exception {
        Item item = itemRepository.selectById(itemId);
        ByteArrayOutputStream baos = getByteArrayOutputStream(affectedDate, item.getCatalogItemId(), null, Optional.empty());
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        headers.set("Content-disposition", "inline; filename=\"imei-" + item.getItemDescriptionNoColor() + ".csv\"");
        byte[] byteArray = baos.toByteArray();
        headers.setContentLength(byteArray.length);
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/price-drop/addPayout", method = RequestMethod.POST)
    public String updatePriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
                                  Model model) throws Exception {
        boolean response = false;
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
        if (priceDrop.getProcessTimestamp() == null) {
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
            priceDrop.setPriceDropIn(priceDropProcessModel.getPriceDropIn());
            // priceDrop.setProcessTimestamp(LocalDateTime.now());
            priceDropRepository.persist(priceDrop);
            response = true;
        }
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
        return "response";
    }

    @RequestMapping(value = "/priceDropImeis/{priceDropId}", method = RequestMethod.GET)
    public String priceDropStatus(HttpServletRequest request, @PathVariable int priceDropId, Model model)
            throws Exception {

        PriceDropImeisModel priceDropImeisModel = new PriceDropImeisModel();

        // This call is used to persit imeis to pricedrop imeis in case its not there.
        // This should be called while creating price drop.
        // priceDropService.priceDropStatus(priceDropId);

        List<String> pendingImeis = new ArrayList<>();
        List<String> approvedImeis = new ArrayList<>();
        List<String> rejectedImeis = new ArrayList<>();
        List<String> holdImeis = new ArrayList<>();
        List<PriceDropIMEI> priceDropImeis = priceDropIMEIRepository.selectByPriceDropId(priceDropId);
        for (PriceDropIMEI priceDropIMEI : priceDropImeis) {
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.PENDING)) {
                pendingImeis.add(priceDropIMEI.getImei());
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.APPROVED)) {
                approvedImeis.add(priceDropIMEI.getImei());
            }
            if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.REJECTED)) {
                rejectedImeis.add(priceDropIMEI.getImei());
            } else if (priceDropIMEI.getStatus().equals(PriceDropImeiStatus.HOLD)) {
                holdImeis.add(priceDropIMEI.getImei());

            }
        }
        LOGGER.info("pendingImeis" + pendingImeis);
        LOGGER.info("approvedImeis" + approvedImeis);
        LOGGER.info("rejectedImeis" + rejectedImeis);
        LOGGER.info("priceDropImeis" + priceDropImeis);

        priceDropImeisModel.setPendingImeis(pendingImeis);
        priceDropImeisModel.setPriceDropId(priceDropId);
        priceDropImeisModel.setApprovedImeis(approvedImeis);
        priceDropImeisModel.setHoldImeis(holdImeis);
        priceDropImeisModel.setRejectedImeis(rejectedImeis);
        model.addAttribute("response1", mvcResponseSender.createResponseString(priceDropImeisModel));
        return "response";
    }

    @RequestMapping(value = "/processPriceDrop", method = RequestMethod.POST)
    public String processPriceDrop(HttpServletRequest request, @RequestBody PriceDropProcessModel priceDropProcessModel,
                                   Model model) throws Exception {
        PriceDrop priceDrop = priceDropRepository.selectById(priceDropProcessModel.getPriceDropId());
        boolean response = false;
        if (priceDrop.getPartnerPayout() == 0) {
            priceDrop.setPartnerPayout(priceDropProcessModel.getPartnerPayout());
        }
        priceDrop.setProcessTimestamp(LocalDateTime.now());
        priceDropService.processPriceDrop(priceDrop.getId(), priceDropProcessModel.isActivatedOnly());
        response = true;
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
        return "response";
    }

    @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
    public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel)
            throws Exception {
        boolean response = false;
        priceDropModel.setAllColors(true);
        if (this.validatePriceDrop(priceDropModel)) {
            TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
            float oldDp = tagListing.getSellingPrice();
            float oldMop = tagListing.getMop();
            float oldTp = 0;
            float newDp = priceDropModel.getDp();

            if (newDp != oldDp) {
                List<Item> allItems = null;
                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
                if (priceDropModel.isAllColors()) {
                    allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());

                } else {
                    allItems = Arrays.asList(currentItem);
                }
                for (Item item : allItems) {
                    TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
                    if (itemTagListing == null)
                        continue;
                    itemTagListing.setSellingPrice(newDp);
                    itemTagListing.setMop(priceDropModel.getMop());
                    List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
                    for (VendorItemPricing vip : vipList) {
                        oldTp = vip.getNlc();
                        vip.setDp(newDp);
                        vip.setMop(priceDropModel.getMop());
                        //Lets not update NLC/TP as it has to be managed by Category Tea,
                        //vip.setNlc(priceDropModel.getTp());
                        //vip.setTp(priceDropModel.getTp());
                        vendorItemPricingRepository.persist(vip);
                    }
                    transactionService.updatePriceDrop(item.getId(), newDp);
                }

                // Add to itemPricing history
                ItemPricingHistory iph = new ItemPricingHistory();
                iph.setCatalogId(currentItem.getCatalogItemId());
                iph.setTp(priceDropModel.getTp());
                iph.setDp(priceDropModel.getDp());
                iph.setMop(priceDropModel.getMop());
                // TODO: changedBy
                iph.setChangedBy("me");
                iph.setCreateTimestamp(LocalDateTime.now());
                itemPricingHistoryRepository.persist(iph);

                PriceDrop priceDrop = new PriceDrop();
                priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
                priceDrop.setTp(oldTp);
                priceDrop.setNlc(oldTp);
                priceDrop.setMop(oldMop);
                priceDrop.setOldDp(oldDp);
                priceDrop.setAmount(oldDp - newDp);
                priceDrop.setNewDp(newDp);
                priceDrop.setCreatedOn(LocalDateTime.now());
                priceDrop.setCatalogItemId(currentItem.getCatalogItemId());
                priceDropRepository.persist(priceDrop);
                priceDropService.priceDropStatus(priceDrop.getId());
                response = true;

                this.sendPriceChangeNotification(priceDrop);
            } else {
                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(),
                        "Price Drop Should be greater than 0");
            }
        }
        model.addAttribute("response1", mvcResponseSender.createResponseString(response));
        return "response";
    }

    private void sendPriceChangeNotification(PriceDrop priceDrop) throws ProfitMandiBusinessException {
        List<Item> items = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId());
        String title = "Price has been %s for %s";


        SendNotificationModel sendNotificationModel = new SendNotificationModel();
        sendNotificationModel.setCampaignName("pricechange");
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
        sendNotificationModel.setTitle("");
        StringBuffer sb = new StringBuffer();
        String message = null;
        if (priceDrop.getDropAmount() > 0) {
            title = String.format(title, "dropped", items.get(0).getItemDescriptionNoColor());
            message = String.format("Price has been dropped from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(priceDrop.getDropAmount()),
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
        } else {
            title = String.format(title, "increased", items.get(0).getItemDescriptionNoColor());
            message = String.format("Price has been increased from Rs.%s. Old DP - Rs.%s, New DP - Rs.%s", FormattingUtils.formatDecimal(-priceDrop.getDropAmount()),
                    FormattingUtils.formatDecimal(priceDrop.getOldDp()), FormattingUtils.formatDecimal(priceDrop.getNewDp()));
        }
        sendNotificationModel.setTitle(title);
        sendNotificationModel.setMessage(message);
        sendNotificationModel.setMessageType(MessageType.pricechange);
        notificationService.sendNotificationToAll(sendNotificationModel);
    }

    @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
    public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
                                                        Model model) throws ProfitMandiBusinessException, Exception {

        PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
        Map<String, PriceDropIMEI> priceDropIMEIsMap = priceDropIMEIRepository.selectByPriceDropId(priceDropId).stream()
                .collect(Collectors.toMap(x -> x.getImei(), x -> x));
        LOGGER.info("PriceDropImeis {}, priceDropId {}", priceDropIMEIsMap, priceDropId);
        Item item = itemRepository.selectAllByCatalogItemId(priceDrop.getCatalogItemId()).get(0);
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        headers.set("Content-disposition",
                "inline; filename=pricedrop-" + item.getItemDescriptionNoColor().replaceAll("\\s?,\\s?", " ") + "-"
                        + FormattingUtils.formatDate(priceDrop.getAffectedOn()) + ".csv");
        ByteArrayOutputStream baos = null;
        if (priceDropIMEIsMap.size() == 0) {
            priceDropService.priceDropStatus(priceDrop.getId());
            baos = FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
                    "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
                    "Grn On", "Activation Timestamp", "Activation Added On"), new ArrayList<>());
        } else {

            LOGGER.info("In else block");
            baos = getByteArrayOutputStream(priceDrop.getAffectedOn(), priceDrop.getCatalogItemId(), priceDropIMEIsMap, Optional.of(priceDrop.getCreatedOn()));
        }
        byte[] byteArray = baos.toByteArray();
        headers.setContentLength(byteArray.length);
        return new ResponseEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);

    }

    @RequestMapping(value = "/updatePriceDropImeis", method = RequestMethod.POST)
    public String updatePriceDropImeis(@RequestBody PriceDropImeisModel priceDropImeisModel,
                                       Model model) throws Exception {
        final PriceDropImeiStatus status;

        switch (priceDropImeisModel.getUpdatedStatus()) {
            case "approved": {
                status = PriceDropImeiStatus.APPROVED;
                break;
            }
            case "pending": {
                status = PriceDropImeiStatus.PENDING;
                break;
            }
            case "rejected": {
                status = PriceDropImeiStatus.REJECTED;
                break;
            }
            case "hold": {
                status = PriceDropImeiStatus.HOLD;
                break;
            }
            default:
                throw new IllegalStateException("Unexpected value: " + priceDropImeisModel.getUpdatedStatus());
        }

        if (PriceDropImeiStatus.PENDING.equals(status)) {
            List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByStatuses(Arrays.asList(PriceDropImeiStatus.REJECTED, PriceDropImeiStatus.HOLD),
                    priceDropImeisModel.getPriceDropId());
            LOGGER.info("hello" + priceDropIMEIs);
            for (PriceDropIMEI priceDropIMEI : priceDropIMEIs) {
                if (priceDropIMEI.getStatus().equals(status) || !priceDropImeisModel.getUpdatedImeis().contains(priceDropIMEI.getImei())) {
                    continue;
                }
                priceDropIMEI.setStatus(PriceDropImeiStatus.PENDING);
            }
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
            return "response";
        }

        if (status.equals(PriceDropImeiStatus.APPROVED)) {
            priceDropService.processPriceDrop(priceDropImeisModel.getPriceDropId(),
                    priceDropImeisModel.getUpdatedImeis());
        }

        List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository
                .selectByPriceDropId(priceDropImeisModel.getPriceDropId());
        List<PriceDropIMEI> priceDropIMEIsToProcess = priceDropIMEIs.stream()
                .filter(x -> priceDropImeisModel.getUpdatedImeis().contains(x.getImei()))
                .filter(x -> !x.getStatus().equals(status)).collect(Collectors.toList());
        for (PriceDropIMEI priceDropImei : priceDropIMEIsToProcess) {
            if (status.equals(PriceDropImeiStatus.REJECTED)
                    && priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
                priceDropImei.setStatus(PriceDropImeiStatus.REJECTED);
                priceDropImei.setRejectionReason(priceDropImeisModel.getRejectionReason());
                priceDropImei.setRejectTimestamp(LocalDateTime.now());
            } else if (status.equals(PriceDropImeiStatus.HOLD)) {
                if (priceDropImei.getStatus().equals(PriceDropImeiStatus.PENDING)) {
                    priceDropImei.setStatus(PriceDropImeiStatus.HOLD);
                } else {
                    throw new ProfitMandiBusinessException("INVALID STATUS", status, "only  allowed For PENDING IMEIs");
                }

            }

        }

        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        return "response";

    }

    private ByteArrayOutputStream getByteArrayOutputStream(LocalDateTime affectedOn, Integer catalogItemId,
                                                           Map<String, PriceDropIMEI> priceDropImeis, Optional<LocalDateTime> createdOn) throws Exception {

        List<ImeiDropSummaryModel> imeiDropSummaryModelList = priceDropService
                .getAllSerialNumbersByAffectedDate(affectedOn, catalogItemId, createdOn);
        List<List<?>> rows = new ArrayList<>();
        for (ImeiDropSummaryModel imeiDropSummaryModel : imeiDropSummaryModelList) {
            if (priceDropImeis == null) {
                rows.add(this.getRow(imeiDropSummaryModel, null));
            } else if (priceDropImeis.get(imeiDropSummaryModel.getSerialNumber()) != null) {
                rows.add(this.getRow(imeiDropSummaryModel, priceDropImeis.get(imeiDropSummaryModel.getSerialNumber())));
            }
        }
        return FileUtil.getCSVByteStream(Arrays.asList("IMEI Number", "Store Name", "Store Code", "Item ID", "Brand",
                "Model Name", "Model Number", "Color", "Status", "Rejection Reason", "Last Scanned", "Vendor Name",
                "Grn On", "Activation Timestamp", "Activation Added On"), rows);
    }

    private List<? extends Serializable> getRow(ImeiDropSummaryModel imeiDropSummaryModel,
                                                PriceDropIMEI priceDropIMEI) {
        List<Serializable> row = new ArrayList<>();
        row.add(imeiDropSummaryModel.getSerialNumber());
        row.add(imeiDropSummaryModel.getStoreName());
        row.add(imeiDropSummaryModel.getPartnerCode());
        row.add(imeiDropSummaryModel.getItemId());
        row.add(imeiDropSummaryModel.getBrand());
        row.add(imeiDropSummaryModel.getModelName());
        row.add(imeiDropSummaryModel.getModelNumber());
        row.add(imeiDropSummaryModel.getColor());
        if (priceDropIMEI != null) {
            row.add(priceDropIMEI.getStatus());
            row.add(priceDropIMEI.getRejectionReason());
        } else {
            row.add(PriceDropImeiStatus.PENDING);
            row.add("");
        }
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getLastScanned()));
        row.add(imeiDropSummaryModel.getVendorName());
        row.add(FormattingUtils.formatReporitcoDate(imeiDropSummaryModel.getGrnOn()));
        row.add(imeiDropSummaryModel.getActivationTimestamp());
        row.add(imeiDropSummaryModel.getActivationAddedOn());
        return row;
    }

    private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
        if (priceDropModel.getMop() > 0 && priceDropModel.getDp() > 0 && priceDropModel.getTp() > 0) {
            return true;
        }
        return false;
    }

    @Autowired
    BrandsService brandsService;

    @RequestMapping(value = "/priceCircular")
    public String priceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
        int fofoId = Utils.SYSTEM_PARTNER_ID;
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
        model.addAttribute("brands", brands);
        model.addAttribute("isAdmin", true);
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));

        return "partner-price-circular";
    }

    @RequestMapping(value = "/partnerPriceCircular")
    public String partnerPriceCircular(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
        int fofoId = Utils.SYSTEM_PARTNER_ID;
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
        brands.addAll(brandsService.getBrandsToDisplay(6).stream().map(x -> (String) x.getName())
                .collect(Collectors.toSet()));
        model.addAttribute("brands", brands);
        model.addAttribute("isAdmin", false);

        return "partner-price-circular";
    }

    @RequestMapping(value = "/priceCircularByBrand")
    public String priceCircularByBrand(HttpServletRequest request, @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId)
            throws ProfitMandiBusinessException {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
        } else {
            fofoId = loginDetails.getFofoId();
        }
        FofoStore fs = fofoStoreRepository.selectByRetailerId(fofoId);

        //.minusDays(2)
        PriceCircularModel priceCircularModel = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
        //Get slowmong/missign category for that brand
        //get stock with us missing as well as with partner missing
        //filter that stock
        return this.getPriceCircularView(priceCircularModel, model, fs.getCode());
    }

    public String getPriceCircularView(PriceCircularModel priceCircularModel, Model model, String partnerCode) {
        List<String> allMarginsSet = new ArrayList<>(this.getSchemeHeaders(priceCircularModel));
        List<String> sellins = SchemeType.IN_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
        List<String> sellouts = SchemeType.OUT_TYPES.stream().map(x -> x.getValue()).filter(x -> allMarginsSet.contains(x)).collect(Collectors.toList());
        List<String> allMargins = new ArrayList<>();
        allMargins.addAll(sellins);
        allMargins.addAll(sellouts);
        LOGGER.info("Sellins - {}", sellins);
        LOGGER.info("Sellouts - {}", sellouts);
        model.addAttribute("priceCircularItemModels", priceCircularModel.getPriceCircularItemModelNews());
        model.addAttribute("allMargins", allMargins);
        model.addAttribute("sellins", sellins);
        model.addAttribute("sellouts", sellouts);
        model.addAttribute("offers", priceCircularModel.getOffers());
        model.addAttribute("upgradeOffer", priceCircularModel.isUpgradeOffer());
        model.addAttribute("mvcResponseSender", mvcResponseSender);
        model.addAttribute("partnerCode", partnerCode);
        return "price-circular-table";
    }

    private Set<String> getSchemeHeaders(PriceCircularModel priceCircular) {
        Set<String> schemeHeaders = new HashSet<>();
        priceCircular.getPriceCircularItemModelNews().stream().forEach(priceCircularItemModelNew -> {
            Map<String, AmountModel> headerMap = new HashMap<>();
            priceCircularItemModelNew.setHeaderSchemeModelsMap(headerMap);
            priceCircularItemModelNew.getSchemeSummaryModels().stream().forEach(schemeSummaryModel -> {
                if (schemeSummaryModel == null) return;
                schemeSummaryModel.setHeader(schemeSummaryModel.getSchemeType().getValue());
                if (!headerMap.containsKey(schemeSummaryModel.getHeader())) {
                    headerMap.put(schemeSummaryModel.getHeader(), new AmountModel(schemeSummaryModel.getAmount(), schemeSummaryModel.getAmountType()));
                } else {
                    AmountModel model = headerMap.get(schemeSummaryModel.getHeader());
                    model.setAmount(model.getAmount() + schemeSummaryModel.getAmount());
                }
                schemeHeaders.add(schemeSummaryModel.getHeader());
            });
        });

        LOGGER.info("Scheme headers - {}", schemeHeaders);
        return schemeHeaders;
    }

    //private static final List<String> SELLINS = Arrays.asList("Base Payout", "Cash Discount", "Upfront Margin");
    //private static final List<String> SELLOUTS = Arrays.asList("Tertiary Payout", "Hygiene Payout", "Investment Payout", "Category Payout", "Activation Margin", "Special Support");


    @RequestMapping(value = "/downloadNlcByBrand")
    public ResponseEntity<ByteArrayResource> downloadNlcByBrand(HttpServletRequest request,
                                                                @RequestParam String brand, Model model, @RequestParam(defaultValue = "0", required = false) int fofoId) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        if (fofoId > 0 && roleManager.isAdmin(loginDetails.getRoleIds())) {
        } else {
            fofoId = loginDetails.getFofoId();
        }
        PriceCircularModel priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, brand, LocalDate.now());
        /*List<Integer> catalogIds = priceCircular.getPriceCircularItemModelNews().stream().limit(10).map(x->x.getCatalogId()).collect(Collectors.toList());
        priceCircular = priceCircularService.getPriceCircularByOffer(fofoId, catalogIds, LocalDate.now());*/
        ByteArrayOutputStream baos = getNlcBaos(brand, priceCircular);
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        headers.set("Content-disposition", "inline; filename=\"" + brand + ".csv\"");
        byte[] byteArray = baos.toByteArray();
        headers.setContentLength(byteArray.length);
        return new ResponseEntity<>(new ByteArrayResource(byteArray), headers, HttpStatus.OK);
    }

    private ByteArrayOutputStream getNlcBaos(String brand, PriceCircularModel priceCircular) throws Exception {
        List<List<?>> rows = new ArrayList<>();
        for (PriceCircularItemModelNew priceCircularItemModel : priceCircular.getPriceCircularItemModelNews()) {
            List<Serializable> row = new ArrayList<>();
            row.add(priceCircularItemModel.getCatalogId());
            row.add(brand);
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelName());
            row.add(priceCircularItemModel.getCatalogSummaryModel().getModelNumber());
            //TODO: fix nlc
            //row.add(priceCircularItemModel.getNetPrice());
            rows.add(row);
        }
        return FileUtil.getCSVByteStream(Arrays.asList("Model Id", "Brand", "Model Name", "Model Number", "Partner Landing"), rows);
    }

    @RequestMapping(value = "/selectPriceDropStatus", method = RequestMethod.GET)
    public String selectPriceDropStatus(HttpServletRequest request,
                                        @RequestParam(name = "selectedStatus", required = true, defaultValue = "") String selectedStatus,
                                        Model model) throws Exception {

        model.addAttribute("selectedStatus", selectedStatus);
        return "pricedrop-status-change";
    }

}