Subversion Repositories SmartDukaan

Rev

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