Subversion Repositories SmartDukaan

Rev

Rev 35894 | 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
35857 amit 204
        redisShortCacheManager.getCache("publishedOffersWithAchievement").clear();
35894 amit 205
        // Evict offer detail (price circular) for each involved partner; key=(fofoId, offerId), 0=admin
35893 amit 206
        for (Offer offer : offers) {
207
            PartnerCriteria partnerCriteria = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
208
            if (partnerCriteria != null && partnerCriteria.getFofoIds() != null) {
209
                for (Integer fofoId : partnerCriteria.getFofoIds()) {
210
                    thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(fofoId, offer.getId()));
211
                }
212
            }
213
            thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(0, offer.getId()));
214
        }
32868 amit.gupta 215
        if (active) {
216
            for (Offer offer : offers) {
32505 amit.gupta 217
                this.sendNotification(offer);
218
            }
219
        }
32868 amit.gupta 220
 
221
 
32505 amit.gupta 222
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
223
        return "response";
224
    }
27391 tejbeer 225
 
35857 amit 226
    @RequestMapping(value = "/offers/publishAll", method = RequestMethod.POST)
227
    public ResponseEntity<?> publishAllUnpublished(@RequestParam YearMonth yearMonth)
228
            throws ProfitMandiBusinessException, Exception {
229
        List<Offer> published = offerService.publishAllUnpublished(yearMonth);
230
        if (!published.isEmpty()) {
35894 amit 231
            // Evict partner-to-offer mapping and offer listing
35857 amit 232
            redisCacheManager.getCache("catalog.published_yearmonth").evict(yearMonth);
233
            oneDayCacheManager.getCache("allOffers").evict(yearMonth);
234
            redisShortCacheManager.getCache("publishedOffersWithAchievement").clear();
35894 amit 235
            // Evict offer detail (price circular) for each involved partner; key=(fofoId, offerId), 0=admin
35857 amit 236
            for (Offer offer : published) {
35893 amit 237
                PartnerCriteria pc = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
238
                if (pc != null && pc.getFofoIds() != null) {
239
                    for (Integer fofoId : pc.getFofoIds()) {
240
                        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(fofoId, offer.getId()));
241
                    }
242
                }
243
                thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(0, offer.getId()));
244
            }
245
            for (Offer offer : published) {
35857 amit 246
                this.sendNotification(offer);
247
            }
248
        }
249
        return responseSender.ok(published.size() + " offers published");
250
    }
251
 
252
    @RequestMapping(value = "/offer/delete/{offerId}", method = RequestMethod.DELETE)
253
    public ResponseEntity<?> deleteOffer(@PathVariable int offerId) throws ProfitMandiBusinessException {
254
        offerService.deleteOffer(offerId);
255
        return responseSender.ok(true);
256
    }
257
 
32505 amit.gupta 258
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
259
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
260
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
261
        Offer offer = offerRepository.selectById(offerId);
262
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
263
        // return "response";
264
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
265
        Map<String, Object> model1 = new HashMap<>();
266
        model1.put("offer", createOfferRequest);
267
        model1.put("lessThan", "<");
268
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
269
        model.addAttribute("response1", htmlContent);
270
        return "response";
271
    }
29900 amit.gupta 272
 
32505 amit.gupta 273
    private void sendNotification(Offer offer) throws Exception {
274
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
275
            return;
276
        }
277
        String fileName = "offer-" + offer.getId() + ".png";
32868 amit.gupta 278
        //String htmlFileName = fileName.replace("png", "html");
32505 amit.gupta 279
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
34620 amit.gupta 280
        boolean isLiveDemo = createOfferRequest.getTargetSlabs().stream()
281
                .map(x -> x.getItemCriteriaPayouts())
282
                .flatMap(List::stream)
283
                .map(ItemCriteriaPayout::getItemCriteria)
284
                .map(ItemCriteria::getCatalogIds)
285
                .flatMap(List::stream)
286
                .anyMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"));
287
        if (!isLiveDemo) {
288
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
289
            sendNotificationModel.setCampaignName("SchemeOffer");
290
            sendNotificationModel.setTitle(offer.getName());
291
            sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
292
                    + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
293
                    + FormattingUtils.formatDateMonth(offer.getEndDate()));
294
            sendNotificationModel.setType("url");
295
            String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
296
            sendNotificationModel.setImageUrl(imageUrl);
297
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
298
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
299
            sendNotificationModel.setMessageType(MessageType.scheme);
300
            //Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
29900 amit.gupta 301
 
34620 amit.gupta 302
            Map<String, InputStream> fileStreamsMap = new HashMap<>();
303
            Map<String, Object> model = new HashMap<>();
304
            model.put("offer", createOfferRequest);
305
            String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
306
            LOGGER.info("this.getContentFromTemplate {}", htmlContent);
307
            fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
308
            // fileStreamsMap.put(htmlFileName, new
309
            // ByteArrayInputStream(htmlContent.getBytes()));
310
            List<Integer> fofoIds = null;
311
            if (isProd) {
312
                this.uploadFile(fileStreamsMap);
313
            }
314
 
315
            List<Integer> fofoIdSet = new ArrayList<>(offerRepository.getEligibleFofoIds(offer));
316
            //LOGGER.info(fofoIdSet);
317
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(new ArrayList<>(fofoIdSet));
318
            sendNotificationModel.setUserIds(userIds);
319
            notificationService.sendNotification(sendNotificationModel);
320
            sendWhatsapp(offer, fofoIds, imageUrl);
32868 amit.gupta 321
        }
32505 amit.gupta 322
    }
27876 amit.gupta 323
 
32505 amit.gupta 324
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
35205 amit 325
        offerService.sendWhatsapp(offer, fofoIds, imageUrl);
32505 amit.gupta 326
    }
27391 tejbeer 327
 
32505 amit.gupta 328
    private InputStream asInputStream(BufferedImage bi) throws Exception {
329
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
330
        ImageIO.write(bi, "png", baos);
331
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 332
 
32505 amit.gupta 333
    }
27391 tejbeer 334
 
32505 amit.gupta 335
    private ChannelSftp setupJsch() throws JSchException {
336
        JSch jsch = new JSch();
33471 amit.gupta 337
        Session jschSession = jsch.getSession("root", "172.105.58.16");
32505 amit.gupta 338
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
339
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
340
                getClass().getClassLoader().getResource("id_rsa").getPath());
341
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
342
        // jschSession.setPassword("spic@2015static0");
343
        jschSession.setConfig("StrictHostKeyChecking", "no");
344
        jschSession.connect();
345
        return (ChannelSftp) jschSession.openChannel("sftp");
346
    }
30426 tejbeer 347
 
32505 amit.gupta 348
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
349
            throws SftpException, FileNotFoundException {
27391 tejbeer 350
 
32505 amit.gupta 351
        channelSftp.cd(destinationPath);
352
        String folderName = "image" + LocalDate.now();
27391 tejbeer 353
 
32505 amit.gupta 354
        channelSftp.cd(destinationPath);
355
        SftpATTRS attrs = null;
27391 tejbeer 356
 
32505 amit.gupta 357
        // check if the directory is already existing
358
        try {
359
            attrs = channelSftp.stat(folderName);
360
        } catch (Exception e) {
361
            System.out.println(destinationPath + "/" + folderName + " not found");
362
        }
27391 tejbeer 363
 
32505 amit.gupta 364
        // else create a directory
365
        if (attrs == null) {
366
            channelSftp.mkdir(folderName);
367
            channelSftp.chmod(0755, ".");
368
        }
369
        channelSftp.cd(folderName);
27391 tejbeer 370
 
32505 amit.gupta 371
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
372
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
373
        }
27391 tejbeer 374
 
32505 amit.gupta 375
    }
29926 amit.gupta 376
 
32505 amit.gupta 377
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
378
        ChannelSftp channelSftp = setupJsch();
379
        channelSftp.connect();
380
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
381
        channelSftp.exit();
382
    }
27391 tejbeer 383
 
32505 amit.gupta 384
    private InputStream getImageBuffer(String html) throws Exception {
35923 aman 385
        // Sanitize HTML to valid XHTML for Flying Saucer (Java2DRenderer requires well-formed XML)
386
        org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(html);
387
        doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
388
        doc.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
389
        doc.outputSettings().charset("UTF-8");
390
        html = doc.html();
29900 amit.gupta 391
 
32505 amit.gupta 392
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
393
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
394
        String address = "file:" + fileName;
395
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
396
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
397
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
398
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
399
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
400
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
401
        renderer.setRenderingHints(hints);
402
        BufferedImage img = renderer.getImage();
403
        ByteArrayOutputStream os = new ByteArrayOutputStream();
404
        ImageIO.write(img, "png", os);
405
        return new ByteArrayInputStream(os.toByteArray());
406
    }
29926 amit.gupta 407
 
32505 amit.gupta 408
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
409
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
410
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
411
        MockHttpServletRequest req = new MockHttpServletRequest();
412
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
413
        resolvedView.render(model, req, mockResp);
414
        return mockResp.getContentAsString();
415
    }
29926 amit.gupta 416
 
32505 amit.gupta 417
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
418
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
419
            throws ProfitMandiBusinessException {
30017 amit.gupta 420
 
32505 amit.gupta 421
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
422
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
423
        model.addAttribute("offers", publishedOffers);
424
        model.addAttribute("yearMonth", yearMonth);
425
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 426
 
32505 amit.gupta 427
        return "offer_history";
428
    }
30723 amit.gupta 429
 
32505 amit.gupta 430
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
431
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
432
            throws ProfitMandiBusinessException {
433
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 434
 
32505 amit.gupta 435
        model.addAttribute("offer", createOfferRequest);
436
        return "offer-details";
437
    }
29926 amit.gupta 438
 
32505 amit.gupta 439
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
440
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
441
            throws Exception {
442
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
443
        if (!createOfferRequest.isActive()) {
444
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
445
        }
446
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
447
            offerService.processSellin(createOfferRequest);
448
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
449
            offerService.processActivationtOffer(createOfferRequest);
450
        }
451
        return responseSender.ok(true);
452
    }
29926 amit.gupta 453
 
32505 amit.gupta 454
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
455
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
456
            throws Exception {
457
        final HttpHeaders headers = new HttpHeaders();
458
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
459
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
460
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
33999 tejus.loha 461
        ByteArrayOutputStream baos = offerService.createCSVOfferReport(createOfferRequest);
32505 amit.gupta 462
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
463
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
464
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
465
    }
29900 amit.gupta 466
 
32505 amit.gupta 467
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
468
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
469
        Offer offer = offerRepository.selectById(offerId);
470
        model.addAttribute("offer", offer);
471
        return "offer-edit";
29900 amit.gupta 472
 
32505 amit.gupta 473
    }
29900 amit.gupta 474
 
34176 tejus.loha 475
    @RequestMapping(value = "/published-offers", method = RequestMethod.GET)
476
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam int yearMonth, @RequestParam(required = false, defaultValue = "") String brandFilter, Model model)
32505 amit.gupta 477
            throws ProfitMandiBusinessException {
34176 tejus.loha 478
        LOGGER.info("publishedOffersCalled");
32505 amit.gupta 479
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
480
        int fofoId = loginDetails.getFofoId();
481
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
482
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 483
 
34617 amit.gupta 484
        List<CreateOfferRequest> publishedOffers = null;
485
        if (!brandFilter.isEmpty()) {
486
            publishedOffers = createOffers.stream()
34176 tejus.loha 487
                    .filter(createOffer -> createOffer.getTargetSlabs().stream()
488
                            .map(x -> x.getItemCriteriaPayouts())
489
                            .flatMap(List::stream)
490
                            .map(ItemCriteriaPayout::getItemCriteria)
491
                            .map(ItemCriteria::getBrands)
492
                            .flatMap(List::stream)
493
                            .anyMatch(brand -> brand.equals(brandFilter)))
494
                    .collect(Collectors.toList());
34617 amit.gupta 495
        } else {
496
            publishedOffers = createOffers.stream().filter(createOffer -> createOffer.getTargetSlabs().stream()
34557 amit.gupta 497
                    .map(x -> x.getItemCriteriaPayouts())
498
                    .flatMap(List::stream)
499
                    .map(ItemCriteriaPayout::getItemCriteria)
34559 amit.gupta 500
                    .map(ItemCriteria::getCatalogIds)
34557 amit.gupta 501
                    .flatMap(List::stream)
34559 amit.gupta 502
                    .noneMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"))).collect(Collectors.toList());
34176 tejus.loha 503
        }
29926 amit.gupta 504
 
34176 tejus.loha 505
        model.addAttribute("publishedOffers", publishedOffers);
506
 
32505 amit.gupta 507
        return "published-offers";
508
    }
29926 amit.gupta 509
 
32505 amit.gupta 510
    @PostMapping(value = "/offers/upload")
511
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
512
            throws Exception {
513
        offerService.createOffers(targetFile.getInputStream());
514
        model.addAttribute("response1", true);
515
        return "response";
516
    }
29926 amit.gupta 517
 
32505 amit.gupta 518
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
519
    public String getOfferMargins(HttpServletRequest request,
520
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
521
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
522
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
523
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 524
 
32505 amit.gupta 525
        model.addAttribute("offer", createOfferRequest);
35415 amit 526
        model.addAttribute("isAdmin", isAdmin);
29900 amit.gupta 527
 
32505 amit.gupta 528
        return "offer_margin_detail_partner";
30470 amit.gupta 529
 
32505 amit.gupta 530
    }
29900 amit.gupta 531
 
35501 ranu 532
    @RequestMapping(value = "/todayOffer")
533
    public String todayOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
534
 
535
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
536
        if (fofoId == 0) {
537
            fofoId = loginDetails.getFofoId();
538
        }
539
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
540
 
541
        // 1. IDs to exclude entirely
542
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
543
 
544
        // 2. Brands that must come first (in this specific order)
545
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
546
 
547
        List<BrandCatalog> sortedBrands = allBrands.stream()
548
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
549
                .sorted((b1, b2) -> {
550
                    // Get the index of the brand name in our priority list
551
                    int index1 = priorityOrder.indexOf(b1.getName());
552
                    int index2 = priorityOrder.indexOf(b2.getName());
553
 
554
                    // If brand is NOT in priority list, give it a high index (move to bottom)
555
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
556
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
557
 
558
                    if (p1 != p2) {
559
                        return Integer.compare(p1, p2); // Sort by priority first
560
                    }
561
 
562
                    // If both are "Others", sort them alphabetically
563
                    return b1.getName().compareToIgnoreCase(b2.getName());
564
                })
565
                .collect(Collectors.toList());
566
 
567
        model.addAttribute("brands", sortedBrands);
568
        model.addAttribute("fofoId", fofoId);
569
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
570
 
571
        return "today-offer";
572
    }
573
 
574
    @RequestMapping(value = "/todayOfferList")
575
    public String todayOfferList(HttpServletRequest request, Model model, @RequestParam String brand, @RequestParam(defaultValue = "0", required = false) int fofoId) throws ProfitMandiBusinessException {
576
 
577
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
578
        if (fofoId == 0) {
579
            fofoId = loginDetails.getFofoId();
580
        }
581
 
582
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
583
 
584
        List<TodayOfferModel> todayOfferModels = todayOfferService.findAllTodayOffer(brand, fofoId);
585
 
586
        List<TodayOfferModel> groupedOffers = todayOfferService.groupSameOffers(todayOfferModels);
587
        model.addAttribute("brands", brands);
35505 ranu 588
        model.addAttribute("fofoId", fofoId);
35501 ranu 589
        model.addAttribute("todayOfferModels", todayOfferModels);
590
        model.addAttribute("groupedOffers", groupedOffers);
591
 
592
 
593
        return "today-offer-list";
594
    }
595
 
596
    @RequestMapping(value = "/todayFofoOffer")
597
    public String todayFofoOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
598
 
599
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
600
        if (fofoId == 0) {
601
            fofoId = loginDetails.getFofoId();
602
        }
603
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
604
 
605
        // 1. IDs to exclude entirely
606
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
607
 
608
        // 2. Brands that must come first (in this specific order)
609
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
610
 
611
        List<BrandCatalog> sortedBrands = allBrands.stream()
612
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
613
                .sorted((b1, b2) -> {
614
                    // Get the index of the brand name in our priority list
615
                    int index1 = priorityOrder.indexOf(b1.getName());
616
                    int index2 = priorityOrder.indexOf(b2.getName());
617
 
618
                    // If brand is NOT in priority list, give it a high index (move to bottom)
619
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
620
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
621
 
622
                    if (p1 != p2) {
623
                        return Integer.compare(p1, p2); // Sort by priority first
624
                    }
625
 
626
                    // If both are "Others", sort them alphabetically
627
                    return b1.getName().compareToIgnoreCase(b2.getName());
628
                })
629
                .collect(Collectors.toList());
630
 
631
        model.addAttribute("brands", sortedBrands);
632
        model.addAttribute("fofoId", fofoId);
633
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
634
 
635
        return "today-fofo-offer";
636
    }
637
 
35886 amit 638
    // ===== Offer Partner & Target Management (Admin Only) =====
639
 
640
    @RequestMapping(value = "/offer/partners", method = RequestMethod.GET)
641
    public String getOfferPartners(HttpServletRequest request, @RequestParam int offerId, Model model) throws Exception {
642
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
643
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
644
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
645
        }
646
        CreateOfferRequest offer = offerService.getOffer(0, offerId);
647
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
648
 
35888 amit 649
        // Partners are stored in partner_criteria JSON, not in offer_partners table
650
        List<Integer> partnerFofoIds = offer.getPartnerCriteria() != null
651
                ? offer.getPartnerCriteria().getFofoIds() : new ArrayList<>();
652
        if (partnerFofoIds == null) partnerFofoIds = new ArrayList<>();
653
 
35886 amit 654
        List<Integer> allFofoIds = fofoStoreRepository.selectActiveStores().stream()
655
                .map(x -> x.getId()).collect(Collectors.toList());
656
        Map<Integer, CustomRetailer> allRetailersMap = allFofoIds.stream()
657
                .map(id -> customRetailerMap.get(id))
658
                .filter(x -> x != null)
659
                .collect(Collectors.toMap(CustomRetailer::getPartnerId, x -> x));
660
 
661
        model.addAttribute("offer", offer);
662
        model.addAttribute("offerId", offerId);
35888 amit 663
        model.addAttribute("partnerFofoIds", partnerFofoIds);
35886 amit 664
        model.addAttribute("customRetailerMap", customRetailerMap);
665
        model.addAttribute("allRetailersMap", allRetailersMap);
666
        return "offer_partners";
667
    }
668
 
669
    @RequestMapping(value = "/offer/removePartners", method = RequestMethod.POST)
670
    public ResponseEntity<?> removePartnersFromOffer(HttpServletRequest request,
671
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds,
672
            @RequestParam(required = false, defaultValue = "false") boolean createNewOffer,
673
            @RequestParam(required = false) List<Integer> targets) throws Exception {
674
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
675
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
676
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
677
        }
678
        Offer offer = offerRepository.selectById(offerId);
679
        YearMonth ym = YearMonth.from(offer.getStartDate());
680
 
681
        offerService.removePartnersFromOffer(offerId, fofoIds);
682
 
683
        Integer newOfferId = null;
684
        String message;
685
        if (createNewOffer && targets != null && !targets.isEmpty()) {
686
            newOfferId = offerService.cloneOfferForPartners(offerId, fofoIds, targets);
687
            message = "Partner(s) removed from Offer #" + offerId + ". New Offer #" + newOfferId + " created (Unpublished).";
688
        } else {
689
            message = "Partner(s) removed from Offer #" + offerId + ".";
690
        }
691
 
35894 amit 692
        // Evict partner-to-offer mapping (removed partners no longer see this offer)
35892 amit 693
        oneDayCacheManager.getCache("allOffers").evict(ym);
694
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
695
        redisShortCacheManager.getCache("publishedOffersWithAchievement").clear();
35894 amit 696
        // Evict offer detail (price circular) for removed partners; key=(fofoId, offerId), 0=admin
35892 amit 697
        for (Integer fofoId : fofoIds) {
698
            thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(fofoId, offerId));
699
        }
700
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(0, offerId));
701
 
35886 amit 702
        Map<String, Object> response = new HashMap<>();
703
        response.put("message", message);
704
        response.put("newOfferId", newOfferId);
705
        response.put("yearMonth", ym.toString());
706
        return responseSender.ok(response);
707
    }
708
 
709
    @RequestMapping(value = "/offer/addPartners", method = RequestMethod.POST)
710
    public ResponseEntity<?> addPartnersToOffer(HttpServletRequest request,
711
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds) throws Exception {
712
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
713
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
714
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
715
        }
716
        offerService.addPartnersToOffer(offerId, fofoIds);
717
 
718
        Offer offer = offerRepository.selectById(offerId);
719
        YearMonth ym = YearMonth.from(offer.getStartDate());
35894 amit 720
        // Evict partner-to-offer mapping (added partners now see this offer)
35892 amit 721
        oneDayCacheManager.getCache("allOffers").evict(ym);
722
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
723
        redisShortCacheManager.getCache("publishedOffersWithAchievement").clear();
35894 amit 724
        // Evict offer detail (price circular) for added partners; key=(fofoId, offerId), 0=admin
35892 amit 725
        for (Integer fofoId : fofoIds) {
726
            thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(fofoId, offerId));
727
        }
728
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(0, offerId));
35886 amit 729
 
730
        Map<String, Object> response = new HashMap<>();
731
        response.put("message", "Partner(s) added to Offer #" + offerId + ".");
732
        response.put("yearMonth", ym.toString());
733
        return responseSender.ok(response);
734
    }
735
 
736
    @RequestMapping(value = "/offer/updateTargets", method = RequestMethod.POST)
737
    public ResponseEntity<?> updateOfferTargets(HttpServletRequest request,
738
            @RequestParam int offerId, @RequestParam List<Integer> targets) throws Exception {
739
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
740
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
741
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
742
        }
743
        offerService.updateOfferTargets(offerId, targets);
744
 
745
        Offer offer = offerRepository.selectById(offerId);
746
        YearMonth ym = YearMonth.from(offer.getStartDate());
35894 amit 747
        // Evict offer listing and partner-to-offer mapping (targets changed for published offer)
35886 amit 748
        oneDayCacheManager.getCache("allOffers").evict(ym);
749
        redisCacheManager.getCache("catalog.published_yearmonth").evict(ym);
750
        redisShortCacheManager.getCache("publishedOffersWithAchievement").clear();
35894 amit 751
        // Evict offer detail (price circular) for all partners of this offer; key=(fofoId, offerId), 0=admin
35893 amit 752
        PartnerCriteria partnerCriteria = gson.fromJson(offer.getPartnerCriteria(), PartnerCriteria.class);
35892 amit 753
        if (partnerCriteria != null && partnerCriteria.getFofoIds() != null) {
754
            for (Integer fofoId : partnerCriteria.getFofoIds()) {
755
                thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(fofoId, offerId));
756
            }
757
        }
758
        thirtyMinsTimeOutCacheManager.getCache("partnerOffers").evict(new SimpleKey(0, offerId));
35886 amit 759
 
760
        return responseSender.ok("Targets updated for Offer #" + offerId);
761
    }
762
 
27895 amit.gupta 763
}