Subversion Repositories SmartDukaan

Rev

Rev 36492 | 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());
179
        List<Offer> offers = offerRepository.selectAllByIds(offerIds);
32868 amit.gupta 180
 
181
        //Consider only offers that have opposite status
182
        offers = offers.stream().filter(x -> x.isActive() != active).collect(Collectors.toList());
183
 
32505 amit.gupta 184
        for (Offer offer : offers) {
32868 amit.gupta 185
            offer.setActive(active);
36050 amit 186
            offerService.evictOfferCaches(offer.getId());
32505 amit.gupta 187
        }
32868 amit.gupta 188
        if (active) {
189
            for (Offer offer : offers) {
32505 amit.gupta 190
                this.sendNotification(offer);
191
            }
192
        }
32868 amit.gupta 193
 
194
 
32505 amit.gupta 195
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
196
        return "response";
197
    }
27391 tejbeer 198
 
35857 amit 199
    @RequestMapping(value = "/offers/publishAll", method = RequestMethod.POST)
200
    public ResponseEntity<?> publishAllUnpublished(@RequestParam YearMonth yearMonth)
201
            throws ProfitMandiBusinessException, Exception {
202
        List<Offer> published = offerService.publishAllUnpublished(yearMonth);
203
        if (!published.isEmpty()) {
204
            for (Offer offer : published) {
36050 amit 205
                offerService.evictOfferCaches(offer.getId());
35857 amit 206
                this.sendNotification(offer);
207
            }
208
        }
209
        return responseSender.ok(published.size() + " offers published");
210
    }
211
 
212
    @RequestMapping(value = "/offer/delete/{offerId}", method = RequestMethod.DELETE)
213
    public ResponseEntity<?> deleteOffer(@PathVariable int offerId) throws ProfitMandiBusinessException {
214
        offerService.deleteOffer(offerId);
215
        return responseSender.ok(true);
216
    }
217
 
32505 amit.gupta 218
    @RequestMapping(value = "/offer/testimage/{offerId}", method = RequestMethod.GET)
219
    public String testOffer(HttpServletRequest request, @PathVariable int offerId, Model model,
220
                            @RequestParam(defaultValue = "true") boolean active) throws ProfitMandiBusinessException, Exception {
221
        Offer offer = offerRepository.selectById(offerId);
222
        // model.addAttribute("response1", mvcResponseSender.createResponseString(true));
223
        // return "response";
224
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
225
        Map<String, Object> model1 = new HashMap<>();
226
        model1.put("offer", createOfferRequest);
227
        model1.put("lessThan", "<");
228
        String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model1);
229
        model.addAttribute("response1", htmlContent);
230
        return "response";
231
    }
29900 amit.gupta 232
 
32505 amit.gupta 233
    private void sendNotification(Offer offer) throws Exception {
234
        if (!YearMonth.from(offer.getStartDate()).equals(YearMonth.now())) {
235
            return;
236
        }
237
        String fileName = "offer-" + offer.getId() + ".png";
32868 amit.gupta 238
        //String htmlFileName = fileName.replace("png", "html");
32505 amit.gupta 239
        CreateOfferRequest createOfferRequest = offerService.getCreateOfferRequest(offer);
34620 amit.gupta 240
        boolean isLiveDemo = createOfferRequest.getTargetSlabs().stream()
241
                .map(x -> x.getItemCriteriaPayouts())
242
                .flatMap(List::stream)
243
                .map(ItemCriteriaPayout::getItemCriteria)
244
                .map(ItemCriteria::getCatalogIds)
245
                .flatMap(List::stream)
246
                .anyMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"));
247
        if (!isLiveDemo) {
248
            SendNotificationModel sendNotificationModel = new SendNotificationModel();
249
            sendNotificationModel.setCampaignName("SchemeOffer");
250
            sendNotificationModel.setTitle(offer.getName());
251
            sendNotificationModel.setMessage(createOfferRequest.getSchemeType().name() + " of select models, "
252
                    + FormattingUtils.formatDateMonth(offer.getStartDate()) + " to "
253
                    + FormattingUtils.formatDateMonth(offer.getEndDate()));
254
            sendNotificationModel.setType("url");
255
            String imageUrl = IMAGE_STATIC_SERVER_URL + "/" + "image" + LocalDate.now() + "/" + fileName;
256
            sendNotificationModel.setImageUrl(imageUrl);
257
            sendNotificationModel.setUrl("https://app.smartdukaan.com/pages/home/notifications");
258
            sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
259
            sendNotificationModel.setMessageType(MessageType.scheme);
260
            //Map<Integer, List<Offer>> offersMap = offerRepository.selectAllPublishedMapByPartner(YearMonth.now());
29900 amit.gupta 261
 
34620 amit.gupta 262
            Map<String, InputStream> fileStreamsMap = new HashMap<>();
263
            Map<String, Object> model = new HashMap<>();
264
            model.put("offer", createOfferRequest);
265
            String htmlContent = this.getContentFromTemplate("offer_margin_detail_notify", model);
266
            LOGGER.info("this.getContentFromTemplate {}", htmlContent);
267
            fileStreamsMap.put(fileName, this.getImageBuffer(htmlContent));
268
            // fileStreamsMap.put(htmlFileName, new
269
            // ByteArrayInputStream(htmlContent.getBytes()));
270
            List<Integer> fofoIds = null;
271
            if (isProd) {
272
                this.uploadFile(fileStreamsMap);
273
            }
274
 
275
            List<Integer> fofoIdSet = new ArrayList<>(offerRepository.getEligibleFofoIds(offer));
276
            //LOGGER.info(fofoIdSet);
277
            List<Integer> userIds = userAccountRepository.selectUserIdsByRetailerIds(new ArrayList<>(fofoIdSet));
278
            sendNotificationModel.setUserIds(userIds);
279
            notificationService.sendNotification(sendNotificationModel);
280
            sendWhatsapp(offer, fofoIds, imageUrl);
32868 amit.gupta 281
        }
32505 amit.gupta 282
    }
27876 amit.gupta 283
 
32505 amit.gupta 284
    private void sendWhatsapp(Offer offer, List<Integer> fofoIds, String imageUrl) throws Exception {
35205 amit 285
        offerService.sendWhatsapp(offer, fofoIds, imageUrl);
32505 amit.gupta 286
    }
27391 tejbeer 287
 
32505 amit.gupta 288
    private InputStream asInputStream(BufferedImage bi) throws Exception {
289
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
290
        ImageIO.write(bi, "png", baos);
291
        return new ByteArrayInputStream(baos.toByteArray());
27391 tejbeer 292
 
32505 amit.gupta 293
    }
27391 tejbeer 294
 
32505 amit.gupta 295
    private ChannelSftp setupJsch() throws JSchException {
296
        JSch jsch = new JSch();
33471 amit.gupta 297
        Session jschSession = jsch.getSession("root", "172.105.58.16");
32505 amit.gupta 298
        // Session jschSession = jsch.getSession("root", "173.255.254.24");
299
        LOGGER.info("getClass().getResource(\"id_rsa\") {}",
300
                getClass().getClassLoader().getResource("id_rsa").getPath());
301
        jsch.addIdentity(getClass().getClassLoader().getResource("id_rsa").getPath());
302
        // jschSession.setPassword("spic@2015static0");
303
        jschSession.setConfig("StrictHostKeyChecking", "no");
304
        jschSession.connect();
305
        return (ChannelSftp) jschSession.openChannel("sftp");
306
    }
30426 tejbeer 307
 
32505 amit.gupta 308
    private void fileUpload(ChannelSftp channelSftp, Map<String, InputStream> streamsFileMap, String destinationPath)
309
            throws SftpException, FileNotFoundException {
27391 tejbeer 310
 
32505 amit.gupta 311
        channelSftp.cd(destinationPath);
312
        String folderName = "image" + LocalDate.now();
27391 tejbeer 313
 
32505 amit.gupta 314
        channelSftp.cd(destinationPath);
315
        SftpATTRS attrs = null;
27391 tejbeer 316
 
32505 amit.gupta 317
        // check if the directory is already existing
318
        try {
319
            attrs = channelSftp.stat(folderName);
320
        } catch (Exception e) {
321
            System.out.println(destinationPath + "/" + folderName + " not found");
322
        }
27391 tejbeer 323
 
32505 amit.gupta 324
        // else create a directory
325
        if (attrs == null) {
326
            channelSftp.mkdir(folderName);
327
            channelSftp.chmod(0755, ".");
328
        }
329
        channelSftp.cd(folderName);
27391 tejbeer 330
 
32505 amit.gupta 331
        for (Map.Entry<String, InputStream> streamsFileEntry : streamsFileMap.entrySet()) {
332
            channelSftp.put(streamsFileEntry.getValue(), streamsFileEntry.getKey(), ChannelSftp.OVERWRITE);
333
        }
27391 tejbeer 334
 
32505 amit.gupta 335
    }
29926 amit.gupta 336
 
32505 amit.gupta 337
    private void uploadFile(Map<String, InputStream> fileStreamsMap) throws Exception {
338
        ChannelSftp channelSftp = setupJsch();
339
        channelSftp.connect();
340
        this.fileUpload(channelSftp, fileStreamsMap, IMAGE_REMOTE_DIR + "");
341
        channelSftp.exit();
342
    }
27391 tejbeer 343
 
32505 amit.gupta 344
    private InputStream getImageBuffer(String html) throws Exception {
35923 aman 345
        // Sanitize HTML to valid XHTML for Flying Saucer (Java2DRenderer requires well-formed XML)
346
        org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(html);
347
        doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
348
        doc.outputSettings().escapeMode(org.jsoup.nodes.Entities.EscapeMode.xhtml);
349
        doc.outputSettings().charset("UTF-8");
350
        html = doc.html();
29900 amit.gupta 351
 
32505 amit.gupta 352
        String fileName = "/tmp/" + Instant.now().toEpochMilli();
353
        FileUtils.writeStringToFile(new File(fileName), html, "UTF-8");
354
        String address = "file:" + fileName;
355
        Java2DRenderer renderer = new Java2DRenderer(address, 400);
356
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_COLOR_RENDERING,
357
                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
358
        hints.add(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
359
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
360
        hints.add(new RenderingHints(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC));
361
        renderer.setRenderingHints(hints);
362
        BufferedImage img = renderer.getImage();
363
        ByteArrayOutputStream os = new ByteArrayOutputStream();
364
        ImageIO.write(img, "png", os);
365
        return new ByteArrayInputStream(os.toByteArray());
366
    }
29926 amit.gupta 367
 
32505 amit.gupta 368
    private String getContentFromTemplate(String template, Map<String, Object> model) throws Exception {
369
        View resolvedView = viewResolver.resolveViewName(template, Locale.US);
370
        MockHttpServletResponse mockResp = new MockHttpServletResponse();
371
        MockHttpServletRequest req = new MockHttpServletRequest();
372
        LOGGER.info("Resolved view ->  {}, {}, {}, {}", resolvedView, model, req, mockResp);
373
        resolvedView.render(model, req, mockResp);
374
        return mockResp.getContentAsString();
375
    }
29926 amit.gupta 376
 
32505 amit.gupta 377
    @RequestMapping(value = "/offerHistory", method = RequestMethod.GET)
378
    public String getPaginatedOffers(HttpServletRequest request, @RequestParam YearMonth yearMonth, Model model)
379
            throws ProfitMandiBusinessException {
30017 amit.gupta 380
 
32505 amit.gupta 381
        List<CreateOfferRequest> publishedOffers = offerService.getAllOffers(yearMonth).values().stream()
382
                .sorted(Comparator.comparing(CreateOfferRequest::getId).reversed()).collect(Collectors.toList());
383
        model.addAttribute("offers", publishedOffers);
384
        model.addAttribute("yearMonth", yearMonth);
385
        model.addAttribute("currentMonth", yearMonth.equals(YearMonth.now()));
29926 amit.gupta 386
 
32505 amit.gupta 387
        return "offer_history";
388
    }
30723 amit.gupta 389
 
32505 amit.gupta 390
    @RequestMapping(value = "/offer-details", method = RequestMethod.GET)
391
    public String schemeDetails(HttpServletRequest request, @RequestParam int offerId, Model model)
392
            throws ProfitMandiBusinessException {
393
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
29900 amit.gupta 394
 
32505 amit.gupta 395
        model.addAttribute("offer", createOfferRequest);
396
        return "offer-details";
397
    }
29926 amit.gupta 398
 
32505 amit.gupta 399
    @RequestMapping(value = "/offer/process/{offerId}", method = RequestMethod.GET)
400
    public ResponseEntity<?> processOfferRequest(HttpServletRequest request, @PathVariable int offerId, Model model)
401
            throws Exception {
402
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
403
        if (!createOfferRequest.isActive()) {
404
            throw new ProfitMandiBusinessException("Offer not active", "Offer not active", "Offer not active");
405
        }
36487 amit 406
        if (offerBatchService.hasUnfinishedBatch(offerId)) {
407
            throw new ProfitMandiBusinessException("Reprocessing not allowed",
408
                    "Existing batch for this offer is not fully processed yet",
409
                    "Existing batch for this offer is not fully processed yet");
410
        }
411
        Offer offer = offerRepository.selectById(offerId);
412
        offer.setProcessedTimestamp(LocalDateTime.now());
36348 amit 413
        String message = offerBatchService.submitBatchAsync(offerId);
414
        return responseSender.ok(message);
32505 amit.gupta 415
    }
29926 amit.gupta 416
 
32505 amit.gupta 417
    @RequestMapping(value = "/offerDownload", method = RequestMethod.GET)
418
    public ResponseEntity<?> dowloadOfferSummary(HttpServletRequest request, @RequestParam int offerId, Model model)
419
            throws Exception {
420
        final HttpHeaders headers = new HttpHeaders();
421
        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
422
        headers.set("Content-disposition", "inline; filename=offer-" + offerId + ".csv");
423
        CreateOfferRequest createOfferRequest = offerService.getOffer(0, offerId);
33999 tejus.loha 424
        ByteArrayOutputStream baos = offerService.createCSVOfferReport(createOfferRequest);
32505 amit.gupta 425
        final InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
426
        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
427
        return new ResponseEntity<>(inputStreamResource, headers, HttpStatus.OK);
428
    }
29900 amit.gupta 429
 
32505 amit.gupta 430
    @RequestMapping(value = "/offerById", method = RequestMethod.GET)
431
    public String offerById(HttpServletRequest request, int offerId, Model model) throws ProfitMandiBusinessException {
432
        Offer offer = offerRepository.selectById(offerId);
433
        model.addAttribute("offer", offer);
434
        return "offer-edit";
29900 amit.gupta 435
 
32505 amit.gupta 436
    }
29900 amit.gupta 437
 
34176 tejus.loha 438
    @RequestMapping(value = "/published-offers", method = RequestMethod.GET)
439
    public String publishedOffersOnMonthBefore(HttpServletRequest request, @RequestParam int yearMonth, @RequestParam(required = false, defaultValue = "") String brandFilter, Model model)
32505 amit.gupta 440
            throws ProfitMandiBusinessException {
34176 tejus.loha 441
        LOGGER.info("publishedOffersCalled");
32505 amit.gupta 442
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
443
        int fofoId = loginDetails.getFofoId();
444
        List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(fofoId,
445
                YearMonth.from(LocalDate.now()).minusMonths(yearMonth));
29900 amit.gupta 446
 
34617 amit.gupta 447
        List<CreateOfferRequest> publishedOffers = null;
448
        if (!brandFilter.isEmpty()) {
449
            publishedOffers = createOffers.stream()
34176 tejus.loha 450
                    .filter(createOffer -> createOffer.getTargetSlabs().stream()
451
                            .map(x -> x.getItemCriteriaPayouts())
452
                            .flatMap(List::stream)
453
                            .map(ItemCriteriaPayout::getItemCriteria)
454
                            .map(ItemCriteria::getBrands)
455
                            .flatMap(List::stream)
456
                            .anyMatch(brand -> brand.equals(brandFilter)))
457
                    .collect(Collectors.toList());
34617 amit.gupta 458
        } else {
459
            publishedOffers = createOffers.stream().filter(createOffer -> createOffer.getTargetSlabs().stream()
34557 amit.gupta 460
                    .map(x -> x.getItemCriteriaPayouts())
461
                    .flatMap(List::stream)
462
                    .map(ItemCriteriaPayout::getItemCriteria)
34559 amit.gupta 463
                    .map(ItemCriteria::getCatalogIds)
34557 amit.gupta 464
                    .flatMap(List::stream)
34559 amit.gupta 465
                    .noneMatch(catalogId -> catalogRepository.selectCatalogById(catalogId).getBrand().equals("Live Demo"))).collect(Collectors.toList());
34176 tejus.loha 466
        }
29926 amit.gupta 467
 
34176 tejus.loha 468
        model.addAttribute("publishedOffers", publishedOffers);
469
 
32505 amit.gupta 470
        return "published-offers";
471
    }
29926 amit.gupta 472
 
32505 amit.gupta 473
    @PostMapping(value = "/offers/upload")
474
    public String uploadOffers(HttpServletRequest request, @RequestPart("file") MultipartFile targetFile, Model model)
475
            throws Exception {
476
        offerService.createOffers(targetFile.getInputStream());
477
        model.addAttribute("response1", true);
478
        return "response";
479
    }
29926 amit.gupta 480
 
32505 amit.gupta 481
    @RequestMapping(value = "/getOfferMargins", method = RequestMethod.GET)
482
    public String getOfferMargins(HttpServletRequest request,
483
                                  @RequestParam(name = "offerId", defaultValue = "0") int offerId, Model model) throws Exception {
484
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
485
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
486
        CreateOfferRequest createOfferRequest = offerService.getOffer(isAdmin ? 0 : loginDetails.getFofoId(), offerId);
29900 amit.gupta 487
 
32505 amit.gupta 488
        model.addAttribute("offer", createOfferRequest);
36501 amit 489
        model.addAttribute("isAdmin", isAdmin);
36492 amit 490
        model.addAttribute("isFinanceTeam", isAdmin && this.hasCategory(this.getUserPositions(loginDetails), ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS));
29900 amit.gupta 491
 
32505 amit.gupta 492
        return "offer_margin_detail_partner";
30470 amit.gupta 493
 
32505 amit.gupta 494
    }
29900 amit.gupta 495
 
35501 ranu 496
    @RequestMapping(value = "/todayOffer")
497
    public String todayOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
498
 
499
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
500
        if (fofoId == 0) {
501
            fofoId = loginDetails.getFofoId();
502
        }
503
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
504
 
505
        // 1. IDs to exclude entirely
506
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
507
 
508
        // 2. Brands that must come first (in this specific order)
509
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
510
 
511
        List<BrandCatalog> sortedBrands = allBrands.stream()
512
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
513
                .sorted((b1, b2) -> {
514
                    // Get the index of the brand name in our priority list
515
                    int index1 = priorityOrder.indexOf(b1.getName());
516
                    int index2 = priorityOrder.indexOf(b2.getName());
517
 
518
                    // If brand is NOT in priority list, give it a high index (move to bottom)
519
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
520
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
521
 
522
                    if (p1 != p2) {
523
                        return Integer.compare(p1, p2); // Sort by priority first
524
                    }
525
 
526
                    // If both are "Others", sort them alphabetically
527
                    return b1.getName().compareToIgnoreCase(b2.getName());
528
                })
529
                .collect(Collectors.toList());
530
 
531
        model.addAttribute("brands", sortedBrands);
532
        model.addAttribute("fofoId", fofoId);
533
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
534
 
535
        return "today-offer";
536
    }
537
 
36492 amit 538
    @Autowired
539
    com.spice.profitmandi.dao.repository.cs.PositionRepository positionRepository;
540
 
541
    @Autowired
542
    com.spice.profitmandi.dao.repository.auth.AuthRepository authRepository;
543
 
544
    private List<com.spice.profitmandi.dao.entity.cs.Position> getUserPositions(LoginDetails loginDetails) throws ProfitMandiBusinessException {
545
        com.spice.profitmandi.dao.entity.auth.AuthUser authUser = authRepository.selectByEmailOrMobile(loginDetails.getEmailId());
546
        return positionRepository.selectAllByAuthUserId(authUser.getId());
547
    }
548
 
549
    private boolean hasCategory(List<com.spice.profitmandi.dao.entity.cs.Position> positions, int categoryId) {
550
        return positions.stream().anyMatch(x -> x.getCategoryId() == categoryId);
551
    }
552
 
553
    private boolean hasCategoryL2Plus(List<com.spice.profitmandi.dao.entity.cs.Position> positions, int categoryId) {
554
        return positions.stream()
555
                .filter(x -> x.getCategoryId() == categoryId)
556
                .anyMatch(x -> com.spice.profitmandi.dao.enumuration.cs.EscalationType.L2.isGreaterThanEqualTo(x.getEscalationType()));
557
    }
558
 
559
    private boolean canReceive(List<com.spice.profitmandi.dao.entity.cs.Position> positions) {
560
        // Warehouse/Logistics team OR Finance L2+ can receive
561
        return hasCategory(positions, ProfitMandiConstants.TICKET_CATEGORY_WAREHOUSE)
562
                || hasCategory(positions, ProfitMandiConstants.TICKET_CATEGORY_LOGISTICS)
563
                || hasCategoryL2Plus(positions, ProfitMandiConstants.TICKET_CATEGORY_ACCOUNTS);
564
    }
565
 
35501 ranu 566
    @RequestMapping(value = "/todayOfferList")
567
    public String todayOfferList(HttpServletRequest request, Model model, @RequestParam String brand, @RequestParam(defaultValue = "0", required = false) int fofoId) throws ProfitMandiBusinessException {
568
 
569
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
570
        if (fofoId == 0) {
571
            fofoId = loginDetails.getFofoId();
572
        }
573
 
574
        List<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toList());
575
 
576
        List<TodayOfferModel> todayOfferModels = todayOfferService.findAllTodayOffer(brand, fofoId);
577
 
578
        List<TodayOfferModel> groupedOffers = todayOfferService.groupSameOffers(todayOfferModels);
579
        model.addAttribute("brands", brands);
35505 ranu 580
        model.addAttribute("fofoId", fofoId);
35501 ranu 581
        model.addAttribute("todayOfferModels", todayOfferModels);
582
        model.addAttribute("groupedOffers", groupedOffers);
583
 
584
 
585
        return "today-offer-list";
586
    }
587
 
588
    @RequestMapping(value = "/todayFofoOffer")
589
    public String todayFofoOffer(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws ProfitMandiBusinessException {
590
 
591
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
592
        if (fofoId == 0) {
593
            fofoId = loginDetails.getFofoId();
594
        }
595
        List<BrandCatalog> allBrands = brandsService.getBrandsToDisplay(3);
596
 
597
        // 1. IDs to exclude entirely
598
        List<Integer> excludedIds = Arrays.asList(132, 133, 28, 17, 125);
599
 
600
        // 2. Brands that must come first (in this specific order)
601
        List<String> priorityOrder = Arrays.asList("Samsung", "Oppo", "Vivo", "Xiaomi", "Realme");
602
 
603
        List<BrandCatalog> sortedBrands = allBrands.stream()
604
                .filter(brand -> !excludedIds.contains(brand.getId())) // Remove excluded
605
                .sorted((b1, b2) -> {
606
                    // Get the index of the brand name in our priority list
607
                    int index1 = priorityOrder.indexOf(b1.getName());
608
                    int index2 = priorityOrder.indexOf(b2.getName());
609
 
610
                    // If brand is NOT in priority list, give it a high index (move to bottom)
611
                    int p1 = (index1 != -1) ? index1 : Integer.MAX_VALUE;
612
                    int p2 = (index2 != -1) ? index2 : Integer.MAX_VALUE;
613
 
614
                    if (p1 != p2) {
615
                        return Integer.compare(p1, p2); // Sort by priority first
616
                    }
617
 
618
                    // If both are "Others", sort them alphabetically
619
                    return b1.getName().compareToIgnoreCase(b2.getName());
620
                })
621
                .collect(Collectors.toList());
622
 
623
        model.addAttribute("brands", sortedBrands);
624
        model.addAttribute("fofoId", fofoId);
625
        model.addAttribute("date", FormattingUtils.format(LocalDateTime.now()));
626
 
627
        return "today-fofo-offer";
628
    }
629
 
35886 amit 630
    // ===== Offer Partner & Target Management (Admin Only) =====
631
 
632
    @RequestMapping(value = "/offer/partners", method = RequestMethod.GET)
633
    public String getOfferPartners(HttpServletRequest request, @RequestParam int offerId, Model model) throws Exception {
634
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
635
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
636
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
637
        }
638
        CreateOfferRequest offer = offerService.getOffer(0, offerId);
639
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers();
640
 
35888 amit 641
        // Partners are stored in partner_criteria JSON, not in offer_partners table
642
        List<Integer> partnerFofoIds = offer.getPartnerCriteria() != null
643
                ? offer.getPartnerCriteria().getFofoIds() : new ArrayList<>();
644
        if (partnerFofoIds == null) partnerFofoIds = new ArrayList<>();
645
 
35886 amit 646
        List<Integer> allFofoIds = fofoStoreRepository.selectActiveStores().stream()
647
                .map(x -> x.getId()).collect(Collectors.toList());
648
        Map<Integer, CustomRetailer> allRetailersMap = allFofoIds.stream()
649
                .map(id -> customRetailerMap.get(id))
650
                .filter(x -> x != null)
651
                .collect(Collectors.toMap(CustomRetailer::getPartnerId, x -> x));
652
 
653
        model.addAttribute("offer", offer);
654
        model.addAttribute("offerId", offerId);
35888 amit 655
        model.addAttribute("partnerFofoIds", partnerFofoIds);
35886 amit 656
        model.addAttribute("customRetailerMap", customRetailerMap);
657
        model.addAttribute("allRetailersMap", allRetailersMap);
658
        return "offer_partners";
659
    }
660
 
661
    @RequestMapping(value = "/offer/removePartners", method = RequestMethod.POST)
662
    public ResponseEntity<?> removePartnersFromOffer(HttpServletRequest request,
663
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds,
664
            @RequestParam(required = false, defaultValue = "false") boolean createNewOffer,
665
            @RequestParam(required = false) List<Integer> targets) throws Exception {
666
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
667
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
668
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
669
        }
670
        Offer offer = offerRepository.selectById(offerId);
671
        YearMonth ym = YearMonth.from(offer.getStartDate());
672
 
673
        offerService.removePartnersFromOffer(offerId, fofoIds);
674
 
675
        Integer newOfferId = null;
676
        String message;
677
        if (createNewOffer && targets != null && !targets.isEmpty()) {
678
            newOfferId = offerService.cloneOfferForPartners(offerId, fofoIds, targets);
679
            message = "Partner(s) removed from Offer #" + offerId + ". New Offer #" + newOfferId + " created (Unpublished).";
680
        } else {
681
            message = "Partner(s) removed from Offer #" + offerId + ".";
682
        }
683
 
36050 amit 684
        offerService.evictOfferCaches(offerId);
35892 amit 685
 
35886 amit 686
        Map<String, Object> response = new HashMap<>();
687
        response.put("message", message);
688
        response.put("newOfferId", newOfferId);
689
        response.put("yearMonth", ym.toString());
690
        return responseSender.ok(response);
691
    }
692
 
693
    @RequestMapping(value = "/offer/addPartners", method = RequestMethod.POST)
694
    public ResponseEntity<?> addPartnersToOffer(HttpServletRequest request,
695
            @RequestParam int offerId, @RequestParam List<Integer> fofoIds) throws Exception {
696
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
697
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
698
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
699
        }
700
        offerService.addPartnersToOffer(offerId, fofoIds);
36050 amit 701
        offerService.evictOfferCaches(offerId);
35886 amit 702
 
703
        Offer offer = offerRepository.selectById(offerId);
704
        YearMonth ym = YearMonth.from(offer.getStartDate());
705
        Map<String, Object> response = new HashMap<>();
706
        response.put("message", "Partner(s) added to Offer #" + offerId + ".");
707
        response.put("yearMonth", ym.toString());
708
        return responseSender.ok(response);
709
    }
710
 
711
    @RequestMapping(value = "/offer/updateTargets", method = RequestMethod.POST)
712
    public ResponseEntity<?> updateOfferTargets(HttpServletRequest request,
713
            @RequestParam int offerId, @RequestParam List<Integer> targets) throws Exception {
714
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
715
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
716
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
717
        }
718
        offerService.updateOfferTargets(offerId, targets);
36050 amit 719
        offerService.evictOfferCaches(offerId);
35925 amit 720
        return responseSender.ok("Targets updated for Offer #" + offerId);
721
    }
35886 amit 722
 
35925 amit 723
    @RequestMapping(value = "/offer/updateSlabs", method = RequestMethod.POST, consumes = "application/json")
724
    public ResponseEntity<?> updateOfferSlabs(HttpServletRequest request,
725
            @RequestBody com.spice.profitmandi.dao.model.UpdateOfferSlabsRequest updateRequest) throws Exception {
726
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
727
        if (!roleManager.isAdmin(loginDetails.getRoleIds())) {
728
            throw new ProfitMandiBusinessException("Unauthorized", "Unauthorized", "");
729
        }
730
        offerService.updateOfferSlabs(updateRequest);
36050 amit 731
        offerService.evictOfferCaches(updateRequest.getOfferId());
35925 amit 732
        return responseSender.ok("Slabs updated for Offer #" + updateRequest.getOfferId());
733
    }
734
 
35886 amit 735
 
27895 amit.gupta 736
}