Subversion Repositories SmartDukaan

Rev

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