Subversion Repositories SmartDukaan

Rev

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