Subversion Repositories SmartDukaan

Rev

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