Subversion Repositories SmartDukaan

Rev

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