Subversion Repositories SmartDukaan

Rev

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