Subversion Repositories SmartDukaan

Rev

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