Subversion Repositories SmartDukaan

Rev

Rev 35925 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27391 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
35923 aman 3
import com.google.gson.Gson;
29943 amit.gupta 4
import com.jcraft.jsch.*;
29900 amit.gupta 5
import com.spice.profitmandi.common.enumuration.MessageType;
27391 tejbeer 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
7
import com.spice.profitmandi.common.model.CustomRetailer;
27876 amit.gupta 8
import com.spice.profitmandi.common.model.ProfitMandiConstants;
29900 amit.gupta 9
import com.spice.profitmandi.common.model.SendNotificationModel;
29904 amit.gupta 10
import com.spice.profitmandi.common.util.FormattingUtils;
27876 amit.gupta 11
import com.spice.profitmandi.common.web.util.ResponseSender;
35501 ranu 12
import com.spice.profitmandi.dao.entity.catalog.BrandCatalog;
27391 tejbeer 13
import com.spice.profitmandi.dao.entity.catalog.Offer;
14
import com.spice.profitmandi.dao.entity.fofo.PartnerType;
15
import com.spice.profitmandi.dao.enumuration.catalog.ItemCriteriaType;
30651 amit.gupta 16
import com.spice.profitmandi.dao.enumuration.catalog.OfferSchemeType;
27391 tejbeer 17
import com.spice.profitmandi.dao.model.CreateOfferRequest;
34176 tejus.loha 18
import com.spice.profitmandi.dao.model.ItemCriteriaPayout;
35501 ranu 19
import com.spice.profitmandi.dao.model.TodayOfferModel;
35923 aman 20
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
21
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
23
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
27391 tejbeer 24
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
29926 amit.gupta 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
29900 amit.gupta 26
import com.spice.profitmandi.service.NotificationService;
29785 amit.gupta 27
import com.spice.profitmandi.service.authentication.RoleManager;
33043 amit.gupta 28
import com.spice.profitmandi.service.catalog.BrandsService;
34176 tejus.loha 29
import com.spice.profitmandi.service.offers.ItemCriteria;
27876 amit.gupta 30
import com.spice.profitmandi.service.offers.OfferService;
35923 aman 31
import com.spice.profitmandi.service.offers.PartnerCriteria;
35501 ranu 32
import com.spice.profitmandi.service.offers.TodayOfferService;
27391 tejbeer 33
import com.spice.profitmandi.service.user.RetailerService;
34
import com.spice.profitmandi.web.model.LoginDetails;
35
import com.spice.profitmandi.web.util.CookiesProcessor;
36
import com.spice.profitmandi.web.util.MVCResponseSender;
29943 amit.gupta 37
import org.apache.commons.io.FileUtils;
38
import org.apache.commons.io.output.ByteArrayOutputStream;
39
import org.apache.logging.log4j.LogManager;
40
import org.apache.logging.log4j.Logger;
41
import org.springframework.beans.factory.annotation.Autowired;
32868 amit.gupta 42
import org.springframework.beans.factory.annotation.Value;
29943 amit.gupta 43
import org.springframework.cache.CacheManager;
35923 aman 44
import org.springframework.cache.interceptor.SimpleKey;
29943 amit.gupta 45
import org.springframework.core.io.InputStreamResource;
46
import org.springframework.http.HttpHeaders;
47
import org.springframework.http.HttpStatus;
48
import org.springframework.http.ResponseEntity;
32204 amit.gupta 49
import org.springframework.mock.web.MockHttpServletRequest;
50
import org.springframework.mock.web.MockHttpServletResponse;
29943 amit.gupta 51
import org.springframework.stereotype.Controller;
35501 ranu 52
import org.springframework.transaction.annotation.Transactional;
29943 amit.gupta 53
import org.springframework.ui.Model;
54
import org.springframework.web.bind.annotation.*;
55
import org.springframework.web.multipart.MultipartFile;
32204 amit.gupta 56
import org.springframework.web.servlet.View;
57
import org.springframework.web.servlet.ViewResolver;
29943 amit.gupta 58
import org.xhtmlrenderer.swing.Java2DRenderer;
27391 tejbeer 59
 
29943 amit.gupta 60
import javax.imageio.ImageIO;
61
import javax.servlet.http.HttpServletRequest;
62
import java.awt.*;
63
import java.awt.image.BufferedImage;
64
import java.io.ByteArrayInputStream;
65
import java.io.File;
66
import java.io.FileNotFoundException;
67
import java.io.InputStream;
33713 tejus.loha 68
import java.time.Instant;
69
import java.time.LocalDate;
70
import java.time.LocalDateTime;
71
import java.time.YearMonth;
35923 aman 72
import java.util.*;
35501 ranu 73
import java.util.List;
29943 amit.gupta 74
import java.util.stream.Collectors;
75
 
27391 tejbeer 76
@Controller
35458 amit 77
@Transactional(rollbackFor = Throwable.class)
27391 tejbeer 78
public class OfferController {
32505 amit.gupta 79
    private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
80
    private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
81
    private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
82
    @Autowired
83
    UserAccountRepository userAccountRepository;
84
    @Autowired
85
    RoleManager roleManager;
86
    @Autowired
87
    private OfferRepository offerRepository;
88
    @Autowired
89
    private OfferMarginRepository offerMarginRepository;
90
    @Autowired
91
    private FofoStoreRepository fofoStoreRepository;
92
    @Autowired
93
    private ResponseSender responseSender;
94
    @Autowired
95
    private ViewResolver viewResolver;
96
    @Autowired
97
    private ItemRepository itemRepository;
98
    @Autowired
99
    private MVCResponseSender mvcResponseSender;
100
    @Autowired
101
    private RetailerService retailerService;
102
    @Autowired
103
    private NotificationService notificationService;
104
    @Autowired
105
    private CookiesProcessor cookiesProcessor;
106
    @Autowired
107
    private OfferService offerService;
108
    @Autowired
109
    private CacheManager oneDayCacheManager;
27391 tejbeer 110
 
33043 amit.gupta 111
    @Autowired
35857 amit 112
    private CacheManager redisCacheManager;
113
 
114
    @Autowired
115
    private CacheManager redisShortCacheManager;
116
 
117
    @Autowired
35892 amit 118
    private CacheManager thirtyMinsTimeOutCacheManager;
119
 
120
    @Autowired
35893 amit 121
    private Gson gson;
122
 
123
    @Autowired
33043 amit.gupta 124
    BrandsService brandsService;
34553 amit.gupta 125
 
34552 amit.gupta 126
    @Autowired
127
    private CatalogRepository catalogRepository;
33043 amit.gupta 128
 
35501 ranu 129
    @Autowired
130
    TodayOfferService todayOfferService;
131
 
32505 amit.gupta 132
    @RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
133
    public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
134
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
135
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
136
                .collect(Collectors.toList());
27391 tejbeer 137
 
33713 tejus.loha 138
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
32505 amit.gupta 139
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
33615 amit.gupta 140
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.SMART_WATCH_CATEGORY_ID));
32505 amit.gupta 141
        //Lets allow demo
142
        brands.add("Live Demo");
27391 tejbeer 143
 
32505 amit.gupta 144
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
27876 amit.gupta 145
 
32505 amit.gupta 146
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
147
                .filter(x -> x != null).collect(Collectors.toList()).stream()
148
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
32204 amit.gupta 149
 
32505 amit.gupta 150
        model.addAttribute("customRetailersMap", customRetailersMap);
151
        model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
152
        model.addAttribute("brands", brands);
153
        model.addAttribute("partnerCategories", PartnerType.values());
154
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
155
        return "scheme_offer";
27391 tejbeer 156
 
32505 amit.gupta 157
    }
29926 amit.gupta 158
 
32505 amit.gupta 159
    @RequestMapping(value = "/createOffer", method = RequestMethod.POST)
160
    public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
161
                              Model model) throws Exception {
162
        LOGGER.info("createOfferRequest [{}]", createOfferRequest);
163
        offerService.addOfferService(createOfferRequest);
32868 amit.gupta 164
        oneDayCacheManager.getCache("allOffers").evict(YearMonth.from(createOfferRequest.getStartDate()));
32505 amit.gupta 165
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
166
        return "response";
27391 tejbeer 167
 
32505 amit.gupta 168
    }
27391 tejbeer 169
 
32505 amit.gupta 170
    @RequestMapping(value = "/offers/published", method = RequestMethod.GET)
171
    public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
172
            throws Exception {
173
        LOGGER.info("Published");
174
        offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
175
        return "scheme_offer/published";
27391 tejbeer 176
 
32505 amit.gupta 177
    }
27391 tejbeer 178
 
32868 amit.gupta 179
    @Value("${prod}")
180
    private boolean isProd;
181
 
32505 amit.gupta 182
    @RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
183
    public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
184
                                Model model, @RequestParam(defaultValue = "true") boolean active)
185
            throws ProfitMandiBusinessException, Exception {
186
        List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
187
                .collect(Collectors.toList());
188
        List<Offer> offers = offerRepository.selectAllByIds(offerIds);
32868 amit.gupta 189
 
190
        //Consider only offers that have opposite status
191
        offers = offers.stream().filter(x -> x.isActive() != active).collect(Collectors.toList());
192
 
193
        Set<YearMonth> yearMonthsToEvict = new HashSet<>();
32505 amit.gupta 194
        for (Offer offer : offers) {
32868 amit.gupta 195
            offer.setActive(active);
196
            yearMonthsToEvict.add(YearMonth.from(offer.getStartDate()));
32505 amit.gupta 197
        }
35894 amit 198
        // Evict partner-to-offer mapping (which partners see which offers)
32868 amit.gupta 199
        for (YearMonth ymToEvict : yearMonthsToEvict) {
35857 amit 200
            redisCacheManager.getCache("catalog.published_yearmonth").evict(ymToEvict);
32868 amit.gupta 201
            oneDayCacheManager.getCache("allOffers").evict(ymToEvict);
32505 amit.gupta 202
        }
35894 amit 203
        // Evict partner's published offer list with achievement data
35925 amit 204
        oneDayCacheManager.getCache("publishedOffersWithAchievement").clear();
205
        redisShortCacheManager.getCache("todayOffers").clear();
36047 amit 206
        // Evict all partner offer caches (price circular)
207
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").clear();
32868 amit.gupta 208
        if (active) {
209
            for (Offer offer : offers) {
32505 amit.gupta 210
                this.sendNotification(offer);
211
            }
212
        }
32868 amit.gupta 213
 
214
 
32505 amit.gupta 215
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
216
        return "response";
217
    }
27391 tejbeer 218
 
35857 amit 219
    @RequestMapping(value = "/offers/publishAll", method = RequestMethod.POST)
220
    public ResponseEntity<?> publishAllUnpublished(@RequestParam YearMonth yearMonth)
221
            throws ProfitMandiBusinessException, Exception {
222
        List<Offer> published = offerService.publishAllUnpublished(yearMonth);
223
        if (!published.isEmpty()) {
35894 amit 224
            // Evict partner-to-offer mapping and offer listing
35857 amit 225
            redisCacheManager.getCache("catalog.published_yearmonth").evict(yearMonth);
226
            oneDayCacheManager.getCache("allOffers").evict(yearMonth);
35925 amit 227
            oneDayCacheManager.getCache("publishedOffersWithAchievement").clear();
228
        redisShortCacheManager.getCache("todayOffers").clear();
36047 amit 229
            // Evict all partner offer caches (price circular)
230
            thirtyMinsTimeOutCacheManager.getCache("partnerOffers").clear();
35857 amit 231
            for (Offer offer : published) {
232
                this.sendNotification(offer);
233
            }
234
        }
235
        return responseSender.ok(published.size() + " offers published");
236
    }
237
 
238
    @RequestMapping(value = "/offer/delete/{offerId}", method = RequestMethod.DELETE)
239
    public ResponseEntity<?> deleteOffer(@PathVariable int offerId) throws ProfitMandiBusinessException {
240
        offerService.deleteOffer(offerId);
241
        return responseSender.ok(true);
242
    }
243
 
32505 amit.gupta 244
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
245
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
246
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
247
        Offer offer = offerRepository.selectById(offerId);
248
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
249
        // return "response";
250
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
251
        Map<String, Object> model1 = new HashMap<>();
252
        model1.put("offer", createOfferRequest);
253
        model1.put("lessThan", "<");
254
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
255
        model.addAttribute("response1", htmlContent);
256
        return "response";
257
    }
29900 amit.gupta 258
 
32505 amit.gupta 259
    private void sendNotification(Offer offer) throws Exception {
260
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
261
            return;
262
        }
263
        String fileName = "offer-" + offer.getId() + ".png";
32868 amit.gupta 264
        //String htmlFileName = fileName.replace("png", "html");
32505 amit.gupta 265
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
34620 amit.gupta 266
        boolean isLiveDemo = createOfferRequest.getTargetSlabs().stream()
267
                .map(x -> x.getItemCriteriaPayouts())
268
                .flatMap(List::stream)
269
                .map(ItemCriteriaPayout::getItemCriteria)
270
                .map(ItemCriteria::getCatalogIds)
271
                .flatMap(List::stream)
272
                .anyMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"));
273
        if (!isLiveDemo) {
274
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
275
            sendNotificationModel.setCampaignName("SchemeOffer");
276
            sendNotificationModel.setTitle(offer.getName());
277
            sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
278
                    + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
279
                    + FormattingUtils.formatDateMonth(offer.getEndDate()));
280
            sendNotificationModel.setType("url");
281
            String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
282
            sendNotificationModel.setImageUrl(imageUrl);
283
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
284
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
285
            sendNotificationModel.setMessageType(MessageType.scheme);
286
            //Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
29900 amit.gupta 287
 
34620 amit.gupta 288
            Map<String, InputStream> fileStreamsMap = new HashMap<>();
289
            Map<String, Object> model = new HashMap<>();
290
            model.put("offer", createOfferRequest);
291
            String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
292
            LOGGER.info("this.getContentFromTemplate {}", htmlContent);
293
            fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
294
            // fileStreamsMap.put(htmlFileName, new
295
            // ByteArrayInputStream(htmlContent.getBytes()));
296
            List<Integer> fofoIds = null;
297
            if (isProd) {
298
                this.uploadFile(fileStreamsMap);
299
            }
300
 
301
            List<Integer> fofoIdSet = new ArrayList<>(offerRepository.getEligibleFofoIds(offer));
302
            //LOGGER.info(fofoIdSet);
303
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(new ArrayList<>(fofoIdSet));
304
            sendNotificationModel.setUserIds(userIds);
305
            notificationService.sendNotification(sendNotificationModel);
306
            sendWhatsapp(offer, fofoIds, imageUrl);
32868 amit.gupta 307
        }
32505 amit.gupta 308
    }
27876 amit.gupta 309
 
32505 amit.gupta 310
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
35205 amit 311
        offerService.sendWhatsapp(offer, fofoIds, imageUrl);
32505 amit.gupta 312
    }
27391 tejbeer 313
 
32505 amit.gupta 314
    private InputStream asInputStream(BufferedImage bi) throws Exception {
315
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
316
        ImageIO.write(bi, "png", baos);
317
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 318
 
32505 amit.gupta 319
    }
27391 tejbeer 320
 
32505 amit.gupta 321
    private ChannelSftp setupJsch() throws JSchException {
322
        JSch jsch = new JSch();
33471 amit.gupta 323
        Session jschSession = jsch.getSession("root", "172.105.58.16");
32505 amit.gupta 324
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
325
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
326
                getClass().getClassLoader().getResource("id_rsa").getPath());
327
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
328
        // jschSession.setPassword("spic@2015static0");
329
        jschSession.setConfig("StrictHostKeyChecking", "no");
330
        jschSession.connect();
331
        return (ChannelSftp) jschSession.openChannel("sftp");
332
    }
30426 tejbeer 333
 
32505 amit.gupta 334
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
335
            throws SftpException, FileNotFoundException {
27391 tejbeer 336
 
32505 amit.gupta 337
        channelSftp.cd(destinationPath);
338
        String folderName = "image" + LocalDate.now();
27391 tejbeer 339
 
32505 amit.gupta 340
        channelSftp.cd(destinationPath);
341
        SftpATTRS attrs = null;
27391 tejbeer 342
 
32505 amit.gupta 343
        // check if the directory is already existing
344
        try {
345
            attrs = channelSftp.stat(folderName);
346
        } catch (Exception e) {
347
            System.out.println(destinationPath + "/" + folderName + " not found");
348
        }
27391 tejbeer 349
 
32505 amit.gupta 350
        // else create a directory
351
        if (attrs == null) {
352
            channelSftp.mkdir(folderName);
353
            channelSftp.chmod(0755, ".");
354
        }
355
        channelSftp.cd(folderName);
27391 tejbeer 356
 
32505 amit.gupta 357
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
358
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
359
        }
27391 tejbeer 360
 
32505 amit.gupta 361
    }
29926 amit.gupta 362
 
32505 amit.gupta 363
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
364
        ChannelSftp channelSftp = setupJsch();
365
        channelSftp.connect();
366
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
367
        channelSftp.exit();
368
    }
27391 tejbeer 369
 
32505 amit.gupta 370
    private InputStream getImageBuffer(String html) throws Exception {
35923 aman 371
        // Sanitize HTML to valid XHTML for Flying Saucer (Java2DRenderer requires well-formed XML)
372
        org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(html);
373
        doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
374
        doc.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
375
        doc.outputSettings().charset("UTF-8");
376
        html = doc.html();
29900 amit.gupta 377
 
32505 amit.gupta 378
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
379
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
380
        String address = "file:" + fileName;
381
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
382
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
383
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
384
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
385
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
386
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
387
        renderer.setRenderingHints(hints);
388
        BufferedImage img = renderer.getImage();
389
        ByteArrayOutputStream os = new ByteArrayOutputStream();
390
        ImageIO.write(img, "png", os);
391
        return new ByteArrayInputStream(os.toByteArray());
392
    }
29926 amit.gupta 393
 
32505 amit.gupta 394
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
395
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
396
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
397
        MockHttpServletRequest req = new MockHttpServletRequest();
398
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
399
        resolvedView.render(model, req, mockResp);
400
        return mockResp.getContentAsString();
401
    }
29926 amit.gupta 402
 
32505 amit.gupta 403
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
404
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
405
            throws ProfitMandiBusinessException {
30017 amit.gupta 406
 
32505 amit.gupta 407
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
408
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
409
        model.addAttribute("offers", publishedOffers);
410
        model.addAttribute("yearMonth", yearMonth);
411
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 412
 
32505 amit.gupta 413
        return "offer_history";
414
    }
30723 amit.gupta 415
 
32505 amit.gupta 416
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
417
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
418
            throws ProfitMandiBusinessException {
419
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 420
 
32505 amit.gupta 421
        model.addAttribute("offer", createOfferRequest);
422
        return "offer-details";
423
    }
29926 amit.gupta 424
 
32505 amit.gupta 425
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
426
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
427
            throws Exception {
428
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
429
        if (!createOfferRequest.isActive()) {
430
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
431
        }
432
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
433
            offerService.processSellin(createOfferRequest);
434
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
435
            offerService.processActivationtOffer(createOfferRequest);
436
        }
437
        return responseSender.ok(true);
438
    }
29926 amit.gupta 439
 
32505 amit.gupta 440
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
441
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
442
            throws Exception {
443
        final HttpHeaders headers = new HttpHeaders();
444
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
445
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
446
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
33999 tejus.loha 447
        ByteArrayOutputStream baos = offerService.createCSVOfferReport(createOfferRequest);
32505 amit.gupta 448
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
449
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
450
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
451
    }
29900 amit.gupta 452
 
32505 amit.gupta 453
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
454
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
455
        Offer offer = offerRepository.selectById(offerId);
456
        model.addAttribute("offer", offer);
457
        return "offer-edit";
29900 amit.gupta 458
 
32505 amit.gupta 459
    }
29900 amit.gupta 460
 
34176 tejus.loha 461
    @RequestMapping(value = "/published-offers", method = RequestMethod.GET)
462
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam int yearMonth, @RequestParam(required = false, defaultValue = "") String brandFilter, Model model)
32505 amit.gupta 463
            throws ProfitMandiBusinessException {
34176 tejus.loha 464
        LOGGER.info("publishedOffersCalled");
32505 amit.gupta 465
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
466
        int fofoId = loginDetails.getFofoId();
467
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
468
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 469
 
34617 amit.gupta 470
        List<CreateOfferRequest> publishedOffers = null;
471
        if (!brandFilter.isEmpty()) {
472
            publishedOffers = createOffers.stream()
34176 tejus.loha 473
                    .filter(createOffer -> createOffer.getTargetSlabs().stream()
474
                            .map(x -> x.getItemCriteriaPayouts())
475
                            .flatMap(List::stream)
476
                            .map(ItemCriteriaPayout::getItemCriteria)
477
                            .map(ItemCriteria::getBrands)
478
                            .flatMap(List::stream)
479
                            .anyMatch(brand -> brand.equals(brandFilter)))
480
                    .collect(Collectors.toList());
34617 amit.gupta 481
        } else {
482
            publishedOffers = createOffers.stream().filter(createOffer -> createOffer.getTargetSlabs().stream()
34557 amit.gupta 483
                    .map(x -> x.getItemCriteriaPayouts())
484
                    .flatMap(List::stream)
485
                    .map(ItemCriteriaPayout::getItemCriteria)
34559 amit.gupta 486
                    .map(ItemCriteria::getCatalogIds)
34557 amit.gupta 487
                    .flatMap(List::stream)
34559 amit.gupta 488
                    .noneMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"))).collect(Collectors.toList());
34176 tejus.loha 489
        }
29926 amit.gupta 490
 
34176 tejus.loha 491
        model.addAttribute("publishedOffers", publishedOffers);
492
 
32505 amit.gupta 493
        return "published-offers";
494
    }
29926 amit.gupta 495
 
32505 amit.gupta 496
    @PostMapping(value = "/offers/upload")
497
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
498
            throws Exception {
499
        offerService.createOffers(targetFile.getInputStream());
500
        model.addAttribute("response1", true);
501
        return "response";
502
    }
29926 amit.gupta 503
 
32505 amit.gupta 504
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
505
    public String getOfferMargins(HttpServletRequest request,
506
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
507
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
508
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
509
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 510
 
32505 amit.gupta 511
        model.addAttribute("offer", createOfferRequest);
35415 amit 512
        model.addAttribute("isAdmin", isAdmin);
29900 amit.gupta 513
 
32505 amit.gupta 514
        return "offer_margin_detail_partner";
30470 amit.gupta 515
 
32505 amit.gupta 516
    }
29900 amit.gupta 517
 
35501 ranu 518
    @RequestMapping(value = "/todayOffer")
519
    public String todayOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
520
 
521
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
522
        if (fofoId == 0) {
523
            fofoId = loginDetails.getFofoId();
524
        }
525
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
526
 
527
        // 1. IDs to exclude entirely
528
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
529
 
530
        // 2. Brands that must come first (in this specific order)
531
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
532
 
533
        List<BrandCatalog> sortedBrands = allBrands.stream()
534
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
535
                .sorted((b1, b2) -> {
536
                    // Get the index of the brand name in our priority list
537
                    int index1 = priorityOrder.indexOf(b1.getName());
538
                    int index2 = priorityOrder.indexOf(b2.getName());
539
 
540
                    // If brand is NOT in priority list, give it a high index (move to bottom)
541
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
542
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
543
 
544
                    if (p1 != p2) {
545
                        return Integer.compare(p1, p2); // Sort by priority first
546
                    }
547
 
548
                    // If both are "Others", sort them alphabetically
549
                    return b1.getName().compareToIgnoreCase(b2.getName());
550
                })
551
                .collect(Collectors.toList());
552
 
553
        model.addAttribute("brands", sortedBrands);
554
        model.addAttribute("fofoId", fofoId);
555
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
556
 
557
        return "today-offer";
558
    }
559
 
560
    @RequestMapping(value = "/todayOfferList")
561
    public String todayOfferList(HttpServletRequest request, Model model, @RequestParam String brand, @RequestParam(defaultValue = "0", required = false) int fofoId) throws ProfitMandiBusinessException {
562
 
563
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
564
        if (fofoId == 0) {
565
            fofoId = loginDetails.getFofoId();
566
        }
567
 
568
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
569
 
570
        List<TodayOfferModel> todayOfferModels = todayOfferService.findAllTodayOffer(brand, fofoId);
571
 
572
        List<TodayOfferModel> groupedOffers = todayOfferService.groupSameOffers(todayOfferModels);
573
        model.addAttribute("brands", brands);
35505 ranu 574
        model.addAttribute("fofoId", fofoId);
35501 ranu 575
        model.addAttribute("todayOfferModels", todayOfferModels);
576
        model.addAttribute("groupedOffers", groupedOffers);
577
 
578
 
579
        return "today-offer-list";
580
    }
581
 
582
    @RequestMapping(value = "/todayFofoOffer")
583
    public String todayFofoOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
584
 
585
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
586
        if (fofoId == 0) {
587
            fofoId = loginDetails.getFofoId();
588
        }
589
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
590
 
591
        // 1. IDs to exclude entirely
592
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
593
 
594
        // 2. Brands that must come first (in this specific order)
595
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
596
 
597
        List<BrandCatalog> sortedBrands = allBrands.stream()
598
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
599
                .sorted((b1, b2) -> {
600
                    // Get the index of the brand name in our priority list
601
                    int index1 = priorityOrder.indexOf(b1.getName());
602
                    int index2 = priorityOrder.indexOf(b2.getName());
603
 
604
                    // If brand is NOT in priority list, give it a high index (move to bottom)
605
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
606
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
607
 
608
                    if (p1 != p2) {
609
                        return Integer.compare(p1, p2); // Sort by priority first
610
                    }
611
 
612
                    // If both are "Others", sort them alphabetically
613
                    return b1.getName().compareToIgnoreCase(b2.getName());
614
                })
615
                .collect(Collectors.toList());
616
 
617
        model.addAttribute("brands", sortedBrands);
618
        model.addAttribute("fofoId", fofoId);
619
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
620
 
621
        return "today-fofo-offer";
622
    }
623
 
35886 amit 624
    // ===== Offer Partner & Target Management (Admin Only) =====
625
 
626
    @RequestMapping(value = "/offer/partners", method = RequestMethod.GET)
627
    public String getOfferPartners(HttpServletRequest request, @RequestParam int offerId, Model model) throws Exception {
628
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
629
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
630
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
631
        }
632
        CreateOfferRequest offer = offerService.getOffer(0, offerId);
633
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
634
 
35888 amit 635
        // Partners are stored in partner_criteria JSON, not in offer_partners table
636
        List<Integer> partnerFofoIds = offer.getPartnerCriteria() != null
637
                ? offer.getPartnerCriteria().getFofoIds() : new ArrayList<>();
638
        if (partnerFofoIds == null) partnerFofoIds = new ArrayList<>();
639
 
35886 amit 640
        List<Integer> allFofoIds = fofoStoreRepository.selectActiveStores().stream()
641
                .map(x -> x.getId()).collect(Collectors.toList());
642
        Map<Integer, CustomRetailer> allRetailersMap = allFofoIds.stream()
643
                .map(id -> customRetailerMap.get(id))
644
                .filter(x -> x != null)
645
                .collect(Collectors.toMap(CustomRetailer::getPartnerId, x -> x));
646
 
647
        model.addAttribute("offer", offer);
648
        model.addAttribute("offerId", offerId);
35888 amit 649
        model.addAttribute("partnerFofoIds", partnerFofoIds);
35886 amit 650
        model.addAttribute("customRetailerMap", customRetailerMap);
651
        model.addAttribute("allRetailersMap", allRetailersMap);
652
        return "offer_partners";
653
    }
654
 
655
    @RequestMapping(value = "/offer/removePartners", method = RequestMethod.POST)
656
    public ResponseEntity<?> removePartnersFromOffer(HttpServletRequest request,
657
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds,
658
            @RequestParam(required = false, defaultValue = "false") boolean createNewOffer,
659
            @RequestParam(required = false) List<Integer> targets) throws Exception {
660
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
661
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
662
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
663
        }
664
        Offer offer = offerRepository.selectById(offerId);
665
        YearMonth ym = YearMonth.from(offer.getStartDate());
666
 
667
        offerService.removePartnersFromOffer(offerId, fofoIds);
668
 
669
        Integer newOfferId = null;
670
        String message;
671
        if (createNewOffer && targets != null && !targets.isEmpty()) {
672
            newOfferId = offerService.cloneOfferForPartners(offerId, fofoIds, targets);
673
            message = "Partner(s) removed from Offer #" + offerId + ". New Offer #" + newOfferId + " created (Unpublished).";
674
        } else {
675
            message = "Partner(s) removed from Offer #" + offerId + ".";
676
        }
677
 
35894 amit 678
        // Evict partner-to-offer mapping (removed partners no longer see this offer)
35892 amit 679
        oneDayCacheManager.getCache("allOffers").evict(ym);
680
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
35925 amit 681
        oneDayCacheManager.getCache("publishedOffersWithAchievement").clear();
682
        redisShortCacheManager.getCache("todayOffers").clear();
36047 amit 683
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").clear();
35892 amit 684
 
35886 amit 685
        Map<String, Object> response = new HashMap<>();
686
        response.put("message", message);
687
        response.put("newOfferId", newOfferId);
688
        response.put("yearMonth", ym.toString());
689
        return responseSender.ok(response);
690
    }
691
 
692
    @RequestMapping(value = "/offer/addPartners", method = RequestMethod.POST)
693
    public ResponseEntity<?> addPartnersToOffer(HttpServletRequest request,
694
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds) throws Exception {
695
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
696
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
697
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
698
        }
699
        offerService.addPartnersToOffer(offerId, fofoIds);
700
 
701
        Offer offer = offerRepository.selectById(offerId);
702
        YearMonth ym = YearMonth.from(offer.getStartDate());
35894 amit 703
        // Evict partner-to-offer mapping (added partners now see this offer)
35892 amit 704
        oneDayCacheManager.getCache("allOffers").evict(ym);
705
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
35925 amit 706
        oneDayCacheManager.getCache("publishedOffersWithAchievement").clear();
707
        redisShortCacheManager.getCache("todayOffers").clear();
36047 amit 708
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").clear();
35886 amit 709
 
710
        Map<String, Object> response = new HashMap<>();
711
        response.put("message", "Partner(s) added to Offer #" + offerId + ".");
712
        response.put("yearMonth", ym.toString());
713
        return responseSender.ok(response);
714
    }
715
 
716
    @RequestMapping(value = "/offer/updateTargets", method = RequestMethod.POST)
717
    public ResponseEntity<?> updateOfferTargets(HttpServletRequest request,
718
            @RequestParam int offerId, @RequestParam List<Integer> targets) throws Exception {
719
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
720
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
721
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
722
        }
723
        offerService.updateOfferTargets(offerId, targets);
35925 amit 724
        evictOfferCaches(offerId);
725
        return responseSender.ok("Targets updated for Offer #" + offerId);
726
    }
35886 amit 727
 
35925 amit 728
    @RequestMapping(value = "/offer/updateSlabs", method = RequestMethod.POST, consumes = "application/json")
729
    public ResponseEntity<?> updateOfferSlabs(HttpServletRequest request,
730
            @RequestBody com.spice.profitmandi.dao.model.UpdateOfferSlabsRequest updateRequest) throws Exception {
731
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
732
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
733
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
734
        }
735
        offerService.updateOfferSlabs(updateRequest);
736
        evictOfferCaches(updateRequest.getOfferId());
737
        return responseSender.ok("Slabs updated for Offer #" + updateRequest.getOfferId());
738
    }
739
 
740
    private void evictOfferCaches(int offerId) {
35886 amit 741
        Offer offer = offerRepository.selectById(offerId);
742
        YearMonth ym = YearMonth.from(offer.getStartDate());
743
        oneDayCacheManager.getCache("allOffers").evict(ym);
744
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
35925 amit 745
        oneDayCacheManager.getCache("publishedOffersWithAchievement").clear();
746
        redisShortCacheManager.getCache("todayOffers").clear();
36047 amit 747
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").clear();
35886 amit 748
    }
749
 
27895 amit.gupta 750
}