Subversion Repositories SmartDukaan

Rev

Rev 37270 | 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.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.dao.entity.catalog.Catalog;
import com.spice.profitmandi.dao.entity.catalog.ModelHotDeal;
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
import com.spice.profitmandi.dao.service.solr.FofoSolr;
import com.spice.profitmandi.service.catalog.BrandsService;
import com.spice.profitmandi.service.catalog.HotDealAttributes;
import com.spice.profitmandi.service.catalog.ModelHotDealService;
import com.spice.profitmandi.web.model.LoginDetails;
import com.spice.profitmandi.web.util.CookiesProcessor;
import com.spice.profitmandi.web.util.MVCResponseSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(HotDealController.class);
    private static final int MOBILE_BRAND_CATEGORY_ID = 3;

    @Autowired
    private ModelHotDealService modelHotDealService;

    @Autowired
    private BrandsService brandsService;

    @Autowired
    private CatalogRepository catalogRepository;

    @Autowired
    private CookiesProcessor cookiesProcessor;

    @Autowired
    private MVCResponseSender mvcResponseSender;

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(value = "/manageHotDeals", method = RequestMethod.GET)
    public String manageHotDeals(HttpServletRequest request, Model model) throws Exception {
        model.addAttribute("brands", brandsService.getAllActiveBrands());
        model.addAttribute("maxDeals", ModelHotDealService.MAX_ACTIVE_DEALS_PER_BRAND);
        return "hot-deals";
    }

    /** All deals across brands: server-side searched + paginated table fragment. */
    @RequestMapping(value = "/hotDeals/all", method = RequestMethod.GET)
    public String getAllHotDeals(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(required = false, defaultValue = "") String q,
                                 Model model) throws Exception {
        int pageSize = 20;
        long total = modelHotDealService.countDeals(q);
        int pages = (int) Math.max(1, (total + pageSize - 1) / pageSize);
        page = Math.min(Math.max(1, page), pages);
        model.addAttribute("deals", modelHotDealService.searchDeals(q, page, pageSize));
        model.addAttribute("total", total);
        model.addAttribute("page", page);
        model.addAttribute("pages", pages);
        return "hot-deals-table";
    }

    /** Active-slot usage for a brand, e.g. "3 / 15". */
    @RequestMapping(value = "/hotDeals/slots", method = RequestMethod.GET)
    public String getSlots(@RequestParam int brandId, Model model) throws Exception {
        model.addAttribute("response1", modelHotDealService.countActive(brandId)
                + " / " + ModelHotDealService.MAX_ACTIVE_DEALS_PER_BRAND);
        return "response";
    }

    @RequestMapping(value = "/hotDeals/models", method = RequestMethod.GET)
    public String getModelsForBrand(@RequestParam int brandId, Model model) throws Exception {
        List<Catalog> catalogs = catalogRepository.selectAllByBrandId(brandId);
        Set<Integer> activeIds = modelHotDealService.getDealsForBrand(brandId).stream()
                .filter(deal -> !"EXPIRED".equals(deal.getStatus()))
                .map(ModelHotDeal::getCatalogItemId)
                .collect(Collectors.toSet());
        List<Map<String, Object>> models = catalogs.stream()
                .filter(catalog -> !activeIds.contains(catalog.getId()))
                .map(catalog -> {
                    Map<String, Object> entry = new HashMap<>();
                    entry.put("catalogId", catalog.getId());
                    entry.put("description", catalog.getDescription());
                    return entry;
                })
                .collect(Collectors.toList());
        model.addAttribute("response1", objectMapper.writeValueAsString(models));
        return "response";
    }

    @RequestMapping(value = "/hotDeals/add", method = RequestMethod.POST)
    public String addHotDeal(HttpServletRequest request, @RequestParam int brandId,
                             @RequestParam int catalogItemId, @RequestParam String startDate,
                             @RequestParam String endDate,
                             @RequestParam(required = false) Integer warrantyMonths,
                             @RequestParam(required = false) String condition,
                             @RequestParam(required = false) Boolean fresh,
                             @RequestParam(required = false) Boolean financeMapping,
                             @RequestParam(required = false) Boolean affordability,
                             Model model) throws Exception {
        // required=false so a missing field reaches the service's mandatory-field
        // validation and comes back as a readable message instead of a Spring 400
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        try {
            HotDealAttributes attributes = new HotDealAttributes(warrantyMonths, condition,
                    fresh, financeMapping, affordability);
            modelHotDealService.addDeal(brandId, catalogItemId, LocalDate.parse(startDate),
                    LocalDate.parse(endDate), attributes, loginDetails.getEmailId());
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } catch (ProfitMandiBusinessException e) {
            LOGGER.warn("Hot deal add rejected: {}", e.getMessage());
            model.addAttribute("response1", e.getMessage());
        }
        return "response";
    }

    @RequestMapping(value = "/hotDeals/update", method = RequestMethod.POST)
    public String updateHotDeal(HttpServletRequest request, @RequestParam int id,
                                @RequestParam String startDate, @RequestParam String endDate,
                                @RequestParam(required = false) Integer warrantyMonths,
                                @RequestParam(required = false) String condition,
                                @RequestParam(required = false) Boolean fresh,
                                @RequestParam(required = false) Boolean financeMapping,
                                @RequestParam(required = false) Boolean affordability,
                                Model model) throws Exception {
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
        try {
            HotDealAttributes attributes = new HotDealAttributes(warrantyMonths, condition,
                    fresh, financeMapping, affordability);
            modelHotDealService.updateDeal(id, LocalDate.parse(startDate), LocalDate.parse(endDate),
                    attributes, loginDetails.getEmailId());
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } catch (ProfitMandiBusinessException e) {
            LOGGER.warn("Hot deal update rejected: {}", e.getMessage());
            model.addAttribute("response1", e.getMessage());
        }
        return "response";
    }

    @Autowired
    private FofoSolr fofoSolr;

    /**
     * Manual, explicit Solr push for the selected deal models (Category team button).
     * Calls the indexer directly - deliberately NOT the prod-gated change event - so
     * curated models are searchable immediately without waiting for the daily sync.
     */
    @RequestMapping(value = "/hotDeals/pushSolr", method = RequestMethod.POST)
    public String pushDealsToSolr(@RequestParam String catalogIds, Model model) throws Exception {
        List<String> ok = new java.util.ArrayList<>();
        List<String> failed = new java.util.ArrayList<>();
        for (String raw : catalogIds.split(",")) {
            String id = raw.trim();
            if (id.isEmpty()) {
                continue;
            }
            try {
                fofoSolr.updateSingleCatalog(Integer.parseInt(id));
                ok.add(id);
            } catch (Exception e) {
                LOGGER.error("Manual Solr push failed for catalogId={}", id, e);
                failed.add(id + " (" + e.getMessage() + ")");
            }
        }
        String summary = "Pushed " + ok.size() + " model(s) to Solr"
                + (failed.isEmpty() ? "" : "; FAILED: " + String.join(", ", failed));
        model.addAttribute("response1", summary);
        return "response";
    }

    @RequestMapping(value = "/hotDeals/remove", method = RequestMethod.POST)
    public String removeHotDeal(@RequestParam int id, Model model) throws Exception {
        try {
            modelHotDealService.removeDeal(id);
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } catch (ProfitMandiBusinessException e) {
            LOGGER.warn("Hot deal remove rejected: {}", e.getMessage());
            model.addAttribute("response1", e.getMessage());
        }
        return "response";
    }
}