Subversion Repositories SmartDukaan

Rev

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