Subversion Repositories SmartDukaan

Rev

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