Subversion Repositories SmartDukaan

Rev

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