Subversion Repositories SmartDukaan

Rev

Rev 37288 | 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.common.model.ProfitMandiConstants;
import com.spice.profitmandi.dao.entity.catalog.ModelHotDeal;
import com.spice.profitmandi.dao.entity.catalog.Catalog;
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.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 {
        return "hot-deals";
    }

    /** All hot deal models: 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.listAll(q, page, pageSize));
        model.addAttribute("total", total);
        model.addAttribute("page", page);
        model.addAttribute("pages", pages);
        return "hot-deals-table";
    }

    /**
     * Every Hot Deal-brand model. One brand now, and no expiry, so there is nothing to
     * filter out. No category filter either: the brand spans mobile, refurbished, earbuds
     * and LED TV, so the old mobile-only restriction would have hidden most of it.
     */
    @RequestMapping(value = "/hotDeals/models", method = RequestMethod.GET)
    public String getHotDealModels(Model model) throws Exception {
        List<Catalog> catalogs = catalogRepository.selectAllByCatalogIds(new java.util.ArrayList<>(
                catalogRepository.selectCatalogIdsByBrand(ProfitMandiConstants.HOT_DEAL_BRAND)));
        List<Map<String, Object>> models = catalogs.stream()
                .map(catalog -> {
                    Map<String, Object> entry = new HashMap<>();
                    entry.put("catalogId", catalog.getId());
                    entry.put("description", catalog.getDescription());
                    // Drives the OEM mapping autosuggest, which is scoped to this brand.
                    ModelHotDeal attributes = modelHotDealService.getAttributes(catalog.getId());
                    entry.put("oemBrand", attributes == null ? "" : attributes.getOemBrand());
                    return entry;
                })
                .collect(Collectors.toList());
        model.addAttribute("response1", objectMapper.writeValueAsString(models));
        return "response";
    }

    /**
     * Create or update the five pill attributes for one Hot Deal model. Replaces the old
     * add/update pair: there is no date window to set and no cap to respect, so the only
     * thing left to edit is the attributes, and whether a row already exists is an
     * implementation detail the caller should not have to know.
     */
    @RequestMapping(value = "/hotDeals/saveAttributes", method = RequestMethod.POST)
    public String saveAttributes(HttpServletRequest request, @RequestParam int catalogItemId,
                                 @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,
                                 @RequestParam(required = false) Integer oemCatalogId,
                                 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.saveAttributes(catalogItemId, attributes, oemCatalogId, loginDetails.getEmailId());
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
        } catch (ProfitMandiBusinessException e) {
            LOGGER.warn("Hot deal attributes rejected: {}", e.getMessage());
            model.addAttribute("response1", e.getMessage());
        }
        return "response";
    }

    /**
     * Catalogs under one OEM brand, for the optional channel-counterpart autosuggest.
     * Scoped to the brand the hot-deal model came from, so ops cannot map a Samsung deal
     * onto a Vivo model; the service re-checks this on save.
     */
    @RequestMapping(value = "/hotDeals/oemModels", method = RequestMethod.GET)
    public String getOemModels(@RequestParam String brand, Model model) throws Exception {
        List<Map<String, Object>> models = new java.util.ArrayList<>();
        if (brand != null && !brand.trim().isEmpty()
                && !ProfitMandiConstants.HOT_DEAL_BRAND.equalsIgnoreCase(brand.trim())) {
            for (Catalog catalog : catalogRepository.selectAllByCatalogIds(new java.util.ArrayList<>(
                    catalogRepository.selectCatalogIdsByBrand(brand.trim())))) {
                Map<String, Object> entry = new HashMap<>();
                entry.put("catalogId", catalog.getId());
                entry.put("description", catalog.getDescription());
                models.add(entry);
            }
        }
        model.addAttribute("response1", objectMapper.writeValueAsString(models));
        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.removeAttributes(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";
    }
}