Subversion Repositories SmartDukaan

Rev

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