Subversion Repositories SmartDukaan

Rev

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