Subversion Repositories SmartDukaan

Rev

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