Subversion Repositories SmartDukaan

Rev

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