Subversion Repositories SmartDukaan

Rev

Rev 33999 | Rev 34176 | 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;
17
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
18
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
19
import com.spice.profitmandi.dao.repository.catalog.OfferPartnerRepository;
20
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
21
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
22
import com.spice.profitmandi.dao.repository.dtr.Mongo;
29926 amit.gupta 23
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
27391 tejbeer 24
import com.spice.profitmandi.dao.repository.fofo.PartnerTypeChangeService;
29900 amit.gupta 25
import com.spice.profitmandi.service.NotificationService;
29785 amit.gupta 26
import com.spice.profitmandi.service.authentication.RoleManager;
33043 amit.gupta 27
import com.spice.profitmandi.service.catalog.BrandsService;
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;
124
 
32505 amit.gupta 125
    @RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
126
    public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
127
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
128
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
129
                .collect(Collectors.toList());
27391 tejbeer 130
 
33713 tejus.loha 131
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
32505 amit.gupta 132
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
33615 amit.gupta 133
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.SMART_WATCH_CATEGORY_ID));
32505 amit.gupta 134
        //Lets allow demo
135
        brands.add("Live Demo");
27391 tejbeer 136
 
32505 amit.gupta 137
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
27876 amit.gupta 138
 
32505 amit.gupta 139
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
140
                .filter(x -> x != null).collect(Collectors.toList()).stream()
141
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
32204 amit.gupta 142
 
32505 amit.gupta 143
        model.addAttribute("customRetailersMap", customRetailersMap);
144
        model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
145
        model.addAttribute("brands", brands);
146
        model.addAttribute("partnerCategories", PartnerType.values());
147
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
148
        return "scheme_offer";
27391 tejbeer 149
 
32505 amit.gupta 150
    }
29926 amit.gupta 151
 
32505 amit.gupta 152
    @RequestMapping(value = "/createOffer", method = RequestMethod.POST)
153
    public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
154
                              Model model) throws Exception {
155
        LOGGER.info("createOfferRequest [{}]", createOfferRequest);
156
        offerService.addOfferService(createOfferRequest);
32868 amit.gupta 157
        oneDayCacheManager.getCache("allOffers").evict(YearMonth.from(createOfferRequest.getStartDate()));
32505 amit.gupta 158
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
159
        return "response";
27391 tejbeer 160
 
32505 amit.gupta 161
    }
27391 tejbeer 162
 
32505 amit.gupta 163
    @RequestMapping(value = "/offers/published", method = RequestMethod.GET)
164
    public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
165
            throws Exception {
166
        LOGGER.info("Published");
167
        offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
168
        return "scheme_offer/published";
27391 tejbeer 169
 
32505 amit.gupta 170
    }
27391 tejbeer 171
 
32868 amit.gupta 172
    @Value("${prod}")
173
    private boolean isProd;
174
 
32505 amit.gupta 175
    @RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
176
    public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
177
                                Model model, @RequestParam(defaultValue = "true") boolean active)
178
            throws ProfitMandiBusinessException, Exception {
179
        List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
180
                .collect(Collectors.toList());
181
        List<Offer> offers = offerRepository.selectAllByIds(offerIds);
32868 amit.gupta 182
 
183
        //Consider only offers that have opposite status
184
        offers = offers.stream().filter(x -> x.isActive() != active).collect(Collectors.toList());
185
 
186
        Set<YearMonth> yearMonthsToEvict = new HashSet<>();
32505 amit.gupta 187
        for (Offer offer : offers) {
32868 amit.gupta 188
            offer.setActive(active);
189
            yearMonthsToEvict.add(YearMonth.from(offer.getStartDate()));
32505 amit.gupta 190
        }
32868 amit.gupta 191
        //Evict caches
192
        for (YearMonth ymToEvict : yearMonthsToEvict) {
193
            oneDayCacheManager.getCache("catalog.published_yearmonth").evict(ymToEvict);
194
            oneDayCacheManager.getCache("allOffers").evict(ymToEvict);
32505 amit.gupta 195
        }
32868 amit.gupta 196
        if (active) {
197
            for (Offer offer : offers) {
32505 amit.gupta 198
                this.sendNotification(offer);
199
            }
200
        }
32868 amit.gupta 201
 
202
 
32505 amit.gupta 203
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
204
        return "response";
205
    }
27391 tejbeer 206
 
32505 amit.gupta 207
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
208
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
209
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
210
        Offer offer = offerRepository.selectById(offerId);
211
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
212
        // return "response";
213
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
214
        Map<String, Object> model1 = new HashMap<>();
215
        model1.put("offer", createOfferRequest);
216
        model1.put("lessThan", "<");
217
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
218
        model.addAttribute("response1", htmlContent);
219
        return "response";
220
    }
29900 amit.gupta 221
 
32505 amit.gupta 222
    private void sendNotification(Offer offer) throws Exception {
223
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
224
            return;
225
        }
226
        String fileName = "offer-" + offer.getId() + ".png";
32868 amit.gupta 227
        //String htmlFileName = fileName.replace("png", "html");
32505 amit.gupta 228
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
229
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
230
        sendNotificationModel.setCampaignName("SchemeOffer");
231
        sendNotificationModel.setTitle(offer.getName());
232
        sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
233
                + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
234
                + FormattingUtils.formatDateMonth(offer.getEndDate()));
235
        sendNotificationModel.setType("url");
236
        String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
237
        sendNotificationModel.setImageUrl(imageUrl);
238
        sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
239
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
240
        sendNotificationModel.setMessageType(MessageType.scheme);
34137 amit.gupta 241
        //Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
29900 amit.gupta 242
 
32505 amit.gupta 243
        Map<String, InputStream> fileStreamsMap = new HashMap<>();
244
        Map<String, Object> model = new HashMap<>();
245
        model.put("offer", createOfferRequest);
246
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
247
        LOGGER.info("this.getContentFromTemplate {}", htmlContent);
248
        fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
249
        // fileStreamsMap.put(htmlFileName, new
250
        // ByteArrayInputStream(htmlContent.getBytes()));
251
        List<Integer> fofoIds = null;
32868 amit.gupta 252
        if (isProd) {
253
            this.uploadFile(fileStreamsMap);
254
        }
29900 amit.gupta 255
 
33043 amit.gupta 256
        List<Integer> fofoIdSet = new ArrayList<>(offerRepository.getEligibleFofoIds(offer));
34137 amit.gupta 257
        //LOGGER.info(fofoIdSet);
33043 amit.gupta 258
        List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(new ArrayList<>(fofoIdSet));
259
        sendNotificationModel.setUserIds(userIds);
260
        notificationService.sendNotification(sendNotificationModel);
261
        sendWhatsapp(offer, fofoIds, imageUrl);
262
 
32505 amit.gupta 263
    }
27876 amit.gupta 264
 
32505 amit.gupta 265
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
266
        if (fofoIds == null) {
267
            fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId()).collect(Collectors.toList());
268
        }
269
        final List<Integer> finalFofoIds = fofoIds;
32532 amit.gupta 270
        //List<String> mobileNumbers = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> finalFofoIds.contains(x.getKey())).map(x -> x.getValue().getMobileNumber()).collect(Collectors.toList());
271
        List<String> mobileNumbers = new ArrayList<>();
272
        mobileNumbers.add("9911565032");
32505 amit.gupta 273
        String message = "%s\n" +
274
                "On %s of select models\n" +
275
                "From %s to %s\n" +
276
                "\n" +
277
                "Happy Selling\n" +
278
                "Team Smartdukaan";
32510 amit.gupta 279
        //TV's mobile
32505 amit.gupta 280
        for (String mobileNumber : mobileNumbers) {
32855 amit.gupta 281
            notificationService.sendWhatsappMediaMessage(String.format(message, offer.getName(),
282
                    offer.getSchemeType().toString(), FormattingUtils.formatDate(offer.getStartDate()),
283
                    FormattingUtils.formatDate(offer.getEndDate())), mobileNumber, imageUrl, "offer-" + offer.getId() + ".png", WhatsappMessageType.IMAGE);
32505 amit.gupta 284
        }
285
    }
27391 tejbeer 286
 
32505 amit.gupta 287
    private InputStream asInputStream(BufferedImage bi) throws Exception {
288
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
289
        ImageIO.write(bi, "png", baos);
290
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 291
 
32505 amit.gupta 292
    }
27391 tejbeer 293
 
32505 amit.gupta 294
    private ChannelSftp setupJsch() throws JSchException {
295
        JSch jsch = new JSch();
33471 amit.gupta 296
        Session jschSession = jsch.getSession("root", "172.105.58.16");
32505 amit.gupta 297
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
298
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
299
                getClass().getClassLoader().getResource("id_rsa").getPath());
300
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
301
        // jschSession.setPassword("spic@2015static0");
302
        jschSession.setConfig("StrictHostKeyChecking", "no");
303
        jschSession.connect();
304
        return (ChannelSftp) jschSession.openChannel("sftp");
305
    }
30426 tejbeer 306
 
32505 amit.gupta 307
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
308
            throws SftpException, FileNotFoundException {
27391 tejbeer 309
 
32505 amit.gupta 310
        channelSftp.cd(destinationPath);
311
        String folderName = "image" + LocalDate.now();
27391 tejbeer 312
 
32505 amit.gupta 313
        channelSftp.cd(destinationPath);
314
        SftpATTRS attrs = null;
27391 tejbeer 315
 
32505 amit.gupta 316
        // check if the directory is already existing
317
        try {
318
            attrs = channelSftp.stat(folderName);
319
        } catch (Exception e) {
320
            System.out.println(destinationPath + "/" + folderName + " not found");
321
        }
27391 tejbeer 322
 
32505 amit.gupta 323
        // else create a directory
324
        if (attrs == null) {
325
            channelSftp.mkdir(folderName);
326
            channelSftp.chmod(0755, ".");
327
        }
328
        channelSftp.cd(folderName);
27391 tejbeer 329
 
32505 amit.gupta 330
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
331
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
332
        }
27391 tejbeer 333
 
32505 amit.gupta 334
    }
29926 amit.gupta 335
 
32505 amit.gupta 336
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
337
        ChannelSftp channelSftp = setupJsch();
338
        channelSftp.connect();
339
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
340
        channelSftp.exit();
341
    }
27391 tejbeer 342
 
32505 amit.gupta 343
    private InputStream getImageBuffer(String html) throws Exception {
29900 amit.gupta 344
 
32505 amit.gupta 345
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
346
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
347
        String address = "file:" + fileName;
348
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
349
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
350
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
351
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
352
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
353
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
354
        renderer.setRenderingHints(hints);
355
        BufferedImage img = renderer.getImage();
356
        ByteArrayOutputStream os = new ByteArrayOutputStream();
357
        ImageIO.write(img, "png", os);
358
        return new ByteArrayInputStream(os.toByteArray());
359
    }
29926 amit.gupta 360
 
32505 amit.gupta 361
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
362
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
363
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
364
        MockHttpServletRequest req = new MockHttpServletRequest();
365
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
366
        resolvedView.render(model, req, mockResp);
367
        return mockResp.getContentAsString();
368
    }
29926 amit.gupta 369
 
32505 amit.gupta 370
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
371
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
372
            throws ProfitMandiBusinessException {
30017 amit.gupta 373
 
32505 amit.gupta 374
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
375
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
376
        model.addAttribute("offers", publishedOffers);
377
        model.addAttribute("yearMonth", yearMonth);
378
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 379
 
32505 amit.gupta 380
        return "offer_history";
381
    }
30723 amit.gupta 382
 
32505 amit.gupta 383
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
384
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
385
            throws ProfitMandiBusinessException {
386
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 387
 
32505 amit.gupta 388
        model.addAttribute("offer", createOfferRequest);
389
        return "offer-details";
390
    }
29926 amit.gupta 391
 
32505 amit.gupta 392
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
393
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
394
            throws Exception {
395
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
396
        if (!createOfferRequest.isActive()) {
397
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
398
        }
399
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
400
            offerService.processSellin(createOfferRequest);
401
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
402
            offerService.processActivationtOffer(createOfferRequest);
403
        }
404
        return responseSender.ok(true);
405
    }
29926 amit.gupta 406
 
32505 amit.gupta 407
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
408
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
409
            throws Exception {
410
        final HttpHeaders headers = new HttpHeaders();
411
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
412
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
413
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
33999 tejus.loha 414
        ByteArrayOutputStream baos = offerService.createCSVOfferReport(createOfferRequest);
32505 amit.gupta 415
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
416
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
417
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
418
    }
29900 amit.gupta 419
 
32505 amit.gupta 420
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
421
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
422
        Offer offer = offerRepository.selectById(offerId);
423
        model.addAttribute("offer", offer);
424
        return "offer-edit";
29900 amit.gupta 425
 
32505 amit.gupta 426
    }
29900 amit.gupta 427
 
32505 amit.gupta 428
    @RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
429
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
430
            throws ProfitMandiBusinessException {
431
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
432
        int fofoId = loginDetails.getFofoId();
433
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
434
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 435
 
32505 amit.gupta 436
        model.addAttribute("publishedOffers", createOffers);
29926 amit.gupta 437
 
32505 amit.gupta 438
        return "published-offers";
439
    }
29926 amit.gupta 440
 
32505 amit.gupta 441
    @PostMapping(value = "/offers/upload")
442
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
443
            throws Exception {
444
        offerService.createOffers(targetFile.getInputStream());
445
        model.addAttribute("response1", true);
446
        return "response";
447
    }
29926 amit.gupta 448
 
32505 amit.gupta 449
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
450
    public String getOfferMargins(HttpServletRequest request,
451
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
452
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
453
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
454
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 455
 
32505 amit.gupta 456
        model.addAttribute("offer", createOfferRequest);
29900 amit.gupta 457
 
32505 amit.gupta 458
        return "offer_margin_detail_partner";
30470 amit.gupta 459
 
32505 amit.gupta 460
    }
29900 amit.gupta 461
 
27895 amit.gupta 462
}