Subversion Repositories SmartDukaan

Rev

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