Subversion Repositories SmartDukaan

Rev

Rev 37643 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
37212 amit 1
package com.spice.profitmandi.web.controller;
2
 
3
import com.fasterxml.jackson.databind.ObjectMapper;
4
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
37643 amit 5
import com.spice.profitmandi.common.model.ProfitMandiConstants;
6
import com.spice.profitmandi.dao.entity.catalog.ModelHotDeal;
37212 amit 7
import com.spice.profitmandi.dao.entity.catalog.Catalog;
8
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
37288 ranu 9
import com.spice.profitmandi.dao.service.solr.FofoSolr;
37212 amit 10
import com.spice.profitmandi.service.catalog.BrandsService;
37246 amit 11
import com.spice.profitmandi.service.catalog.HotDealAttributes;
37212 amit 12
import com.spice.profitmandi.service.catalog.ModelHotDealService;
13
import com.spice.profitmandi.web.model.LoginDetails;
14
import com.spice.profitmandi.web.util.CookiesProcessor;
15
import com.spice.profitmandi.web.util.MVCResponseSender;
16
import org.slf4j.Logger;
17
import org.slf4j.LoggerFactory;
18
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.stereotype.Controller;
37229 amit 20
import org.springframework.transaction.annotation.Transactional;
37212 amit 21
import org.springframework.ui.Model;
22
import org.springframework.web.bind.annotation.RequestMapping;
23
import org.springframework.web.bind.annotation.RequestMethod;
24
import org.springframework.web.bind.annotation.RequestParam;
25
 
26
import javax.servlet.http.HttpServletRequest;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Set;
31
import java.util.stream.Collectors;
32
 
33
@Controller
37229 amit 34
@Transactional(rollbackFor = Throwable.class)
37212 amit 35
public class HotDealController {
36
 
37
    private static final Logger LOGGER = LoggerFactory.getLogger(HotDealController.class);
38
    private static final int MOBILE_BRAND_CATEGORY_ID = 3;
39
 
40
    @Autowired
41
    private ModelHotDealService modelHotDealService;
42
 
43
    @Autowired
44
    private BrandsService brandsService;
45
 
46
    @Autowired
47
    private CatalogRepository catalogRepository;
48
 
49
    @Autowired
50
    private CookiesProcessor cookiesProcessor;
51
 
52
    @Autowired
53
    private MVCResponseSender mvcResponseSender;
54
 
55
    @Autowired
56
    private ObjectMapper objectMapper;
57
 
58
    @RequestMapping(value = "/manageHotDeals", method = RequestMethod.GET)
59
    public String manageHotDeals(HttpServletRequest request, Model model) throws Exception {
38016 amit 60
        model.addAttribute("oemBrands", modelHotDealService.oemBrandNames());
37212 amit 61
        return "hot-deals";
62
    }
63
 
38016 amit 64
    /**
65
     * Every Hot Deal-brand model, with or without an attributes row: server-side searched +
66
     * paginated table fragment. {@code attention} narrows to models missing attributes or an
67
     * OEM brand - the ones that silently drop out of the partner app's brand chips.
68
     */
37256 amit 69
    @RequestMapping(value = "/hotDeals/all", method = RequestMethod.GET)
70
    public String getAllHotDeals(@RequestParam(defaultValue = "1") int page,
71
                                 @RequestParam(required = false, defaultValue = "") String q,
38016 amit 72
                                 @RequestParam(required = false, defaultValue = "false") boolean attention,
37256 amit 73
                                 Model model) throws Exception {
74
        int pageSize = 20;
38016 amit 75
        long total = modelHotDealService.countDeals(q, attention);
37256 amit 76
        int pages = (int) Math.max(1, (total + pageSize - 1) / pageSize);
77
        page = Math.min(Math.max(1, page), pages);
38016 amit 78
        long[] stats = modelHotDealService.stats();
79
        model.addAttribute("deals", modelHotDealService.listAll(q, attention, page, pageSize));
80
        model.addAttribute("oemBrands", modelHotDealService.oemBrandNames());
81
        model.addAttribute("statTotal", stats[0]);
82
        model.addAttribute("statNoAttributes", stats[1]);
83
        model.addAttribute("statNoOemBrand", stats[2]);
84
        model.addAttribute("attention", attention);
37256 amit 85
        model.addAttribute("total", total);
86
        model.addAttribute("page", page);
87
        model.addAttribute("pages", pages);
37212 amit 88
        return "hot-deals-table";
89
    }
90
 
37643 amit 91
    /**
92
     * Every Hot Deal-brand model. One brand now, and no expiry, so there is nothing to
93
     * filter out. No category filter either: the brand spans mobile, refurbished, earbuds
94
     * and LED TV, so the old mobile-only restriction would have hidden most of it.
95
     */
37212 amit 96
    @RequestMapping(value = "/hotDeals/models", method = RequestMethod.GET)
37643 amit 97
    public String getHotDealModels(Model model) throws Exception {
98
        List<Catalog> catalogs = catalogRepository.selectAllByCatalogIds(new java.util.ArrayList<>(
99
                catalogRepository.selectCatalogIdsByBrand(ProfitMandiConstants.HOT_DEAL_BRAND)));
38016 amit 100
        // model_name holds the original brand on Hot Deal models; offered only when it is a real brand
101
        Map<String, String> brandByLowerName = new HashMap<>();
102
        for (String brand : modelHotDealService.oemBrandNames()) {
103
            brandByLowerName.put(brand.toLowerCase(), brand);
104
        }
37212 amit 105
        List<Map<String, Object>> models = catalogs.stream()
106
                .map(catalog -> {
107
                    Map<String, Object> entry = new HashMap<>();
108
                    entry.put("catalogId", catalog.getId());
109
                    entry.put("description", catalog.getDescription());
38016 amit 110
                    // Pre-fills the OEM brand picker, which in turn scopes the OEM model autosuggest.
37643 amit 111
                    ModelHotDeal attributes = modelHotDealService.getAttributes(catalog.getId());
38016 amit 112
                    String stored = attributes == null ? null : attributes.getOemBrand();
113
                    String suggested = catalog.getModelName() == null ? null
114
                            : brandByLowerName.get(catalog.getModelName().trim().toLowerCase());
115
                    entry.put("oemBrand", stored != null ? stored : (suggested == null ? "" : suggested));
116
                    entry.put("oemBrandSuggested", stored == null && suggested != null);
37212 amit 117
                    return entry;
118
                })
119
                .collect(Collectors.toList());
120
        model.addAttribute("response1", objectMapper.writeValueAsString(models));
121
        return "response";
122
    }
123
 
37643 amit 124
    /**
125
     * Create or update the five pill attributes for one Hot Deal model. Replaces the old
126
     * add/update pair: there is no date window to set and no cap to respect, so the only
127
     * thing left to edit is the attributes, and whether a row already exists is an
128
     * implementation detail the caller should not have to know.
129
     */
130
    @RequestMapping(value = "/hotDeals/saveAttributes", method = RequestMethod.POST)
131
    public String saveAttributes(HttpServletRequest request, @RequestParam int catalogItemId,
132
                                 @RequestParam(required = false) Integer warrantyMonths,
133
                                 @RequestParam(required = false) String condition,
134
                                 @RequestParam(required = false) Boolean fresh,
135
                                 @RequestParam(required = false) Boolean financeMapping,
136
                                 @RequestParam(required = false) Boolean affordability,
38016 amit 137
                                 @RequestParam(required = false) String oemBrand,
37643 amit 138
                                 @RequestParam(required = false) Integer oemCatalogId,
139
                                 Model model) throws Exception {
37246 amit 140
        // required=false so a missing field reaches the service's mandatory-field
141
        // validation and comes back as a readable message instead of a Spring 400
37212 amit 142
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
143
        try {
37246 amit 144
            HotDealAttributes attributes = new HotDealAttributes(warrantyMonths, condition,
37270 amit 145
                    fresh, financeMapping, affordability);
38016 amit 146
            modelHotDealService.saveAttributes(catalogItemId, attributes, oemBrand, oemCatalogId,
147
                    loginDetails.getEmailId());
37212 amit 148
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
149
        } catch (ProfitMandiBusinessException e) {
37643 amit 150
            LOGGER.warn("Hot deal attributes rejected: {}", e.getMessage());
37212 amit 151
            model.addAttribute("response1", e.getMessage());
152
        }
153
        return "response";
154
    }
155
 
37643 amit 156
    /**
157
     * Catalogs under one OEM brand, for the optional channel-counterpart autosuggest.
158
     * Scoped to the brand the hot-deal model came from, so ops cannot map a Samsung deal
159
     * onto a Vivo model; the service re-checks this on save.
160
     */
161
    @RequestMapping(value = "/hotDeals/oemModels", method = RequestMethod.GET)
162
    public String getOemModels(@RequestParam String brand, Model model) throws Exception {
163
        List<Map<String, Object>> models = new java.util.ArrayList<>();
164
        if (brand != null && !brand.trim().isEmpty()
165
                && !ProfitMandiConstants.HOT_DEAL_BRAND.equalsIgnoreCase(brand.trim())) {
166
            for (Catalog catalog : catalogRepository.selectAllByCatalogIds(new java.util.ArrayList<>(
167
                    catalogRepository.selectCatalogIdsByBrand(brand.trim())))) {
168
                Map<String, Object> entry = new HashMap<>();
169
                entry.put("catalogId", catalog.getId());
170
                entry.put("description", catalog.getDescription());
171
                models.add(entry);
172
            }
37212 amit 173
        }
37643 amit 174
        model.addAttribute("response1", objectMapper.writeValueAsString(models));
37212 amit 175
        return "response";
176
    }
177
 
37270 amit 178
    @Autowired
179
    private FofoSolr fofoSolr;
180
 
181
    /**
182
     * Manual, explicit Solr push for the selected deal models (Category team button).
183
     * Calls the indexer directly - deliberately NOT the prod-gated change event - so
184
     * curated models are searchable immediately without waiting for the daily sync.
185
     */
186
    @RequestMapping(value = "/hotDeals/pushSolr", method = RequestMethod.POST)
187
    public String pushDealsToSolr(@RequestParam String catalogIds, Model model) throws Exception {
188
        List<String> ok = new java.util.ArrayList<>();
189
        List<String> failed = new java.util.ArrayList<>();
190
        for (String raw : catalogIds.split(",")) {
191
            String id = raw.trim();
192
            if (id.isEmpty()) {
193
                continue;
194
            }
195
            try {
196
                fofoSolr.updateSingleCatalog(Integer.parseInt(id));
197
                ok.add(id);
198
            } catch (Exception e) {
199
                LOGGER.error("Manual Solr push failed for catalogId={}", id, e);
200
                failed.add(id + " (" + e.getMessage() + ")");
201
            }
202
        }
203
        String summary = "Pushed " + ok.size() + " model(s) to Solr"
204
                + (failed.isEmpty() ? "" : "; FAILED: " + String.join(", ", failed));
205
        model.addAttribute("response1", summary);
206
        return "response";
207
    }
208
 
37212 amit 209
    @RequestMapping(value = "/hotDeals/remove", method = RequestMethod.POST)
210
    public String removeHotDeal(@RequestParam int id, Model model) throws Exception {
211
        try {
37643 amit 212
            modelHotDealService.removeAttributes(id);
37212 amit 213
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
214
        } catch (ProfitMandiBusinessException e) {
215
            LOGGER.warn("Hot deal remove rejected: {}", e.getMessage());
216
            model.addAttribute("response1", e.getMessage());
217
        }
218
        return "response";
219
    }
220
}