Subversion Repositories SmartDukaan

Rev

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