Subversion Repositories SmartDukaan

Rev

Rev 36521 | 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
 
35923 aman 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;
29904 amit.gupta 10
import com.spice.profitmandi.common.util.FormattingUtils;
27876 amit.gupta 11
import com.spice.profitmandi.common.web.util.ResponseSender;
35501 ranu 12
import com.spice.profitmandi.dao.entity.catalog.BrandCatalog;
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;
34176 tejus.loha 18
import com.spice.profitmandi.dao.model.ItemCriteriaPayout;
35501 ranu 19
import com.spice.profitmandi.dao.model.TodayOfferModel;
35923 aman 20
import com.spice.profitmandi.dao.repository.catalog.CatalogRepository;
21
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
22
import com.spice.profitmandi.dao.repository.catalog.OfferMarginRepository;
23
import com.spice.profitmandi.dao.repository.catalog.OfferRepository;
27391 tejbeer 24
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
29926 amit.gupta 25
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
29900 amit.gupta 26
import com.spice.profitmandi.service.NotificationService;
29785 amit.gupta 27
import com.spice.profitmandi.service.authentication.RoleManager;
33043 amit.gupta 28
import com.spice.profitmandi.service.catalog.BrandsService;
34176 tejus.loha 29
import com.spice.profitmandi.service.offers.ItemCriteria;
36344 amit 30
import com.spice.profitmandi.service.offers.OfferBatchService;
27876 amit.gupta 31
import com.spice.profitmandi.service.offers.OfferService;
35923 aman 32
import com.spice.profitmandi.service.offers.PartnerCriteria;
35501 ranu 33
import com.spice.profitmandi.service.offers.TodayOfferService;
27391 tejbeer 34
import com.spice.profitmandi.service.user.RetailerService;
35
import com.spice.profitmandi.web.model.LoginDetails;
36
import com.spice.profitmandi.web.util.CookiesProcessor;
37
import com.spice.profitmandi.web.util.MVCResponseSender;
29943 amit.gupta 38
import org.apache.commons.io.FileUtils;
39
import org.apache.commons.io.output.ByteArrayOutputStream;
40
import org.apache.logging.log4j.LogManager;
41
import org.apache.logging.log4j.Logger;
42
import org.springframework.beans.factory.annotation.Autowired;
32868 amit.gupta 43
import org.springframework.beans.factory.annotation.Value;
29943 amit.gupta 44
import org.springframework.core.io.InputStreamResource;
45
import org.springframework.http.HttpHeaders;
46
import org.springframework.http.HttpStatus;
47
import org.springframework.http.ResponseEntity;
32204 amit.gupta 48
import org.springframework.mock.web.MockHttpServletRequest;
49
import org.springframework.mock.web.MockHttpServletResponse;
29943 amit.gupta 50
import org.springframework.stereotype.Controller;
35501 ranu 51
import org.springframework.transaction.annotation.Transactional;
29943 amit.gupta 52
import org.springframework.ui.Model;
53
import org.springframework.web.bind.annotation.*;
54
import org.springframework.web.multipart.MultipartFile;
32204 amit.gupta 55
import org.springframework.web.servlet.View;
56
import org.springframework.web.servlet.ViewResolver;
29943 amit.gupta 57
import org.xhtmlrenderer.swing.Java2DRenderer;
27391 tejbeer 58
 
29943 amit.gupta 59
import javax.imageio.ImageIO;
60
import javax.servlet.http.HttpServletRequest;
61
import java.awt.*;
62
import java.awt.image.BufferedImage;
63
import java.io.ByteArrayInputStream;
64
import java.io.File;
65
import java.io.FileNotFoundException;
66
import java.io.InputStream;
33713 tejus.loha 67
import java.time.Instant;
68
import java.time.LocalDate;
69
import java.time.LocalDateTime;
70
import java.time.YearMonth;
35923 aman 71
import java.util.*;
35501 ranu 72
import java.util.List;
29943 amit.gupta 73
import java.util.stream.Collectors;
74
 
27391 tejbeer 75
@Controller
35458 amit 76
@Transactional(rollbackFor = Throwable.class)
27391 tejbeer 77
public class OfferController {
32505 amit.gupta 78
    private static final Logger LOGGER = LogManager.getLogger(OfferController.class);
79
    private static final String IMAGE_REMOTE_DIR = "/var/www/dtrdashboard/uploads/campaigns/";
80
    private static final String IMAGE_STATIC_SERVER_URL = "https://images.smartdukaan.com/uploads/campaigns";
81
    @Autowired
82
    UserAccountRepository userAccountRepository;
83
    @Autowired
84
    RoleManager roleManager;
85
    @Autowired
86
    private OfferRepository offerRepository;
87
    @Autowired
88
    private OfferMarginRepository offerMarginRepository;
89
    @Autowired
90
    private FofoStoreRepository fofoStoreRepository;
91
    @Autowired
92
    private ResponseSender responseSender;
93
    @Autowired
94
    private ViewResolver viewResolver;
95
    @Autowired
96
    private ItemRepository itemRepository;
97
    @Autowired
98
    private MVCResponseSender mvcResponseSender;
99
    @Autowired
100
    private RetailerService retailerService;
101
    @Autowired
102
    private NotificationService notificationService;
103
    @Autowired
104
    private CookiesProcessor cookiesProcessor;
105
    @Autowired
106
    private OfferService offerService;
27391 tejbeer 107
 
33043 amit.gupta 108
    @Autowired
36344 amit 109
    private OfferBatchService offerBatchService;
110
 
111
    @Autowired
35893 amit 112
    private Gson gson;
113
 
114
    @Autowired
33043 amit.gupta 115
    BrandsService brandsService;
34553 amit.gupta 116
 
34552 amit.gupta 117
    @Autowired
118
    private CatalogRepository catalogRepository;
33043 amit.gupta 119
 
35501 ranu 120
    @Autowired
121
    TodayOfferService todayOfferService;
122
 
32505 amit.gupta 123
    @RequestMapping(value = "/getCreateOffer", method = RequestMethod.GET)
124
    public String getCreateOffer(HttpServletRequest request, Model model) throws ProfitMandiBusinessException {
125
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
126
        List<Integer> fofoIds = fofoStoreRepository.selectActiveStores().stream().map(x -> x.getId())
127
                .collect(Collectors.toList());
27391 tejbeer 128
 
33713 tejus.loha 129
        Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
32505 amit.gupta 130
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
33615 amit.gupta 131
        brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.SMART_WATCH_CATEGORY_ID));
32505 amit.gupta 132
        //Lets allow demo
133
        brands.add("Live Demo");
27391 tejbeer 134
 
32505 amit.gupta 135
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
27876 amit.gupta 136
 
32505 amit.gupta 137
        Map<Integer, CustomRetailer> customRetailersMap = fofoIds.stream().map(x -> customRetailerMap.get(x))
138
                .filter(x -> x != null).collect(Collectors.toList()).stream()
139
                .collect(Collectors.toMap(x -> x.getPartnerId(), x -> x));
32204 amit.gupta 140
 
32505 amit.gupta 141
        model.addAttribute("customRetailersMap", customRetailersMap);
142
        model.addAttribute("itemCriteriaType", ItemCriteriaType.values());
143
        model.addAttribute("brands", brands);
144
        model.addAttribute("partnerCategories", PartnerType.values());
145
        model.addAttribute("warehouseRegion", ProfitMandiConstants.WAREHOUSE_MAP);
146
        return "scheme_offer";
27391 tejbeer 147
 
32505 amit.gupta 148
    }
29926 amit.gupta 149
 
32505 amit.gupta 150
    @RequestMapping(value = "/createOffer", method = RequestMethod.POST)
151
    public String createOffer(HttpServletRequest request, @RequestBody CreateOfferRequest createOfferRequest,
152
                              Model model) throws Exception {
153
        LOGGER.info("createOfferRequest [{}]", createOfferRequest);
154
        offerService.addOfferService(createOfferRequest);
36050 amit 155
        offerService.evictOfferCaches(createOfferRequest.getId());
32505 amit.gupta 156
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
157
        return "response";
27391 tejbeer 158
 
32505 amit.gupta 159
    }
27391 tejbeer 160
 
32505 amit.gupta 161
    @RequestMapping(value = "/offers/published", method = RequestMethod.GET)
162
    public String getPublishedOffers(HttpServletRequest request, @RequestParam int fofoId, Model model)
163
            throws Exception {
164
        LOGGER.info("Published");
165
        offerService.getPublishedOffers(fofoId, YearMonth.from(LocalDateTime.now()));
166
        return "scheme_offer/published";
27391 tejbeer 167
 
32505 amit.gupta 168
    }
27391 tejbeer 169
 
32868 amit.gupta 170
    @Value("${prod}")
171
    private boolean isProd;
172
 
32505 amit.gupta 173
    @RequestMapping(value = "/offer/active/{offerId}", method = RequestMethod.GET)
174
    public String activateOffer(HttpServletRequest request, @PathVariable(name = "offerId") String offerIdsString,
175
                                Model model, @RequestParam(defaultValue = "true") boolean active)
176
            throws ProfitMandiBusinessException, Exception {
177
        List<Integer> offerIds = Arrays.stream(offerIdsString.split(",")).map(x -> Integer.parseInt(x))
178
                .collect(Collectors.toList());
32868 amit.gupta 179
 
36634 amit 180
        // REQUIRES_NEW: commits active flag to DB before cache eviction
181
        List<Offer> offers = offerService.activateOffers(offerIds, active);
32868 amit.gupta 182
 
32505 amit.gupta 183
        for (Offer offer : offers) {
36050 amit 184
            offerService.evictOfferCaches(offer.getId());
32505 amit.gupta 185
        }
32868 amit.gupta 186
        if (active) {
187
            for (Offer offer : offers) {
36634 amit 188
                try {
189
                    this.sendNotification(offer);
190
                } catch (Exception e) {
191
                    LOGGER.error("Notification failed for offer {}", offer.getId(), e);
192
                }
32505 amit.gupta 193
            }
194
        }
32868 amit.gupta 195
 
32505 amit.gupta 196
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
197
        return "response";
198
    }
27391 tejbeer 199
 
35857 amit 200
    @RequestMapping(value = "/offers/publishAll", method = RequestMethod.POST)
201
    public ResponseEntity<?> publishAllUnpublished(@RequestParam YearMonth yearMonth)
202
            throws ProfitMandiBusinessException, Exception {
203
        List<Offer> published = offerService.publishAllUnpublished(yearMonth);
204
        if (!published.isEmpty()) {
205
            for (Offer offer : published) {
36050 amit 206
                offerService.evictOfferCaches(offer.getId());
36634 amit 207
                try {
208
                    this.sendNotification(offer);
209
                } catch (Exception e) {
210
                    LOGGER.error("Notification failed for offer {}", offer.getId(), e);
211
                }
35857 amit 212
            }
213
        }
214
        return responseSender.ok(published.size() + " offers published");
215
    }
216
 
217
    @RequestMapping(value = "/offer/delete/{offerId}", method = RequestMethod.DELETE)
218
    public ResponseEntity<?> deleteOffer(@PathVariable int offerId) throws ProfitMandiBusinessException {
219
        offerService.deleteOffer(offerId);
220
        return responseSender.ok(true);
221
    }
222
 
32505 amit.gupta 223
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
224
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
225
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
226
        Offer offer = offerRepository.selectById(offerId);
227
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
228
        // return "response";
229
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
230
        Map<String, Object> model1 = new HashMap<>();
231
        model1.put("offer", createOfferRequest);
232
        model1.put("lessThan", "<");
233
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
234
        model.addAttribute("response1", htmlContent);
235
        return "response";
236
    }
29900 amit.gupta 237
 
32505 amit.gupta 238
    private void sendNotification(Offer offer) throws Exception {
239
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
240
            return;
241
        }
242
        String fileName = "offer-" + offer.getId() + ".png";
32868 amit.gupta 243
        //String htmlFileName = fileName.replace("png", "html");
32505 amit.gupta 244
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
34620 amit.gupta 245
        boolean isLiveDemo = createOfferRequest.getTargetSlabs().stream()
246
                .map(x -> x.getItemCriteriaPayouts())
247
                .flatMap(List::stream)
248
                .map(ItemCriteriaPayout::getItemCriteria)
249
                .map(ItemCriteria::getCatalogIds)
250
                .flatMap(List::stream)
251
                .anyMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"));
252
        if (!isLiveDemo) {
253
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
254
            sendNotificationModel.setCampaignName("SchemeOffer");
255
            sendNotificationModel.setTitle(offer.getName());
256
            sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
257
                    + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
258
                    + FormattingUtils.formatDateMonth(offer.getEndDate()));
259
            sendNotificationModel.setType("url");
260
            String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
261
            sendNotificationModel.setImageUrl(imageUrl);
262
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
263
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
264
            sendNotificationModel.setMessageType(MessageType.scheme);
265
            //Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
29900 amit.gupta 266
 
34620 amit.gupta 267
            Map<String, InputStream> fileStreamsMap = new HashMap<>();
268
            Map<String, Object> model = new HashMap<>();
269
            model.put("offer", createOfferRequest);
270
            String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
271
            LOGGER.info("this.getContentFromTemplate {}", htmlContent);
272
            fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
273
            // fileStreamsMap.put(htmlFileName, new
274
            // ByteArrayInputStream(htmlContent.getBytes()));
275
            List<Integer> fofoIds = null;
276
            if (isProd) {
277
                this.uploadFile(fileStreamsMap);
278
            }
279
 
280
            List<Integer> fofoIdSet = new ArrayList<>(offerRepository.getEligibleFofoIds(offer));
281
            //LOGGER.info(fofoIdSet);
282
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(new ArrayList<>(fofoIdSet));
283
            sendNotificationModel.setUserIds(userIds);
284
            notificationService.sendNotification(sendNotificationModel);
285
            sendWhatsapp(offer, fofoIds, imageUrl);
32868 amit.gupta 286
        }
32505 amit.gupta 287
    }
27876 amit.gupta 288
 
32505 amit.gupta 289
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
35205 amit 290
        offerService.sendWhatsapp(offer, fofoIds, imageUrl);
32505 amit.gupta 291
    }
27391 tejbeer 292
 
32505 amit.gupta 293
    private InputStream asInputStream(BufferedImage bi) throws Exception {
294
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
295
        ImageIO.write(bi, "png", baos);
296
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 297
 
32505 amit.gupta 298
    }
27391 tejbeer 299
 
32505 amit.gupta 300
    private ChannelSftp setupJsch() throws JSchException {
301
        JSch jsch = new JSch();
33471 amit.gupta 302
        Session jschSession = jsch.getSession("root", "172.105.58.16");
32505 amit.gupta 303
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
304
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
305
                getClass().getClassLoader().getResource("id_rsa").getPath());
306
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
307
        // jschSession.setPassword("spic@2015static0");
308
        jschSession.setConfig("StrictHostKeyChecking", "no");
309
        jschSession.connect();
310
        return (ChannelSftp) jschSession.openChannel("sftp");
311
    }
30426 tejbeer 312
 
32505 amit.gupta 313
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
314
            throws SftpException, FileNotFoundException {
27391 tejbeer 315
 
32505 amit.gupta 316
        channelSftp.cd(destinationPath);
317
        String folderName = "image" + LocalDate.now();
27391 tejbeer 318
 
32505 amit.gupta 319
        channelSftp.cd(destinationPath);
320
        SftpATTRS attrs = null;
27391 tejbeer 321
 
32505 amit.gupta 322
        // check if the directory is already existing
323
        try {
324
            attrs = channelSftp.stat(folderName);
325
        } catch (Exception e) {
326
            System.out.println(destinationPath + "/" + folderName + " not found");
327
        }
27391 tejbeer 328
 
32505 amit.gupta 329
        // else create a directory
330
        if (attrs == null) {
331
            channelSftp.mkdir(folderName);
332
            channelSftp.chmod(0755, ".");
333
        }
334
        channelSftp.cd(folderName);
27391 tejbeer 335
 
32505 amit.gupta 336
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
337
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
338
        }
27391 tejbeer 339
 
32505 amit.gupta 340
    }
29926 amit.gupta 341
 
32505 amit.gupta 342
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
343
        ChannelSftp channelSftp = setupJsch();
344
        channelSftp.connect();
345
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
346
        channelSftp.exit();
347
    }
27391 tejbeer 348
 
32505 amit.gupta 349
    private InputStream getImageBuffer(String html) throws Exception {
35923 aman 350
        // Sanitize HTML to valid XHTML for Flying Saucer (Java2DRenderer requires well-formed XML)
351
        org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(html);
352
        doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
353
        doc.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
354
        doc.outputSettings().charset("UTF-8");
355
        html = doc.html();
29900 amit.gupta 356
 
32505 amit.gupta 357
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
358
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
359
        String address = "file:" + fileName;
360
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
361
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
362
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
363
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
364
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
365
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
366
        renderer.setRenderingHints(hints);
367
        BufferedImage img = renderer.getImage();
368
        ByteArrayOutputStream os = new ByteArrayOutputStream();
369
        ImageIO.write(img, "png", os);
370
        return new ByteArrayInputStream(os.toByteArray());
371
    }
29926 amit.gupta 372
 
32505 amit.gupta 373
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
374
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
375
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
376
        MockHttpServletRequest req = new MockHttpServletRequest();
377
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
378
        resolvedView.render(model, req, mockResp);
379
        return mockResp.getContentAsString();
380
    }
29926 amit.gupta 381
 
32505 amit.gupta 382
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
383
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
384
            throws ProfitMandiBusinessException {
30017 amit.gupta 385
 
32505 amit.gupta 386
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
387
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
388
        model.addAttribute("offers", publishedOffers);
389
        model.addAttribute("yearMonth", yearMonth);
390
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 391
 
32505 amit.gupta 392
        return "offer_history";
393
    }
30723 amit.gupta 394
 
32505 amit.gupta 395
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
396
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
397
            throws ProfitMandiBusinessException {
398
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 399
 
32505 amit.gupta 400
        model.addAttribute("offer", createOfferRequest);
401
        return "offer-details";
402
    }
29926 amit.gupta 403
 
32505 amit.gupta 404
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
405
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
406
            throws Exception {
407
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
408
        if (!createOfferRequest.isActive()) {
409
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
410
        }
36487 amit 411
        if (offerBatchService.hasUnfinishedBatch(offerId)) {
412
            throw new ProfitMandiBusinessException("Reprocessing not allowed",
413
                    "Existing batch for this offer is not fully processed yet",
414
                    "Existing batch for this offer is not fully processed yet");
415
        }
416
        Offer offer = offerRepository.selectById(offerId);
417
        offer.setProcessedTimestamp(LocalDateTime.now());
36521 amit 418
        offerService.evictOfferDefinitionCache(offerId);
36348 amit 419
        String message = offerBatchService.submitBatchAsync(offerId);
420
        return responseSender.ok(message);
32505 amit.gupta 421
    }
29926 amit.gupta 422
 
32505 amit.gupta 423
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
424
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
425
            throws Exception {
426
        final HttpHeaders headers = new HttpHeaders();
427
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
428
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
429
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
33999 tejus.loha 430
        ByteArrayOutputStream baos = offerService.createCSVOfferReport(createOfferRequest);
32505 amit.gupta 431
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
432
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
433
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
434
    }
29900 amit.gupta 435
 
32505 amit.gupta 436
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
437
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
438
        Offer offer = offerRepository.selectById(offerId);
439
        model.addAttribute("offer", offer);
440
        return "offer-edit";
29900 amit.gupta 441
 
32505 amit.gupta 442
    }
29900 amit.gupta 443
 
34176 tejus.loha 444
    @RequestMapping(value = "/published-offers", method = RequestMethod.GET)
445
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam int yearMonth, @RequestParam(required = false, defaultValue = "") String brandFilter, Model model)
32505 amit.gupta 446
            throws ProfitMandiBusinessException {
34176 tejus.loha 447
        LOGGER.info("publishedOffersCalled");
32505 amit.gupta 448
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
449
        int fofoId = loginDetails.getFofoId();
450
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
451
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 452
 
34617 amit.gupta 453
        List<CreateOfferRequest> publishedOffers = null;
454
        if (!brandFilter.isEmpty()) {
455
            publishedOffers = createOffers.stream()
34176 tejus.loha 456
                    .filter(createOffer -> createOffer.getTargetSlabs().stream()
457
                            .map(x -> x.getItemCriteriaPayouts())
458
                            .flatMap(List::stream)
459
                            .map(ItemCriteriaPayout::getItemCriteria)
460
                            .map(ItemCriteria::getBrands)
461
                            .flatMap(List::stream)
462
                            .anyMatch(brand -> brand.equals(brandFilter)))
463
                    .collect(Collectors.toList());
34617 amit.gupta 464
        } else {
465
            publishedOffers = createOffers.stream().filter(createOffer -> createOffer.getTargetSlabs().stream()
34557 amit.gupta 466
                    .map(x -> x.getItemCriteriaPayouts())
467
                    .flatMap(List::stream)
468
                    .map(ItemCriteriaPayout::getItemCriteria)
34559 amit.gupta 469
                    .map(ItemCriteria::getCatalogIds)
34557 amit.gupta 470
                    .flatMap(List::stream)
34559 amit.gupta 471
                    .noneMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"))).collect(Collectors.toList());
34176 tejus.loha 472
        }
29926 amit.gupta 473
 
34176 tejus.loha 474
        model.addAttribute("publishedOffers", publishedOffers);
475
 
32505 amit.gupta 476
        return "published-offers";
477
    }
29926 amit.gupta 478
 
32505 amit.gupta 479
    @PostMapping(value = "/offers/upload")
480
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
481
            throws Exception {
482
        offerService.createOffers(targetFile.getInputStream());
483
        model.addAttribute("response1", true);
484
        return "response";
485
    }
29926 amit.gupta 486
 
32505 amit.gupta 487
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
488
    public String getOfferMargins(HttpServletRequest request,
489
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
490
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
491
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
492
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 493
 
32505 amit.gupta 494
        model.addAttribute("offer", createOfferRequest);
36501 amit 495
        model.addAttribute("isAdmin", isAdmin);
36492 amit 496
        model.addAttribute("isFinanceTeam", isAdmin && this.hasCategory(this.getUserPositions(loginDetails), ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS));
29900 amit.gupta 497
 
32505 amit.gupta 498
        return "offer_margin_detail_partner";
30470 amit.gupta 499
 
32505 amit.gupta 500
    }
29900 amit.gupta 501
 
35501 ranu 502
    @RequestMapping(value = "/todayOffer")
503
    public String todayOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
504
 
505
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
506
        if (fofoId == 0) {
507
            fofoId = loginDetails.getFofoId();
508
        }
509
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
510
 
511
        // 1. IDs to exclude entirely
512
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
513
 
514
        // 2. Brands that must come first (in this specific order)
515
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
516
 
517
        List<BrandCatalog> sortedBrands = allBrands.stream()
518
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
519
                .sorted((b1, b2) -> {
520
                    // Get the index of the brand name in our priority list
521
                    int index1 = priorityOrder.indexOf(b1.getName());
522
                    int index2 = priorityOrder.indexOf(b2.getName());
523
 
524
                    // If brand is NOT in priority list, give it a high index (move to bottom)
525
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
526
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
527
 
528
                    if (p1 != p2) {
529
                        return Integer.compare(p1, p2); // Sort by priority first
530
                    }
531
 
532
                    // If both are "Others", sort them alphabetically
533
                    return b1.getName().compareToIgnoreCase(b2.getName());
534
                })
535
                .collect(Collectors.toList());
536
 
537
        model.addAttribute("brands", sortedBrands);
538
        model.addAttribute("fofoId", fofoId);
539
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
540
 
541
        return "today-offer";
542
    }
543
 
36492 amit 544
    @Autowired
545
    com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
546
 
547
    @Autowired
548
    com.spice.profitmandi.dao.repository.auth.AuthRepository authRepository;
549
 
550
    private List<com.spice.profitmandi.dao.entity.cs.Position> getUserPositions(LoginDetails loginDetails) throws ProfitMandiBusinessException {
551
        com.spice.profitmandi.dao.entity.auth.AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
552
        return positionRepository.selectAllByAuthUserId(authUser.getId());
553
    }
554
 
555
    private boolean hasCategory(List<com.spice.profitmandi.dao.entity.cs.Position> positions, int categoryId) {
556
        return positions.stream().anyMatch(x -> x.getCategoryId() == categoryId);
557
    }
558
 
559
    private boolean hasCategoryL2Plus(List<com.spice.profitmandi.dao.entity.cs.Position> positions, int categoryId) {
560
        return positions.stream()
561
                .filter(x -> x.getCategoryId() == categoryId)
562
                .anyMatch(x -> com.spice.profitmandi.dao.enumuration.cs.EscalationType.L2.isGreaterThanEqualTo(x.getEscalationType()));
563
    }
564
 
565
    private boolean canReceive(List<com.spice.profitmandi.dao.entity.cs.Position> positions) {
566
        // Warehouse/Logistics team OR Finance L2+ can receive
567
        return hasCategory(positions, ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
568
                || hasCategory(positions, ProfitMandiConstants.TICKET_CATEGORY_LOGISTICS)
569
                || hasCategoryL2Plus(positions, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS);
570
    }
571
 
35501 ranu 572
    @RequestMapping(value = "/todayOfferList")
573
    public String todayOfferList(HttpServletRequest request, Model model, @RequestParam String brand, @RequestParam(defaultValue = "0", required = false) int fofoId) throws ProfitMandiBusinessException {
574
 
575
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
576
        if (fofoId == 0) {
577
            fofoId = loginDetails.getFofoId();
578
        }
579
 
580
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
581
 
582
        List<TodayOfferModel> todayOfferModels = todayOfferService.findAllTodayOffer(brand, fofoId);
583
 
584
        List<TodayOfferModel> groupedOffers = todayOfferService.groupSameOffers(todayOfferModels);
585
        model.addAttribute("brands", brands);
35505 ranu 586
        model.addAttribute("fofoId", fofoId);
35501 ranu 587
        model.addAttribute("todayOfferModels", todayOfferModels);
588
        model.addAttribute("groupedOffers", groupedOffers);
589
 
590
 
591
        return "today-offer-list";
592
    }
593
 
594
    @RequestMapping(value = "/todayFofoOffer")
595
    public String todayFofoOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
596
 
597
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
598
        if (fofoId == 0) {
599
            fofoId = loginDetails.getFofoId();
600
        }
601
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
602
 
603
        // 1. IDs to exclude entirely
604
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
605
 
606
        // 2. Brands that must come first (in this specific order)
607
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
608
 
609
        List<BrandCatalog> sortedBrands = allBrands.stream()
610
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
611
                .sorted((b1, b2) -> {
612
                    // Get the index of the brand name in our priority list
613
                    int index1 = priorityOrder.indexOf(b1.getName());
614
                    int index2 = priorityOrder.indexOf(b2.getName());
615
 
616
                    // If brand is NOT in priority list, give it a high index (move to bottom)
617
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
618
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
619
 
620
                    if (p1 != p2) {
621
                        return Integer.compare(p1, p2); // Sort by priority first
622
                    }
623
 
624
                    // If both are "Others", sort them alphabetically
625
                    return b1.getName().compareToIgnoreCase(b2.getName());
626
                })
627
                .collect(Collectors.toList());
628
 
629
        model.addAttribute("brands", sortedBrands);
630
        model.addAttribute("fofoId", fofoId);
631
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
632
 
633
        return "today-fofo-offer";
634
    }
635
 
35886 amit 636
    // ===== Offer Partner & Target Management (Admin Only) =====
637
 
638
    @RequestMapping(value = "/offer/partners", method = RequestMethod.GET)
639
    public String getOfferPartners(HttpServletRequest request, @RequestParam int offerId, Model model) throws Exception {
640
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
641
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
642
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
643
        }
644
        CreateOfferRequest offer = offerService.getOffer(0, offerId);
645
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
646
 
35888 amit 647
        // Partners are stored in partner_criteria JSON, not in offer_partners table
648
        List<Integer> partnerFofoIds = offer.getPartnerCriteria() != null
649
                ? offer.getPartnerCriteria().getFofoIds() : new ArrayList<>();
650
        if (partnerFofoIds == null) partnerFofoIds = new ArrayList<>();
651
 
35886 amit 652
        List<Integer> allFofoIds = fofoStoreRepository.selectActiveStores().stream()
653
                .map(x -> x.getId()).collect(Collectors.toList());
654
        Map<Integer, CustomRetailer> allRetailersMap = allFofoIds.stream()
655
                .map(id -> customRetailerMap.get(id))
656
                .filter(x -> x != null)
657
                .collect(Collectors.toMap(CustomRetailer::getPartnerId, x -> x));
658
 
659
        model.addAttribute("offer", offer);
660
        model.addAttribute("offerId", offerId);
35888 amit 661
        model.addAttribute("partnerFofoIds", partnerFofoIds);
35886 amit 662
        model.addAttribute("customRetailerMap", customRetailerMap);
663
        model.addAttribute("allRetailersMap", allRetailersMap);
664
        return "offer_partners";
665
    }
666
 
667
    @RequestMapping(value = "/offer/removePartners", method = RequestMethod.POST)
668
    public ResponseEntity<?> removePartnersFromOffer(HttpServletRequest request,
669
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds,
670
            @RequestParam(required = false, defaultValue = "false") boolean createNewOffer,
671
            @RequestParam(required = false) List<Integer> targets) throws Exception {
672
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
673
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
674
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
675
        }
676
        Offer offer = offerRepository.selectById(offerId);
677
        YearMonth ym = YearMonth.from(offer.getStartDate());
678
 
679
        offerService.removePartnersFromOffer(offerId, fofoIds);
680
 
681
        Integer newOfferId = null;
682
        String message;
683
        if (createNewOffer && targets != null && !targets.isEmpty()) {
684
            newOfferId = offerService.cloneOfferForPartners(offerId, fofoIds, targets);
685
            message = "Partner(s) removed from Offer #" + offerId + ". New Offer #" + newOfferId + " created (Unpublished).";
686
        } else {
687
            message = "Partner(s) removed from Offer #" + offerId + ".";
688
        }
689
 
36050 amit 690
        offerService.evictOfferCaches(offerId);
35892 amit 691
 
35886 amit 692
        Map<String, Object> response = new HashMap<>();
693
        response.put("message", message);
694
        response.put("newOfferId", newOfferId);
695
        response.put("yearMonth", ym.toString());
696
        return responseSender.ok(response);
697
    }
698
 
699
    @RequestMapping(value = "/offer/addPartners", method = RequestMethod.POST)
700
    public ResponseEntity<?> addPartnersToOffer(HttpServletRequest request,
701
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds) throws Exception {
702
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
703
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
704
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
705
        }
706
        offerService.addPartnersToOffer(offerId, fofoIds);
36050 amit 707
        offerService.evictOfferCaches(offerId);
35886 amit 708
 
709
        Offer offer = offerRepository.selectById(offerId);
710
        YearMonth ym = YearMonth.from(offer.getStartDate());
711
        Map<String, Object> response = new HashMap<>();
712
        response.put("message", "Partner(s) added to Offer #" + offerId + ".");
713
        response.put("yearMonth", ym.toString());
714
        return responseSender.ok(response);
715
    }
716
 
717
    @RequestMapping(value = "/offer/updateTargets", method = RequestMethod.POST)
718
    public ResponseEntity<?> updateOfferTargets(HttpServletRequest request,
719
            @RequestParam int offerId, @RequestParam List<Integer> targets) throws Exception {
720
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
721
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
722
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
723
        }
724
        offerService.updateOfferTargets(offerId, targets);
36050 amit 725
        offerService.evictOfferCaches(offerId);
35925 amit 726
        return responseSender.ok("Targets updated for Offer #" + offerId);
727
    }
35886 amit 728
 
35925 amit 729
    @RequestMapping(value = "/offer/updateSlabs", method = RequestMethod.POST, consumes = "application/json")
730
    public ResponseEntity<?> updateOfferSlabs(HttpServletRequest request,
731
            @RequestBody com.spice.profitmandi.dao.model.UpdateOfferSlabsRequest updateRequest) throws Exception {
732
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
733
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
734
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
735
        }
736
        offerService.updateOfferSlabs(updateRequest);
36050 amit 737
        offerService.evictOfferCaches(updateRequest.getOfferId());
35925 amit 738
        return responseSender.ok("Slabs updated for Offer #" + updateRequest.getOfferId());
739
    }
740
 
35886 amit 741
 
27895 amit.gupta 742
}