Subversion Repositories SmartDukaan

Rev

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