Subversion Repositories SmartDukaan

Rev

Rev 37427 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
21615 kshitij.so 1
package com.spice.profitmandi.web.controller;
2
 
25649 tejbeer 3
import com.google.gson.Gson;
28825 tejbeer 4
import com.mongodb.DBObject;
25651 tejbeer 5
import com.spice.profitmandi.common.enumuration.ContentType;
25683 tejbeer 6
import com.spice.profitmandi.common.enumuration.MessageType;
22481 ashik.ali 7
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
31337 amit.gupta 8
import com.spice.profitmandi.common.model.*;
25651 tejbeer 9
import com.spice.profitmandi.common.web.util.ResponseSender;
36890 aman 10
import com.spice.profitmandi.dao.entity.ContactUs;
35247 vikas 11
import com.spice.profitmandi.dao.entity.StoreSalesTarget;
26011 amit.gupta 12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
27355 tejbeer 13
import com.spice.profitmandi.dao.entity.catalog.Item;
32308 amit.gupta 14
import com.spice.profitmandi.dao.entity.catalog.Scheme;
27636 tejbeer 15
import com.spice.profitmandi.dao.entity.catalog.TagListing;
33501 ranu 16
import com.spice.profitmandi.dao.entity.cs.PartnerRegion;
28471 tejbeer 17
import com.spice.profitmandi.dao.entity.cs.Position;
36268 ranu 18
import com.spice.profitmandi.dao.entity.cs.Ticket;
27660 tejbeer 19
import com.spice.profitmandi.dao.entity.cs.TicketAssigned;
25651 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.Document;
25649 tejbeer 21
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaign;
31337 amit.gupta 22
import com.spice.profitmandi.dao.entity.fofo.*;
29720 manish 23
import com.spice.profitmandi.dao.entity.transaction.LineItem;
27586 tejbeer 24
import com.spice.profitmandi.dao.entity.transaction.Order;
29707 tejbeer 25
import com.spice.profitmandi.dao.enumuration.catalog.UpgradeOfferStatus;
36481 ranu 26
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
31259 tejbeer 27
import com.spice.profitmandi.dao.enumuration.fofo.Milestone;
28409 tejbeer 28
import com.spice.profitmandi.dao.enumuration.transaction.OrderStatus;
36849 ranu 29
import com.spice.profitmandi.dao.model.SamsungUpgradeOfferModel;
36816 aman 30
import com.spice.profitmandi.dao.model.*;
34973 aman 31
import com.spice.profitmandi.dao.model.warehouse.LMSGraphRequest;
36890 aman 32
import com.spice.profitmandi.dao.repository.ContactUsRepository;
25976 amit.gupta 33
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
34617 amit.gupta 34
import com.spice.profitmandi.dao.repository.catalog.*;
31662 amit.gupta 35
import com.spice.profitmandi.dao.repository.cs.*;
31337 amit.gupta 36
import com.spice.profitmandi.dao.repository.dtr.*;
37
import com.spice.profitmandi.dao.repository.fofo.*;
27529 tejbeer 38
import com.spice.profitmandi.dao.repository.inventory.ReporticoCacheTableRepository;
39
import com.spice.profitmandi.dao.repository.inventory.SaholicInventoryCISRepository;
29720 manish 40
import com.spice.profitmandi.dao.repository.transaction.LineItemRepository;
27893 tejbeer 41
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
28443 tejbeer 42
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
35104 vikas 43
import com.spice.profitmandi.dao.service.SaleRewardService;
28468 tejbeer 44
import com.spice.profitmandi.service.AdminUser;
45
import com.spice.profitmandi.service.FofoUser;
24336 amit.gupta 46
import com.spice.profitmandi.service.PartnerInvestmentService;
26460 amit.gupta 47
import com.spice.profitmandi.service.PartnerStatsService;
32336 jai.hind 48
import com.spice.profitmandi.service.SshServer.SSHService;
23844 amit.gupta 49
import com.spice.profitmandi.service.authentication.RoleManager;
34176 tejus.loha 50
import com.spice.profitmandi.service.catalog.BrandsService;
32934 amit.gupta 51
import com.spice.profitmandi.service.integrations.psismart.PsiSmartService;
25677 amit.gupta 52
import com.spice.profitmandi.service.inventory.InventoryService;
27876 amit.gupta 53
import com.spice.profitmandi.service.offers.OfferService;
32308 amit.gupta 54
import com.spice.profitmandi.service.scheme.SchemeService;
27586 tejbeer 55
import com.spice.profitmandi.service.transaction.TransactionService;
26005 amit.gupta 56
import com.spice.profitmandi.service.user.RetailerService;
22481 ashik.ali 57
import com.spice.profitmandi.web.model.LoginDetails;
58
import com.spice.profitmandi.web.util.CookiesProcessor;
27529 tejbeer 59
import com.spice.profitmandi.web.util.MVCResponseSender;
31337 amit.gupta 60
import org.apache.logging.log4j.LogManager;
61
import org.apache.logging.log4j.Logger;
62
import org.json.JSONObject;
63
import org.springframework.beans.factory.annotation.Autowired;
64
import org.springframework.beans.factory.annotation.Value;
65
import org.springframework.core.io.InputStreamResource;
66
import org.springframework.http.HttpHeaders;
67
import org.springframework.http.HttpStatus;
68
import org.springframework.http.ResponseEntity;
69
import org.springframework.stereotype.Controller;
35437 amit 70
import org.springframework.transaction.annotation.Transactional;
31337 amit.gupta 71
import org.springframework.ui.Model;
32336 jai.hind 72
import org.springframework.web.bind.annotation.*;
32407 amit.gupta 73
 
31337 amit.gupta 74
import javax.servlet.http.HttpServletRequest;
75
import java.io.File;
76
import java.io.FileInputStream;
77
import java.io.FileNotFoundException;
78
import java.time.LocalDate;
79
import java.time.LocalDateTime;
80
import java.time.LocalTime;
81
import java.time.YearMonth;
82
import java.time.format.DateTimeFormatter;
83
import java.util.*;
84
import java.util.Map.Entry;
85
import java.util.stream.Collectors;
32407 amit.gupta 86
 
31337 amit.gupta 87
import static in.shop2020.model.v1.order.OrderStatus.*;
32407 amit.gupta 88
 
21615 kshitij.so 89
@Controller
35458 amit 90
@Transactional(rollbackFor = Throwable.class)
21615 kshitij.so 91
public class DashboardController {
23923 amit.gupta 92
 
36870 ranu 93
    List<String> emails = Arrays.asList("kamini.sharma@smartdukaan.com", "neeraj.gupta@smartdukaan.com", "amit.gupta@smartdukaan.com", "ranu.rajput@smartdukaan.com", "vikas.jangra@smartdukaan.com", "tanay.gupta@smartdukaan.com", "rudy.kanwar@smartdukaan.com");
27727 tejbeer 94
 
31751 tejbeer 95
    @Value("${web.api.host}")
96
    private String webApiHost;
23923 amit.gupta 97
 
31751 tejbeer 98
    @Value("${web.api.scheme}")
99
    private String webApiScheme;
24288 amit.gupta 100
 
31751 tejbeer 101
    @Autowired
102
    private CsService1 csService1;
31662 amit.gupta 103
 
31751 tejbeer 104
    @Value("${web.api.root}")
105
    private String webApiRoot;
24078 amit.gupta 106
 
31751 tejbeer 107
    @Value("${web.api.port}")
108
    private int webApiPort;
28430 tejbeer 109
 
31751 tejbeer 110
    @Autowired
111
    private PriceDropRepository priceDropRepository;
28443 tejbeer 112
 
31751 tejbeer 113
    @Autowired
37188 ranu 114
    private BrandsRepository brandsRepository;
115
 
116
    @Autowired
31751 tejbeer 117
    private CookiesProcessor cookiesProcessor;
26468 amit.gupta 118
 
31751 tejbeer 119
    @Autowired
120
    private PendingOrderRepository pendingOrderRepository;
28409 tejbeer 121
 
31751 tejbeer 122
    @Autowired
123
    private PartnerStatsService partnerStatsService;
23923 amit.gupta 124
 
31751 tejbeer 125
    @Autowired
126
    private CsService csService;
26090 amit.gupta 127
 
31751 tejbeer 128
    @Autowired
129
    private ResponseSender<?> responseSender;
26012 amit.gupta 130
 
31751 tejbeer 131
    @Autowired
132
    RetailerService retailerService;
25214 amit.gupta 133
 
31751 tejbeer 134
    @Autowired
135
    private AdminUser adminUser;
28468 tejbeer 136
 
31751 tejbeer 137
    @Autowired
138
    private RoleManager roleManager;
23923 amit.gupta 139
 
31751 tejbeer 140
    @Autowired
141
    private FofoStoreRepository fofoStoreRepository;
23884 amit.gupta 142
 
31751 tejbeer 143
    @Autowired
144
    private PartnerInvestmentService partnerInvestmentService;
24288 amit.gupta 145
 
31751 tejbeer 146
    @Autowired
147
    DocumentRepository documentRepository;
26236 amit.gupta 148
 
31751 tejbeer 149
    @Autowired
150
    InventoryItemRepository inventoryItemRepository;
25683 tejbeer 151
 
31751 tejbeer 152
    @Autowired
153
    InventoryService inventoryService;
23923 amit.gupta 154
 
31751 tejbeer 155
    @Autowired
156
    private PendingOrderItemRepository pendingOrderItemRepository;
28409 tejbeer 157
 
31751 tejbeer 158
    @Autowired
159
    private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
24203 amit.gupta 160
 
31751 tejbeer 161
    @Autowired
162
    private FofoOrderItemRepository fofoOrderItemRepository;
26012 amit.gupta 163
 
31751 tejbeer 164
    @Autowired
165
    private PartnerTypeChangeService partnerTypeChangeService;
25136 amit.gupta 166
 
31751 tejbeer 167
    @Autowired
168
    private HygieneDataRepository hygieneDataRepository;
25649 tejbeer 169
 
31751 tejbeer 170
    @Autowired
171
    private UserAccountRepository userAccountRepository;
25649 tejbeer 172
 
31751 tejbeer 173
    @Autowired
174
    private NotificationCampaignRepository notificationCampaignRepository;
25649 tejbeer 175
 
31751 tejbeer 176
    @Autowired
177
    private AuthRepository authRepository;
24880 govind 178
 
31751 tejbeer 179
    @Autowired
180
    private FofoOrderRepository fofoOrderRepository;
26071 tejbeer 181
 
31751 tejbeer 182
    @Autowired
183
    private Gson gson;
25649 tejbeer 184
 
31751 tejbeer 185
    @Autowired
186
    TicketRepository ticketRepository;
26418 tejbeer 187
 
31751 tejbeer 188
    @Autowired
189
    private OfferService offerService;
27876 amit.gupta 190
 
31751 tejbeer 191
    @Autowired
192
    private ItemRepository itemRepository;
26588 tejbeer 193
 
31751 tejbeer 194
    @Autowired
195
    private SaholicInventoryCISRepository saholicInventoryCISRepository;
27529 tejbeer 196
 
31751 tejbeer 197
    @Autowired
198
    private MVCResponseSender mvcResponseSender;
27529 tejbeer 199
 
31751 tejbeer 200
    @Autowired
36890 aman 201
    private ContactUsRepository contactUsRepository;
202
 
203
    @Autowired
31751 tejbeer 204
    private ReporticoCacheTableRepository reporticoCacheTableRepository;
27529 tejbeer 205
 
31751 tejbeer 206
    @Autowired
207
    private TransactionService transactionService;
27586 tejbeer 208
 
31751 tejbeer 209
    @Autowired
210
    private TagListingRepository tagListingRepository;
27632 tejbeer 211
 
31751 tejbeer 212
    @Autowired
213
    private TicketAssignedRepository ticketAssignedRepository;
27660 tejbeer 214
 
31751 tejbeer 215
    @Autowired
216
    private OrderRepository orderRepository;
28468 tejbeer 217
 
31751 tejbeer 218
    @Autowired
219
    private FofoUser fofoUser;
29875 tejbeer 220
 
31751 tejbeer 221
    @Autowired
222
    private ActivatedImeiRepository activatedImeiRepository;
28825 tejbeer 223
 
31751 tejbeer 224
    @Autowired
225
    private Mongo mongoClient;
28825 tejbeer 226
 
31751 tejbeer 227
    @Autowired
228
    private SchemeInOutRepository schemeInOutRepository;
29875 tejbeer 229
 
31751 tejbeer 230
    @Autowired
231
    private LineItemRepository lineItemRepository;
29875 tejbeer 232
 
31751 tejbeer 233
    @Autowired
234
    private FofoLineItemRepository fofoLineItemRepository;
29578 tejbeer 235
 
31751 tejbeer 236
    @Autowired
237
    private PositionRepository positionRepository;
29707 tejbeer 238
 
31751 tejbeer 239
    @Autowired
240
    private MonthlyTargetRepository monthlyTargetRepository;
31285 tejbeer 241
 
31751 tejbeer 242
    @Autowired
243
    private SamsungUpgradeOfferRepository samsungUpgradeOfferRepository;
244
    private static final Logger LOGGER = LogManager.getLogger(DashboardController.class);
32836 amit.gupta 245
 
32407 amit.gupta 246
    @Autowired
247
    private SSHService sshService;
35119 aman 248
 
34176 tejus.loha 249
    @Autowired
250
    BrandsService brandsService;
32407 amit.gupta 251
 
35104 vikas 252
    @Autowired
253
    SaleRewardService saleRewardService;
254
 
35119 aman 255
    @Autowired
256
    SchemeService schemeService;
257
    @Autowired
258
    PrintResourceRegionRepository printResourceRegionRepository;
259
    @Autowired
260
    PartnerRegionRepository partnerRegionRepository;
261
    @Autowired
262
    PrintResourceRepository printResourceRepository;
263
    @Autowired
264
    CatalogRepository catalogRepository;
265
    @Autowired
266
    OfferRepository offerRepository;
267
    @Autowired
268
    OfferPayoutRepository offerPayoutRepository;
269
    @Value("${google.api.key}")
270
    private String googleApiKey;
271
 
31751 tejbeer 272
    @RequestMapping(value = "/12dashboard34", method = RequestMethod.GET)
273
    public String dashboard1(HttpServletRequest request, Model model, @RequestParam int fofoId) throws Exception {
274
        boolean isAdmin = false;
275
        model.addAttribute("isAdmin", isAdmin);
25740 amit.gupta 276
 
31751 tejbeer 277
        model.addAttribute("webApiHost", webApiHost);
278
        model.addAttribute("webApiPort", webApiPort);
279
        model.addAttribute("webApiScheme", webApiScheme);
280
        model.addAttribute("webApiRoot", webApiRoot);
281
        if (isAdmin) {
282
            return "dashboard1";
283
        }
26236 amit.gupta 284
 
31751 tejbeer 285
        FofoStore fofoStore = null;
286
        try {
287
            CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
288
            fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
289
            if (!fofoStore.isActive()) {
290
                return "redirect:/login";
291
            }
25740 amit.gupta 292
 
31751 tejbeer 293
            PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
294
            model.addAttribute("partnerType", partnerType);
295
            model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
296
            model.addAttribute("fofoStore", customRetailer);
297
            model.addAttribute("partnerType", partnerType);
298
            model.addAttribute("hasGift", fofoUser.hasGift(fofoId));
299
            model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
25740 amit.gupta 300
 
31884 tejbeer 301
            model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(fofoId, false));
31751 tejbeer 302
            model.addAttribute("salesMap", fofoUser.getSales(fofoId));
303
            model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(fofoId));
304
            // this.setInvestments
305
            //
306
            Map<Integer, String> monthValueMap = new HashMap<>();
307
            for (int i = 0; i <= 5; i++) {
308
                LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
309
                monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
310
            }
311
            LOGGER.info("monthValueMap" + monthValueMap);
34176 tejus.loha 312
            Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
313
            brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.LED_CATEGORY_ID));
314
            brands.addAll(itemRepository.selectAllBrands(ProfitMandiConstants.SMART_WATCH_CATEGORY_ID));
315
            brands.add("Live Demo");
316
            model.addAttribute("brands", brands);
31751 tejbeer 317
            model.addAttribute("monthValueMap", monthValueMap);
318
            model.addAttribute("investments", fofoUser.getInvestments(fofoId));
319
            model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(fofoId, ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
320
        } catch (ProfitMandiBusinessException e) {
321
            LOGGER.error("FofoStore Code not found of fofoId {}", fofoId);
25740 amit.gupta 322
 
31751 tejbeer 323
        }
25740 amit.gupta 324
 
31751 tejbeer 325
        return "12dashboard34";
326
    }
25740 amit.gupta 327
 
31751 tejbeer 328
    @RequestMapping(value = "/getMonthSale", method = RequestMethod.GET)
329
    public String getMonthsale(HttpServletRequest request, Model model) throws Exception {
330
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
331
        int fofoId = loginDetails.getFofoId();
332
        Map<Integer, MonthSaleModel> monthSaleMap = new HashMap<>();
333
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
334
        int dayOfMonth = curDate.getDayOfMonth();
34781 amit.gupta 335
        YearMonth yearMonth = YearMonth.now();
35284 aman 336
        for (int i = 0; i <= 6; i++) {
31751 tejbeer 337
            LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(i);
338
            int lengthOfMonth = YearMonth.from(startOfMonth).lengthOfMonth();
339
            LOGGER.info("Start of previous Month {}, start of next month Month {}", startOfMonth, startOfMonth.plusMonths(1));
340
            double monthSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusMonths(1), loginDetails.getFofoId(), false).get(fofoId);
35284 aman 341
            LOGGER.info("Month sales - {}", monthSales);
31751 tejbeer 342
            double mtdSales = fofoOrderItemRepository.selectSumMopGroupByRetailer(startOfMonth, startOfMonth.plusDays(Math.min(dayOfMonth, lengthOfMonth)), loginDetails.getFofoId(), false).get(fofoId);
27474 tejbeer 343
 
34781 amit.gupta 344
            PartnerType partnerType = partnerTypeChangeService.getTypeOnMonth(fofoId, yearMonth.minusMonths(i));
27474 tejbeer 345
 
31751 tejbeer 346
            MonthSaleModel ms = new MonthSaleModel();
347
            ms.setMtdSales(fofoUser.format((long) mtdSales));
348
            ms.setMonthlySales(fofoUser.format(((long) monthSales)));
349
            ms.setPartnerType(partnerType);
350
            ms.setMonth(startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
351
            monthSaleMap.put(i, ms);
352
        }
27474 tejbeer 353
 
31751 tejbeer 354
        model.addAttribute("monthSales", monthSaleMap);
355
        return "monthSales";
356
    }
27474 tejbeer 357
 
35064 aman 358
    @RequestMapping(value = "/getBrandwisePartnerSale", method = RequestMethod.GET)
359
    @ResponseBody
35284 aman 360
    public List<Map<String, Object>> getBrandwisePartnerSale(
361
            HttpServletRequest request,
362
            @RequestParam(name = "month", required = true, defaultValue = "0") int month,
363
            Model model) throws Exception {
364
 
35064 aman 365
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
366
        int fofoId = loginDetails.getFofoId();
35284 aman 367
 
368
        List<BrandWisePartnerSaleModel> mobileList =
369
                fofoStoreRepository.selectBrandWiseMonthlyPartnerSale(Collections.singletonList(fofoId), month);
370
 
371
        List<BrandWisePartnerSaleModel> accList =
372
                fofoStoreRepository.selectBrandWiseMonthlyPartnerAccessoriesSale(Collections.singletonList(fofoId), month);
373
 
35064 aman 374
        List<Map<String, Object>> response = new ArrayList<>();
35284 aman 375
 
376
        for (BrandWisePartnerSaleModel m : mobileList) {
35064 aman 377
            Map<String, Object> row = new HashMap<>();
378
            row.put("brand", m.getBrand());
36242 aman 379
            row.put("lmtd", fofoUser.format(m.getLmtd()));
380
            row.put("lmtdQty", m.getLmtdQty());
35064 aman 381
            row.put("mtd", fofoUser.format(m.getMtd()));
382
            row.put("mtdQty", m.getMtdQty());
383
            response.add(row);
384
        }
385
 
35284 aman 386
        long accLmtd = 0;
36242 aman 387
        long accLmtdQty = 0;
35284 aman 388
        long accMtd = 0;
389
        long accMtdQty = 0;
390
        for (BrandWisePartnerSaleModel a : accList) {
391
            accLmtd += a.getLmtd();
36242 aman 392
            accLmtdQty += a.getLmtdQty();
35284 aman 393
            accMtd += a.getMtd();
394
            accMtdQty += a.getMtdQty();
395
        }
396
        if (!accList.isEmpty()) {
397
            Map<String, Object> accRow = new HashMap<>();
398
            accRow.put("brand", "Accessories");
399
            accRow.put("lmtd", fofoUser.format(accLmtd));
36242 aman 400
            accRow.put("lmtdQty", accLmtdQty);
35284 aman 401
            accRow.put("mtd", fofoUser.format(accMtd));
402
            accRow.put("mtdQty", accMtdQty);
403
            response.add(accRow);
404
        }
35064 aman 405
 
406
        return response;
407
    }
408
 
35284 aman 409
 
35064 aman 410
    @RequestMapping(value = "/getBrandItemwisePartnerSale", method = RequestMethod.GET)
411
    @ResponseBody
412
    public List<BrandItemWisePartnerSaleModel> getBrandItemwisePartnerSale(HttpServletRequest request, @RequestParam(name = "month", required = true, defaultValue = "0") int month, @RequestParam(name = "brand") String brand, @RequestParam(name = "fofoId") Integer fofoId, Model model) throws Exception {
413
        List<BrandItemWisePartnerSaleModel> brandItemWisePartnerSaleModels = fofoStoreRepository.selectPartnerBrandItemMonthlySale(Collections.singletonList(fofoId), month, brand);
414
        LOGGER.info("brandItemWisePartnerSaleModels {}", brandItemWisePartnerSaleModels);
415
        return brandItemWisePartnerSaleModels;
416
    }
417
 
35119 aman 418
    @RequestMapping(value = "/getBrandItemwisePartnerSecondarySale", method = RequestMethod.GET)
419
    @ResponseBody
420
    public List<BrandItemWisePartnerSaleModel> getBrandItemwisePartnerSecondarySale(HttpServletRequest request, @RequestParam(name = "month", required = true, defaultValue = "0") int month, @RequestParam(name = "brand") String brand, @RequestParam(name = "fofoId") Integer fofoId, Model model) throws Exception {
421
        List<BrandItemWisePartnerSaleModel> brandItemWisePartnerSaleModels = fofoStoreRepository.selectPartnerBrandItemMonthlySecondarySale(Collections.singletonList(fofoId), month, brand);
422
        LOGGER.info("brandItemWisePartnerSaleModels {}", brandItemWisePartnerSaleModels);
423
        return brandItemWisePartnerSaleModels;
424
    }
35064 aman 425
 
35583 ranu 426
    @RequestMapping(value = "/dasboard/getDateWiseBulletins", method = RequestMethod.GET)
427
    public String getDateWiseBulletins(HttpServletRequest request,
428
                                       @RequestParam("date") String date,
429
                                       Model model) throws Exception {
32308 amit.gupta 430
 
37095 ranu 431
        // Callers on the partner-facing domain don't always carry the fofo admin
432
        // cookies (FOFO_ID / EMAIL_ID / ROLE_IDS) — cookiesProcessor would then
433
        // throw ProfitMandiBusinessException and the global handler would turn it
434
        // into a 400. Bulletins are per-position, so a session-less request has
435
        // nothing to show — return an empty bulletin list instead of failing.
436
        LoginDetails loginDetails;
437
        try {
438
            loginDetails = cookiesProcessor.getCookiesObject(request);
439
        } catch (ProfitMandiBusinessException e) {
440
            model.addAttribute("bulletins", new LinkedHashMap<>());
441
            return "bulletin-list";
442
        }
35583 ranu 443
        String email = loginDetails.getEmailId();
444
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
37095 ranu 445
        List<Position> positions = authUser == null
446
                ? new ArrayList<>()
447
                : positionRepository.selectAllByAuthUserId(authUser.getId());
35583 ranu 448
        LocalDate selectedDate = LocalDate.parse(date);
449
 
36849 ranu 450
        // Short-circuit when the caller has no Position rows. getTodayBulletin's
451
        // `positions` parameter is @NotEmpty validated — handing it an empty list
452
        // throws "List should not be empty" and 500s the dashboard. A user with
453
        // no positions simply has no bulletins to see, so render an empty page.
37096 ranu 454
        //
455
        // Bulletin fetch is best-effort: it fans out to several sub-services
456
        // (catalog offers / schemes / web offers / prebooking). If any one of
457
        // them throws, we'd otherwise bubble a 500/400 to the caller. For this
458
        // endpoint we prefer to degrade to an empty list rather than fail the
459
        // page — the frontend renders nothing, which is what the user asked for.
460
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> dbBulletins;
461
        if (positions == null || positions.isEmpty()) {
462
            dbBulletins = new HashMap<>();
463
        } else {
464
            try {
465
                dbBulletins = adminUser.getTodayBulletin(positions, selectedDate.atStartOfDay());
466
            } catch (Exception e) {
467
                LOGGER.warn("getTodayBulletin failed for date={} authUserId={}: {}",
468
                        date, authUser != null ? authUser.getId() : null, e.getMessage());
469
                dbBulletins = new HashMap<>();
470
            }
471
        }
35583 ranu 472
 
35585 ranu 473
        // Final ordered map (STRICT enum order)
35583 ranu 474
        Map<ProfitMandiConstants.BULLETIN_TYPE_ENUM, List<BulletinOfferModal>> bulletins =
475
                new LinkedHashMap<>();
476
 
477
        for (ProfitMandiConstants.BULLETIN_TYPE_ENUM type :
478
                ProfitMandiConstants.BULLETIN_TYPE_ENUM.values()) {
35585 ranu 479
 
480
            List<BulletinOfferModal> list = dbBulletins.get(type);
481
 
482
            if (list != null && !list.isEmpty()) {
483
                bulletins.put(type, list);   // only add if has data
484
            }
35583 ranu 485
        }
486
 
487
        model.addAttribute("bulletins", bulletins);
488
        return "bulletin-list";
489
    }
490
 
491
 
37427 ranu 492
    static String formatIndianCurrency(long amount) {
37327 ranu 493
        if (amount >= 10000000L) {
494
            return String.format("%.2f Cr", amount / 10000000.0);
31751 tejbeer 495
        }
37327 ranu 496
        if (amount >= 100000L) {
497
            return String.format("%.2f L", amount / 100000.0);
498
        }
499
        return String.format("%,d", amount);
31751 tejbeer 500
    }
29875 tejbeer 501
 
31751 tejbeer 502
    @RequestMapping(value = "/getGrnPendingOrderStatus", method = RequestMethod.GET)
503
    public String getGrnPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 504
 
31751 tejbeer 505
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
506
        int fofoId = loginDetails.getFofoId();
507
        List<Order> grnPendingOrders = orderRepository.selectGrnTimestampNull(fofoId, Arrays.asList(in.shop2020.model.v1.order.OrderStatus.DELIVERY_SUCCESS));
29746 manish 508
 
31751 tejbeer 509
        model.addAttribute("grnPendingOrders", grnPendingOrders);
510
        return "purchase-grn-order-status";
511
    }
29875 tejbeer 512
 
31751 tejbeer 513
    @RequestMapping(value = "/getPendingOrderStatus", method = RequestMethod.GET)
514
    public String getPendingOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 515
 
31751 tejbeer 516
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
517
        int fofoId = loginDetails.getFofoId();
518
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
29875 tejbeer 519
 
31751 tejbeer 520
        orderStatus.add(in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING);
29875 tejbeer 521
 
31751 tejbeer 522
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
523
        List<Integer> submittedOrderIds = order.stream().filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.SUBMITTED_FOR_PROCESSING).map(x -> x.getId()).collect(Collectors.toList());
524
        model.addAttribute("submittedOrderIds", submittedOrderIds);
525
        if (!submittedOrderIds.isEmpty()) {
29875 tejbeer 526
 
31751 tejbeer 527
            List<LineItem> submittedLineItem = lineItemRepository.selectLineItem(submittedOrderIds);
528
            Map<Integer, LineItem> submittedLineItemMap = submittedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
33075 amit.gupta 529
            //LOGGER.info("submittedLineItemMap {}", submittedLineItemMap);
31751 tejbeer 530
            model.addAttribute("submittedLineItemMap", submittedLineItemMap);
531
        }
29875 tejbeer 532
 
31751 tejbeer 533
        return "purchase-pending-order-status";
534
    }
29875 tejbeer 535
 
31751 tejbeer 536
    @RequestMapping(value = "/getBilledOrderStatus", method = RequestMethod.GET)
537
    public String getBilledOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 538
 
31751 tejbeer 539
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
540
        int fofoId = loginDetails.getFofoId();
541
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
542
        orderStatus.add(in.shop2020.model.v1.order.OrderStatus.BILLED);
29875 tejbeer 543
 
31751 tejbeer 544
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
545
        List<Integer> billedOrderIds = order.stream().filter(x -> x.getStatus() == in.shop2020.model.v1.order.OrderStatus.BILLED).map(x -> x.getId()).collect(Collectors.toList());
546
        LOGGER.info("billedOrderIds {}", billedOrderIds);
547
        model.addAttribute("billedOrderIds", billedOrderIds);
29875 tejbeer 548
 
31751 tejbeer 549
        if (!billedOrderIds.isEmpty()) {
550
            List<LineItem> billedLineItem = lineItemRepository.selectLineItem(billedOrderIds);
551
            Map<Integer, LineItem> billedLineItemMap = billedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
552
            LOGGER.info("billedLineItemMap {}", billedLineItemMap);
553
            model.addAttribute("billedLineItemMap", billedLineItemMap);
554
        }
29875 tejbeer 555
 
31751 tejbeer 556
        return "purchase-billed-order-status";
557
    }
29875 tejbeer 558
 
31751 tejbeer 559
    @RequestMapping(value = "/getShippedOrderStatus", method = RequestMethod.GET)
560
    public String getShippedOrderStatus(HttpServletRequest request, Model model) throws Exception {
29875 tejbeer 561
 
31751 tejbeer 562
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
563
        int fofoId = loginDetails.getFofoId();
564
        ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
29875 tejbeer 565
 
31751 tejbeer 566
        orderStatus.add(SHIPPED_FROM_WH);
29875 tejbeer 567
 
31751 tejbeer 568
        List<Order> order = orderRepository.selectOrders(fofoId, orderStatus);
569
        List<Integer> shippedOrderIds = order.stream().filter(x -> x.getPartnerGrnTimestamp() == null).map(x -> x.getId()).collect(Collectors.toList());
570
        model.addAttribute("shippedOrderIds", shippedOrderIds);
571
        LOGGER.info("shippedOrderIds {}", shippedOrderIds);
29875 tejbeer 572
 
31751 tejbeer 573
        if (!shippedOrderIds.isEmpty()) {
574
            List<LineItem> shippedLineItem = lineItemRepository.selectLineItem(shippedOrderIds);
575
            Map<Integer, LineItem> shippedLineItemMap = shippedLineItem.stream().collect(Collectors.toMap(x -> x.getOrderId(), x -> x));
576
            LOGGER.info("shippedLineItemMap {}", shippedLineItemMap);
29875 tejbeer 577
 
31751 tejbeer 578
            model.addAttribute("shippedLineItemMap", shippedLineItemMap);
579
        }
580
        return "purchase-shipped-order-status";
581
    }
23923 amit.gupta 582
 
31337 amit.gupta 583
 
31353 amit.gupta 584
 
31751 tejbeer 585
    @RequestMapping(value = "/partnerTotalIncomeByMonth/{yearMonth}", method = RequestMethod.GET)
32836 amit.gupta 586
    public String getPartnerTotalIncomeByMonth(HttpServletRequest request, @PathVariable int yearMonth, Model model) throws
587
            Exception {
30224 tejbeer 588
 
31751 tejbeer 589
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
34813 aman 590
        Map<String, Object> data = retailerService
591
                .computeIncomeMap(loginDetails.getFofoId(), yearMonth);
592
//        long pendingIncome = 0;
593
//        long partnerPurchaseIn = 0;
594
//        long partnerCreditedSale = 0;
595
//        long partnerFrontIncome = 0;
596
//
597
//        LocalDateTime startOfMonth = LocalDate.now().minusMonths(yearMonth).withDayOfMonth(1).atStartOfDay();
598
//        LocalDateTime endOfMonth = startOfMonth.plusMonths(1).toLocalDate().atStartOfDay();
599
//
600
//        AllPurchaseInventoryModel partnerlPendingSaleAmount = schemeInOutRepository.selectAllPendingSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
601
//        AllPurchaseInventoryModel partnerCreditedSaleAmount = schemeInOutRepository.selectAllCreditedSaleInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
602
//        AllPurchaseInventoryModel partnerPurchaseInAmount = schemeInOutRepository.selectAllPurchaseInventoryByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
603
//
604
//        AllPurchaseInventoryModel partnerFrontIncomes = schemeInOutRepository.selectFrontIncomeByFofoId(loginDetails.getFofoId(), startOfMonth, endOfMonth);
605
//
606
//        List<OfferPayoutImeiIncomeModel> offerPayoutImeiIncomeModels = offerPayoutRepository.getTotalPayoutsByPartnerPeriod(YearMonth.of(startOfMonth.getYear(), startOfMonth.getMonth()), loginDetails.getFofoId(), null, null);
607
//
608
//        long additionalIncome = offerPayoutImeiIncomeModels.stream().collect(Collectors.summingDouble(x -> x.getSalePayout() + x.getPurchasePayout())).longValue();
609
//        // AllPurchaseInventoryModel partnerAdditionalIncome =
610
//        // offerRepository.selectPurchaseIncome(loginDetails.getFofoId(), startOfMonth,
611
//        // endOfMonth);
612
//
613
//        LOGGER.info("partnerfrontIncomes" + partnerFrontIncomes);
614
//
615
//        LOGGER.info("partnerCreditedSaleAmount" + partnerCreditedSaleAmount);
616
//        LOGGER.info("partnerPurchaseInAmount" + partnerPurchaseInAmount);
617
//        LOGGER.info("partnerlPendingSaleAmount" + partnerlPendingSaleAmount);
618
//
619
//        if (partnerlPendingSaleAmount != null) {
620
//
621
//            pendingIncome = partnerlPendingSaleAmount.getAmount();
622
//
623
//            LOGGER.info("pendingIncome" + pendingIncome);
624
//
625
//        }
626
//
627
//        if (partnerCreditedSaleAmount != null) {
628
//
629
//            partnerCreditedSale = partnerCreditedSaleAmount.getAmount();
630
//
631
//            LOGGER.info("partnerCreditedSale" + partnerCreditedSale);
632
//
633
//        }
634
//        if (partnerFrontIncomes != null) {
635
//
636
//            partnerFrontIncome = partnerFrontIncomes.getAmount();
637
//            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
638
//
639
//        }
640
//        if (partnerPurchaseInAmount != null) {
641
//
642
//            partnerPurchaseIn = partnerPurchaseInAmount.getAmount();
643
//            LOGGER.info("partnerPurchaseIn" + partnerPurchaseIn);
644
//
645
//        }
646
//
647
//        LOGGER.info("partnerPurchaseInTT" + partnerPurchaseIn);
648
//        LOGGER.info("partnerCreditedSaleTT" + partnerCreditedSale);
649
//        LOGGER.info("pendingIncomeTT" + pendingIncome);
650
//
651
//        long totalIncome = partnerCreditedSale + partnerPurchaseIn + pendingIncome + partnerFrontIncome + additionalIncome;
652
//
653
//        long creditedIncome = partnerCreditedSale + partnerPurchaseIn + partnerFrontIncome + additionalIncome;
654
//
655
//        long pendingTotalIncome = pendingIncome;
656
//        LOGGER.info("totalIncome" + totalIncome);
657
//        LOGGER.info("creditedIncome" + creditedIncome);
658
//        LOGGER.info("pendingTotalIncome" + pendingTotalIncome);
659
//
660
        model.addAttribute("totalIncome", data.get("totalIncome"));
661
        model.addAttribute("creditedIncome", data.get("creditedIncome"));
662
        model.addAttribute("pendingTotalIncome", data.get("pendingIncome"));
663
//
664
//        Map<Integer, String> monthValueMap = new HashMap<>();
665
//        for (int i = 0; i <= 5; i++) {
666
//            LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
667
//            monthValueMap.put(i, monthStart.format(DateTimeFormatter.ofPattern("MMM''uu")));
668
//        }
669
//
670
        model.addAttribute("month", data.get("monthIndex"));
671
        model.addAttribute("monthValueMap", data.get("monthValueMap"));
672
        LOGGER.info("income data", data);
673
        model.addAttribute("data", data);
31751 tejbeer 674
        return "partner-total-income";
675
    }
30224 tejbeer 676
 
31751 tejbeer 677
    @RequestMapping(value = "/getMonthsInvestment", method = RequestMethod.GET)
32836 amit.gupta 678
    public String getMonthsInvestment(HttpServletRequest request,
679
                                      @RequestParam(name = "month", required = true, defaultValue = "0") int month, Model model) throws Exception {
31751 tejbeer 680
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
681
        int fofoId = loginDetails.getFofoId();
682
        Map<String, Object> investment = fofoUser.getInvestmentsMonths(fofoId, month);
28430 tejbeer 683
 
31751 tejbeer 684
        LocalDateTime currentMonthStart = LocalDateTime.now().withDayOfMonth(1);
685
        LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
686
        LocalDateTime currentMonthEnd = currentMonthStart.plusMonths(1).withDayOfMonth(1);
32626 amit.gupta 687
        double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(currentMonthStart, currentMonthEnd)) / 2;
688
        double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(lastMonthStart, currentMonthStart)) / 2;
689
        double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.withEndDate(currentMonthEnd)) / 2;
31751 tejbeer 690
        model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
691
        model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
692
        model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
28272 tejbeer 693
 
31751 tejbeer 694
        long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
28272 tejbeer 695
 
31751 tejbeer 696
        long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false, currentMonthStart.minusMonths(month), currentMonthEnd.minusMonths(month));
697
        if (hygieneCount == 0 && invalidHygieneCount == 0) {
698
            invalidHygieneCount = 1;
699
        }
700
        Map<Integer, String> monthValueMap = new HashMap<>();
701
        for (int i = 0; i <= 5; i++) {
702
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
703
            monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
704
        }
705
        model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
706
        model.addAttribute("monthValueMap", monthValueMap);
707
        model.addAttribute("investments", investment);
708
        model.addAttribute("monthDays", LocalDate.now().minusMonths(month).lengthOfMonth());
709
        model.addAttribute("dayOfMonth", LocalDate.now().minusMonths(month).lengthOfMonth());
710
        model.addAttribute("month", month);
711
        return "performance";
712
    }
28272 tejbeer 713
 
31751 tejbeer 714
    @RequestMapping(value = "/investmentDetails", method = RequestMethod.GET)
715
    public String getInvestmentDetails(HttpServletRequest request, Model model) throws Exception {
716
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
717
        int fofoId = loginDetails.getFofoId();
718
        ChartInvestmentModel cm = fofoUser.getInvestmentChart(fofoId);
719
        model.addAttribute("chartPieMap", gson.toJson(cm));
27884 tejbeer 720
 
31751 tejbeer 721
        LOGGER.info("InvestmentChart" + gson.toJson(cm));
722
        LOGGER.info("InvestmentChart" + cm);
723
        return "investmentdetails";
724
    }
27884 tejbeer 725
 
31751 tejbeer 726
    @RequestMapping(value = "/getlmsLineChart", method = RequestMethod.GET)
34528 ranu 727
    public String getlmsLineChart(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
728
        if (fofoId == 0) {
729
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
730
            fofoId = loginDetails.getFofoId();
731
        }
28430 tejbeer 732
 
34528 ranu 733
        ChartModel cm = fofoUser.getLmsLineChart(fofoId);
734
 
31751 tejbeer 735
        LOGGER.info("linechartMap" + gson.toJson(cm));
736
        model.addAttribute("linechartMap", gson.toJson(cm));
737
        return "lmsLineChart";
738
    }
28430 tejbeer 739
 
31751 tejbeer 740
    @RequestMapping(value = "/getMonthlyPurchaseLineChart", method = RequestMethod.GET)
34528 ranu 741
    public String getMonthlyPurchaseLineChart(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
742
        if (fofoId == 0) {
743
            LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
744
            fofoId = loginDetails.getFofoId();
745
        }
31751 tejbeer 746
        ChartModel cm = fofoUser.getPurchaseOrderChart(fofoId);
28439 tejbeer 747
 
31751 tejbeer 748
        LOGGER.info("chartMap" + gson.toJson(cm));
749
        model.addAttribute("chartMap", gson.toJson(cm));
28439 tejbeer 750
 
31751 tejbeer 751
        return "purchase_chart";
752
    }
28439 tejbeer 753
 
31751 tejbeer 754
    @RequestMapping(value = "/getBarChart", method = RequestMethod.GET)
34388 tejus.loha 755
    public String getBarChart(HttpServletRequest request, @RequestParam(required = false) LocalDate from, @RequestParam(required = false) LocalDate to,@RequestParam(required = false) Boolean isQuantity ,Model model) throws Exception {
31751 tejbeer 756
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
757
        int fofoId = loginDetails.getFofoId();
34388 tejus.loha 758
        LocalDateTime curDate = from == null ? LocalDate.now().atStartOfDay().withDayOfMonth(1) : from.atStartOfDay();
759
        LocalDateTime lastDate = to == null ? LocalDate.now().atStartOfDay().with(LocalTime.MAX) : to.atStartOfDay();
760
        isQuantity = isQuantity==null?false:isQuantity;
761
        ChartModel cm = fofoUser.getBrandChart(fofoId, from, to,isQuantity);
762
        LOGGER.info("from" + curDate);
763
        LOGGER.info("to" + lastDate);
31751 tejbeer 764
        LOGGER.info("chartMap" + gson.toJson(cm));
765
        model.addAttribute("chartMap", gson.toJson(cm));
34388 tejus.loha 766
        model.addAttribute("from", curDate.toLocalDate());
767
        model.addAttribute("to", lastDate.toLocalDate());
768
        model.addAttribute("fofoId", fofoId);
769
        model.addAttribute("isQuantity",isQuantity);
31751 tejbeer 770
        return "bar_chart";
771
    }
28430 tejbeer 772
 
34388 tejus.loha 773
    @GetMapping(value = "/brandWiseFofoSaleData")
774
    public String getBarChartModelWise(HttpServletRequest request,
775
                                       @RequestParam LocalDate from,
776
                                       @RequestParam LocalDate to,
777
                                       @RequestParam String brand,
778
                                       @RequestParam boolean isQuantity,
779
                                       @RequestParam int fofoId, Model model) throws Exception {
780
        ChartModel cm = fofoUser.getModelBrandChart(fofoId, brand, from, to,isQuantity);
781
 
782
        LOGGER.info("chartMap" + gson.toJson(cm));
783
 
784
        model.addAttribute("chartMap", gson.toJson(cm));
785
        return "bar_chart_model_wise";
786
    }
787
 
31751 tejbeer 788
    @RequestMapping(value = "/getPriceDropDetails", method = RequestMethod.GET)
32836 amit.gupta 789
    public String getPriceDropDetails(HttpServletRequest request,
790
                                      @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
791
                                      @RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
792
                                      @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws
793
            Exception {
28455 tejbeer 794
 
31751 tejbeer 795
        LOGGER.info("params" + fofoId + brand + yearMonth);
28455 tejbeer 796
 
31751 tejbeer 797
        List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository.selectBrandPendingPriceDropWithDetailsByYearMonth(fofoId, brand, yearMonth);
28455 tejbeer 798
 
31751 tejbeer 799
        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
28455 tejbeer 800
 
31751 tejbeer 801
        model.addAttribute("priceDropdetailsList", priceDropdetailsList);
28455 tejbeer 802
 
31751 tejbeer 803
        return "price-drop-details";
804
    }
28825 tejbeer 805
 
31751 tejbeer 806
    @RequestMapping(value = "/getPriceDropDetailSixMonths", method = RequestMethod.GET)
32836 amit.gupta 807
    public String getPriceDropDetailSixMonths(HttpServletRequest request,
808
                                              @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
809
                                              @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
28455 tejbeer 810
 
31751 tejbeer 811
        LOGGER.info("params" + fofoId + brand);
812
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
813
        LocalDateTime startfMonthSixMonth = curDate.withDayOfMonth(1).minusMonths(12);
814
        LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(6);
28641 amit.gupta 815
 
31751 tejbeer 816
        List<PriceDropWithDetailsByYearMonthModel> priceDropdetailsList = priceDropRepository.selectBrandPendingPriceDropWithDetailsAndSixMonth(fofoId, brand, startfMonthSixMonth, endMonthTotal);
28641 amit.gupta 817
 
31751 tejbeer 818
        LOGGER.info("priceDropdetailsList" + priceDropdetailsList);
28641 amit.gupta 819
 
31751 tejbeer 820
        model.addAttribute("priceDropdetailsList", priceDropdetailsList);
28641 amit.gupta 821
 
31751 tejbeer 822
        return "price-drop-details";
823
    }
28641 amit.gupta 824
 
31751 tejbeer 825
    @RequestMapping(value = "/getMonthlyPriceDrop", method = RequestMethod.GET)
34528 ranu 826
    public String getMonthlyPriceDropTabular(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
31751 tejbeer 827
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
34528 ranu 828
        if (fofoId == 0) {
829
            fofoId = loginDetails.getFofoId();
830
        }
831
 
31751 tejbeer 832
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
28455 tejbeer 833
 
31751 tejbeer 834
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
835
        LocalDateTime startfMonthTotal = curDate.withDayOfMonth(1).minusMonths(12);
836
        LocalDateTime endMonthTotal = curDate.withDayOfMonth(1).minusMonths(5);
28455 tejbeer 837
 
31751 tejbeer 838
        LOGGER.info("startfMonthTotal" + startfMonthTotal);
29875 tejbeer 839
 
31751 tejbeer 840
        LOGGER.info("endMonthTotal" + endMonthTotal);
841
        List<YearMonth> yms = new ArrayList<YearMonth>();
28455 tejbeer 842
 
31751 tejbeer 843
        for (int i = 0; i <= 5; i++) {
844
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
845
        }
846
        Collections.reverse(yms);
847
        model.addAttribute("yms", yms);
848
        LOGGER.info("ym" + yms);
28455 tejbeer 849
 
31751 tejbeer 850
        List<PriceDropYearMonthModel> priceDropYearMonthModels = priceDropRepository.selectBrandPendingPriceDropByYearMonth(fofoId, startOfMonth);
28455 tejbeer 851
 
31751 tejbeer 852
        List<PriceDropBrandModel> priceDropBrandSixMonthTotals = priceDropRepository.selectSixMonthBrandPriceDropByYearMonth(fofoId, startfMonthTotal, endMonthTotal);
28641 amit.gupta 853
 
31751 tejbeer 854
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
28455 tejbeer 855
 
31751 tejbeer 856
        Map<String, Map<YearMonth, Double>> brandMonthValue = new HashMap<>();
28641 amit.gupta 857
 
31751 tejbeer 858
        LOGGER.info("priceDropBrandSixMonthTotals" + priceDropBrandSixMonthTotals);
28825 tejbeer 859
 
31751 tejbeer 860
        Map<String, Double> priceDropBrandSixMonthMap = priceDropBrandSixMonthTotals.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
28825 tejbeer 861
 
31751 tejbeer 862
        model.addAttribute("priceDropBrandSixMonthMap", priceDropBrandSixMonthMap);
863
        LOGGER.info("priceDropYearMonthModels" + priceDropYearMonthModels);
28641 amit.gupta 864
 
31751 tejbeer 865
        for (PriceDropYearMonthModel pdm : priceDropYearMonthModels) {
866
            Map<YearMonth, Double> brandValue = new HashMap<>();
28455 tejbeer 867
 
31751 tejbeer 868
            if (brandMonthValue.containsKey(pdm.getBrand())) {
869
                brandValue = brandMonthValue.get(pdm.getBrand());
870
                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
871
            } else {
28455 tejbeer 872
 
31751 tejbeer 873
                brandValue.put(YearMonth.parse(pdm.getYearMonth(), dateTimeFormatter), (double) pdm.getAmount());
28455 tejbeer 874
 
31751 tejbeer 875
            }
876
            brandMonthValue.put(pdm.getBrand(), brandValue);
877
        }
878
        List<String> brands = new ArrayList<>();
879
        brands.add("Accessories");
880
        brands.add("Oppo");
881
        brands.add("Vivo");
882
        brands.add("Samsung");
883
        brands.add("Realme");
884
        brands.add("MI");
885
        brands.add("Tecno");
886
        brands.add("Itel");
887
        brands.add("Nokia");
29578 tejbeer 888
 
31751 tejbeer 889
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
28455 tejbeer 890
 
31751 tejbeer 891
        model.addAttribute("brands", brands);
28825 tejbeer 892
 
31751 tejbeer 893
        for (String brand : brands) {
894
            Map<YearMonth, Double> yearMonthValue = brandMonthValue.get(brand);
895
            for (int i = 5; i >= 0; i--) {
28455 tejbeer 896
 
31751 tejbeer 897
                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
28455 tejbeer 898
 
31751 tejbeer 899
                if (yearMonthValue != null) {
900
                    if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
901
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
902
                    }
28455 tejbeer 903
 
31751 tejbeer 904
                } else {
905
                    yearMonthValue = new HashMap<>();
906
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
907
                }
908
            }
28455 tejbeer 909
 
31751 tejbeer 910
            Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
28455 tejbeer 911
 
31751 tejbeer 912
            brandMonthValue.put(brand, sortedMonthBrandValue);
28455 tejbeer 913
 
31751 tejbeer 914
            sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
28455 tejbeer 915
 
31751 tejbeer 916
        }
28455 tejbeer 917
 
31751 tejbeer 918
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
919
        model.addAttribute("fofoId", fofoId);
28455 tejbeer 920
 
31751 tejbeer 921
        model.addAttribute("sortedBrandValue", sortedBrandValue);
28455 tejbeer 922
 
31751 tejbeer 923
        return "price-drop-tabular";
924
    }
28455 tejbeer 925
 
31751 tejbeer 926
    @RequestMapping(value = "/getMonthlyActivation", method = RequestMethod.GET)
34528 ranu 927
    public String getMonthlyActivation(HttpServletRequest request, Model model, @RequestParam(name = "fofoId", defaultValue = "0") int fofoId) throws Exception {
31751 tejbeer 928
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
34528 ranu 929
        if (fofoId == 0) {
930
            fofoId = loginDetails.getFofoId();
931
        }
28455 tejbeer 932
 
31751 tejbeer 933
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
934
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
29578 tejbeer 935
 
31751 tejbeer 936
        List<YearMonth> yms = new ArrayList<YearMonth>();
29578 tejbeer 937
 
31751 tejbeer 938
        for (int i = 0; i <= 5; i++) {
939
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
940
        }
941
        Collections.reverse(yms);
942
        model.addAttribute("yms", yms);
943
        LOGGER.info("ym" + yms);
29578 tejbeer 944
 
31751 tejbeer 945
        List<ActivationYearMonthModel> pendingActivationModels = schemeInOutRepository.selectPendingActivationGroupByBrandYearMonth(fofoId, startOfMonth);
29578 tejbeer 946
 
31751 tejbeer 947
        List<ActivationBrandModel> pendingActivationBeforeSixMonth = schemeInOutRepository.selectByYearMonthActivationGroupByBrand(fofoId, startOfMonth);
29578 tejbeer 948
 
31751 tejbeer 949
        Map<String, Double> pendingActivationBeforeSixMonthMap = pendingActivationBeforeSixMonth.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
29578 tejbeer 950
 
31751 tejbeer 951
        model.addAttribute("pendingActivationBeforeSixMonthMap", pendingActivationBeforeSixMonthMap);
29578 tejbeer 952
 
31751 tejbeer 953
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
29578 tejbeer 954
 
31751 tejbeer 955
        Map<String, Map<YearMonth, Double>> activationBrandMonthMap = new HashMap<>();
29578 tejbeer 956
 
31751 tejbeer 957
        for (ActivationYearMonthModel pam : pendingActivationModels) {
958
            Map<YearMonth, Double> brandValue = new HashMap<>();
29578 tejbeer 959
 
31751 tejbeer 960
            if (activationBrandMonthMap.containsKey(pam.getBrand())) {
961
                brandValue = activationBrandMonthMap.get(pam.getBrand());
962
                brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
963
            } else {
29578 tejbeer 964
 
31751 tejbeer 965
                brandValue.put(YearMonth.parse(pam.getYearMonth(), dateTimeFormatter), (double) pam.getAmount());
29578 tejbeer 966
 
31751 tejbeer 967
            }
968
            activationBrandMonthMap.put(pam.getBrand(), brandValue);
969
        }
28455 tejbeer 970
 
31751 tejbeer 971
        List<String> brands = new ArrayList<>();
972
        brands.add("Oppo");
973
        brands.add("Vivo");
974
        brands.add("Samsung");
975
        brands.add("Realme");
976
        brands.add("MI");
977
        brands.add("Tecno");
978
        brands.add("Itel");
979
        brands.add("Nokia");
980
        brands.add("Lava");
981
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
29578 tejbeer 982
 
31751 tejbeer 983
        model.addAttribute("brands", brands);
29578 tejbeer 984
 
31751 tejbeer 985
        for (String brand : brands) {
986
            Map<YearMonth, Double> yearMonthValue = activationBrandMonthMap.get(brand);
987
            for (int i = 5; i >= 0; i--) {
988
                LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
989
                if (yearMonthValue != null) {
990
                    if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
991
                        yearMonthValue.put(YearMonth.from(startMonth), 0.0);
992
                    }
29578 tejbeer 993
 
31751 tejbeer 994
                } else {
995
                    yearMonthValue = new HashMap<>();
996
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
997
                }
998
            }
999
            Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1000
            activationBrandMonthMap.put(brand, sortedMonthBrandValue);
1001
            sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1002
        }
28455 tejbeer 1003
 
31751 tejbeer 1004
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
1005
        model.addAttribute("sortedBrandValue", sortedBrandValue);
1006
        model.addAttribute("fofoId", fofoId);
1007
        return "activation-tabular";
1008
    }
28455 tejbeer 1009
 
31751 tejbeer 1010
    @RequestMapping(value = "/getMonthlyActivationItemDetail", method = RequestMethod.GET)
32836 amit.gupta 1011
    public String getMonthlyActivationItemDetail(HttpServletRequest request,
1012
                                                 @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1013
                                                 @RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1014
                                                 @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws
1015
            Exception {
28455 tejbeer 1016
 
31751 tejbeer 1017
        LOGGER.info("params" + fofoId + brand + yearMonth);
29578 tejbeer 1018
 
31751 tejbeer 1019
        List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository.selectBrandPendingActivationItemDetails(fofoId, brand, yearMonth);
29578 tejbeer 1020
 
35395 amit 1021
        if (!activationItemDetails.isEmpty()) {
1022
            // Batch fetch to avoid N+1 queries
1023
            List<Integer> inventoryItemIds = activationItemDetails.stream()
1024
                    .map(ActivationItemDetailModel::getInventoryItemId)
1025
                    .collect(Collectors.toList());
29578 tejbeer 1026
 
35395 amit 1027
            Map<Integer, List<FofoLineItem>> lineItemsByInventoryId;
1028
            try {
1029
                lineItemsByInventoryId = fofoLineItemRepository
1030
                        .selectByInventoryItemIds(inventoryItemIds).stream()
1031
                        .collect(Collectors.groupingBy(FofoLineItem::getInventoryItemId));
1032
            } catch (ProfitMandiBusinessException e) {
1033
                LOGGER.error("Error fetching FofoLineItems by inventory IDs", e);
1034
                lineItemsByInventoryId = new HashMap<>();
1035
            }
29578 tejbeer 1036
 
35395 amit 1037
            // Get max FofoOrderItemId for each inventory item
1038
            Set<Integer> fofoOrderItemIds = lineItemsByInventoryId.values().stream()
1039
                    .map(list -> list.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1))
1040
                    .filter(id -> id > 0)
1041
                    .collect(Collectors.toSet());
29578 tejbeer 1042
 
35395 amit 1043
            Map<Integer, FofoOrderItem> fofoOrderItemMap;
1044
            try {
1045
                fofoOrderItemMap = fofoOrderItemRepository
1046
                        .selectByIds(new ArrayList<>(fofoOrderItemIds)).stream()
1047
                        .collect(Collectors.toMap(FofoOrderItem::getId, foi -> foi));
1048
            } catch (ProfitMandiBusinessException e) {
1049
                LOGGER.error("Error fetching FofoOrderItems by IDs", e);
1050
                fofoOrderItemMap = new HashMap<>();
1051
            }
29578 tejbeer 1052
 
35395 amit 1053
            Set<Integer> orderIds = fofoOrderItemMap.values().stream()
1054
                    .map(FofoOrderItem::getOrderId)
1055
                    .collect(Collectors.toSet());
29578 tejbeer 1056
 
35395 amit 1057
            Map<Integer, FofoOrder> fofoOrderMap = new HashMap<>();
1058
            try {
1059
                fofoOrderMap = fofoOrderRepository
1060
                        .selectAllByOrderIds(new ArrayList<>(orderIds)).stream()
1061
                        .collect(Collectors.toMap(FofoOrder::getId, fo -> fo));
1062
            } catch (ProfitMandiBusinessException e) {
1063
                LOGGER.error("Error fetching FofoOrders by order IDs", e);
1064
            }
29578 tejbeer 1065
 
35395 amit 1066
            for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1067
                List<FofoLineItem> flis = lineItemsByInventoryId.get(activationItemDetail.getInventoryItemId());
1068
                if (flis != null && !flis.isEmpty()) {
1069
                    int maxFofoOrderItemId = flis.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1);
1070
                    FofoOrderItem foi = fofoOrderItemMap.get(maxFofoOrderItemId);
1071
                    if (foi != null) {
1072
                        FofoOrder fo = fofoOrderMap.get(foi.getOrderId());
1073
                        if (fo != null) {
1074
                            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1075
                        }
1076
                    }
1077
                }
1078
            }
31751 tejbeer 1079
        }
1080
        LOGGER.info("activationItemDetails" + activationItemDetails);
29578 tejbeer 1081
 
31751 tejbeer 1082
        model.addAttribute("activationItemDetails", activationItemDetails);
29578 tejbeer 1083
 
31751 tejbeer 1084
        return "activation-pending-item-details";
1085
    }
28455 tejbeer 1086
 
31751 tejbeer 1087
    @RequestMapping(value = "/getMonthlyActivationBeforeSixMonthsItemDetail", method = RequestMethod.GET)
32836 amit.gupta 1088
    public String getMonthlyActivationItemDetail(HttpServletRequest request,
1089
                                                 @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1090
                                                 @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
31751 tejbeer 1091
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
29578 tejbeer 1092
 
31751 tejbeer 1093
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
29578 tejbeer 1094
 
31751 tejbeer 1095
        List<ActivationItemDetailModel> activationItemDetails = schemeInOutRepository.selectBrandPendingActivationItemDetailByYearMonth(fofoId, brand, startOfMonth);
29578 tejbeer 1096
 
35395 amit 1097
        if (!activationItemDetails.isEmpty()) {
1098
            // Batch fetch to avoid N+1 queries
1099
            List<Integer> inventoryItemIds = activationItemDetails.stream()
1100
                    .map(ActivationItemDetailModel::getInventoryItemId)
1101
                    .collect(Collectors.toList());
29578 tejbeer 1102
 
35395 amit 1103
            Map<Integer, List<FofoLineItem>> lineItemsByInventoryId;
1104
            try {
1105
                lineItemsByInventoryId = fofoLineItemRepository
1106
                        .selectByInventoryItemIds(inventoryItemIds).stream()
1107
                        .collect(Collectors.groupingBy(FofoLineItem::getInventoryItemId));
1108
            } catch (ProfitMandiBusinessException e) {
1109
                LOGGER.error("Error fetching FofoLineItems by inventory IDs", e);
1110
                lineItemsByInventoryId = new HashMap<>();
1111
            }
29578 tejbeer 1112
 
35395 amit 1113
            Set<Integer> fofoOrderItemIds = lineItemsByInventoryId.values().stream()
1114
                    .map(list -> list.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1))
1115
                    .filter(id -> id > 0)
1116
                    .collect(Collectors.toSet());
29578 tejbeer 1117
 
35395 amit 1118
            Map<Integer, FofoOrderItem> fofoOrderItemMap;
1119
            try {
1120
                fofoOrderItemMap = fofoOrderItemRepository
1121
                        .selectByIds(new ArrayList<>(fofoOrderItemIds)).stream()
1122
                        .collect(Collectors.toMap(FofoOrderItem::getId, foi -> foi));
1123
            } catch (ProfitMandiBusinessException e) {
1124
                LOGGER.error("Error fetching FofoOrderItems by IDs", e);
1125
                fofoOrderItemMap = new HashMap<>();
1126
            }
29578 tejbeer 1127
 
35395 amit 1128
            Set<Integer> orderIds = fofoOrderItemMap.values().stream()
1129
                    .map(FofoOrderItem::getOrderId)
1130
                    .collect(Collectors.toSet());
29578 tejbeer 1131
 
35395 amit 1132
            Map<Integer, FofoOrder> fofoOrderMap = new HashMap<>();
1133
            try {
1134
                fofoOrderMap = fofoOrderRepository
1135
                        .selectAllByOrderIds(new ArrayList<>(orderIds)).stream()
1136
                        .collect(Collectors.toMap(FofoOrder::getId, fo -> fo));
1137
            } catch (ProfitMandiBusinessException e) {
1138
                LOGGER.error("Error fetching FofoOrders by order IDs", e);
1139
            }
29578 tejbeer 1140
 
35395 amit 1141
            for (ActivationItemDetailModel activationItemDetail : activationItemDetails) {
1142
                List<FofoLineItem> flis = lineItemsByInventoryId.get(activationItemDetail.getInventoryItemId());
1143
                if (flis != null && !flis.isEmpty()) {
1144
                    int maxFofoOrderItemId = flis.stream().mapToInt(FofoLineItem::getFofoOrderItemId).max().orElse(-1);
1145
                    FofoOrderItem foi = fofoOrderItemMap.get(maxFofoOrderItemId);
1146
                    if (foi != null) {
1147
                        FofoOrder fo = fofoOrderMap.get(foi.getOrderId());
1148
                        if (fo != null) {
1149
                            activationItemDetail.setInvoiceNumber(fo.getInvoiceNumber());
1150
                        }
1151
                    }
1152
                }
1153
            }
31751 tejbeer 1154
        }
1155
        LOGGER.info("activationItemDetails" + activationItemDetails);
29578 tejbeer 1156
 
31751 tejbeer 1157
        model.addAttribute("activationItemDetails", activationItemDetails);
29578 tejbeer 1158
 
31751 tejbeer 1159
        return "activation-pending-item-details";
1160
    }
29578 tejbeer 1161
 
31751 tejbeer 1162
    @RequestMapping(value = "/getMonthlySamsungUpgradeOffer", method = RequestMethod.GET)
1163
    public String getMonthlySamsungUpgradeOffer(HttpServletRequest request, Model model) throws Exception {
1164
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1165
        int fofoId = loginDetails.getFofoId();
29707 tejbeer 1166
 
31751 tejbeer 1167
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
1168
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
29707 tejbeer 1169
 
31751 tejbeer 1170
        List<YearMonth> yms = new ArrayList<YearMonth>();
29707 tejbeer 1171
 
31751 tejbeer 1172
        for (int i = 0; i <= 5; i++) {
1173
            yms.add(YearMonth.from(curDate.withDayOfMonth(1).minusMonths(i)));
1174
        }
1175
        Collections.reverse(yms);
1176
        model.addAttribute("yms", yms);
1177
        LOGGER.info("ym" + yms);
29707 tejbeer 1178
 
31751 tejbeer 1179
        List<SamsungUpgradeOfferModel> suos = samsungUpgradeOfferRepository.selectUpgradeOfferGroupByYearMonth(fofoId, UpgradeOfferStatus.approved, startOfMonth);
29707 tejbeer 1180
 
31751 tejbeer 1181
        LOGGER.info("suos" + suos);
29707 tejbeer 1182
 
31751 tejbeer 1183
        List<BrandAmountModel> beforeSixMonthOffers = samsungUpgradeOfferRepository.selectUpgradeOfferByYearMonthGroupByBrand(fofoId, UpgradeOfferStatus.approved, startOfMonth);
29707 tejbeer 1184
 
31751 tejbeer 1185
        Map<String, Double> pendingUpgradeOfferBeforeSixMonthMap = beforeSixMonthOffers.stream().collect(Collectors.toMap(x -> x.getBrand(), x -> (double) x.getAmount()));
29707 tejbeer 1186
 
31751 tejbeer 1187
        model.addAttribute("pendingUpgradeOfferBeforeSixMonthMap", pendingUpgradeOfferBeforeSixMonthMap);
29707 tejbeer 1188
 
31751 tejbeer 1189
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
29707 tejbeer 1190
 
31751 tejbeer 1191
        Map<String, Map<YearMonth, Double>> upgradeOfferBrandMonthMap = new HashMap<>();
29707 tejbeer 1192
 
31751 tejbeer 1193
        for (SamsungUpgradeOfferModel suo : suos) {
1194
            Map<YearMonth, Double> brandValue = new HashMap<>();
29707 tejbeer 1195
 
31751 tejbeer 1196
            if (upgradeOfferBrandMonthMap.containsKey(suo.getBrand())) {
1197
                brandValue = upgradeOfferBrandMonthMap.get(suo.getBrand());
1198
                brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
1199
            } else {
29707 tejbeer 1200
 
31751 tejbeer 1201
                brandValue.put(YearMonth.parse(suo.getYearMonth(), dateTimeFormatter), (double) suo.getAmount());
29707 tejbeer 1202
 
31751 tejbeer 1203
            }
1204
            upgradeOfferBrandMonthMap.put(suo.getBrand(), brandValue);
1205
        }
29707 tejbeer 1206
 
31751 tejbeer 1207
        Map<String, List<Double>> sortedBrandValue = new LinkedHashMap<>();
1208
        String brand = "Samsung";
29707 tejbeer 1209
 
31751 tejbeer 1210
        Map<YearMonth, Double> yearMonthValue = upgradeOfferBrandMonthMap.get(brand);
1211
        for (int i = 5; i >= 0; i--) {
1212
            LocalDateTime startMonth = curDate.withDayOfMonth(1).minusMonths(i);
1213
            if (yearMonthValue != null) {
1214
                if (yearMonthValue.get(YearMonth.from(startMonth)) == null) {
1215
                    yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1216
                }
29707 tejbeer 1217
 
31751 tejbeer 1218
            } else {
1219
                yearMonthValue = new HashMap<>();
1220
                yearMonthValue.put(YearMonth.from(startMonth), 0.0);
1221
            }
1222
        }
1223
        Map<YearMonth, Double> sortedMonthBrandValue = new TreeMap<>(yearMonthValue);
1224
        upgradeOfferBrandMonthMap.put(brand, sortedMonthBrandValue);
1225
        sortedBrandValue.put(brand, sortedMonthBrandValue.values().stream().collect(Collectors.toList()));
1226
        LOGGER.info("sortedBrandValue" + sortedBrandValue);
29707 tejbeer 1227
 
31751 tejbeer 1228
        model.addAttribute("brand", brand);
1229
        model.addAttribute("sortedBrandValue", sortedBrandValue);
1230
        model.addAttribute("fofoId", fofoId);
1231
        return "upgrade-offer-tabular";
29707 tejbeer 1232
 
31751 tejbeer 1233
    }
29707 tejbeer 1234
 
31751 tejbeer 1235
    @RequestMapping(value = "/getMonthlyUpgradeOfferItemDetail", method = RequestMethod.GET)
32836 amit.gupta 1236
    public String getMonthlyUpgradeOfferItemDetail(HttpServletRequest request,
1237
                                                   @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1238
                                                   @RequestParam(name = "brand", required = true, defaultValue = "0") String brand,
1239
                                                   @RequestParam(name = "yearMonth", required = false, defaultValue = "0") String yearMonth, Model model) throws
1240
            Exception {
29707 tejbeer 1241
 
31751 tejbeer 1242
        LOGGER.info("params" + fofoId + brand + yearMonth);
1243
        List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository.selectUpgradeOfferItemDetails(fofoId, UpgradeOfferStatus.approved, brand, yearMonth);
29707 tejbeer 1244
 
31751 tejbeer 1245
        model.addAttribute("offerItems", offerItems);
29707 tejbeer 1246
 
31751 tejbeer 1247
        return "upgrade-offer-item-detail";
1248
    }
29707 tejbeer 1249
 
31751 tejbeer 1250
    @RequestMapping(value = "/getUpgradeOfferBeforeSixMonthItemDetail", method = RequestMethod.GET)
32836 amit.gupta 1251
    public String getUpgradeOfferBeforeSixMonthItemDetail(HttpServletRequest request,
1252
                                                          @RequestParam(name = "fofoId", required = true, defaultValue = "0") int fofoId,
1253
                                                          @RequestParam(name = "brand", required = true, defaultValue = "0") String brand, Model model) throws Exception {
31751 tejbeer 1254
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
29707 tejbeer 1255
 
31751 tejbeer 1256
        LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
29707 tejbeer 1257
 
31751 tejbeer 1258
        List<UpgradeOfferItemDetailModel> offerItems = samsungUpgradeOfferRepository.selectUpgradeOfferItemDetailByYearMonth(fofoId, UpgradeOfferStatus.approved, brand, startOfMonth);
29707 tejbeer 1259
 
31751 tejbeer 1260
        model.addAttribute("offerItems", offerItems);
29707 tejbeer 1261
 
31751 tejbeer 1262
        return "upgrade-offer-item-detail";
1263
    }
29707 tejbeer 1264
 
31751 tejbeer 1265
    @RequestMapping(value = "/getAuthUserPartners", method = RequestMethod.GET)
32836 amit.gupta 1266
    public String AuthUserPartnersDetail(HttpServletRequest request, Model model, @RequestParam int authId) throws
1267
            Exception {
26418 tejbeer 1268
 
31751 tejbeer 1269
        Map<Integer, List<Integer>> pp = csService.getAuthUserIdPartnerIdMapping();
1270
        Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
26418 tejbeer 1271
 
31751 tejbeer 1272
        Map<Integer, PartnerDetailModel> fofoIdAndallValues = partnerStatsService.getAllPartnerStats();
1273
        if (authId != 0) {
1274
            List<Integer> fofoIds = pp.get(authId);
1275
            fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1276
        } else {
1277
        }
26418 tejbeer 1278
 
36268 ranu 1279
        // Build escalation map: fofoId -> escalation label (from open tickets)
1280
        Set<Integer> escalationSubCatIds = new HashSet<>(Arrays.asList(
1281
                ProfitMandiConstants.RBM_L2_ESCALATION,
1282
                ProfitMandiConstants.RBM_L3_ESCALATION,
1283
                ProfitMandiConstants.SALES_ESCALATION));
1284
        Map<Integer, String> escalationMap = new HashMap<>();
1285
        List<Integer> partnerFofoIds = new ArrayList<>(fofoIdAndallValues.keySet());
1286
        if (!partnerFofoIds.isEmpty()) {
1287
            List<Ticket> openTickets = ticketRepository.selectAllOpenTickets(partnerFofoIds);
1288
            for (Ticket t : openTickets) {
1289
                if (t.getCloseTimestamp() == null && escalationSubCatIds.contains(t.getSubCategoryId())) {
1290
                    String label;
1291
                    if (t.getSubCategoryId() == ProfitMandiConstants.RBM_L2_ESCALATION) {
1292
                        label = "RBM L2 Escalation";
1293
                    } else if (t.getSubCategoryId() == ProfitMandiConstants.RBM_L3_ESCALATION) {
1294
                        label = "RBM L3 Escalation";
1295
                    } else {
1296
                        label = "Sales Escalation";
1297
                    }
1298
                    // If partner already has an escalation, keep higher priority (Sales > L3 > L2)
1299
                    String existing = escalationMap.get(t.getFofoId());
1300
                    if (existing == null || label.contains("Sales") || (label.contains("L3") && !existing.contains("Sales"))) {
1301
                        escalationMap.put(t.getFofoId(), label);
1302
                    }
1303
                }
1304
            }
1305
        }
1306
        model.addAttribute("escalationMap", escalationMap);
1307
 
31751 tejbeer 1308
        model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1309
        model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
26418 tejbeer 1310
 
31751 tejbeer 1311
        return "auth_user_partner_detail";
1312
    }
26418 tejbeer 1313
 
31751 tejbeer 1314
    @RequestMapping(value = "/getWarehousePartners", method = RequestMethod.GET)
32836 amit.gupta 1315
    public String warehousePartnersDetail(HttpServletRequest request, Model model, @RequestParam int warehouseId) throws
1316
            Exception {
31751 tejbeer 1317
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1318
        String email = loginDetails.getEmailId();
28472 tejbeer 1319
 
35480 amit 1320
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1321
        if (authfofoIds == null) {
1322
            authfofoIds = new HashSet<>();
1323
        }
31751 tejbeer 1324
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(new ArrayList<>(authfofoIds)).stream().collect(Collectors.groupingBy(
1325
                FofoStore::getWarehouseId, Collectors.mapping(FofoStore::getId, Collectors.toList())));
27701 tejbeer 1326
 
35099 amit 1327
        if (!warehouseIdFofoIdMap.containsKey(7573)) {
1328
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
1329
        }
1330
 
31751 tejbeer 1331
        Map<Integer, CustomRetailer> fofoIdAndPartnerMap = retailerService.getFofoRetailers(false);
1332
        Map<Integer, PartnerDetailModel> fofoIdAndallValues = adminUser.getPartnersStatDataFromFile();
35480 amit 1333
        if (fofoIdAndallValues == null) {
1334
            fofoIdAndallValues = new HashMap<>();
1335
        }
31751 tejbeer 1336
        if (warehouseId != 0) {
1337
            List<Integer> fofoIds = warehouseIdFofoIdMap.get(warehouseId);
35480 amit 1338
            if (fofoIds != null) {
1339
                fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
1340
            }
35854 amit 1341
        } else {
1342
            Set<Integer> finalAuthfofoIds = authfofoIds;
1343
            fofoIdAndallValues = fofoIdAndallValues.entrySet().stream().filter(x -> finalAuthfofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
31751 tejbeer 1344
        }
1345
        ChartInvestmentModel cm = adminUser.getAllStatePartnerType(fofoIdAndallValues);
1346
        model.addAttribute("chartPieMap", gson.toJson(cm));
27545 tejbeer 1347
 
31751 tejbeer 1348
        LOGGER.info("adminUserChart" + gson.toJson(cm));
29164 manish 1349
 
31751 tejbeer 1350
        Map<Integer, MonthlyTarget> monthlyTargetMap = monthlyTargetRepository.selectByDate(YearMonth.now()).stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31211 tejbeer 1351
 
36268 ranu 1352
        // Build escalation map from open tickets
1353
        Set<Integer> escalationSubCatIds2 = new HashSet<>(Arrays.asList(
1354
                ProfitMandiConstants.RBM_L2_ESCALATION,
1355
                ProfitMandiConstants.RBM_L3_ESCALATION,
1356
                ProfitMandiConstants.SALES_ESCALATION));
1357
        Map<Integer, String> escalationMap = new HashMap<>();
1358
        List<Integer> partnerFofoIds2 = new ArrayList<>(fofoIdAndallValues.keySet());
1359
        if (!partnerFofoIds2.isEmpty()) {
1360
            List<Ticket> openTickets = ticketRepository.selectAllOpenTickets(partnerFofoIds2);
1361
            for (Ticket t : openTickets) {
1362
                if (t.getCloseTimestamp() == null && escalationSubCatIds2.contains(t.getSubCategoryId())) {
1363
                    String label;
1364
                    if (t.getSubCategoryId() == ProfitMandiConstants.RBM_L2_ESCALATION) {
1365
                        label = "RBM L2 Escalation";
1366
                    } else if (t.getSubCategoryId() == ProfitMandiConstants.RBM_L3_ESCALATION) {
1367
                        label = "RBM L3 Escalation";
1368
                    } else {
1369
                        label = "Sales Escalation";
1370
                    }
1371
                    String existing = escalationMap.get(t.getFofoId());
1372
                    if (existing == null || label.contains("L3") || (label.contains("Sales") && !existing.contains("L3"))) {
1373
                        escalationMap.put(t.getFofoId(), label);
1374
                    }
1375
                }
1376
            }
1377
        }
1378
        model.addAttribute("escalationMap", escalationMap);
1379
 
31751 tejbeer 1380
        model.addAttribute("fofoIdAndallValues", fofoIdAndallValues);
1381
        model.addAttribute("fofoIdAndPartnerMap", fofoIdAndPartnerMap);
1382
        model.addAttribute("monthlyTargetMap", monthlyTargetMap);
27545 tejbeer 1383
 
31751 tejbeer 1384
        List<PartnerType> partnerTypes = Arrays.asList(PartnerType.values()).stream().filter(x -> !x.equals(PartnerType.ALL)).collect(Collectors.toList());
31211 tejbeer 1385
 
31751 tejbeer 1386
        model.addAttribute("partnerTypes", partnerTypes);
31154 tejbeer 1387
 
31751 tejbeer 1388
        return "auth_user_partner_detail";
1389
    }
27545 tejbeer 1390
 
31662 amit.gupta 1391
 
31751 tejbeer 1392
    @RequestMapping(value = "/getWarehouseWiseBrandStock", method = RequestMethod.GET)
32836 amit.gupta 1393
    public String getWarehouseWiseBrandStock(HttpServletRequest request, Model
1394
            model, @RequestParam List<Integer> warehouseId) throws Exception {
31751 tejbeer 1395
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1396
        String email = loginDetails.getEmailId();
36481 ranu 1397
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1398
        List<Position> positions = positionRepository.selectAllByAuthUserId(authUser.getId());
35099 amit 1399
 
37286 ranu 1400
        // Same see-all rule as AdminUser.adminPanel:
1401
        //   - RBM  L3 and above
37287 ranu 1402
        //   - Sales L5 and above
37286 ranu 1403
        boolean isRbmL3OrAbove = positions.stream().anyMatch(pos ->
1404
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_RBM
1405
                        && pos.getEscalationType() != null
36481 ranu 1406
                        && pos.getEscalationType() != EscalationType.L1
37286 ranu 1407
                        && pos.getEscalationType() != EscalationType.L2);
37287 ranu 1408
        boolean isSalesL5OrAbove = positions.stream().anyMatch(pos ->
37286 ranu 1409
                pos.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES
1410
                        && pos.getEscalationType() != null
1411
                        && pos.getEscalationType() != EscalationType.L1
37285 ranu 1412
                        && pos.getEscalationType() != EscalationType.L2
37287 ranu 1413
                        && pos.getEscalationType() != EscalationType.L3
1414
                        && pos.getEscalationType() != EscalationType.L4);
1415
        boolean canSeeAllStores = isRbmL3OrAbove || isSalesL5OrAbove;
36481 ranu 1416
 
1417
        Set<Integer> fofoIds;
37285 ranu 1418
        if (canSeeAllStores) {
36481 ranu 1419
            fofoIds = fofoStoreRepository.selectActiveStores().stream()
1420
                    .map(x -> x.getId()).collect(Collectors.toSet());
1421
        } else {
1422
            fofoIds = csService1.getAuthFofoIds(email, true);
1423
        }
1424
 
1425
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository
1426
                .selectActivePartnersByRetailerIds(new ArrayList<>(fofoIds)).stream()
1427
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
1428
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
1429
 
35099 amit 1430
        if (!warehouseIdFofoIdMap.containsKey(7573)) {
1431
            warehouseIdFofoIdMap.put(7573, new ArrayList<>());
1432
        }
36725 ranu 1433
        if (!warehouseIdFofoIdMap.containsKey(10516)) {
1434
            warehouseIdFofoIdMap.put(10516, new ArrayList<>());
1435
        }
36480 ranu 1436
        if (!warehouseIdFofoIdMap.containsKey(7678)) {
1437
            warehouseIdFofoIdMap.put(7678, new ArrayList<>());
1438
        }
31751 tejbeer 1439
        List<WarehouseWiseBrandStockModel> warehouseWiseBrandStock = new ArrayList<>();
1440
        if (!warehouseId.contains(0)) {
1441
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(warehouseId);
1442
        } else {
1443
            LOGGER.info("warehouseIdFofoIdMap" + warehouseIdFofoIdMap.keySet());
1444
            warehouseWiseBrandStock = saholicInventoryCISRepository.selectGroupByWarehouseAndBrand(new ArrayList<>(warehouseIdFofoIdMap.keySet()));
27701 tejbeer 1445
 
31751 tejbeer 1446
        }
1447
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1448
        model.addAttribute("warehouseWiseBrandStock", warehouseWiseBrandStock);
1449
        model.addAttribute("warehouseId", warehouseId);
1450
        model.addAttribute("warehouseMap", warehouseMap);
27660 tejbeer 1451
 
31751 tejbeer 1452
        return "warehouse_brand_stock";
1453
    }
27509 tejbeer 1454
 
31751 tejbeer 1455
    @RequestMapping(value = "/getWarehouseWiseData", method = RequestMethod.GET)
1456
    public String getWarehouseWiseData(HttpServletRequest request, Model model) throws Exception {
1457
        inventoryService.getItemAvailabilityAndIndent();
1458
        model.addAttribute("response1", mvcResponseSender.createResponseString(true));
1459
        return "response";
1460
    }
27529 tejbeer 1461
 
37374 ranu 1462
    // AJAX endpoint for the main-dashboard "Warehouse Wise Report" brand filter.
1463
    // Returns the tbody fragment for the selected brand(s); empty brand = all brands (same numbers as the default page load).
1464
    @RequestMapping(value = "/getWarehouseStockByBrand", method = RequestMethod.GET)
1465
    public String getWarehouseStockByBrand(HttpServletRequest request,
1466
                                           @RequestParam(name = "brand", required = false) List<String> brands,
1467
                                           Model model) throws Exception {
1468
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1469
        LinkedHashMap<Integer, WarehouseWiseStockModel> stockMap =
1470
                adminUser.getWarehouseStockMap(loginDetails.getEmailId(), brands);
1471
        // Same shape adminPanel uses so the Total Values row (key 0) renders its label.
1472
        LinkedHashMap<Integer, String> warehouseMap = new LinkedHashMap<>(ProfitMandiConstants.WAREHOUSE_MAP);
1473
        warehouseMap.put(0, "Total Values");
1474
        model.addAttribute("warehouseStockMap", stockMap);
1475
        model.addAttribute("warehouseMap", warehouseMap);
1476
        return "warehouse_wise_stock_rows";
1477
    }
1478
 
31751 tejbeer 1479
    @RequestMapping(value = "/getWarehouseWiseBrandAndCategory", method = RequestMethod.GET)
32836 amit.gupta 1480
    public String getWarehouseWiseBrandAndCategory(HttpServletRequest request, Model
1481
            model, @RequestParam List<Integer> warehouseId, @RequestParam List<String> brands, @RequestParam String
1482
                                                           category) throws Exception {
27509 tejbeer 1483
 
31751 tejbeer 1484
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1485
        List<String> listbrands = saholicInventoryCISRepository.selectAllBrand();
1486
        List<String> listCategory = saholicInventoryCISRepository.selectAllSubCategory();
27539 tejbeer 1487
 
31751 tejbeer 1488
        model.addAttribute("warehouseMap", warehouseMap);
1489
        model.addAttribute("brands", listbrands);
1490
        model.addAttribute("listCategory", listCategory);
27538 tejbeer 1491
 
31751 tejbeer 1492
        model.addAttribute("selectedBrand", brands);
1493
        model.addAttribute("selectedWarehouse", warehouseId);
1494
        model.addAttribute("selectedCategory", category);
27539 tejbeer 1495
 
31751 tejbeer 1496
        return "warehouse_brand_item_stock";
1497
    }
27509 tejbeer 1498
 
31751 tejbeer 1499
    @RequestMapping(value = "/getWarehouseWiseItemStock", method = RequestMethod.GET)
32836 amit.gupta 1500
    public String getWarehouseWiseItemStock(HttpServletRequest request, Model
34176 tejus.loha 1501
            model, @RequestParam(name = "warehouseId") List<Integer> warehouseIds, @RequestParam List<String> brands, @RequestParam String
32836 amit.gupta 1502
                                                    category) throws Exception {
31751 tejbeer 1503
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
32836 amit.gupta 1504
        if (warehouseIds.contains(0)) {
1505
            warehouseIds.addAll(warehouseMap.keySet());
31751 tejbeer 1506
        }
37188 ranu 1507
        // Band-aid for URL '+' decode issue on brand names (e.g. "Ai+"):
1508
        // if a brand doesn't exist in catalog.brand as-is but "<brand>+" does,
1509
        // switch to the plus variant. Zero regression for the other brands.
1510
        brands = brands.stream().map(b -> {
1511
            if (b == null || b.trim().isEmpty()) return b;
1512
            String probe = b.replaceAll("\\s+$", "");
1513
            try {
1514
                if (brandsRepository.selectByBrand(b) == null
1515
                        && (probe.equals(b) || brandsRepository.selectByBrand(probe) == null)) {
1516
                    String withPlus = probe + "+";
1517
                    if (brandsRepository.selectByBrand(withPlus) != null) {
1518
                        LOGGER.info("getWarehouseWiseItemStock brand fallback: '{}' -> '{}'", b, withPlus);
1519
                        return withPlus;
1520
                    }
1521
                }
1522
            } catch (Exception e) {
1523
                LOGGER.warn("getWarehouseWiseItemStock brand fallback failed for '{}': {}", b, e.getMessage());
1524
            }
1525
            return b;
1526
        }).collect(Collectors.toList());
32836 amit.gupta 1527
        List<WarehouseWiseitemStockModel> warehouseWiseItemStock = saholicInventoryCISRepository.selectWarehouseItemStock(warehouseIds, brands, category);
27539 tejbeer 1528
 
31751 tejbeer 1529
        model.addAttribute("warehouseWiseItemStock", warehouseWiseItemStock);
1530
        model.addAttribute("warehouseMap", warehouseMap);
1531
        return "warehouse_item_details";
1532
    }
27538 tejbeer 1533
 
31751 tejbeer 1534
    @RequestMapping(value = "/getWarehouseWiseBrandPartnerSale", method = RequestMethod.GET)
32836 amit.gupta 1535
    public String getWarehouseWiseBrandPartnerSale(HttpServletRequest request, Model model, @RequestParam String
1536
            brand) throws Exception {
27701 tejbeer 1537
 
37190 ranu 1538
        // Band-aid for URL '+' decode issue on brand names (e.g. "Ai+"):
1539
        // if the incoming brand isn't found in catalog.brand but "<brand>+" is,
1540
        // switch to the plus variant. Zero regression for the other brands.
1541
        if (brand != null && !brand.trim().isEmpty()) {
1542
            String probe = brand.replaceAll("\\s+$", "");
1543
            try {
1544
                if (brandsRepository.selectByBrand(brand) == null
1545
                        && (probe.equals(brand) || brandsRepository.selectByBrand(probe) == null)) {
1546
                    String withPlus = probe + "+";
1547
                    if (brandsRepository.selectByBrand(withPlus) != null) {
1548
                        LOGGER.info("getWarehouseWiseBrandPartnerSale brand fallback: '{}' -> '{}'", brand, withPlus);
1549
                        brand = withPlus;
1550
                    }
1551
                }
1552
            } catch (Exception e) {
1553
                LOGGER.warn("getWarehouseWiseBrandPartnerSale brand fallback failed for '{}': {}", brand, e.getMessage());
1554
            }
1555
        }
1556
 
31751 tejbeer 1557
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1558
        String email = loginDetails.getEmailId();
27701 tejbeer 1559
 
31751 tejbeer 1560
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
28472 tejbeer 1561
 
31751 tejbeer 1562
        Map<Integer, WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository.selectGroupByWarehouseBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds)).stream().collect(Collectors.toMap(x -> x.getWarehouseId(), x -> x));
27670 tejbeer 1563
 
31751 tejbeer 1564
        List<WarehouseWiseBrandUnbilledActivatedModel> unbilledStock = fofoStoreRepository.selectUnbilledActivateStockGroupByWarehouse(brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1565
 
31751 tejbeer 1566
        for (WarehouseWiseBrandUnbilledActivatedModel un : unbilledStock) {
1567
            WarehouseWiseBrandSaleModel bpt = warehouseWiseBrandPartnerSales.get(un.getWarehouseId());
1568
            if (bpt != null) {
1569
                bpt.setAmtd(un.getUnbilledMtd());
1570
                bpt.setUamtdQty(un.getUnbilledQty());
1571
            } else {
1572
                bpt = new WarehouseWiseBrandSaleModel();
1573
                bpt.setWarehouseId(un.getWarehouseId());
1574
                bpt.setAmtd(un.getUnbilledMtd());
1575
                bpt.setUamtdQty(un.getUnbilledQty());
1576
                bpt.setLms(0);
1577
                bpt.setLmtd(0);
1578
                bpt.setMtd(0);
1579
                bpt.setMtdQty(0);
1580
                bpt.setLmtd(0);
1581
                bpt.setLmtdQty(0);
1582
                warehouseWiseBrandPartnerSales.put(un.getWarehouseId(), bpt);
1583
            }
1584
        }
1585
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27591 tejbeer 1586
 
31751 tejbeer 1587
        Set<String> brands = inventoryService.getAllTagListingBrands();
1588
        model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1589
        model.addAttribute("warehouseMap", warehouseMap);
1590
        model.addAttribute("brands", brands);
1591
        model.addAttribute("selectedbrand", brand);
1592
        return "warehousewise_brand_partners_sale";
1593
    }
27556 tejbeer 1594
 
31751 tejbeer 1595
    @RequestMapping(value = "/getWarehouseWiseAccesoriesBrandPartnerSale", method = RequestMethod.GET)
32836 amit.gupta 1596
    public String getWarehouseWiseAccesoriesBrandPartnerSale(HttpServletRequest request, Model
1597
            model, @RequestParam String brand) throws Exception {
31751 tejbeer 1598
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1599
        String email = loginDetails.getEmailId();
1600
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1601
        Set<Integer> authfofoIds = storeGuyMap.get(email);
28472 tejbeer 1602
 
31751 tejbeer 1603
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
1604
        if (authfofoIds == null) {
35395 amit 1605
            List<Position> positions1 = positionRepository.selectAllByAuthUserId(authUser.getId());
31751 tejbeer 1606
            if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER).count() > 0) {
1607
                authfofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
1608
            }
1609
        }
1610
        List<WarehouseWiseBrandSaleModel> warehouseWiseBrandPartnerSales = fofoStoreRepository.selectGroupByWarehouseAccesoriesBrandWisePartnerSale(brand, new ArrayList<>(authfofoIds));
1611
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
27594 tejbeer 1612
 
31751 tejbeer 1613
        Set<String> brands = inventoryService.getAllTagListingBrands();
1614
        model.addAttribute("warehouseWiseBrandPartnerSales", warehouseWiseBrandPartnerSales);
1615
        model.addAttribute("warehouseMap", warehouseMap);
1616
        model.addAttribute("brands", brands);
1617
        model.addAttribute("selectedbrand", brand);
1618
        return "warehousewise_accessoriesbrand_sale";
1619
    }
27594 tejbeer 1620
 
31751 tejbeer 1621
    @RequestMapping(value = "/getWarehouseBrandWiseItemSale", method = RequestMethod.GET)
32836 amit.gupta 1622
    public String getWarehouseBrandWiseItemSale(HttpServletRequest request, Model
1623
            model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
31751 tejbeer 1624
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1625
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1626
        String email = loginDetails.getEmailId();
1627
        Set<Integer> authfofoIds = csService1.getAuthFofoIds(email, true);
1628
        Map<Integer, WarehouseBrandWiseItemSaleModel> branditemSalesMap = fofoStoreRepository.selectWarehouseBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds)).stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x));
27670 tejbeer 1629
 
31751 tejbeer 1630
        List<WarehouseBrandItemUnbilledActivatedModel> unbilledItems = fofoStoreRepository.selectWarehouseBrandItemUnbilledActivateStock(warehouseId, brand, new ArrayList<>(authfofoIds));
27670 tejbeer 1631
 
31751 tejbeer 1632
        for (WarehouseBrandItemUnbilledActivatedModel un : unbilledItems) {
1633
            WarehouseBrandWiseItemSaleModel bpt = branditemSalesMap.get(un.getItemId());
1634
            if (bpt != null) {
1635
                bpt.setAmtd(un.getAmtd());
1636
                bpt.setUamtdQty(un.getUnmtdQty());
1637
            } else {
1638
                bpt = new WarehouseBrandWiseItemSaleModel();
1639
                bpt.setWarehouseId(un.getWarehouseId());
1640
                bpt.setItemId(un.getItemId());
1641
                bpt.setAmtd(un.getAmtd());
1642
                bpt.setUamtdQty(un.getUnmtdQty());
1643
                bpt.setBrand(un.getBrand());
1644
                bpt.setModelName(un.getModelName());
1645
                bpt.setModelNumber(un.getModelNumber());
1646
                bpt.setColor(un.getColor());
1647
                bpt.setLms(0);
1648
                bpt.setLmtd(0);
1649
                bpt.setMtd(0);
1650
                bpt.setMtdQty(0);
1651
                bpt.setLmtd(0);
1652
                bpt.setLmtdQty(0);
1653
                branditemSalesMap.put(un.getItemId(), bpt);
1654
            }
1655
        }
1656
        model.addAttribute("branditemSales", branditemSalesMap);
1657
        model.addAttribute("warehouseMap", warehouseMap);
1658
        return "warehouse_partner_itemwise_sale";
1659
    }
27556 tejbeer 1660
 
31751 tejbeer 1661
    @RequestMapping(value = "/getWarehouseAccesoriesBrandWiseItemSale", method = RequestMethod.GET)
32836 amit.gupta 1662
    public String getWarehouseAccesoriesBrandWiseItemSale(HttpServletRequest request, Model
1663
            model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
31751 tejbeer 1664
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
1665
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1666
        String email = loginDetails.getEmailId();
1667
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1668
        Set<Integer> authfofoIds = storeGuyMap.get(email);
1669
        List<WarehouseBrandWiseItemSaleModel> branditemSales = fofoStoreRepository.selectWarehouseAccesoriesBrandItemSale(warehouseId, brand, new ArrayList<>(authfofoIds));
1670
        model.addAttribute("branditemSales", branditemSales);
1671
        model.addAttribute("warehouseMap", warehouseMap);
1672
        return "warehouse_accessories_itemwsie_sale";
1673
    }
27594 tejbeer 1674
 
36890 aman 1675
    // Users allowed to add / edit / delete contact-us entries.
1676
    private static final Set<String> CONTACT_US_EDITORS = new HashSet<>(Arrays.asList(
1677
            "kangan.monga@smartdukaan.com",
1678
            "gaurav.mathur1@smartdukaan.com"));
1679
 
1680
    private boolean isContactUsEditor(LoginDetails loginDetails) {
1681
        return loginDetails != null && loginDetails.getEmailId() != null
1682
                && CONTACT_US_EDITORS.contains(loginDetails.getEmailId().trim().toLowerCase());
1683
    }
1684
 
31751 tejbeer 1685
    @RequestMapping(value = "/contactUs", method = RequestMethod.GET)
1686
    public String contactUs(HttpServletRequest request, Model model) throws Throwable {
36890 aman 1687
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
31751 tejbeer 1688
        model.addAttribute("appContextPath", request.getContextPath());
36890 aman 1689
        // Defensive: never let a DB hiccup turn the contact page into a 500.
1690
        // The table is provisioned by ContactUsTableBootstrap, but if a query
1691
        // still fails we render the page with empty lists rather than crashing.
1692
        try {
1693
            model.addAttribute("mainContacts", contactUsRepository.findActiveBySection(ContactUs.SECTION_MAIN));
1694
            model.addAttribute("escalationContacts", contactUsRepository.findActiveBySection(ContactUs.SECTION_ESCALATION));
1695
        } catch (Exception e) {
1696
            LOGGER.error("Failed loading contact_us data; rendering empty contact list", e);
1697
            model.addAttribute("mainContacts", java.util.Collections.emptyList());
1698
            model.addAttribute("escalationContacts", java.util.Collections.emptyList());
1699
        }
1700
        model.addAttribute("contactUsEditor", isContactUsEditor(loginDetails));
31751 tejbeer 1701
        return "contact-us";
1702
    }
23923 amit.gupta 1703
 
36890 aman 1704
    @RequestMapping(value = "/contactUs/save", method = RequestMethod.POST)
1705
    @ResponseBody
1706
    public Map<String, Object> saveContactUs(HttpServletRequest request,
1707
                                             @RequestParam(name = "id", defaultValue = "0") int id,
1708
                                             @RequestParam(name = "section") String section,
1709
                                             @RequestParam(name = "area", defaultValue = "") String area,
1710
                                             @RequestParam(name = "baseArea", defaultValue = "") String baseArea,
1711
                                             @RequestParam(name = "name", defaultValue = "") String name,
1712
                                             @RequestParam(name = "designation", defaultValue = "") String designation,
1713
                                             @RequestParam(name = "mobile", defaultValue = "") String mobile,
37019 aman 1714
                                             @RequestParam(name = "email", defaultValue = "") String email,
1715
                                             @RequestParam(name = "position", defaultValue = "") String position,
1716
                                             @RequestParam(name = "afterId", defaultValue = "0") int afterId) throws Exception {
36890 aman 1717
        Map<String, Object> response = new HashMap<>();
1718
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1719
        if (!isContactUsEditor(loginDetails)) {
1720
            response.put("success", false);
1721
            response.put("message", "You are not authorised to edit contacts.");
1722
            return response;
1723
        }
1724
 
1725
        if (!ContactUs.SECTION_MAIN.equals(section) && !ContactUs.SECTION_ESCALATION.equals(section)) {
1726
            response.put("success", false);
1727
            response.put("message", "Invalid section.");
1728
            return response;
1729
        }
1730
        if (name == null || name.trim().isEmpty()) {
1731
            response.put("success", false);
1732
            response.put("message", "Name is required.");
1733
            return response;
1734
        }
1735
 
1736
        ContactUs contact;
1737
        if (id > 0) {
1738
            contact = contactUsRepository.selectById(id);
1739
            if (contact == null || !contact.isActive()) {
1740
                response.put("success", false);
1741
                response.put("message", "Contact not found.");
1742
                return response;
1743
            }
1744
        } else {
1745
            contact = new ContactUs();
1746
            contact.setSection(section);
1747
            contact.setSortOrder(contactUsRepository.maxSortOrder(section) + 10);
1748
        }
1749
        contact.setArea(area == null ? "" : area.trim());
1750
        contact.setBaseArea(baseArea == null ? "" : baseArea.trim());
1751
        contact.setName(name.trim());
1752
        contact.setDesignation(designation == null ? "" : designation.trim());
1753
        contact.setMobile(mobile == null || mobile.trim().isEmpty() ? "-" : mobile.trim());
1754
        contact.setEmail(email == null ? "" : email.trim());
1755
        contactUsRepository.persist(contact);
1756
 
37019 aman 1757
        // Position control: place the new/edited contact within its section. A NEW contact defaults
1758
        // to the bottom; an EDIT keeps its place unless the editor explicitly chose a new position.
1759
        String pos = (position == null || position.trim().isEmpty())
1760
                ? (id > 0 ? "KEEP" : "BOTTOM")
1761
                : position.trim().toUpperCase();
1762
        if (!"KEEP".equals(pos)) {
1763
            repositionInSection(section, contact.getId(), pos, afterId);
1764
        }
1765
 
36890 aman 1766
        response.put("success", true);
1767
        return response;
1768
    }
1769
 
1770
    @RequestMapping(value = "/contactUs/delete", method = RequestMethod.POST)
1771
    @ResponseBody
1772
    public Map<String, Object> deleteContactUs(HttpServletRequest request,
1773
                                               @RequestParam(name = "id") int id) throws Exception {
1774
        Map<String, Object> response = new HashMap<>();
1775
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1776
        if (!isContactUsEditor(loginDetails)) {
1777
            response.put("success", false);
1778
            response.put("message", "You are not authorised to edit contacts.");
1779
            return response;
1780
        }
1781
        ContactUs contact = contactUsRepository.selectById(id);
1782
        if (contact == null) {
1783
            response.put("success", false);
1784
            response.put("message", "Contact not found.");
1785
            return response;
1786
        }
1787
        contact.setActive(false);
1788
        contactUsRepository.persist(contact);
1789
        response.put("success", true);
1790
        return response;
1791
    }
1792
 
37019 aman 1793
    @RequestMapping(value = "/contactUs/reorder", method = RequestMethod.POST)
1794
    @ResponseBody
1795
    public Map<String, Object> reorderContactUs(HttpServletRequest request,
1796
                                                @RequestParam(name = "id") int id,
1797
                                                @RequestParam(name = "direction") String direction) throws Exception {
1798
        Map<String, Object> response = new HashMap<>();
1799
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1800
        if (!isContactUsEditor(loginDetails)) {
1801
            response.put("success", false);
1802
            response.put("message", "You are not authorised to edit contacts.");
1803
            return response;
1804
        }
1805
        ContactUs contact = contactUsRepository.selectById(id);
1806
        if (contact == null || !contact.isActive()) {
1807
            response.put("success", false);
1808
            response.put("message", "Contact not found.");
1809
            return response;
1810
        }
1811
        boolean up = "UP".equalsIgnoreCase(direction);
1812
        List<ContactUs> list = contactUsRepository.findActiveBySection(contact.getSection());
1813
        int idx = indexOfContact(list, id);
1814
        int target = up ? idx - 1 : idx + 1;
1815
        if (idx < 0 || target < 0 || target >= list.size()) {
1816
            // Already at the top/bottom edge - nothing to move.
1817
            response.put("success", true);
1818
            return response;
1819
        }
1820
        ContactUs tmp = list.get(idx);
1821
        list.set(idx, list.get(target));
1822
        list.set(target, tmp);
1823
        renumberSequential(list);
1824
        response.put("success", true);
1825
        return response;
1826
    }
1827
 
1828
    /**
1829
     * Places {@code contactId} within its section per {@code position} (TOP | BOTTOM | AFTER) and
1830
     * renumbers the whole section's sort_order to a clean 10, 20, 30 … sequence, so ordering is
1831
     * always gap-free and deterministic. {@code afterId} is only consulted for AFTER.
1832
     */
1833
    private void repositionInSection(String section, int contactId, String position, int afterId) {
1834
        List<ContactUs> list = contactUsRepository.findActiveBySection(section);
1835
        int movingIdx = indexOfContact(list, contactId);
1836
        if (movingIdx < 0) {
1837
            return; // not found (should not happen immediately after persist)
1838
        }
1839
        ContactUs moving = list.remove(movingIdx);
1840
        int index;
1841
        if ("TOP".equals(position)) {
1842
            index = 0;
1843
        } else if ("AFTER".equals(position)) {
1844
            int anchorIdx = indexOfContact(list, afterId);
1845
            index = (anchorIdx >= 0) ? anchorIdx + 1 : list.size();
1846
        } else { // BOTTOM
1847
            index = list.size();
1848
        }
1849
        list.add(index, moving);
1850
        renumberSequential(list);
1851
    }
1852
 
1853
    /** Assigns sort_order 10, 20, 30 … in list order, persisting only rows whose order changed. */
1854
    private void renumberSequential(List<ContactUs> orderedContacts) {
1855
        for (int i = 0; i < orderedContacts.size(); i++) {
1856
            ContactUs c = orderedContacts.get(i);
1857
            int newOrder = (i + 1) * 10;
1858
            if (c.getSortOrder() != newOrder) {
1859
                c.setSortOrder(newOrder);
1860
                contactUsRepository.persist(c);
1861
            }
1862
        }
1863
    }
1864
 
1865
    private int indexOfContact(List<ContactUs> list, int id) {
1866
        for (int i = 0; i < list.size(); i++) {
1867
            if (list.get(i).getId() == id) {
1868
                return i;
1869
            }
1870
        }
1871
        return -1;
1872
    }
1873
 
31751 tejbeer 1874
    @RequestMapping(value = "/notifications", method = RequestMethod.GET)
32836 amit.gupta 1875
    public String getNotificationsWithType(HttpServletRequest request, @RequestParam(required = false) MessageType
1876
            messageType, @RequestParam(name = "offset", defaultValue = "0") int offset,
1877
                                           @RequestParam(name = "limit", defaultValue = "20") int limit, Model model) throws Exception {
31751 tejbeer 1878
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1879
        int userId = 0;
1880
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
1881
        if (isAdmin) {
1882
            userId = loginDetails.getFofoId();
1883
        } else {
1884
            userId = userAccountRepository.selectUserIdByRetailerId(loginDetails.getFofoId());
1885
        }
1886
        List<Notification> notifications = null;
25683 tejbeer 1887
 
31751 tejbeer 1888
        List<NotificationCampaign> notificationCampaigns = notificationCampaignRepository.getNotifications(messageType, userId, offset, limit);
35943 amit 1889
        LOGGER.debug("messageType {}", messageType);
34176 tejus.loha 1890
        if (messageType != null) {
1891
            notifications = fofoUser.getNotifications(notificationCampaigns, messageType);
26086 tejbeer 1892
 
34176 tejus.loha 1893
            model.addAttribute("notifications", notifications);
25683 tejbeer 1894
 
35943 amit 1895
            LOGGER.debug("notifications count {}", notifications.size());
34176 tejus.loha 1896
        }
31751 tejbeer 1897
        return "notification-template";
1898
    }
25683 tejbeer 1899
 
31751 tejbeer 1900
    @RequestMapping(value = "/notifyDocument/documentId", method = RequestMethod.GET)
32836 amit.gupta 1901
    public ResponseEntity<?> retailerDocumentById(HttpServletRequest request,
1902
                                                  @RequestParam(name = ProfitMandiConstants.DOCUMENT_ID) int documentId, @RequestParam int cid) throws
1903
            ProfitMandiBusinessException {
31751 tejbeer 1904
        Document document = documentRepository.selectById(documentId);
1905
        NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
1906
        if (nc.getDocumentId() == null) {
1907
            throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1908
        }
1909
        if (nc.getDocumentId() != documentId) {
1910
            throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, documentId, "RTLR_1014");
1911
        }
1912
        return responseSender.ok(document);
1913
    }
25649 tejbeer 1914
 
32934 amit.gupta 1915
    @Autowired
1916
    PsiSmartService psiSmartService;
34176 tejus.loha 1917
 
32934 amit.gupta 1918
    @RequestMapping(value = "/psi/auth-endpoint", method = RequestMethod.GET)
32935 amit.gupta 1919
    public ResponseEntity<?> getPartnerPSIUrl(HttpServletRequest request) throws Exception {
32934 amit.gupta 1920
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
1921
        CustomRetailer customRetailer = retailerService.getAllFofoRetailers().get(loginDetails.getFofoId());
1922
        return responseSender.ok(psiSmartService.getRegistrationEndPoint(customRetailer.getMobileNumber()));
1923
    }
1924
 
31751 tejbeer 1925
    @RequestMapping(value = "/notifyDocument/download", method = RequestMethod.GET)
32836 amit.gupta 1926
    public ResponseEntity<?> downloadRetailerDocument(HttpServletRequest request, @RequestParam int cid, Model model) throws
1927
            ProfitMandiBusinessException {
25651 tejbeer 1928
 
31751 tejbeer 1929
        NotificationCampaign nc = notificationCampaignRepository.selectById(cid);
25651 tejbeer 1930
 
31751 tejbeer 1931
        if (nc.getDocumentId() == null) {
1932
            throw new ProfitMandiBusinessException("cid", nc.getId(), "not available");
1933
        }
25651 tejbeer 1934
 
31751 tejbeer 1935
        Document document = documentRepository.selectById(nc.getDocumentId());
25651 tejbeer 1936
 
31751 tejbeer 1937
        FileInputStream file = null;
1938
        try {
1939
            file = new FileInputStream(document.getPath() + File.separator + document.getName());
1940
        } catch (FileNotFoundException e) {
1941
            LOGGER.error("Retailer Document file not found : ", e);
1942
            throw new ProfitMandiBusinessException(ProfitMandiConstants.DOCUMENT_ID, document.getId(), "RTLR_1013");
1943
        }
32308 amit.gupta 1944
// ByteArrayOutputStream byteArrayOutputStream = new
1945
// ByteArrayOutputStream();
1946
// ExcelUtils.writeSchemeModels(schemeModels, byteArrayOutputStream);
25651 tejbeer 1947
 
31751 tejbeer 1948
        final HttpHeaders headers = new HttpHeaders();
1949
        String contentType = "";
1950
        if (document.getContentType() == ContentType.JPEG) {
1951
            contentType = "image/jpeg";
1952
        } else if (document.getContentType() == ContentType.PNG) {
1953
            contentType = "image/png";
1954
        } else if (document.getContentType() == ContentType.PDF) {
1955
            contentType = "application/pdf";
1956
        }
1957
        headers.set("Content-Type", contentType);
1958
        headers.set("Content-disposition", "inline; filename=" + document.getName());
1959
        headers.setContentLength(document.getSize());
1960
        final InputStreamResource inputStreamResource = new InputStreamResource(file);
1961
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1962
    }
26460 amit.gupta 1963
 
31751 tejbeer 1964
    @RequestMapping(value = "/getItemWiseTertiary", method = RequestMethod.GET)
32836 amit.gupta 1965
    public String getItemWiseTertiary(HttpServletRequest request,
1966
                                      @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws ProfitMandiBusinessException {
31751 tejbeer 1967
        List<ItemWiseTertiaryModel> itemWiseTertiary = fofoOrderRepository.SelectItemWiseTertiary(fofoId);
27579 tejbeer 1968
 
31751 tejbeer 1969
        LOGGER.info("itemWiseTertiary" + itemWiseTertiary);
1970
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1971
        model.addAttribute("customRetailer", customRetailer);
1972
        model.addAttribute("itemWiseTertiary", itemWiseTertiary);
1973
        return "item-wise-tertiary";
1974
    }
27579 tejbeer 1975
 
31751 tejbeer 1976
    @RequestMapping(value = "/getItemWiseIndent", method = RequestMethod.GET)
32836 amit.gupta 1977
    public String getItemWiseIndent(HttpServletRequest request,
1978
                                    @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws ProfitMandiBusinessException {
27586 tejbeer 1979
 
31751 tejbeer 1980
        List<Order> unbilledOrders = transactionService.getInTransitOrders(fofoId);
1981
        model.addAttribute("unbilledOrders", unbilledOrders);
27586 tejbeer 1982
 
31751 tejbeer 1983
        return "item-wise-indent";
1984
    }
27586 tejbeer 1985
 
31751 tejbeer 1986
    @RequestMapping(value = "/getPartnerInvestment", method = RequestMethod.GET)
32836 amit.gupta 1987
    public String getPartnerInvestment(HttpServletRequest request,
1988
                                       @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 1989
        Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
1990
        PartnerDetailModel partnerDetailModel = partnerStats.get(fofoId);
1991
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
1992
        model.addAttribute("partnerDetailModel", partnerDetailModel);
1993
        model.addAttribute("customRetailer", customRetailer);
1994
        return "partner-investment";
1995
    }
27727 tejbeer 1996
 
31751 tejbeer 1997
    @RequestMapping(value = "/getPartnerPendingIndentItem", method = RequestMethod.GET)
32836 amit.gupta 1998
    public String getPartnerPendingIndentItem(HttpServletRequest request, @RequestParam int warehouseId,
1999
                                              @RequestParam int itemId, Model model) throws ProfitMandiBusinessException {
31751 tejbeer 2000
        List<PartnerPendingIndentItemModel> partnerPendingIndent = fofoStoreRepository.selectPartnerPendingIndentItem(itemId, warehouseId);
27636 tejbeer 2001
 
31751 tejbeer 2002
        model.addAttribute("partnerPendingIndent", partnerPendingIndent);
2003
        return "partner-pending-indent-item";
2004
    }
27704 amit.gupta 2005
 
31751 tejbeer 2006
    @RequestMapping(value = "/getPatnerActivateStock", method = RequestMethod.GET)
32836 amit.gupta 2007
    public String getPartnerActivateStockItem(HttpServletRequest request,
2008
                                              @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 2009
        List<ActivateItemModel> activateStocks = new ArrayList<>();
2010
        List<InventoryItem> inventoryItems = inventoryItemRepository.selectByActivatedNotSold(fofoId);
2011
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
27636 tejbeer 2012
 
31751 tejbeer 2013
        for (InventoryItem inventoryItem : inventoryItems) {
2014
            TagListing tagListing = tagListingRepository.selectByItemId(inventoryItem.getItemId());
2015
            Item item = itemRepository.selectById(inventoryItem.getItemId());
2016
            ActivateItemModel aim = new ActivateItemModel();
2017
            aim.setFofoId(inventoryItem.getFofoId());
2018
            aim.setQuantity(inventoryItem.getGoodQuantity());
2019
            aim.setAmount(tagListing.getSellingPrice());
2020
            aim.setItemDescription(item.getItemDescription());
2021
            aim.setItemId(inventoryItem.getItemId());
2022
            activateStocks.add(aim);
2023
        }
27636 tejbeer 2024
 
31751 tejbeer 2025
        model.addAttribute("activateStocks", activateStocks);
2026
        model.addAttribute("customRetailer", customRetailer);
2027
        return "partner-activate-stock";
2028
    }
27636 tejbeer 2029
 
31751 tejbeer 2030
    @RequestMapping(value = "/getPatnerBrandWiseMTDSale", method = RequestMethod.GET)
32836 amit.gupta 2031
    public String getPatnerBrandWiseMTDSale(HttpServletRequest request,
2032
                                            @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 2033
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
2034
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2035
        Map<String, Double> brandMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
2036
        Map<String, Long> brandMtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), fofoId);
2037
        Double accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
2038
        Long accesoriesmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false)).get(fofoId);
27638 tejbeer 2039
 
31751 tejbeer 2040
        LOGGER.info("accesoriesmtdsale" + accesoriesmtdsale);
2041
        model.addAttribute("brandMtdAmount", brandMtdAmount);
2042
        model.addAttribute("brandMtdQty", brandMtdQty);
2043
        model.addAttribute("accesoriesmtdsale", accesoriesmtdsale);
2044
        model.addAttribute("accesoriesmtdqty", accesoriesmtdqty);
27638 tejbeer 2045
 
31751 tejbeer 2046
        model.addAttribute("customRetailer", customRetailer);
2047
        return "partner-brand-mtd-sale";
2048
    }
27636 tejbeer 2049
 
31751 tejbeer 2050
    @RequestMapping(value = "/getPatnerBrandWiseLMTDSale", method = RequestMethod.GET)
32836 amit.gupta 2051
    public String getPatnerBrandWiseLMTDSale(HttpServletRequest request,
2052
                                             @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 2053
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
2054
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2055
        Map<String, Double> brandLMtdAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2056
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
2057
        Map<String, Long> brandLmtdQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2058
                curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), fofoId);
27637 tejbeer 2059
 
31751 tejbeer 2060
        Double accesorieslmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false)).get(fofoId);
2061
        Long accesorieslmtdqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.with(LocalTime.MAX).minusMonths(1), Optional.of(false)).get(fofoId);
27638 tejbeer 2062
 
31751 tejbeer 2063
        model.addAttribute("brandLMtdAmount", brandLMtdAmount);
2064
        model.addAttribute("brandLmtdQty", brandLmtdQty);
2065
        model.addAttribute("accesorieslmtdqty", accesorieslmtdqty);
2066
        model.addAttribute("accesorieslmtdsale", accesorieslmtdsale);
2067
        model.addAttribute("customRetailer", customRetailer);
2068
        return "partner-brand-lmtd-sale";
2069
    }
27637 tejbeer 2070
 
31751 tejbeer 2071
    @RequestMapping(value = "/getPatnerBrandWiseLMSSale", method = RequestMethod.GET)
32836 amit.gupta 2072
    public String getPatnerBrandWiseLMSSale(HttpServletRequest request,
2073
                                            @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 2074
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
2075
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2076
        int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
27660 tejbeer 2077
 
31751 tejbeer 2078
        Map<String, Double> brandLMSAmount = fofoOrderItemRepository.selectSumAmountGroupByBrand(
2079
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
2080
        Map<String, Long> brandLmsQty = fofoOrderItemRepository.selectSumQuantityGroupByBrand(
2081
                curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), fofoId);
27660 tejbeer 2082
 
31751 tejbeer 2083
        Double accesorieslmssale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
2084
        Long accesorieslmsqty = fofoOrderRepository.selectSumSaleQuantityGroupByFofoIdsForMobileOrAccessories(fofoId, curDate.withDayOfMonth(1).minusMonths(1), curDate.withDayOfMonth(1), Optional.of(false)).get(fofoId);
27660 tejbeer 2085
 
31751 tejbeer 2086
        model.addAttribute("brandLMSAmount", brandLMSAmount);
2087
        model.addAttribute("brandLmsQty", brandLmsQty);
2088
        model.addAttribute("accesorieslmssale", accesorieslmssale);
2089
        model.addAttribute("accesorieslmsqty", accesorieslmsqty);
2090
        model.addAttribute("customRetailer", customRetailer);
2091
        return "partner-brand-lms-sale";
2092
    }
27660 tejbeer 2093
 
31751 tejbeer 2094
    @RequestMapping(value = "/getPatnerInStock", method = RequestMethod.GET)
32836 amit.gupta 2095
    public String getPatnerInStock(HttpServletRequest request,
2096
                                   @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
27640 tejbeer 2097
 
31751 tejbeer 2098
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
27640 tejbeer 2099
 
31751 tejbeer 2100
        List<InStockBrandModel> mobileStocks = currentInventorySnapshotRepository.selectSumInStockMobileGroupByBrand(fofoId);
2101
        List<InStockBrandModel> accesStock = currentInventorySnapshotRepository.selectSumInStockAccessoriesGroupByBrand(fofoId);
27640 tejbeer 2102
 
31751 tejbeer 2103
        List<InStockBrandItemModel> stockItemlist = currentInventorySnapshotRepository.selectInStockItemsByBrand(fofoId);
27660 tejbeer 2104
 
31751 tejbeer 2105
        Map<String, List<InStockBrandItemModel>> stockItemMap = stockItemlist.stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
27660 tejbeer 2106
 
31751 tejbeer 2107
        model.addAttribute("stockItemMap", stockItemMap);
2108
        model.addAttribute("mobileStock", mobileStocks);
2109
        model.addAttribute("accesStock", accesStock);
2110
        model.addAttribute("customRetailer", customRetailer);
2111
        return "partner-instock-item";
2112
    }
27640 tejbeer 2113
 
31751 tejbeer 2114
    @RequestMapping(value = "/getOpenTicketByFofoId", method = RequestMethod.GET)
32836 amit.gupta 2115
    public String getOpenTicketByFofoId(HttpServletRequest request,
2116
                                        @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, Model model) throws Exception {
31751 tejbeer 2117
        Map<Integer, AuthUser> ticketIdAuthUser = new HashMap<>();
2118
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2119
        List<Integer> ticketIds = ticketRepository.selectAllOpenTicketByRetailer(fofoId).stream().map(x -> x.getId()).collect(Collectors.toList());
2120
        List<TicketAssigned> ticketAssigns = ticketAssignedRepository.selectByTicketIds(ticketIds);
27660 tejbeer 2121
 
35395 amit 2122
        if (!ticketAssigns.isEmpty()) {
2123
            // Batch fetch AuthUsers to avoid N+1 queries
2124
            Set<Integer> assigneeIds = ticketAssigns.stream()
2125
                    .map(TicketAssigned::getAssineeId)
2126
                    .collect(Collectors.toSet());
2127
 
2128
            Map<Integer, AuthUser> authUserMap = authRepository.selectByIds(new ArrayList<>(assigneeIds)).stream()
2129
                    .collect(Collectors.toMap(AuthUser::getId, au -> au));
2130
 
2131
            for (TicketAssigned ticketAssign : ticketAssigns) {
2132
                AuthUser authUser = authUserMap.get(ticketAssign.getAssineeId());
2133
                if (authUser != null) {
2134
                    ticketIdAuthUser.put(ticketAssign.getTicketId(), authUser);
2135
                }
2136
            }
31751 tejbeer 2137
        }
2138
        model.addAttribute("ticketIdAuthUser", ticketIdAuthUser);
2139
        model.addAttribute("ticketAssigns", ticketAssigns);
2140
        model.addAttribute("customRetailer", customRetailer);
2141
        return "open-ticket";
2142
    }
27660 tejbeer 2143
 
31751 tejbeer 2144
    @RequestMapping(value = "/getPartnerSecondarySale", method = RequestMethod.GET)
32836 amit.gupta 2145
    public String getPartnerSecondarySale(HttpServletRequest request,
2146
                                          @RequestParam(name = ProfitMandiConstants.FOFO_ID) int fofoId, @RequestParam String timeValue, Model model) throws
2147
            Exception {
31751 tejbeer 2148
        LocalDateTime curDate = LocalDate.now().atStartOfDay();
2149
        CustomRetailer customRetailer = retailerService.getFofoRetailer(fofoId);
2150
        int lengthOfMonth = YearMonth.from(curDate.minusMonths(1)).lengthOfMonth();
2151
        LocalDateTime startDate = null;
2152
        LocalDateTime endDate = null;
2153
        List<InStockBrandModel> secondarySale = null;
2154
        Map<String, List<InStockBrandItemModel>> secondaryItemSale = null;
27893 tejbeer 2155
 
31751 tejbeer 2156
        if (timeValue.equals("mtd")) {
2157
            startDate = curDate.withDayOfMonth(1);
2158
            endDate = curDate.with(LocalTime.MAX);
2159
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2160
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
2161
            LOGGER.info("secondarySalemtd" + secondarySale);
2162
        } else if (timeValue.equals("lmtd")) {
2163
            startDate = curDate.withDayOfMonth(1).minusMonths(1);
2164
            endDate = curDate.with(LocalTime.MAX).minusMonths(1);
2165
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
27893 tejbeer 2166
 
31751 tejbeer 2167
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2168
            LOGGER.info("secondarySalelmtd" + secondarySale);
27893 tejbeer 2169
 
31751 tejbeer 2170
        } else {
2171
            startDate = curDate.withDayOfMonth(1).minusMonths(1);
2172
            endDate = curDate.withDayOfMonth(1);
2173
            secondaryItemSale = orderRepository.selectAllBilledOrderBrandItemByFofoId(startDate, endDate, fofoId).stream().collect(Collectors.groupingBy(InStockBrandItemModel::getBrand));
27893 tejbeer 2174
 
31751 tejbeer 2175
            secondarySale = orderRepository.selectAllBilledOrderBrandByFofoId(startDate, endDate, fofoId);
2176
            LOGGER.info("secondarySalelms" + secondarySale);
27893 tejbeer 2177
 
31751 tejbeer 2178
        }
27893 tejbeer 2179
 
31751 tejbeer 2180
        LOGGER.info("secondarySale" + secondarySale);
2181
        model.addAttribute("secondarySale", secondarySale);
2182
        model.addAttribute("secondaryItemSale", secondaryItemSale);
2183
        model.addAttribute("customRetailer", customRetailer);
27893 tejbeer 2184
 
31751 tejbeer 2185
        return "partner-secondary-order";
2186
    }
27893 tejbeer 2187
 
31751 tejbeer 2188
    @RequestMapping(value = "/getMobileBrandWise", method = RequestMethod.GET)
2189
    public String getMobileBrandWise(HttpServletRequest request, Model model) throws Exception {
2190
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2191
        String email = loginDetails.getEmailId();
28451 tejbeer 2192
 
31751 tejbeer 2193
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
2194
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28451 tejbeer 2195
 
31751 tejbeer 2196
        Map<String, BrandWisePartnerSaleModel> partnersBrandSaleMap = null;
2197
        partnersBrandSaleMap = fofoStoreRepository.selectGroupByBrandWarehousePartnerSale(new ArrayList<>(fofoIds)).stream().collect(Collectors.toMap(x -> x.getBrand(), x -> x));
28451 tejbeer 2198
 
31751 tejbeer 2199
        List<BrandWiseUnbilledActivateStockModel> unbilledActivatedStock = fofoStoreRepository.selectUnbilledActivateStockGroupByBrand(new ArrayList<>(fofoIds));
2200
        for (BrandWiseUnbilledActivateStockModel un : unbilledActivatedStock) {
2201
            BrandWisePartnerSaleModel bpt = partnersBrandSaleMap.get(un.getBrand());
2202
            if (bpt != null) {
2203
                bpt.setAmtd(un.getUnbilledMtd());
2204
                bpt.setUamtdQty(un.getUnbilledMTDQty());
2205
            } else {
2206
                bpt = new BrandWisePartnerSaleModel();
2207
                bpt.setBrand(un.getBrand());
2208
                bpt.setAmtd(un.getUnbilledMtd());
2209
                bpt.setUamtdQty(un.getUnbilledMTDQty());
2210
                bpt.setLms(0);
2211
                bpt.setLmtd(0);
2212
                bpt.setMtd(0);
2213
                bpt.setMtdQty(0);
2214
                bpt.setLmtd(0);
2215
                bpt.setLmtdQty(0);
2216
                partnersBrandSaleMap.put(un.getBrand(), bpt);
2217
            }
2218
        }
28451 tejbeer 2219
 
31751 tejbeer 2220
        model.addAttribute("brandSalesMap", partnersBrandSaleMap);
28451 tejbeer 2221
 
31751 tejbeer 2222
        return "mobile-brand-wise-report";
2223
    }
28451 tejbeer 2224
 
31751 tejbeer 2225
    @RequestMapping(value = "/getAccessoriesBrandWise", method = RequestMethod.GET)
2226
    public String getAccessoriesBrandWise(HttpServletRequest request, Model model) throws Exception {
2227
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2228
        String email = loginDetails.getEmailId();
28451 tejbeer 2229
 
31751 tejbeer 2230
        Set<Integer> fofoIds = csService1.getAuthFofoIds(email, true);
28451 tejbeer 2231
 
31751 tejbeer 2232
        List<BrandWisePartnerSaleModel> accessoriesBrandSales = null;
28451 tejbeer 2233
 
31751 tejbeer 2234
        accessoriesBrandSales = fofoStoreRepository.selectGroupByBrandAccesoriesWarehousePartnerSale(new ArrayList<>(fofoIds));
28451 tejbeer 2235
 
31751 tejbeer 2236
        model.addAttribute("accessoriesBrandSales", accessoriesBrandSales);
2237
        return "accessories-brand-wise-report";
2238
    }
28451 tejbeer 2239
 
34973 aman 2240
    @PostMapping("/getMobileLMSGraph")
2241
    public String getMobileLMSGraph(@RequestBody LMSGraphRequest lmsGraphRequest, Model model) throws Exception {
2242
        LocalDate startDate = lmsGraphRequest.getDate().toLocalDate();
2243
        LocalDate endLocalDate = lmsGraphRequest.getEndDate().toLocalDate();
28451 tejbeer 2244
 
34973 aman 2245
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(lmsGraphRequest.getFofoIds())
2246
                .stream()
2247
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
2248
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
2249
 
31751 tejbeer 2250
        ChartModel cm;
34973 aman 2251
        if (lmsGraphRequest.getWarehouseId() != 0) {
2252
            cm = adminUser.getBrandWiseLms(
2253
                    Arrays.asList(lmsGraphRequest.getWarehouseId()),
2254
                    lmsGraphRequest.getFofoIds(),
2255
                    startDate,
2256
                    endLocalDate,
2257
                    lmsGraphRequest.getFilterType()
2258
            );
31751 tejbeer 2259
        } else {
34973 aman 2260
            cm = adminUser.getBrandWiseLms(
2261
                    new ArrayList<>(warehouseIdFofoIdMap.keySet()),
2262
                    lmsGraphRequest.getFofoIds(),
2263
                    startDate,
2264
                    endLocalDate,
2265
                    lmsGraphRequest.getFilterType()
2266
            );
31751 tejbeer 2267
        }
28451 tejbeer 2268
 
34973 aman 2269
        LOGGER.info("chartMap: " + gson.toJson(cm));
31751 tejbeer 2270
        model.addAttribute("chartMap", gson.toJson(cm));
34973 aman 2271
 
31751 tejbeer 2272
        return "brand-wise-mobile-lms-chart";
2273
    }
28451 tejbeer 2274
 
34973 aman 2275
 
31751 tejbeer 2276
    @RequestMapping(value = "/getMobileLMSFilter", method = RequestMethod.GET)
32836 amit.gupta 2277
    public String getMobileLMSFilter(HttpServletRequest request,
2278
                                     @RequestParam(required = false, defaultValue = "0") int warehouseId,
2279
                                     @RequestParam(required = false) LocalDateTime date, @RequestParam(required = false) LocalDateTime endDate, Model
2280
                                             model) throws Exception {
28461 tejbeer 2281
 
31751 tejbeer 2282
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2283
        String email = loginDetails.getEmailId();
28461 tejbeer 2284
 
31751 tejbeer 2285
        if (date == null) {
2286
            LocalDateTime curDate = LocalDate.now().atStartOfDay();
28461 tejbeer 2287
 
31751 tejbeer 2288
            LocalDateTime startOfMonth = curDate.withDayOfMonth(1).minusMonths(6);
2289
            date = startOfMonth.toLocalDate().atStartOfDay();
2290
        }
28461 tejbeer 2291
 
31751 tejbeer 2292
        if (endDate == null) {
2293
            LocalDateTime curDate = LocalDate.now().atTime(LocalTime.MAX);
30279 tejbeer 2294
 
31751 tejbeer 2295
            endDate = curDate;
30279 tejbeer 2296
 
31751 tejbeer 2297
        }
30279 tejbeer 2298
 
31751 tejbeer 2299
        Map<String, Object> map = adminUser.getFilter(warehouseId, email, date, endDate);
2300
        model.addAttribute("warehouseId", warehouseId);
2301
        model.addAllAttributes(map);
28461 tejbeer 2302
 
31751 tejbeer 2303
        return "chart-filter-lms";
2304
    }
28461 tejbeer 2305
 
35514 amit 2306
    @PostMapping("/getMobileLMPGraph")
2307
    public String getMobileLMPGraph(@RequestBody LMSGraphRequest lmpGraphRequest, Model model) throws Exception {
2308
        LocalDate startDate = lmpGraphRequest.getDate().toLocalDate();
2309
        LocalDate endLocalDate = lmpGraphRequest.getEndDate().toLocalDate();
28461 tejbeer 2310
 
35514 amit 2311
        Map<Integer, List<Integer>> warehouseIdFofoIdMap = fofoStoreRepository.selectActivePartnersByRetailerIds(lmpGraphRequest.getFofoIds())
2312
                .stream()
2313
                .collect(Collectors.groupingBy(FofoStore::getWarehouseId,
2314
                        Collectors.mapping(FofoStore::getId, Collectors.toList())));
2315
 
31751 tejbeer 2316
        ChartModel cm;
35514 amit 2317
        if (lmpGraphRequest.getWarehouseId() != 0) {
2318
            cm = adminUser.getBrandWiseLmp(
2319
                    Arrays.asList(lmpGraphRequest.getWarehouseId()),
2320
                    lmpGraphRequest.getFofoIds(),
2321
                    startDate,
2322
                    endLocalDate,
2323
                    lmpGraphRequest.getFilterType()
2324
            );
31751 tejbeer 2325
        } else {
35514 amit 2326
            cm = adminUser.getBrandWiseLmp(
2327
                    new ArrayList<>(warehouseIdFofoIdMap.keySet()),
2328
                    lmpGraphRequest.getFofoIds(),
2329
                    startDate,
2330
                    endLocalDate,
2331
                    lmpGraphRequest.getFilterType()
2332
            );
31751 tejbeer 2333
        }
28461 tejbeer 2334
 
35514 amit 2335
        LOGGER.info("chartMap: " + gson.toJson(cm));
31751 tejbeer 2336
        model.addAttribute("chartMap", gson.toJson(cm));
2337
        return "brand-wise-mobile-lmp-chart";
2338
    }
28461 tejbeer 2339
 
31751 tejbeer 2340
    @RequestMapping(value = "/getSaleCountByMilestone", method = RequestMethod.GET)
32836 amit.gupta 2341
    public String getSaleCountByMilestone(HttpServletRequest request,
2342
                                          @RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
31259 tejbeer 2343
 
31751 tejbeer 2344
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2345
        String email = loginDetails.getEmailId();
2346
        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);
31259 tejbeer 2347
 
31751 tejbeer 2348
        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
32792 shampa 2349
        Set<Integer> fofoIds = null;
34176 tejus.loha 2350
        if (authFofoIds != null) {
32792 shampa 2351
            fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
2352
        }
31267 tejbeer 2353
 
32792 shampa 2354
 
31751 tejbeer 2355
        Map<Integer, Double> last3MonthSale = fofoOrderItemRepository.selectSumMopGroupByRetailer(
2356
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now(), 0, false);
31318 tejbeer 2357
 
31751 tejbeer 2358
        if (fofoIds != null && fofoIds.size() > 0) {
2359
            if (warehouseId != 0) {
2360
                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId).stream().map(x -> x).collect(Collectors.toSet());
2361
            }
2362
            Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
2363
            if (partnerStats != null) {
2364
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x)).map(x -> partnerStats.get(x)).collect(Collectors.toList());
2365
                Map<Milestone, List<Integer>> avg3Monthlms = new HashMap<>();
2366
                if (!last3MonthSale.isEmpty()) {
2367
                    int days = 60 + LocalDateTime.now().getDayOfMonth();
2368
                    for (Entry<Integer, Double> last3MonthEntry : last3MonthSale.entrySet()) {
2369
                        if (fofoIds.contains(last3MonthEntry.getKey())) {
2370
                            Double monthSale = last3MonthEntry.getValue();
2371
                            if (monthSale == null) {
2372
                                monthSale = (double) 0;
31319 tejbeer 2373
 
31751 tejbeer 2374
                            }
2375
                            double avg3MonthSale = (monthSale / days) * 30;
2376
                            Milestone milestone = Milestone.get((int) avg3MonthSale);
31318 tejbeer 2377
 
31751 tejbeer 2378
                            List<Integer> values = null;
31318 tejbeer 2379
 
31751 tejbeer 2380
                            if (avg3Monthlms.containsKey(milestone)) {
31319 tejbeer 2381
 
31751 tejbeer 2382
                                values = avg3Monthlms.get(milestone);
2383
                                values.add(last3MonthEntry.getKey());
2384
                                avg3Monthlms.put(milestone, values);
31267 tejbeer 2385
 
31751 tejbeer 2386
                            } else {
2387
                                values = new ArrayList<>();
31267 tejbeer 2388
 
31751 tejbeer 2389
                                values.add(last3MonthEntry.getKey());
2390
                                avg3Monthlms.put(milestone, values);
31267 tejbeer 2391
 
31751 tejbeer 2392
                            }
2393
                        }
31267 tejbeer 2394
 
31751 tejbeer 2395
                    }
31263 tejbeer 2396
 
31751 tejbeer 2397
                }
31285 tejbeer 2398
 
31751 tejbeer 2399
                if (partnerDetails != null) {
31318 tejbeer 2400
 
31751 tejbeer 2401
                    Map<Milestone, List<Integer>> mtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getMtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
2402
                    Map<Milestone, List<Integer>> lmtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getLmtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31260 tejbeer 2403
 
31751 tejbeer 2404
                    Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getLms()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31259 tejbeer 2405
 
31751 tejbeer 2406
                    model.addAttribute("mtdMap", mtdMap);
2407
                    model.addAttribute("lmtdMap", lmtdMap);
2408
                    model.addAttribute("avg3Monthlms", avg3Monthlms);
2409
                    model.addAttribute("lmsMap", lmsMap);
2410
                }
31267 tejbeer 2411
 
31751 tejbeer 2412
            }
2413
        }
31273 tejbeer 2414
 
31751 tejbeer 2415
        model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
2416
        model.addAttribute("warehouseId", warehouseId);
2417
        model.addAttribute("milestones", Milestone.values());
31273 tejbeer 2418
 
31751 tejbeer 2419
        return "sale-milestone";
31273 tejbeer 2420
 
31751 tejbeer 2421
    }
31273 tejbeer 2422
 
31751 tejbeer 2423
    @RequestMapping(value = "/getPurchaseCountByMileStone", method = RequestMethod.GET)
32836 amit.gupta 2424
    public String getPurchaseCountByMileStone(HttpServletRequest request,
2425
                                              @RequestParam(required = false, defaultValue = "0") int warehouseId, Model model) throws Exception {
31273 tejbeer 2426
 
31751 tejbeer 2427
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2428
        String email = loginDetails.getEmailId();
31320 tejbeer 2429
 
31751 tejbeer 2430
        Set<Integer> authFofoIds = csService1.getAuthFofoIds(email, true);
31320 tejbeer 2431
 
31751 tejbeer 2432
        Set<Integer> fofoIdlist = fofoStoreRepository.selectActiveStores().stream().filter(x -> !x.isInternal()).map(x -> x.getId()).collect(Collectors.toSet());
32792 shampa 2433
        Set<Integer> fofoIds = null;
34176 tejus.loha 2434
        if (authFofoIds != null) {
32792 shampa 2435
            fofoIds = authFofoIds.stream().filter(x -> fofoIdlist.contains(x)).collect(Collectors.toSet());
2436
        }
31273 tejbeer 2437
 
31751 tejbeer 2438
        Map<Integer, Double> last3MonthS = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
2439
                LocalDateTime.now().withDayOfMonth(1).minusMonths(2), LocalDateTime.now());
31320 tejbeer 2440
 
31751 tejbeer 2441
        if (fofoIds != null && fofoIds.size() > 0) {
2442
            if (warehouseId != 0) {
2443
                fofoIds = fofoStoreRepository.selectPartnerByfofoIdAndWarehouse(new ArrayList<>(fofoIds), warehouseId).stream().map(x -> x).collect(Collectors.toSet());
2444
            }
2445
            Map<Integer, PartnerDetailModel> partnerStats = adminUser.getPartnersStatDataFromFile();
2446
            if (partnerStats != null) {
2447
                List<PartnerDetailModel> partnerDetails = fofoIds.stream().filter(x -> partnerStats.containsKey(x)).map(x -> partnerStats.get(x)).collect(Collectors.toList());
2448
                Map<Milestone, List<Integer>> avg3MonthS = new HashMap<>();
2449
                if (!last3MonthS.isEmpty()) {
2450
                    int days = 60 + LocalDateTime.now().getDayOfMonth();
2451
                    for (Entry<Integer, Double> last3MonthSEntry : last3MonthS.entrySet()) {
2452
                        if (fofoIds.contains(last3MonthSEntry.getKey())) {
2453
                            Double monthSec = last3MonthSEntry.getValue();
2454
                            if (monthSec == null) {
2455
                                monthSec = (double) 0;
31320 tejbeer 2456
 
31751 tejbeer 2457
                            }
2458
                            double avg3MonthSale = (monthSec / days) * 30;
2459
                            Milestone milestone = Milestone.get((int) avg3MonthSale);
31320 tejbeer 2460
 
31751 tejbeer 2461
                            List<Integer> values = null;
2462
                            if (avg3MonthS.containsKey(milestone)) {
2463
                                values = avg3MonthS.get(milestone);
2464
                                values.add(last3MonthSEntry.getKey());
31273 tejbeer 2465
 
31751 tejbeer 2466
                                avg3MonthS.put(milestone, values);
2467
                            } else {
31273 tejbeer 2468
 
31751 tejbeer 2469
                                values = new ArrayList<>();
31273 tejbeer 2470
 
31751 tejbeer 2471
                                values.add(last3MonthSEntry.getKey());
31273 tejbeer 2472
 
31751 tejbeer 2473
                                avg3MonthS.put(milestone, values);
31273 tejbeer 2474
 
31751 tejbeer 2475
                            }
2476
                        }
31273 tejbeer 2477
 
31751 tejbeer 2478
                    }
31267 tejbeer 2479
 
31751 tejbeer 2480
                }
31259 tejbeer 2481
 
31751 tejbeer 2482
                if (partnerDetails != null) {
2483
                    Map<Milestone, List<Integer>> smtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarymtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
2484
                    Map<Milestone, List<Integer>> slmtdMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylmtd()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
2485
                    Map<Milestone, List<Integer>> lmsMap = partnerDetails.stream().collect(Collectors.groupingBy(x -> Milestone.get(x.getSecondarylms()), Collectors.mapping(x -> x.getFofoId(), Collectors.toList())));
31259 tejbeer 2486
 
31751 tejbeer 2487
                    model.addAttribute("smtdMap", smtdMap);
2488
                    model.addAttribute("slmtdMap", slmtdMap);
2489
                    model.addAttribute("avg3MonthS", avg3MonthS);
2490
                    model.addAttribute("lmsMap", lmsMap);
31259 tejbeer 2491
 
31751 tejbeer 2492
                }
28825 tejbeer 2493
 
31751 tejbeer 2494
            }
2495
        }
28825 tejbeer 2496
 
31751 tejbeer 2497
        model.addAttribute("warehouseMap", ProfitMandiConstants.WAREHOUSE_MAP);
2498
        model.addAttribute("warehouseId", warehouseId);
2499
        model.addAttribute("milestones", Milestone.values());
28825 tejbeer 2500
 
31751 tejbeer 2501
        return "purchase-milestone";
28825 tejbeer 2502
 
31751 tejbeer 2503
    }
31152 tejbeer 2504
 
31751 tejbeer 2505
    @RequestMapping(value = "/getActivatedModelWarehouseWise", method = RequestMethod.GET)
32836 amit.gupta 2506
    public String getActivatedModelWarehouseWise(HttpServletRequest request, Model model, @RequestParam String
2507
            brand) throws Exception {
31751 tejbeer 2508
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2509
        List<Integer> fofoIds = getFofoIds(loginDetails);
2510
        List<WarehouseWiseActivatedModel> warehouseWiseActivatedModels = activatedImeiRepository.selectActivatedModelGroupByWarehouse(brand, fofoIds);
2511
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
28825 tejbeer 2512
 
31751 tejbeer 2513
        List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
28825 tejbeer 2514
 
31751 tejbeer 2515
        List<String> brands = mobileBrands.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());
2516
        LOGGER.info("brands" + brands.add("Redmi"));
28825 tejbeer 2517
 
31751 tejbeer 2518
        model.addAttribute("warehouseWiseActivatedModels", warehouseWiseActivatedModels);
2519
        model.addAttribute("warehouseMap", warehouseMap);
2520
        model.addAttribute("brands", brands);
2521
        model.addAttribute("selectedbrand", brand);
2522
        return "warehousewise_activated_model";
2523
    }
28825 tejbeer 2524
 
31751 tejbeer 2525
    @RequestMapping(value = "/getActivatedModelByBrand", method = RequestMethod.GET)
2526
    public String getActivatedModelByBrand(HttpServletRequest request, Model model) throws Exception {
2527
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2528
        Set<Integer> fofoIds = csService1.getAuthFofoIds(loginDetails.getEmailId(), true);
28825 tejbeer 2529
 
31751 tejbeer 2530
        List<BrandWiseActivatedModel> activatedModels = activatedImeiRepository.selectActivatedModelGroupByBrand(new ArrayList<>(fofoIds));
2531
        model.addAttribute("activatedModels", activatedModels);
2532
        return "activation-brandwise-report";
2533
    }
28825 tejbeer 2534
 
31751 tejbeer 2535
    @RequestMapping(value = "/getWarehouseBrandWiseItemActivatedModel", method = RequestMethod.GET)
32836 amit.gupta 2536
    public String getWarehouseBrandWiseItemActivatedModel(HttpServletRequest request, Model
2537
            model, @RequestParam List<Integer> warehouseId, @RequestParam String brand) throws Exception {
31751 tejbeer 2538
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2539
        List<Integer> fofoIds = getFofoIds(loginDetails);
28825 tejbeer 2540
 
31751 tejbeer 2541
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
2542
        List<WarehouseBrandWiseItemActivatedModel> activatedItems = activatedImeiRepository.selectWarehouseBrandActivatedItem(warehouseId, brand, fofoIds);
2543
        model.addAttribute("warehouseMap", warehouseMap);
2544
        model.addAttribute("activatedItems", activatedItems);
2545
        return "warehouse-activated-itemwise-model";
28825 tejbeer 2546
 
31751 tejbeer 2547
    }
28825 tejbeer 2548
 
31751 tejbeer 2549
    @RequestMapping(value = "/getActivatedImeiUpdationDate", method = RequestMethod.GET)
2550
    public String getActivatedImeiUpdationDate(HttpServletRequest request, Model model) throws Exception {
28825 tejbeer 2551
 
31751 tejbeer 2552
        Map<Integer, String> warehouseMap = ProfitMandiConstants.WAREHOUSE_MAP;
35466 amit 2553
        List<String> brands = ProfitMandiConstants.BRANDS;
28825 tejbeer 2554
 
31751 tejbeer 2555
        List<ActivationImeiUpdationModel> activationImeiUpdations = activatedImeiRepository.selectActivatedUpdationDate();
35466 amit 2556
 
2557
        // Create a map for quick lookup of existing results
2558
        Map<String, ActivationImeiUpdationModel> resultMap = activationImeiUpdations.stream()
2559
                .collect(Collectors.toMap(
2560
                        m -> m.getWarehouseId() + "_" + m.getBrand(),
2561
                        m -> m
2562
                ));
2563
 
2564
        // Merge with master data - add missing combinations with null timestamp
2565
        List<ActivationImeiUpdationModel> completeList = new ArrayList<>();
2566
        for (Integer warehouseId : warehouseMap.keySet()) {
2567
            for (String brand : brands) {
2568
                String key = warehouseId + "_" + brand;
2569
                ActivationImeiUpdationModel existing = resultMap.get(key);
2570
                if (existing != null) {
2571
                    completeList.add(existing);
2572
                } else {
2573
                    completeList.add(new ActivationImeiUpdationModel(warehouseId, brand, null));
2574
                }
2575
            }
2576
        }
2577
 
31751 tejbeer 2578
        model.addAttribute("warehouseMap", warehouseMap);
35466 amit 2579
        model.addAttribute("activationImeiUpdations", completeList);
31751 tejbeer 2580
        return "activation-updation-timestamp";
28825 tejbeer 2581
 
31751 tejbeer 2582
    }
31285 tejbeer 2583
 
31751 tejbeer 2584
    private List<Integer> getFofoIds(LoginDetails loginDetails) throws ProfitMandiBusinessException {
2585
        String email = loginDetails.getEmailId();
31287 tejbeer 2586
 
31751 tejbeer 2587
        AuthUser authUser = authRepository.selectByEmailOrMobile(email);
2588
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
31287 tejbeer 2589
 
31751 tejbeer 2590
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
2591
        if (emails.contains(authUser.getEmailId())) {
2592
            fofoIds = storeGuyMap.get("tarun.verma@smartdukaan.com");
2593
            LOGGER.info("fofoIds" + fofoIds);
2594
        }
31287 tejbeer 2595
 
31751 tejbeer 2596
        if (fofoIds == null) {
35395 amit 2597
            List<Position> positions1 = positionRepository.selectAllByAuthUserId(authUser.getId());
31751 tejbeer 2598
            if (positions1.stream().filter(x -> x.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_MASTER).count() > 0) {
2599
                fofoIds = csService.getPositionCustomRetailerMap(positions1).values().stream().flatMap(x -> x.stream()).map(x -> x.getPartnerId()).collect(Collectors.toSet());
2600
            }
2601
        }
2602
        return new ArrayList<>(fofoIds);
2603
    }
31287 tejbeer 2604
 
31751 tejbeer 2605
    @RequestMapping(value = "/getMonthWiseSale", method = RequestMethod.GET)
32836 amit.gupta 2606
    public String getPartnerSaleByMonth(HttpServletRequest request, @RequestParam List<Integer> fofoIds, Model
2607
            model) throws Exception {
31287 tejbeer 2608
 
31751 tejbeer 2609
        YearMonth now = YearMonth.now();
2610
        YearMonth ym = YearMonth.now().minusMonths(12);
2611
        List<YearMonth> list = new ArrayList<>();
2612
        while (!now.isBefore(ym)) {
2613
            list.add(now);
2614
            now = now.minusMonths(1);
2615
        }
31287 tejbeer 2616
 
31751 tejbeer 2617
        model.addAttribute("yearMonth", list);
31287 tejbeer 2618
 
31751 tejbeer 2619
        List<PartnerMonthlySaleModel> partnerMonthlySaleModels = fofoOrderItemRepository.selectPartnerMonthlySale(fofoIds, LocalDateTime.now().minusMonths(12).withDayOfMonth(1));
2620
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-yyyy");
2621
        Map<Integer, Map<YearMonth, Double>> partnerMonthSaleMap = new HashMap<>();
2622
        if (!partnerMonthlySaleModels.isEmpty()) {
31287 tejbeer 2623
 
31751 tejbeer 2624
            partnerMonthSaleMap = partnerMonthlySaleModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.toMap(
2625
                    x -> YearMonth.parse(x.getYearMonth(), dateTimeFormatter), x -> (double) x.getAmount())));
2626
        }
31297 tejbeer 2627
 
31751 tejbeer 2628
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
31297 tejbeer 2629
 
31751 tejbeer 2630
        model.addAttribute("customRetailerMap", customRetailerMap);
31297 tejbeer 2631
 
31751 tejbeer 2632
        model.addAttribute("customRetailerMap", customRetailerMap);
31297 tejbeer 2633
 
31751 tejbeer 2634
        model.addAttribute("partnerMonthSaleMap", partnerMonthSaleMap);
2635
        return "monthly-partner-sale";
31297 tejbeer 2636
 
31751 tejbeer 2637
    }
31297 tejbeer 2638
 
35541 amit 2639
    @RequestMapping(value = "/getMonthWisePurchase", method = RequestMethod.POST)
35543 amit 2640
    public String getMonthWisePurchase(HttpServletRequest request, @RequestBody List<Integer> fofoIds, Model
32836 amit.gupta 2641
            model) throws Exception {
31751 tejbeer 2642
 
2643
        YearMonth now = YearMonth.now();
2644
        YearMonth ym = YearMonth.now().minusMonths(12);
2645
        List<YearMonth> list = new ArrayList<>();
2646
        while (!now.isBefore(ym)) {
2647
            list.add(now);
2648
            now = now.minusMonths(1);
2649
        }
2650
 
2651
        model.addAttribute("yearMonth", list);
2652
 
2653
        List<PartnerMonthlySaleModel> partnerMonthlySaleModels = orderRepository.selectSecondaryGroupByYearMonth(
32445 amit.gupta 2654
                fofoIds, LocalDate.now().withDayOfMonth(1).atStartOfDay().minusMonths(12), LocalDateTime.now());
31751 tejbeer 2655
        Map<Integer, Map<YearMonth, Double>> partnerMonthPurchaseMap = partnerMonthlySaleModels.stream().collect(Collectors.groupingBy(x -> x.getFofoId(), Collectors.groupingBy(
2656
                y -> YearMonth.parse(y.getYearMonth(), DateTimeFormatter.ofPattern("MM-yyyy")), Collectors.summingDouble(x -> x.getAmount()))));
2657
 
2658
        Map<Integer, CustomRetailer> customRetailerMap = retailerService.getAllFofoRetailers().entrySet().stream().filter(x -> fofoIds.contains(x.getKey())).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
2659
        model.addAttribute("customRetailerMap", customRetailerMap);
2660
        model.addAttribute("partnerMonthPurchaseMap", partnerMonthPurchaseMap);
2661
        return "monthly-partner-purchase";
2662
 
2663
    }
32407 amit.gupta 2664
 
32336 jai.hind 2665
    @GetMapping("/restartServer")
32407 amit.gupta 2666
    public String RestartServer(HttpServletRequest request, Model model) throws Exception {
2667
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2668
        if (Arrays.asList("amit.gupta@smartdukaan.com", "shivam.gupta@smartdukaan.com", "vinay.p@smartdukaan.com").contains(loginDetails.getEmailId())) {
2669
            String ipAddress = "45.79.106.95";
2670
            int port = 22;
2671
            String username = "root";
2672
            String password = "spic@2015shop2020";
32408 amit.gupta 2673
            String restartServices = "./restart-services.sh";
2674
            sshService.executeCommand(ipAddress, port, username, password, restartServices);
32407 amit.gupta 2675
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
2676
        } else {
2677
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
2678
        }
32337 jai.hind 2679
        return "response";
2680
    }
32336 jai.hind 2681
 
32337 jai.hind 2682
    @GetMapping("/rebootServer")
32407 amit.gupta 2683
    public String rebootServer(HttpServletRequest request, Model model) throws Exception {
2684
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2685
        if (Arrays.asList("amit.gupta@smartdukaan.com", "shivam.gupta@smartdukaan.com", "vinay.p@smartdukaan.com").contains(loginDetails.getEmailId())) {
2686
            String ipAddress = "45.79.106.95";
2687
            int port = 22;
2688
            String username = "root";
2689
            String password = "spic@2015shop2020";
2690
            String rebootCommand = "reboot";
32337 jai.hind 2691
 
32408 amit.gupta 2692
            sshService.executeCommand(ipAddress, port, username, password, rebootCommand);
32407 amit.gupta 2693
            model.addAttribute("response1", mvcResponseSender.createResponseString(true));
2694
        } else {
2695
            model.addAttribute("response1", mvcResponseSender.createResponseString(false));
2696
        }
32336 jai.hind 2697
        return "response";
2698
    }
32407 amit.gupta 2699
 
32336 jai.hind 2700
    @GetMapping("/getRestartServer")
32407 amit.gupta 2701
    public String getRestartServer(HttpServletRequest request, Model model) {
2702
        return "restart-server-page";
32336 jai.hind 2703
    }
37327 ranu 2704
 
2705
    private static String ordinalDay(int day) {
2706
        if (day >= 11 && day <= 13) return day + "th";
2707
        switch (day % 10) {
2708
            case 1:
2709
                return day + "st";
2710
            case 2:
2711
                return day + "nd";
2712
            case 3:
2713
                return day + "rd";
2714
            default:
2715
                return day + "th";
2716
        }
2717
    }
2718
 
37427 ranu 2719
    static String formatSchemePeriodDisplay(LocalDateTime start, LocalDateTime end) {
37327 ranu 2720
        if (start == null || end == null) return "";
2721
        String startPart = ordinalDay(start.getDayOfMonth()) + " " +
2722
                start.getMonth().getDisplayName(java.time.format.TextStyle.FULL, Locale.ENGLISH);
2723
        String endPart = ordinalDay(end.getDayOfMonth()) + " " +
2724
                end.getMonth().getDisplayName(java.time.format.TextStyle.FULL, Locale.ENGLISH) + " " + end.getYear();
2725
        long months = java.time.temporal.ChronoUnit.MONTHS.between(
2726
                start.toLocalDate().withDayOfMonth(1),
2727
                end.toLocalDate().withDayOfMonth(1)) + 1;
2728
        return startPart + " – " + endPart + " (" + months + " Months)";
2729
    }
2730
 
2731
    @RequestMapping(value = "/dashboard", method = RequestMethod.GET)
2732
    public String dashboard(HttpServletRequest request, Model model) throws Exception {
2733
        LoginDetails loginDetails = cookiesProcessor.getCookiesObject(request);
2734
        String email = loginDetails.getEmailId();
2735
        int fofoId = loginDetails.getFofoId();
2736
        boolean isAdmin = roleManager.isAdmin(loginDetails.getRoleIds());
2737
        model.addAttribute("isAdmin", isAdmin);
2738
 
2739
        model.addAttribute("webApiHost", webApiHost);
2740
        model.addAttribute("webApiPort", webApiPort);
2741
        model.addAttribute("webApiScheme", webApiScheme);
2742
        model.addAttribute("webApiRoot", webApiRoot);
2743
        model.addAttribute("googleApiKey", googleApiKey);
2744
 
2745
        if (isAdmin) {
2746
            return adminUser.adminPanel(loginDetails.getFofoId(), email, model);
2747
        } else {
2748
            FofoStore fofoStore;
2749
            List<PartnerRegion> partnerRegion = partnerRegionRepository.selectByfofoId(fofoId);
2750
            LocalDateTime currentDate = LocalDateTime.now();
2751
            List<PrintResource> printResources = printResourceRepository.selectPrintResourcesByFofoRegion(partnerRegion.get(0).getRegionId(), currentDate);
2752
            LOGGER.info("printresourcesList {}", printResources);
2753
            model.addAttribute("printResources", printResources);
2754
            try {
2755
                fofoStore = fofoStoreRepository.selectByRetailerId(loginDetails.getFofoId());
2756
                if (!fofoStore.isActive()) {
2757
                    return "redirect:/login";
2758
                }
2759
 
2760
                LocalDateTime startDate = LocalDate.now().withDayOfYear(1).atStartOfDay();
2761
                LocalDateTime endtDate = LocalDateTime.now();
2762
                OnlineDeliveredOrderSum onlineDeliveredOrderSum = pendingOrderItemRepository.selectSumSellingPriceOnlineOrder(fofoId, startDate, endtDate);
2763
                LOGGER.info("onlineDeliveredOrderSum" + onlineDeliveredOrderSum.getSellingPrice());
2764
 
2765
                long countOrder = pendingOrderRepository.pendingOrderCount(fofoId, OrderStatus.PROCESSING);
2766
                LOGGER.info("countOrder" + countOrder);
2767
 
2768
                ArrayList<in.shop2020.model.v1.order.OrderStatus> orderStatus = new ArrayList<>();
2769
 
2770
                orderStatus.add(SUBMITTED_FOR_PROCESSING);
2771
                orderStatus.add(BILLED);
2772
                orderStatus.add(SHIPPED_FROM_WH);
2773
                orderStatus.add(DELIVERY_SUCCESS);
2774
 
2775
                List<Order> openOrders = orderRepository.selectGrnTimestampNull(fofoId, orderStatus);
2776
                List<LineItem> submittedLineItemIds = openOrders.stream().filter(x -> x.getStatus().equals(SUBMITTED_FOR_PROCESSING)).map(x -> x.getLineItem()).collect(Collectors.toList());
2777
                List<LineItem> billedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(BILLED)).map(x -> x.getLineItem()).collect(Collectors.toList());
2778
                List<LineItem> shippedOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(SHIPPED_FROM_WH)).map(x -> x.getLineItem()).collect(Collectors.toList());
2779
                List<LineItem> grnPendingLineItemIds = openOrders.stream().filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getLineItem()).collect(Collectors.toList());
2780
 
2781
                long imeiActivationPendingCount = 0;
2782
                long imeiActivationPendingValue = 0;
2783
                //Only delivered orders should be visible
2784
                List<Integer> grnPendingOrderIds = openOrders.stream().filter(x -> x.getStatus().equals(DELIVERY_SUCCESS)).map(x -> x.getId()).collect(Collectors.toList());
2785
                if (grnPendingOrderIds.size() > 0) {
2786
                    List<ImeiActivationTimestampModel> imeiActivationTimestampModels = activatedImeiRepository.selectActivatedImeisByOrders(grnPendingOrderIds);
2787
                    imeiActivationPendingCount = imeiActivationTimestampModels.size();
2788
                    imeiActivationPendingValue = imeiActivationTimestampModels.stream().collect(Collectors.summingDouble(x -> x.getSellingPrice())).longValue();
2789
                }
2790
 
2791
                long grnPendingCount = grnPendingLineItemIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
2792
                long grnPendingValue = grnPendingLineItemIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
2793
                model.addAttribute("grnPendingCount", grnPendingCount);
2794
                model.addAttribute("grnPendingValue", grnPendingValue);
2795
 
2796
                long submittedCount = submittedLineItemIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
2797
                long submittedValue = submittedLineItemIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
2798
                model.addAttribute("submittedCount", submittedCount);
2799
                model.addAttribute("submittedValue", submittedValue);
2800
 
2801
                long billedCount = billedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
2802
                long billedValue = billedOrderIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
2803
                model.addAttribute("billedValue", billedValue);
2804
                model.addAttribute("billedCount", billedCount);
2805
                LOGGER.info("billedCount {}", billedCount);
2806
 
2807
                long shippedCount = shippedOrderIds.stream().collect(Collectors.summingLong(LineItem::getQuantity));
2808
                model.addAttribute("shippedCount", shippedCount);
2809
                LOGGER.info("shippedCount {}", shippedCount);
2810
                long shippedValue = shippedOrderIds.stream().collect(Collectors.summingLong(x -> x.getTotalPrice().longValue()));
2811
                model.addAttribute("shippedValue", shippedValue);
2812
 
2813
                LocalDateTime curDate = LocalDate.now().atStartOfDay();
2814
 
2815
                LocalDateTime currentMonthStart = curDate.withDayOfMonth(1);
2816
                LocalDateTime lastMonthStart = currentMonthStart.minusMonths(1);
2817
                LocalDateTime currentMonthEnd = currentMonthStart.withDayOfMonth(1);
2818
 
2819
                LOGGER.info("lastMonthStart" + lastMonthStart);
2820
                LOGGER.info("currentMonthEnd" + currentMonthEnd);
2821
 
2822
                Scheme staticScheme = schemeService.getStaticScheme(fofoId);
2823
                double schemeAchievement = 0;
2824
                double mobileLedAchievement = 0;
2825
                double accessoriesAchievement = 0;
2826
                long mobileLedTarget = 0;
2827
                long accessoriesTarget = 0;
2828
                long totalTarget = 0;
2829
                int achievementPercent = 0;
2830
                String aimingTier = null;
2831
                if (staticScheme != null) {
37348 ranu 2832
                    // Total achievement = retailer's purchase billings (same source used last year).
2833
                    Map<Integer, Double> schemeAchievementMap = orderRepository.selectBillingDatesBetweenSumGroupByRetailerId(
2834
                            staticScheme.getStartDateTime(), staticScheme.getEndDateTime());
2835
                    schemeAchievement = schemeAchievementMap.getOrDefault(fofoId, 0.0);
2836
 
2837
                    // Category breakdown pulls from the same purchase source (Order + LineItem + Item):
2838
                    // Mobile (10006) + LED (14202) in one bucket, everything else in accessories.
37327 ranu 2839
                    Set<Integer> mobileLedCategoryIds = new HashSet<>(Arrays.asList(10006, 14202));
37348 ranu 2840
                    Map<Integer, Double> mobileLedMap = orderRepository.selectBilledLineRevenueByRetailerAndCategories(
37327 ranu 2841
                            fofoId, staticScheme.getStartDateTime(), staticScheme.getEndDateTime(), mobileLedCategoryIds, true);
37348 ranu 2842
                    Map<Integer, Double> accessoriesMap = orderRepository.selectBilledLineRevenueByRetailerAndCategories(
37327 ranu 2843
                            fofoId, staticScheme.getStartDateTime(), staticScheme.getEndDateTime(), mobileLedCategoryIds, false);
2844
                    mobileLedAchievement = mobileLedMap.getOrDefault(fofoId, 0.0);
2845
                    accessoriesAchievement = accessoriesMap.getOrDefault(fofoId, 0.0);
2846
 
2847
                    mobileLedTarget = staticScheme.getTarget();
2848
                    // Accessories target is fixed at 1% of the assigned mobile+LED target.
2849
                    accessoriesTarget = Math.round(mobileLedTarget * 0.01);
2850
                    totalTarget = mobileLedTarget + accessoriesTarget;
2851
                    achievementPercent = totalTarget > 0 ? (int) Math.round(schemeAchievement * 100.0 / totalTarget) : 0;
2852
 
37427 ranu 2853
                    // "Currently aiming for" — floored at the partner's target tier.
2854
                    // Partner keeps aiming at their assigned tier until achievement crosses it,
2855
                    // then advances to the next tier as achievement crosses each ceiling.
2856
                    long aimBasis = Math.max(mobileLedTarget, (long) schemeAchievement);
2857
                    if (aimBasis < 4000000) {
37327 ranu 2858
                        aimingTier = "Shuruaat";       // up to 40 Lacs
37427 ranu 2859
                    } else if (aimBasis < 7000000) {
37327 ranu 2860
                        aimingTier = "Udaan";          // 40 – 70 Lacs
37427 ranu 2861
                    } else if (aimBasis < 9000000) {
37327 ranu 2862
                        aimingTier = "Raftaar";        // 70 – 90 Lacs
37427 ranu 2863
                    } else if (aimBasis < 12000000) {
37327 ranu 2864
                        aimingTier = "Tarakki";        // 90 Lacs – 1.20 Cr
37427 ranu 2865
                    } else if (aimBasis < 24000000) {
37327 ranu 2866
                        aimingTier = "Vijeta";         // 1.20 – 2.40 Cr
2867
                    } else {
2868
                        aimingTier = "Maharaja";       // 2.40 Cr and above
2869
                    }
2870
                }
2871
 
2872
 
2873
                model.addAttribute("countOrder", countOrder);
2874
                model.addAttribute("onlineDeliveredOrderSum", onlineDeliveredOrderSum.getSellingPrice());
2875
 
2876
                PartnerType partnerType = partnerTypeChangeService.getTypeOnDate(fofoStore.getId(), LocalDate.now());
2877
                model.addAttribute("partnerType", partnerType);
2878
                model.addAttribute("partnerTypeImage", PartnerType.imageMap.get(partnerType));
2879
                model.addAttribute("fofoStore", fofoStore);
2880
                model.addAttribute("partnerType", partnerType);
2881
                model.addAttribute("hasGift", fofoUser.hasGift(loginDetails.getFofoId()));
2882
                model.addAttribute("giftItemId", ProfitMandiConstants.GIFT_ID);
2883
                model.addAttribute("retailers", new JSONObject().append("code", fofoStore.getCode()).append("partnerId", fofoStore.getId()).toString());
2884
                model.addAttribute("activatedImeis", inventoryItemRepository.selectCountByActivatedNotSold(loginDetails.getFofoId()));
2885
                model.addAttribute("imeiActivationPendingCount", imeiActivationPendingCount);
2886
                model.addAttribute("imeiActivationPendingValue", imeiActivationPendingValue);
2887
 
2888
                Map<Integer, Double> accesoriesmtdsale = fofoOrderRepository.selectSumSaleGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(), curDate.withDayOfMonth(1), curDate.with(LocalTime.MAX), Optional.of(false));
2889
 
2890
                Double accesoriesStock = currentInventorySnapshotRepository.selectSumStockGroupByFofoIdsForMobileOrAccessories(loginDetails.getFofoId(), Optional.of(false)).get(loginDetails.getFofoId());
2891
 
2892
                model.addAttribute("accesoriesStock", String.format("%.0f", accesoriesStock));
2893
                model.addAttribute("staticScheme", staticScheme);
2894
                model.addAttribute("schemeAchievement", schemeAchievement);
2895
                model.addAttribute("mobileLedAchievement", mobileLedAchievement);
2896
                model.addAttribute("accessoriesAchievement", accessoriesAchievement);
2897
                model.addAttribute("mobileLedTarget", mobileLedTarget);
2898
                model.addAttribute("accessoriesTarget", accessoriesTarget);
2899
                model.addAttribute("totalTarget", totalTarget);
2900
                model.addAttribute("totalTargetDisplay", formatIndianCurrency(totalTarget));
2901
                model.addAttribute("schemeAchievementDisplay", formatIndianCurrency((long) schemeAchievement));
2902
                model.addAttribute("mobileLedAchievementDisplay", formatIndianCurrency((long) mobileLedAchievement));
2903
                model.addAttribute("accessoriesAchievementDisplay", formatIndianCurrency((long) accessoriesAchievement));
2904
                model.addAttribute("achievementPercent", achievementPercent);
2905
                model.addAttribute("aimingTier", aimingTier);
2906
                if (staticScheme != null) {
2907
                    model.addAttribute("schemePeriodDisplay",
2908
                            formatSchemePeriodDisplay(staticScheme.getStartDateTime(), staticScheme.getEndDateTime()));
2909
                }
2910
                model.addAttribute("brandStockPrices", fofoUser.getBrandStockPrices(loginDetails.getFofoId(), false));
2911
                model.addAttribute("salesMap", fofoUser.getSales(loginDetails.getFofoId()));
2912
                ChartModel cm = fofoUser.getBrandChart(loginDetails.getFofoId(),null,null,false);
2913
 
2914
                LOGGER.info("chartMap" + gson.toJson(cm));
2915
                model.addAttribute("chartMap", gson.toJson(cm));
2916
 
2917
                List<CreateOfferRequest> createOffers = offerService.getPublishedOffers(loginDetails.getFofoId(), YearMonth.from(LocalDateTime.now()));
2918
 
2919
                // Batch fetch all catalog IDs to avoid N+1 queries
2920
                Set<Integer> allCatalogIds = createOffers.stream()
2921
                        .flatMap(offer -> offer.getTargetSlabs().stream())
2922
                        .flatMap(slab -> slab.getItemCriteriaPayouts().stream())
2923
                        .map(ItemCriteriaPayout::getItemCriteria)
2924
                        .flatMap(criteria -> criteria.getCatalogIds().stream())
2925
                        .collect(Collectors.toSet());
2926
 
2927
                final Map<Integer, String> catalogBrandMap = new HashMap<>();
2928
                if (!allCatalogIds.isEmpty()) {
2929
                    try {
2930
                        catalogBrandMap.putAll(catalogRepository.selectAllByIds(new ArrayList<>(allCatalogIds)).stream()
2931
                                .collect(Collectors.toMap(c -> c.getId(), c -> c.getBrand())));
2932
                    } catch (ProfitMandiBusinessException e) {
2933
                        LOGGER.error("Error fetching catalogs by IDs", e);
2934
                    }
2935
                }
2936
 
2937
                List<CreateOfferRequest> publishedOffers = createOffers.stream()
2938
                        .filter(createOffer -> createOffer.getTargetSlabs().stream()
2939
                                .flatMap(slab -> slab.getItemCriteriaPayouts().stream())
2940
                                .map(ItemCriteriaPayout::getItemCriteria)
2941
                                .flatMap(criteria -> criteria.getCatalogIds().stream())
2942
                                .noneMatch(catalogId -> "Live Demo".equals(catalogBrandMap.get(catalogId))))
2943
                        .collect(Collectors.toList());
2944
 
2945
                model.addAttribute("publishedOffers", publishedOffers);
2946
                model.addAttribute("investments", fofoUser.getInvestments(loginDetails.getFofoId()));
2947
                model.addAttribute("isInvestmentOk", partnerInvestmentService.isInvestmentOk(loginDetails.getFofoId(), ProfitMandiConstants.MIN_INVESTMENT_PERCENTAGE, ProfitMandiConstants.CUTOFF_INVESTMENT));
2948
 
2949
                double currentMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(currentMonthStart, currentMonthEnd)) / 2;
2950
                double lastMonthRating = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.of(lastMonthStart, currentMonthStart)) / 2;
2951
                double ratingTillDate = hygieneDataRepository.selectRatingAvg(loginDetails.getFofoId(), DateRangeModel.withEndDate(currentMonthEnd)) / 2;
2952
                model.addAttribute("currentMonthRating", (float) Math.round(currentMonthRating * 10) / 10);
2953
                model.addAttribute("lastMonthRating", (float) Math.round(lastMonthRating * 10) / 10);
2954
                model.addAttribute("ratingTillDate", (float) Math.round(ratingTillDate * 10) / 10);
2955
 
2956
                long hygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), true, currentMonthStart, currentMonthEnd);
2957
 
2958
                long invalidHygieneCount = hygieneDataRepository.selectHygieneCount(loginDetails.getFofoId(), false, currentMonthStart, currentMonthEnd);
2959
                if (hygieneCount == 0 && invalidHygieneCount == 0) {
2960
                    invalidHygieneCount = 1;
2961
                }
2962
                Map<Integer, String> monthValueMap = new HashMap<>();
2963
                for (int i = 0; i <= 12; i++) {
2964
                    LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).minusMonths(i);
2965
                    monthValueMap.put(i, startOfMonth.format(DateTimeFormatter.ofPattern("MMM''uu")));
2966
                }
2967
 
2968
                MonthlyTarget monthlyTarget = monthlyTargetRepository.selectByDateAndFofoId(YearMonth.now(), fofoId);
2969
                model.addAttribute("monthlyTarget", monthlyTarget);
2970
                Set<String> brands = brandsService.getBrandsToDisplay(3).stream().map(x -> x.getName()).collect(Collectors.toSet());
2971
 
2972
                model.addAttribute("brands", brands);
2973
                model.addAttribute("monthValueMap", monthValueMap);
2974
                model.addAttribute("month", 0);
2975
                model.addAttribute("hygienePercentage", (hygieneCount * 100) / (invalidHygieneCount + hygieneCount));
2976
                model.addAttribute("monthDays", LocalDate.now().minusDays(1).lengthOfMonth());
2977
                model.addAttribute("dayOfMonth", LocalDate.now().minusDays(1).getDayOfMonth());
2978
                Map<String, Object> rewardsMap = saleRewardService.findByFofoAndRegionId(fofoId, partnerRegion.get(0).getRegionId());
2979
                StoreSalesTarget targetData = saleRewardService.findTargetsByFofoId(fofoId);
2980
                model.addAttribute("rewardsMap", rewardsMap);
2981
                model.addAttribute("targetData", targetData);
2982
                model.addAttribute("regionId", partnerRegion.get(0).getRegionId());
2983
 
2984
 
2985
 
2986
            } catch (
2987
                    ProfitMandiBusinessException e) {
2988
                LOGGER.error("FofoStore Code not found of fofoId {}", loginDetails.getFofoId());
2989
 
2990
            }
2991
            return "dashboard1";
2992
        }
2993
 
2994
    }
37593 amit 2995
 
21615 kshitij.so 2996
}