Subversion Repositories SmartDukaan

Rev

Rev 32204 | Rev 32510 | 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";
27391 tejbeer 284
 
32505 amit.gupta 285
        for (String mobileNumber : mobileNumbers) {
286
            notificationService.sendWhatsappMediaMessage(String.format(message, offer.getName(), offer.getSchemeType().toString(), FormattingUtils.formatDate(offer.getStartDate()), FormattingUtils.formatDate(offer.getEndDate())), mobileNumber, imageUrl, "offer-" + offer.getId() + ".png");
287
        }
288
    }
27391 tejbeer 289
 
32505 amit.gupta 290
    private InputStream asInputStream(BufferedImage bi) throws Exception {
291
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
292
        ImageIO.write(bi, "png", baos);
293
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 294
 
32505 amit.gupta 295
    }
27391 tejbeer 296
 
32505 amit.gupta 297
    private ChannelSftp setupJsch() throws JSchException {
298
        JSch jsch = new JSch();
299
        Session jschSession = jsch.getSession("root", "192.168.179.131");
300
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
301
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
302
                getClass().getClassLoader().getResource("id_rsa").getPath());
303
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
304
        // jschSession.setPassword("spic@2015static0");
305
        jschSession.setConfig("StrictHostKeyChecking", "no");
306
        jschSession.connect();
307
        return (ChannelSftp) jschSession.openChannel("sftp");
308
    }
30426 tejbeer 309
 
32505 amit.gupta 310
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
311
            throws SftpException, FileNotFoundException {
27391 tejbeer 312
 
32505 amit.gupta 313
        channelSftp.cd(destinationPath);
314
        String folderName = "image" + LocalDate.now();
27391 tejbeer 315
 
32505 amit.gupta 316
        channelSftp.cd(destinationPath);
317
        SftpATTRS attrs = null;
27391 tejbeer 318
 
32505 amit.gupta 319
        // check if the directory is already existing
320
        try {
321
            attrs = channelSftp.stat(folderName);
322
        } catch (Exception e) {
323
            System.out.println(destinationPath + "/" + folderName + " not found");
324
        }
27391 tejbeer 325
 
32505 amit.gupta 326
        // else create a directory
327
        if (attrs == null) {
328
            channelSftp.mkdir(folderName);
329
            channelSftp.chmod(0755, ".");
330
        }
331
        channelSftp.cd(folderName);
27391 tejbeer 332
 
32505 amit.gupta 333
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
334
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
335
        }
27391 tejbeer 336
 
32505 amit.gupta 337
    }
29926 amit.gupta 338
 
32505 amit.gupta 339
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
340
        ChannelSftp channelSftp = setupJsch();
341
        channelSftp.connect();
342
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
343
        channelSftp.exit();
344
    }
27391 tejbeer 345
 
32505 amit.gupta 346
    private InputStream getImageBuffer(String html) throws Exception {
29900 amit.gupta 347
 
32505 amit.gupta 348
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
349
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
350
        String address = "file:" + fileName;
351
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
352
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
353
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
354
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
355
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
356
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
357
        renderer.setRenderingHints(hints);
358
        BufferedImage img = renderer.getImage();
359
        ByteArrayOutputStream os = new ByteArrayOutputStream();
360
        ImageIO.write(img, "png", os);
361
        return new ByteArrayInputStream(os.toByteArray());
362
    }
29926 amit.gupta 363
 
32505 amit.gupta 364
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
365
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
366
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
367
        MockHttpServletRequest req = new MockHttpServletRequest();
368
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
369
        resolvedView.render(model, req, mockResp);
370
        return mockResp.getContentAsString();
371
    }
29926 amit.gupta 372
 
32505 amit.gupta 373
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
374
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
375
            throws ProfitMandiBusinessException {
30017 amit.gupta 376
 
32505 amit.gupta 377
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
378
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
379
        model.addAttribute("offers", publishedOffers);
380
        model.addAttribute("yearMonth", yearMonth);
381
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 382
 
32505 amit.gupta 383
        return "offer_history";
384
    }
30723 amit.gupta 385
 
32505 amit.gupta 386
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
387
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
388
            throws ProfitMandiBusinessException {
389
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 390
 
32505 amit.gupta 391
        model.addAttribute("offer", createOfferRequest);
392
        return "offer-details";
393
    }
29926 amit.gupta 394
 
32505 amit.gupta 395
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
396
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
397
            throws Exception {
398
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
399
        if (!createOfferRequest.isActive()) {
400
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
401
        }
402
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
403
            offerService.processSellin(createOfferRequest);
404
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
405
            offerService.processActivationtOffer(createOfferRequest);
406
        }
407
        return responseSender.ok(true);
408
    }
29926 amit.gupta 409
 
32505 amit.gupta 410
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
411
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
412
            throws Exception {
413
        List<List<?>> listOfRows = new ArrayList<>();
414
        final HttpHeaders headers = new HttpHeaders();
415
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
416
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
417
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
418
        Collection<OfferRowModel> offerRowModels = offerRepository.getOfferRows(createOfferRequest);
419
        ByteArrayOutputStream baos = null;
420
        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
421
            for (OfferRowModel offerRowModel : offerRowModels) {
422
                CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
423
                listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
424
                        createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
425
                        createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
426
                        "--", createOfferRequest.getItemCriteriaString(),
427
                        createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
428
                        createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
429
                        customRetailer.getCode(), offerRowModel.getTotalBasePurchaseValue(), offerRowModel.getAchievedTarget(),
430
                        offerRowModel.getPayoutPurchaseValue(), offerRowModel.getPayout(), offerRowModel.getPayoutType(), offerRowModel.getFinalPayout(), String.join(", ", offerRowModel.getEligibleImeis())));
431
            }
432
            baos = FileUtil.getCSVByteStream(
433
                    Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
434
                            "Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
435
                            "Base Purchase", "Achieved Target", "Eligible Purchase", "Slab Amount", "Slab Amount Type", "Payout Value(Rs.)",
436
                            "Eligible IMEIs", "Billing Pending Imeis"
437
                    ), listOfRows);
438
        } else {
439
            for (OfferRowModel offerRowModel : offerRowModels) {
440
                CustomRetailer customRetailer = retailerService.getFofoRetailer(offerRowModel.getFofoId());
441
                listOfRows.add(Arrays.asList(createOfferRequest.getId(), createOfferRequest.getName(),
442
                        createOfferRequest.getTargetType(), createOfferRequest.getSchemeType(),
443
                        createOfferRequest.getBrandShareTerms(), createOfferRequest.getSellinPercentage(),
444
                        createOfferRequest.getPartnerCriteriaString(), createOfferRequest.getItemCriteriaString(),
445
                        createOfferRequest.getStartDate(), createOfferRequest.getEndDate(),
446
                        createOfferRequest.getCreatedOn(), customRetailer.getPartnerId(), customRetailer.getBusinessName(),
447
                        customRetailer.getCode(),
29900 amit.gupta 448
 
32505 amit.gupta 449
                        offerRowModel.getTotalSale(),
450
                        offerRowModel.getEligibleSale(),
451
                        offerRowModel.getPayoutTargetAchieved(),
452
                        offerRowModel.getPayoutValue(),
453
                        offerRowModel.getPayoutType(),
454
                        offerRowModel.getPayoutValueDp(), offerRowModel.getFinalPayout(),
455
                        String.join(", ", offerRowModel.getEligibleImeis()),
456
                        String.join(", ", offerRowModel.getBaseCriteria()))
457
                );
458
            }
459
            baos = FileUtil.getCSVByteStream(
460
                    Arrays.asList("Id", "Name", "Target Type", "Scheme Type", "Brand %", "Sellin %", "Partner Criteria",
461
                            "Item Criteria", "Start", "End", "Created", "Partner Id", "Partner Name", "Partner Code",
29900 amit.gupta 462
 
32505 amit.gupta 463
                            "Total Value",
464
                            "Eligible Value",
465
                            "Payout Target Achieved", "Payout Amount", "Payout Amount Type",
466
                            "Payout Value DP", "Amount to be credited", "Eligible Activated Imeis"
467
                    ), listOfRows);
468
        }
469
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
470
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
471
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
472
    }
29900 amit.gupta 473
 
32505 amit.gupta 474
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
475
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
476
        Offer offer = offerRepository.selectById(offerId);
29900 amit.gupta 477
 
32505 amit.gupta 478
        model.addAttribute("offer", offer);
29900 amit.gupta 479
 
32505 amit.gupta 480
        return "offer-edit";
29900 amit.gupta 481
 
32505 amit.gupta 482
    }
29900 amit.gupta 483
 
32505 amit.gupta 484
    @RequestMapping(value = "/published-offers/{yearMonth}", method = RequestMethod.GET)
485
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @PathVariable int yearMonth, Model model)
486
            throws ProfitMandiBusinessException {
487
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
488
        int fofoId = loginDetails.getFofoId();
489
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
490
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 491
 
32505 amit.gupta 492
        model.addAttribute("publishedOffers", createOffers);
29926 amit.gupta 493
 
32505 amit.gupta 494
        return "published-offers";
495
    }
29926 amit.gupta 496
 
32505 amit.gupta 497
    @PostMapping(value = "/offers/upload")
498
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
499
            throws Exception {
500
        offerService.createOffers(targetFile.getInputStream());
501
        model.addAttribute("response1", true);
502
        return "response";
503
    }
29926 amit.gupta 504
 
32505 amit.gupta 505
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
506
    public String getOfferMargins(HttpServletRequest request,
507
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
508
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
509
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
510
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 511
 
32505 amit.gupta 512
        model.addAttribute("offer", createOfferRequest);
29900 amit.gupta 513
 
32505 amit.gupta 514
        return "offer_margin_detail_partner";
30470 amit.gupta 515
 
32505 amit.gupta 516
    }
29900 amit.gupta 517
 
27895 amit.gupta 518
}