Subversion Repositories SmartDukaan

Rev

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