Subversion Repositories SmartDukaan

Rev

Rev 36211 | Rev 36286 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25899 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
32978 amit.gupta 3
import com.mongodb.DBObject;
31677 amit.gupta 4
import com.spice.profitmandi.common.enumuration.ActivationType;
31249 tejbeer 5
import com.spice.profitmandi.common.enumuration.MessageType;
25899 tejbeer 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25952 tejbeer 7
import com.spice.profitmandi.common.model.CustomRetailer;
27117 tejbeer 8
import com.spice.profitmandi.common.model.ProfitMandiConstants;
31249 tejbeer 9
import com.spice.profitmandi.common.model.SendNotificationModel;
30433 tejbeer 10
import com.spice.profitmandi.common.util.FileUtil;
25899 tejbeer 11
import com.spice.profitmandi.common.web.util.ResponseSender;
12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30077 tejbeer 13
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionPlan;
30416 tejbeer 14
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
30077 tejbeer 15
import com.spice.profitmandi.dao.entity.auth.PartnerSecondaryPlan;
36267 ranu 16
import com.spice.profitmandi.dao.entity.cs.Activity;
32978 amit.gupta 17
import com.spice.profitmandi.dao.entity.cs.Position;
36267 ranu 18
import com.spice.profitmandi.dao.entity.cs.Ticket;
25899 tejbeer 19
import com.spice.profitmandi.dao.entity.dtr.User;
25952 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
34322 ranu 21
import com.spice.profitmandi.dao.entity.fofo.*;
32978 amit.gupta 22
import com.spice.profitmandi.dao.entity.user.*;
30416 tejbeer 23
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
32978 amit.gupta 24
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
25
import com.spice.profitmandi.dao.enumuration.dtr.*;
26
import com.spice.profitmandi.dao.model.*;
27
import com.spice.profitmandi.dao.repository.auth.*;
28
import com.spice.profitmandi.dao.repository.cs.*;
29
import com.spice.profitmandi.dao.repository.dtr.*;
30087 tejbeer 30
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
35075 aman 31
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
34301 ranu 32
import com.spice.profitmandi.dao.repository.fofo.RbmRatingRepository;
34322 ranu 33
import com.spice.profitmandi.dao.repository.fofo.SalesRatingRepository;
35632 ranu 34
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
30077 tejbeer 35
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
32978 amit.gupta 36
import com.spice.profitmandi.dao.repository.user.AddressRepository;
31249 tejbeer 37
import com.spice.profitmandi.service.AuthService;
38
import com.spice.profitmandi.service.NotificationService;
30348 tejbeer 39
import com.spice.profitmandi.service.PartnerCollectionService;
35725 ranu 40
import com.spice.profitmandi.service.integrations.kommuno.RecordingService;
25952 tejbeer 41
import com.spice.profitmandi.service.user.RetailerService;
28935 tejbeer 42
import com.spice.profitmandi.service.user.StoreTimelineTatService;
25952 tejbeer 43
import com.spice.profitmandi.web.req.CreateFranchiseeRequest;
34322 ranu 44
import com.spice.profitmandi.web.req.RbmSalesRatingRequest;
25952 tejbeer 45
import com.spice.profitmandi.web.res.Partner;
25899 tejbeer 46
import io.swagger.annotations.ApiImplicitParam;
47
import io.swagger.annotations.ApiImplicitParams;
32978 amit.gupta 48
import org.apache.commons.csv.CSVRecord;
49
import org.apache.commons.io.output.ByteArrayOutputStream;
50
import org.apache.logging.log4j.LogManager;
51
import org.apache.logging.log4j.Logger;
52
import org.springframework.beans.factory.annotation.Autowired;
53
import org.springframework.format.annotation.DateTimeFormat;
54
import org.springframework.http.HttpHeaders;
55
import org.springframework.http.HttpStatus;
56
import org.springframework.http.MediaType;
57
import org.springframework.http.ResponseEntity;
58
import org.springframework.mail.javamail.JavaMailSender;
59
import org.springframework.stereotype.Controller;
60
import org.springframework.transaction.annotation.Transactional;
61
import org.springframework.ui.Model;
62
import org.springframework.web.bind.annotation.*;
63
import org.springframework.web.multipart.MultipartFile;
25899 tejbeer 64
 
32978 amit.gupta 65
import javax.servlet.http.HttpServletRequest;
66
import java.io.IOException;
36114 ranu 67
import java.time.DayOfWeek;
32978 amit.gupta 68
import java.time.LocalDate;
69
import java.time.LocalDateTime;
34301 ranu 70
import java.time.YearMonth;
32978 amit.gupta 71
import java.time.format.DateTimeFormatter;
36114 ranu 72
import java.time.temporal.TemporalAdjusters;
32978 amit.gupta 73
import java.util.*;
35415 amit 74
import java.util.HashSet;
32978 amit.gupta 75
import java.util.Map.Entry;
76
import java.util.stream.Collectors;
77
 
25899 tejbeer 78
@Controller
79
@Transactional(rollbackFor = Throwable.class)
80
public class LeadController {
31677 amit.gupta 81
    private static final Logger LOGGER = LogManager.getLogger(LeadController.class);
82
    @Autowired
83
    private ResponseSender<?> responseSender;
25899 tejbeer 84
 
31677 amit.gupta 85
    @Autowired
86
    private AuthRepository authRepository;
25899 tejbeer 87
 
31677 amit.gupta 88
    @Autowired
89
    private LeadRepository leadRepository;
25899 tejbeer 90
 
31677 amit.gupta 91
    @Autowired
32923 ranu 92
    DocumentRepository documentRepository;
93
 
94
    @Autowired
95
    PositionRepository positionRepository;
96
 
97
    @Autowired
98
    private ActivityAttachmentRepository activityAttachmentRepository;
99
 
100
    @Autowired
31677 amit.gupta 101
    private CsService csService;
25952 tejbeer 102
 
31677 amit.gupta 103
    @Autowired
104
    private UserRepository userRepository;
25952 tejbeer 105
 
31677 amit.gupta 106
    @Autowired
32923 ranu 107
    private AddressRepository addressRepository;
108
 
109
    @Autowired
110
 
111
    private UserRoleRepository userRoleRepository;
112
 
113
    @Autowired
31677 amit.gupta 114
    private UserAccountRepository userAccountRepository;
25952 tejbeer 115
 
31677 amit.gupta 116
    @Autowired
117
    private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
25952 tejbeer 118
 
31677 amit.gupta 119
    @Autowired
120
    private RetailerService retailerService;
25952 tejbeer 121
 
31677 amit.gupta 122
    @Autowired
123
    private LeadActivityRepository leadActivityRepository;
25899 tejbeer 124
 
31677 amit.gupta 125
    @Autowired
126
    private FranchiseeVisitRepository franchiseeVisitRepository;
25952 tejbeer 127
 
31677 amit.gupta 128
    @Autowired
129
    private FranchiseeActivityRepository franchiseeActivityRepository;
25952 tejbeer 130
 
31677 amit.gupta 131
    @Autowired
132
    private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
28935 tejbeer 133
 
31677 amit.gupta 134
    @Autowired
135
    private FofoStoreRepository fofoStoreRepository;
28935 tejbeer 136
 
31677 amit.gupta 137
    @Autowired
138
    private StoreTimelineTatService storeTimelineTatService;
28935 tejbeer 139
 
31677 amit.gupta 140
    @Autowired
141
    private PartnerCollectionService partnerCollectionService;
30348 tejbeer 142
 
31677 amit.gupta 143
    @Autowired
144
    private TicketRepository ticketRepository;
30416 tejbeer 145
 
31677 amit.gupta 146
    @Autowired
36267 ranu 147
    private ActivityRepository activityRepository;
148
 
149
    @Autowired
31677 amit.gupta 150
    private TicketCategoryRepository ticketCategoryRepository;
30416 tejbeer 151
 
31677 amit.gupta 152
    @Autowired
153
    private TicketSubCategoryRepository ticketSubCategoryRepository;
30416 tejbeer 154
 
31677 amit.gupta 155
    @Autowired
156
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30416 tejbeer 157
 
31677 amit.gupta 158
    @Autowired
159
    private Mongo mongoClient;
30487 tejbeer 160
 
31677 amit.gupta 161
    @Autowired
162
    private OrderRepository orderRepository;
30487 tejbeer 163
 
31677 amit.gupta 164
    @Autowired
165
    private PartnerCollectionPlanRepository partnerCollectionPlanRepository;
30487 tejbeer 166
 
31677 amit.gupta 167
    @Autowired
168
    private PartnerSecondaryPlanRepository partnerSecondaryPlanRepository;
30487 tejbeer 169
 
31677 amit.gupta 170
    @Autowired
171
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
30487 tejbeer 172
 
31677 amit.gupta 173
    @Autowired
174
    private VisitRequestRepository visitRequestRepository;
31249 tejbeer 175
 
31677 amit.gupta 176
    @Autowired
177
    private AuthService authService;
31249 tejbeer 178
 
31677 amit.gupta 179
    @Autowired
180
    private NotificationService notificationService;
31249 tejbeer 181
 
32923 ranu 182
    @Autowired
183
    JavaMailSender mailSender;
184
 
185
    @Autowired
186
    private TicketAssignedRepository ticketAssignedRepository;
187
 
34124 tejus.loha 188
    @Autowired
189
    LeadDetailRepository leadDetailRepository;
190
 
35075 aman 191
    @Autowired
192
    PurchaseRepository purchaseRepository;
193
 
35632 ranu 194
    @Autowired
195
    private LoanRepository loanRepository;
196
 
35725 ranu 197
    @Autowired
198
    private RecordingService recordingService;
199
 
31677 amit.gupta 200
    @RequestMapping(value = "/lead", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
201
    @ApiImplicitParams({
202
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
34118 tejus.loha 203
 
204
    public ResponseEntity<?> LeadUser(@RequestBody CreateRefferalRequest createRefferalRequest) throws Exception {
35079 vikas 205
        LOGGER.info("CreateReferralRequest - " + createRefferalRequest);
34394 tejus.loha 206
        if (createRefferalRequest.getOutletName() == null || createRefferalRequest.getPotential() == 0) {
35079 vikas 207
            throw new Exception("Outlet should not be empty and potential should be greater > 0");
34386 ranu 208
        }
35288 amit 209
        Lead lead;
210
        AuthUser authUser = authRepository.selectByGmailId(createRefferalRequest.getReffereeEmail());
211
        if (createRefferalRequest.getId() > 0) {
212
            lead = leadRepository.selectById(createRefferalRequest.getId());
213
            lead.setAssignTo(authUser.getId());
31677 amit.gupta 214
        } else {
35288 amit 215
            lead = new Lead();
216
            lead.setFirstName(createRefferalRequest.getFirstName());
217
            lead.setLastName(createRefferalRequest.getLastName());
218
            lead.setLeadMobile(createRefferalRequest.getMobile());
219
            lead.setState(createRefferalRequest.getState());
220
            lead.setCity(createRefferalRequest.getCity());
221
            lead.setAddress(createRefferalRequest.getAddress());
222
            lead.setCreatedTimestamp(LocalDateTime.now());
223
            lead.setOutLetName(createRefferalRequest.getOutletName());
224
            lead.setUpdatedTimestamp(LocalDateTime.now());
225
            lead.setStatus(createRefferalRequest.getStatus());
226
            lead.setSource(createRefferalRequest.getSource());
227
            lead.setNotinterestedReason(createRefferalRequest.getReason());
228
            lead.setPotential(createRefferalRequest.getPotential());
229
            if (createRefferalRequest.getColorCheck() == true) {
230
                lead.setColor("Green");
231
            } else {
232
                lead.setColor("Yellow");
233
            }
234
            String authUserName = authUser.getFullName();
235
            lead.setAuthId(authUser.getId());
236
            lead.setAssignTo(authUser.getId());
35079 vikas 237
            lead.setCreatedBy(authUserName);
238
            leadRepository.persist(lead);
35288 amit 239
 
35079 vikas 240
        }
34118 tejus.loha 241
 
31677 amit.gupta 242
        LeadActivity leadActivity = new LeadActivity();
243
        leadActivity.setLeadId(lead.getId());
35288 amit 244
        leadActivity.setRemark((createRefferalRequest.getId() > 0 ? "Self Assigned." : "") + createRefferalRequest.getRemark());
31677 amit.gupta 245
        leadActivity.setAuthId(authUser.getId());
31249 tejbeer 246
 
31677 amit.gupta 247
        if (createRefferalRequest.getStatus().equals(LeadStatus.followUp)) {
248
            leadActivity.setSchelduleTimestamp(createRefferalRequest.getSchelduleTimestamp());
249
            leadActivity.setCommunicationType(createRefferalRequest.getCommunicationType());
31249 tejbeer 250
 
31677 amit.gupta 251
            if (leadActivity.getCommunicationType().equals(CommunicationType.VISIT)) {
31249 tejbeer 252
 
31677 amit.gupta 253
                visitRequestRepository.createVisitRequest(lead.getId(), "lead", lead.getAssignTo(),
254
                        createRefferalRequest.getSchelduleTimestamp());
255
            }
256
            //
257
            leadActivity.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
258
            lead.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
259
        } else {
260
            leadActivity.setSchelduleTimestamp(null);
261
            leadActivity.setClosureTimestamp(null);
262
            lead.setClosureTimestamp(null);
263
        }
264
        leadActivity.setCreatedTimestamp(LocalDateTime.now());
265
        leadActivityRepository.persist(leadActivity);
25899 tejbeer 266
 
31677 amit.gupta 267
        return responseSender.ok(true);
268
    }
25899 tejbeer 269
 
31677 amit.gupta 270
    @RequestMapping(value = "/lead-description", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
271
    @ApiImplicitParams({
272
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 273
    public ResponseEntity<?> leadDescription(HttpServletRequest request, @RequestParam(name = "gmailId") String
274
                                                     gmailId,
31677 amit.gupta 275
                                             @RequestParam(name = "status") LeadStatus status) throws ProfitMandiBusinessException {
276
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
277
        List<Lead> leads = null;
278
        LOGGER.info("emails" + status);
31249 tejbeer 279
 
35469 vikas 280
        List<VisitRequest> visitRequests = visitRequestRepository.selectByAuthIdAndDate(authUser.getId(),
281
                LocalDate.now());
282
        Map<Integer, List<VisitRequest>> visitRequestMap = null;
283
        if (!visitRequests.isEmpty()) {
284
            visitRequestMap = visitRequests.stream().collect(Collectors.groupingBy(x -> x.getVisitId()));
285
        }
31677 amit.gupta 286
        if (status.equals(LeadStatus.followUp)) {
35469 vikas 287
 
31677 amit.gupta 288
            leads = leadRepository.selectLeadsScheduledBetweenDate(Arrays.asList(authUser.getId()), null, null);
31249 tejbeer 289
 
35469 vikas 290
            if (visitRequestMap != null) {
31677 amit.gupta 291
                for (Lead lead : leads) {
292
                    List<VisitRequest> visitRequest = visitRequestMap.get(lead.getId());
35469 vikas 293
 
31677 amit.gupta 294
                    if (visitRequest != null) {
295
                        if (visitRequest.size() > 1) {
35469 vikas 296
 
297
                            Comparator<VisitRequest> visitComparato = Comparator
298
                                    .comparing(VisitRequest::getCreatedTimestamp);
299
 
300
                            VisitRequest youngestVisit = visitRequest.stream().max(visitComparato).get();
31677 amit.gupta 301
                            lead.setVisitStatus(youngestVisit.getStatus());
35469 vikas 302
 
31677 amit.gupta 303
                        } else {
304
                            lead.setVisitStatus(visitRequest.get(0).getStatus());
35469 vikas 305
 
31677 amit.gupta 306
                        }
307
                    }
35469 vikas 308
 
31677 amit.gupta 309
                }
310
            }
31249 tejbeer 311
 
31677 amit.gupta 312
            leads = leads.stream()
35079 vikas 313
                    .sorted(Comparator.comparing(Lead::getScheduledTimestamp, Comparator.nullsFirst(Comparator.reverseOrder())))
314
                    .collect(Collectors.toList());
35469 vikas 315
            /*
316
             * Collections.sort(leads, (o1, o2) -> { if (o1.getScheduledTimestamp() != null
317
             * && o2.getScheduledTimestamp() != null) { return
318
             * o1.getScheduledTimestamp().isBefore(o2.getScheduledTimestamp()) ? -1 : 1; }
319
             * else if (o1.getScheduledTimestamp() != null) { return 1; } else { return -1;
320
             * } });
321
             */
322
 
31677 amit.gupta 323
        } else {
324
            leads = leadRepository.selectByAssignAuthIdAndStatus(authUser.getId(), status);
35469 vikas 325
 
31677 amit.gupta 326
        }
25979 tejbeer 327
 
31677 amit.gupta 328
        return responseSender.ok(leads);
35469 vikas 329
 
31677 amit.gupta 330
    }
25899 tejbeer 331
 
31677 amit.gupta 332
    @RequestMapping(value = "/getlead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 333
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
334
    public ResponseEntity<?> getLead(HttpServletRequest request, @RequestParam(name = "id") int id) throws
335
            ProfitMandiBusinessException {
25899 tejbeer 336
 
31677 amit.gupta 337
        List<LeadActivity> leadActivities = leadActivityRepository.selectBYLeadId(id);
338
        Lead lead = leadRepository.selectById(id);
339
        lead.setLeadActivities(leadActivities);
340
        return responseSender.ok(lead);
25899 tejbeer 341
 
31677 amit.gupta 342
    }
25899 tejbeer 343
 
35079 vikas 344
    @RequestMapping(value = "/check-existing-lead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 345
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
346
    public ResponseEntity<?> getLeadByMobile(HttpServletRequest request, @RequestParam(name = "mobile") String
347
            mobile) throws ProfitMandiBusinessException {
35079 vikas 348
        int userId = (int) request.getAttribute("userId");
349
        LOGGER.info("userId: " + userId);
350
        Lead lead = leadRepository.selectByMobileNumber(mobile);
351
        return responseSender.ok(lead);
352
 
353
    }
354
 
31677 amit.gupta 355
    @RequestMapping(value = "/leadUpdate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 356
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 357
    public ResponseEntity<?> leadUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
35288 amit 358
                                        @RequestParam(name = "status") LeadStatus status, @RequestParam(name = "colorCheck") Boolean colorCheck,
359
                                        @RequestParam(name = "remark") String remark, @RequestParam(name = "reason") String reason,
360
                                        @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp,
361
                                        @RequestParam(name = "closureTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime closureTimestamp,
362
                                        @RequestParam(name = "communicationType") CommunicationType communicationType) throws
363
            ProfitMandiBusinessException {
25899 tejbeer 364
 
31677 amit.gupta 365
        Lead lead = leadRepository.selectById(id);
25899 tejbeer 366
 
31677 amit.gupta 367
        LeadActivity leadActivity = new LeadActivity();
368
        lead.setStatus(status);
369
        lead.setNotinterestedReason(reason);
370
        leadActivity.setRemark(remark);
371
        leadActivity.setLeadId(id);
34394 tejus.loha 372
        leadActivity.setOutletName(lead.getOutLetName());
373
        leadActivity.setPotential(lead.getPotential());
31677 amit.gupta 374
        leadActivity.setCreatedTimestamp(LocalDateTime.now());
375
        leadActivity.setSchelduleTimestamp(null);
376
        leadActivity.setClosureTimestamp(null);
377
        leadActivity.setAuthId(lead.getAssignTo());
378
        lead.setUpdatedTimestamp(LocalDateTime.now());
379
        if (colorCheck == true) {
380
            lead.setColor("Green");
381
        } else {
382
            lead.setColor("Yellow");
383
        }
384
        if (status == LeadStatus.followUp) {
25899 tejbeer 385
 
31677 amit.gupta 386
            if (schelduleTimestamp != null) {
31249 tejbeer 387
 
31677 amit.gupta 388
                leadActivity.setCommunicationType(communicationType);
31249 tejbeer 389
 
31677 amit.gupta 390
                if (leadActivity.getCommunicationType().equals(CommunicationType.VISIT)) {
31249 tejbeer 391
 
35079 vikas 392
                    visitRequestRepository.createVisitRequest(lead.getId(), "lead", lead.getAssignTo(), schelduleTimestamp);
31677 amit.gupta 393
                }
31249 tejbeer 394
 
31677 amit.gupta 395
            }
396
            leadActivity.setSchelduleTimestamp(schelduleTimestamp);
397
            leadActivity.setClosureTimestamp(closureTimestamp);
398
            lead.setClosureTimestamp(closureTimestamp);
26250 tejbeer 399
 
31677 amit.gupta 400
        } else {
26250 tejbeer 401
 
31677 amit.gupta 402
            leadActivity.setSchelduleTimestamp(null);
403
            leadActivity.setClosureTimestamp(null);
404
            lead.setClosureTimestamp(null);
26244 tejbeer 405
 
31677 amit.gupta 406
        }
407
        leadActivityRepository.persist(leadActivity);
408
        return responseSender.ok(true);
25899 tejbeer 409
 
31677 amit.gupta 410
    }
25952 tejbeer 411
 
31677 amit.gupta 412
    @RequestMapping(value = ProfitMandiConstants.URL_NEW_LEAD, method = RequestMethod.POST)
35288 amit 413
    public ResponseEntity<?> newLead(HttpServletRequest request, @RequestBody CreateRefferalRequest
414
            createRefferalRequest) throws ProfitMandiBusinessException {
31677 amit.gupta 415
        LOGGER.info("requested url : " + request.getRequestURL().toString());
416
        Lead lead = new Lead();
417
        lead.setAddress(createRefferalRequest.getCity());
418
        Long.parseLong(createRefferalRequest.getMobile());
419
        if (createRefferalRequest.getMobile().length() != 10) {
35079 vikas 420
            throw new ProfitMandiBusinessException("Mobile Number", createRefferalRequest.getMobile(), "Number should be of 10 digits");
31677 amit.gupta 421
        }
422
        lead.setLeadMobile(createRefferalRequest.getMobile());
423
        lead.setCity(createRefferalRequest.getCity());
424
        lead.setState(createRefferalRequest.getState());
425
        lead.setLastName(createRefferalRequest.getLastName());
426
        if (lead.getState().equals("Uttar Pradesh")) {
427
            lead.setAssignTo(53);
428
        } else if (lead.getState().equals("Haryana")) {
429
            lead.setAssignTo(53);
430
        } else if (lead.getState().equals("Delhi")) {
431
            lead.setAssignTo(53);
432
        } else {
433
            // Assign to sm
434
            lead.setAssignTo(53);
435
            // Assign to neha
436
            // lead.setAssignTo(1);
437
        }
438
        lead.setAuthId(lead.getAssignTo());
439
        lead.setCreatedBy("daily-sync");
440
        lead.setSource("SD-WEB");
441
        lead.setFirstName(createRefferalRequest.getFirstName());
442
        lead.setStatus(LeadStatus.followUp);
443
        lead.setColor("yellow");
444
        lead.setCreatedTimestamp(LocalDateTime.now());
445
        lead.setUpdatedTimestamp(LocalDateTime.now());
446
        leadRepository.persist(lead);
27117 tejbeer 447
 
31677 amit.gupta 448
        return responseSender.ok(true);
27117 tejbeer 449
 
31677 amit.gupta 450
    }
27117 tejbeer 451
 
31677 amit.gupta 452
    @RequestMapping(value = "/getPartnersList", method = RequestMethod.GET)
35079 vikas 453
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 454
    public ResponseEntity<?> getPartners(HttpServletRequest request, @RequestParam(name = "gmailId") String gmailId)
455
            throws ProfitMandiBusinessException {
25952 tejbeer 456
 
31677 amit.gupta 457
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35630 aman 458
        if (authUser == null) {
459
            LOGGER.warn("No auth user found for gmailId: {}", gmailId);
460
            return responseSender.badRequest("No user found for the provided email");
461
        }
25952 tejbeer 462
 
31677 amit.gupta 463
        Map<String, Set<String>> storeGuyMap = csService.getAuthUserPartnerEmailMapping();
25952 tejbeer 464
 
31677 amit.gupta 465
        Set<String> emails = storeGuyMap.get(authUser.getEmailId());
35630 aman 466
        LOGGER.info("emails: {}", emails);
467
        if (emails == null || emails.isEmpty()) {
468
            LOGGER.info("No partner emails found for user: {}", gmailId);
469
            return responseSender.ok(new ArrayList<>());
470
        }
31677 amit.gupta 471
        List<User> users = userRepository.selectAllByEmailIds(new ArrayList<>(emails));
472
        List<Partner> partners = new ArrayList<>();
473
        for (User user : users) {
35630 aman 474
            try {
475
                UserAccount uc = userAccountRepository.selectSaholicByUserId(user.getId());
476
                if (uc == null) {
477
                    LOGGER.warn("No user account found for userId: {}", user.getId());
478
                    continue;
479
                }
480
                com.spice.profitmandi.dao.entity.user.User userInfo = userUserRepository.selectById(uc.getAccountKey());
481
                if (userInfo == null) {
482
                    LOGGER.warn("No user info found for accountKey: {}", uc.getAccountKey());
483
                    continue;
484
                }
485
                CustomRetailer customRetailer = retailerService.getFofoRetailer(userInfo.getId());
486
                if (customRetailer == null) {
487
                    LOGGER.warn("No custom retailer found for userInfoId: {}", userInfo.getId());
488
                    continue;
489
                }
25952 tejbeer 490
 
35630 aman 491
                Partner partner = new Partner();
492
                partner.setBusinessName(customRetailer.getBusinessName());
493
                partner.setPartnerId(customRetailer.getPartnerId());
494
                partner.setCartId(customRetailer.getCartId());
495
                partner.setEmail(customRetailer.getEmail());
496
                partner.setGstNumber(customRetailer.getGstNumber());
497
                partner.setDisplayName(customRetailer.getDisplayName());
498
                partner.setCity(customRetailer.getAddress() != null ? customRetailer.getAddress().getCity() : null);
499
                partner.setUserId(user.getId());
500
                partners.add(partner);
501
            } catch (Exception e) {
502
                LOGGER.error("Error processing partner for userId: {}", user.getId(), e);
503
            }
31677 amit.gupta 504
        }
35630 aman 505
        LOGGER.info("partners: {}", partners);
31677 amit.gupta 506
        return responseSender.ok(partners);
507
    }
25952 tejbeer 508
 
31677 amit.gupta 509
    @RequestMapping(value = "/franchise-first-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 510
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 511
    public ResponseEntity<?> FranchiseFirstVisit(HttpServletRequest request, @RequestBody CreateFranchiseeRequest
512
            createFranchiseeRequest) throws Exception {
25952 tejbeer 513
 
31677 amit.gupta 514
        FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
515
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
516
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
25952 tejbeer 517
 
31677 amit.gupta 518
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
519
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
520
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
521
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
522
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
523
        franchiseeVisit.setScheduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
524
        // change
525
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 526
 
31677 amit.gupta 527
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
528
        franchiseeVisit.setCreatedBy(authUserName);
529
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 530
 
31677 amit.gupta 531
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 532
 
31677 amit.gupta 533
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
534
        franchiseeActivity.setAction(FranchiseeActivityStatus.FOLLOWUP);
535
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
536
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
537
        franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 538
 
31677 amit.gupta 539
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
540
        franchiseeActivityRepository.persist(franchiseeActivity);
31249 tejbeer 541
 
31677 amit.gupta 542
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
31249 tejbeer 543
 
35079 vikas 544
        visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit", authUser.getId(), createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 545
 
31677 amit.gupta 546
        return responseSender.ok(true);
547
    }
25952 tejbeer 548
 
31677 amit.gupta 549
    @RequestMapping(value = "/franchise-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 550
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 551
    public ResponseEntity<?> FranchiseVisit(HttpServletRequest request,
552
                                            @RequestBody CreateFranchiseeRequest createFranchiseeRequest) throws Exception {
25952 tejbeer 553
 
34394 tejus.loha 554
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, createFranchiseeRequest.getFofoId());
34276 ranu 555
 
31677 amit.gupta 556
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(createFranchiseeRequest.getId());
557
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
558
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
34394 tejus.loha 559
        LOGGER.info("rbmL1 {}", rbmL1);
31677 amit.gupta 560
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
561
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
562
        franchiseeVisit.setPartnerRemark(createFranchiseeRequest.getPartnerRemark());
563
        franchiseeVisit.setOutsideVisibity(createFranchiseeRequest.getOutsideVisibity());
564
        franchiseeVisit.setInstoreVisibility(createFranchiseeRequest.getInstoreVisibility());
565
        franchiseeVisit.setOutsideStock(createFranchiseeRequest.getOutsideStock());
566
        franchiseeVisit.setSystemKnowledge(createFranchiseeRequest.getSystemKnowledge());
567
        franchiseeVisit.setWorkingDevice(createFranchiseeRequest.getWorkingDevice());
568
        franchiseeVisit.setWorkingPrinter(createFranchiseeRequest.getWorkingPrinter());
569
        franchiseeVisit.setCarryBags(createFranchiseeRequest.getCarryBags());
570
        franchiseeVisit.setSmartdukaanTshirt(createFranchiseeRequest.getSmartdukaanTshirt());
571
        franchiseeVisit.setLatestDummies(createFranchiseeRequest.getLatestDummies());
572
        franchiseeVisit.setInvestment(createFranchiseeRequest.getInvestment());
573
        franchiseeVisit.setMtd(createFranchiseeRequest.getMtd());
574
        franchiseeVisit.setHygiene(createFranchiseeRequest.getHygiene());
575
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
576
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
577
        franchiseeVisit.setInformedAboutOnline(createFranchiseeRequest.getOnline());
578
        franchiseeVisit.setPendingBilling(createFranchiseeRequest.getPendingBilling());
34276 ranu 579
        franchiseeVisit.setRbmId(rbmL1);
580
        franchiseeVisit.setRbmRating(createFranchiseeRequest.getRbmRating());
31677 amit.gupta 581
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
582
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
583
        } else {
584
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
585
        }
25952 tejbeer 586
 
31677 amit.gupta 587
        // AuthUser authUser =
588
        // authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
589
        // change
590
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 591
 
31677 amit.gupta 592
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
593
        franchiseeVisit.setCreatedBy(authUserName);
594
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 595
 
31677 amit.gupta 596
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 597
 
31677 amit.gupta 598
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
599
        franchiseeActivity.setAction(createFranchiseeRequest.getAction());
600
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
601
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
602
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
603
            franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getSchelduleTimestamp());
31249 tejbeer 604
 
31677 amit.gupta 605
            visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
606
                    franchiseeVisit.getAuthId(), createFranchiseeRequest.getSchelduleTimestamp());
607
        } else {
608
            franchiseeActivity.setSchelduleTimestamp(null);
609
        }
610
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
611
        franchiseeActivityRepository.persist(franchiseeActivity);
25952 tejbeer 612
 
31677 amit.gupta 613
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
34276 ranu 614
 
34394 tejus.loha 615
        if (!createFranchiseeRequest.getOutsideVisibityReason().isEmpty()) {
34288 ranu 616
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_EXTERNAL_VISIBILITY, createFranchiseeRequest.getOutsideVisibityReason(), authUser.getId());
34276 ranu 617
        }
618
 
34394 tejus.loha 619
        if (!createFranchiseeRequest.getInstoreVisibilityReason().isEmpty()) {
34288 ranu 620
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_INTERNAL_VISIBILITY, createFranchiseeRequest.getInstoreVisibilityReason(), authUser.getId());
34276 ranu 621
        }
622
 
34394 tejus.loha 623
        if (!createFranchiseeRequest.getOutsideStockReason().isEmpty()) {
34288 ranu 624
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_OUTSIDE_STOCK, createFranchiseeRequest.getOutsideStockReason(), authUser.getId());
34276 ranu 625
        }
626
 
34394 tejus.loha 627
        if (!createFranchiseeRequest.getSystemKnowledgeReason().isEmpty()) {
34288 ranu 628
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_TRAINING, ProfitMandiConstants.TICKET_CATEGORY_TRAINING_NEED, createFranchiseeRequest.getSystemKnowledgeReason(), authUser.getId());
34276 ranu 629
        }
630
 
34394 tejus.loha 631
        if (!createFranchiseeRequest.getLatestDummiesReason().isEmpty()) {
34288 ranu 632
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_MARKETING_DUMMIES, createFranchiseeRequest.getLatestDummiesReason(), authUser.getId());
34276 ranu 633
        }
634
 
34394 tejus.loha 635
        if (!createFranchiseeRequest.getInvestmentReason().isEmpty()) {
34288 ranu 636
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_INVESTMENT, createFranchiseeRequest.getInvestmentReason(), authUser.getId());
34276 ranu 637
        }
638
 
34394 tejus.loha 639
        if (!createFranchiseeRequest.getHygieneReason().isEmpty()) {
34288 ranu 640
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_DATA_ACCURACY, createFranchiseeRequest.getHygieneReason(), authUser.getId());
641
        }
34276 ranu 642
 
31677 amit.gupta 643
        return responseSender.ok(true);
34276 ranu 644
 
31677 amit.gupta 645
    }
25952 tejbeer 646
 
31677 amit.gupta 647
    @RequestMapping(value = "/getFranchiseVisit", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 648
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 649
    public ResponseEntity<?> getFranchiseVisit(HttpServletRequest request,
35288 amit 650
                                               @RequestParam(name = "gmailId") String gmailId, @RequestParam(name = "status") FranchiseeVisitStatus
651
                                                       status,
31677 amit.gupta 652
                                               @RequestParam(name = "offset", defaultValue = "0") int offset,
653
                                               @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
654
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35079 vikas 655
        List<VisitRequest> visitRequests = visitRequestRepository.selectByAuthIdAndDate(authUser.getId(), LocalDate.now());
31677 amit.gupta 656
        Map<Integer, List<VisitRequest>> visitRequestMap = null;
657
        if (!visitRequests.isEmpty()) {
658
            visitRequestMap = visitRequests.stream().collect(Collectors.groupingBy(x -> x.getVisitId()));
659
        }
35079 vikas 660
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectByAuthIdAndStatus(authUser.getId(), status, offset, limit);
25952 tejbeer 661
 
35415 amit 662
        // Batch fetch all FranchiseeActivity in one query instead of N+1
663
        List<Integer> activityIds = franchiseeVisits.stream()
664
                .filter(fv -> fv.getFranchiseActivityId() != 0)
665
                .map(FranchiseeVisit::getFranchiseActivityId)
666
                .collect(Collectors.toList());
667
        Map<Integer, FranchiseeActivity> activityMap = new HashMap<>();
668
        if (!activityIds.isEmpty()) {
669
            activityMap = franchiseeActivityRepository.selectByIds(activityIds).stream()
670
                    .collect(Collectors.toMap(FranchiseeActivity::getId, x -> x));
671
        }
672
 
31677 amit.gupta 673
        for (FranchiseeVisit fv : franchiseeVisits) {
674
            if (visitRequestMap != null) {
31249 tejbeer 675
 
31677 amit.gupta 676
                List<VisitRequest> visitRequest = visitRequestMap.get(fv.getId());
677
                if (visitRequest != null) {
678
                    if (visitRequest.size() > 1) {
31249 tejbeer 679
 
35079 vikas 680
                        Comparator<VisitRequest> visitComparato = Comparator.comparing(VisitRequest::getCreatedTimestamp);
31249 tejbeer 681
 
31677 amit.gupta 682
                        VisitRequest youngestVisit = visitRequest.stream().max(visitComparato).get();
683
                        fv.setVisitStatus(youngestVisit.getStatus());
31249 tejbeer 684
 
31677 amit.gupta 685
                    } else {
686
                        fv.setVisitStatus(visitRequest.get(0).getStatus());
31249 tejbeer 687
 
31677 amit.gupta 688
                    }
689
                }
690
            }
691
            if (fv.getFranchiseActivityId() != 0) {
35415 amit 692
                FranchiseeActivity fA = activityMap.get(fv.getFranchiseActivityId());
31677 amit.gupta 693
                fv.setFranchiseeActivity(fA);
694
            }
31249 tejbeer 695
 
31677 amit.gupta 696
        }
25952 tejbeer 697
 
31677 amit.gupta 698
        return responseSender.ok(franchiseeVisits);
25952 tejbeer 699
 
31677 amit.gupta 700
    }
25952 tejbeer 701
 
31677 amit.gupta 702
    @RequestMapping(value = "/getFranchiseActivity", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 703
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 704
    public ResponseEntity<?> getFranchiseActivity(HttpServletRequest request, @RequestParam(name = "id") int id) throws
705
            ProfitMandiBusinessException {
25952 tejbeer 706
 
31677 amit.gupta 707
        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityRepository.selectByFranchiseeVisitId(id);
708
        return responseSender.ok(franchiseeActivities);
25952 tejbeer 709
 
31677 amit.gupta 710
    }
25952 tejbeer 711
 
31677 amit.gupta 712
    @RequestMapping(value = "/getFranchiseeInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 713
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 714
    public ResponseEntity<?> getFranchiseeInfo(HttpServletRequest request, @RequestParam(name = "id") int id) throws
715
            ProfitMandiBusinessException {
31677 amit.gupta 716
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
25952 tejbeer 717
 
31677 amit.gupta 718
        List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
30487 tejbeer 719
 
31677 amit.gupta 720
        List<String> brands = mobileBrands.stream().filter(x -> (boolean) x.get("active"))
721
                .map(x -> (String) x.get("name")).collect(Collectors.toList());
30487 tejbeer 722
 
31677 amit.gupta 723
        franchiseeVisit.setBrands(brands);
30487 tejbeer 724
 
31677 amit.gupta 725
        return responseSender.ok(franchiseeVisit);
25952 tejbeer 726
 
31677 amit.gupta 727
    }
25952 tejbeer 728
 
31677 amit.gupta 729
    @RequestMapping(value = "/franchise-visit-update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 730
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 731
    public ResponseEntity<?> franchiseVisitUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
732
                                                  @RequestParam(name = "action") FranchiseeActivityStatus action,
733
                                                  @RequestParam(name = "resolution") String resolution,
734
                                                  @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp)
31677 amit.gupta 735
            throws ProfitMandiBusinessException {
736
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
25952 tejbeer 737
 
31677 amit.gupta 738
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
25952 tejbeer 739
 
31677 amit.gupta 740
        if (action == FranchiseeActivityStatus.FOLLOWUP) {
30487 tejbeer 741
 
31677 amit.gupta 742
            if (schelduleTimestamp != null) {
31249 tejbeer 743
 
31677 amit.gupta 744
                visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
745
                        franchiseeVisit.getAuthId(), schelduleTimestamp);
746
            }
31249 tejbeer 747
 
31677 amit.gupta 748
            franchiseeActivity.setSchelduleTimestamp(schelduleTimestamp);
749
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
750
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
751
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 752
 
31677 amit.gupta 753
        } else {
30487 tejbeer 754
 
31677 amit.gupta 755
            franchiseeActivity.setSchelduleTimestamp(null);
756
            franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
757
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
758
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
759
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 760
 
31677 amit.gupta 761
        }
25952 tejbeer 762
 
31677 amit.gupta 763
        franchiseeActivity.setResolution(resolution);
764
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
765
        franchiseeActivity.setAction(action);
30487 tejbeer 766
 
31677 amit.gupta 767
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
768
        franchiseeActivityRepository.persist(franchiseeActivity);
30487 tejbeer 769
 
31677 amit.gupta 770
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
771
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
772
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
773
        franchiseeVisitRepository.persist(franchiseeVisit);
30487 tejbeer 774
 
31677 amit.gupta 775
        return responseSender.ok(true);
25952 tejbeer 776
 
31677 amit.gupta 777
    }
28935 tejbeer 778
 
31677 amit.gupta 779
    @RequestMapping(value = "/onBoardingTimelineStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 780
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 781
    public ResponseEntity<?> onBoardingTimelineStatus(HttpServletRequest request, Model model)
782
            throws ProfitMandiBusinessException {
35075 aman 783
        //This userId is of dtr.users
31677 amit.gupta 784
        int userId = (int) request.getAttribute("userId");
35075 aman 785
 
786
        //UserCart contains userId/retailerId in context of user.user as
787
        //uc contains retailerId and cartId of the retailerId that belongs to user schema
31677 amit.gupta 788
        UserCart uc = userAccountRepository.getUserCart(userId);
789
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
790
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
791
        Map<StoreTimeline, OnBoardingTimelineModel> timelineStatus = null;
792
        LOGGER.info("partnerOnBoardingPanel" + partnerOnBoardingPanel);
793
        if (partnerOnBoardingPanel != null) {
28935 tejbeer 794
 
31677 amit.gupta 795
            timelineStatus = storeTimelineTatService.getTimeline(partnerOnBoardingPanel.getId());
796
        }
797
        List<OnBoardingTimelineModel> onBoardingModel = new ArrayList<>();
798
        if (timelineStatus != null) {
799
            onBoardingModel = timelineStatus.values().stream().skip(2).map(x -> x).collect(Collectors.toList());
800
        }
801
        return responseSender.ok(onBoardingModel);
28935 tejbeer 802
 
31677 amit.gupta 803
    }
35288 amit 804
 
35075 aman 805
    @RequestMapping(value = "/purchaseExist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
806
    @ApiImplicitParams({
807
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35415 amit 808
    public ResponseEntity<?> purchaseExist(HttpServletRequest request) throws ProfitMandiBusinessException {
35075 aman 809
        int userId = (int) request.getAttribute("userId");
810
        UserCart uc = userAccountRepository.getUserCart(userId);
35415 amit 811
        return responseSender.ok(purchaseRepository.hasPurchaseForFofoId(uc.getUserId()));
35075 aman 812
    }
35288 amit 813
 
31677 amit.gupta 814
    @RequestMapping(value = "/onBoardingTimelineVisibility", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 815
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 816
    public ResponseEntity<?> onBoardingTimelineVisibility(HttpServletRequest request, Model model)
817
            throws ProfitMandiBusinessException {
818
        int userId = (int) request.getAttribute("userId");
819
        UserCart uc = userAccountRepository.getUserCart(userId);
28982 tejbeer 820
 
31677 amit.gupta 821
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
822
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
823
        boolean status = true;
824
        if (partnerOnBoardingPanel != null) {
28982 tejbeer 825
 
31677 amit.gupta 826
            status = storeTimelineTatService.getTimelineCompleted(partnerOnBoardingPanel.getId());
827
        }
28982 tejbeer 828
 
31677 amit.gupta 829
        LOGGER.info("status" + status);
28983 tejbeer 830
 
31677 amit.gupta 831
        return responseSender.ok(status);
28982 tejbeer 832
 
31677 amit.gupta 833
    }
30077 tejbeer 834
 
31677 amit.gupta 835
    @RequestMapping(value = "/getPartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 836
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 837
    public ResponseEntity<?> getPartnerTarget(HttpServletRequest request, @RequestParam String
838
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
839
            ProfitMandiBusinessException {
30077 tejbeer 840
 
35632 ranu 841
        long startTime = System.currentTimeMillis();
842
        long lapTime = startTime;
843
 
31677 amit.gupta 844
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35632 ranu 845
 
35649 ranu 846
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
847
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
31677 amit.gupta 848
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
30078 tejbeer 849
 
35649 ranu 850
 
31677 amit.gupta 851
        float totalPartnerTargetSecondary = 0;
852
        float totalPartnerTargetCollection = 0;
853
        float totalPartnerAchievementSecondary = 0;
854
        float totalPartnerAchievementCollection = 0;
855
        TargetModel tm = new TargetModel();
856
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
35632 ranu 857
        Map<Integer, Long> partnerTicketCount = new HashMap<>(); // Will be populated after we have fofoIdList
30416 tejbeer 858
 
31677 amit.gupta 859
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
30077 tejbeer 860
 
31677 amit.gupta 861
        if (fofoIds != null && fofoIds.size() > 0) {
32737 amit.gupta 862
            LOGGER.info("fofoIds {}", fofoIds);
31727 amit.gupta 863
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
31677 amit.gupta 864
                    .filter(x -> (!x.isInternal() && (activationType == null || x.getActivationType().equals(activationType))))
865
                    .map(x -> x.getId()).collect(Collectors.toList());
35632 ranu 866
            LOGGER.info("PERF: selectByRetailerIds took {} ms", System.currentTimeMillis() - lapTime);
867
            lapTime = System.currentTimeMillis();
868
            LOGGER.info("fofoIdList size: {}", fofoIdList.size());
869
 
870
            // Optimized: fetch ticket counts only for specific fofoIds instead of all retailers
871
            if (!fofoIdList.isEmpty()) {
872
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
873
            }
874
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
875
            lapTime = System.currentTimeMillis();
31677 amit.gupta 876
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
30077 tejbeer 877
 
31677 amit.gupta 878
            if (dayValue.equals("previous")) {
879
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
30138 tejbeer 880
 
31677 amit.gupta 881
            }
30087 tejbeer 882
 
31686 amit.gupta 883
            if (fofoIdList.size() > 0) {
30453 tejbeer 884
 
35632 ranu 885
                // Fetch fofoIds with overdue loans (pending amount > 0 and created > 15 days ago)
886
                // Optimized: returns only fofoIds, not full Loan objects
887
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
888
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
889
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
890
                lapTime = System.currentTimeMillis();
891
 
892
                // Fetch fofoIds with MTD billing above threshold (20000)
893
                // Optimized: direct query on orders table instead of complex RBM query
894
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
895
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
35650 ranu 896
                long billingThreshold = 1000L; // Same as RbmWeeklyBillingModel.BILLING_THRESHOLD
35632 ranu 897
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
898
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
899
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
900
                lapTime = System.currentTimeMillis();
901
 
35079 vikas 902
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
35632 ranu 903
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
904
                lapTime = System.currentTimeMillis();
30087 tejbeer 905
 
31686 amit.gupta 906
                if (!partnerDailyInvestments.isEmpty()) {
35079 vikas 907
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31686 amit.gupta 908
                }
30077 tejbeer 909
 
35632 ranu 910
                // Optimized: fetch only specific fofoIds instead of all retailers
911
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
912
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
913
                lapTime = System.currentTimeMillis();
30426 tejbeer 914
 
31686 amit.gupta 915
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
35632 ranu 916
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
917
                lapTime = System.currentTimeMillis();
30453 tejbeer 918
 
31686 amit.gupta 919
                long todayCollectionCount = 0;
920
                if (!remarkIds.isEmpty()) {
921
                    todayCollectionCount = partnerCollectionRemarkRepository
922
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
923
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
924
                            .collect(Collectors.counting());
30453 tejbeer 925
 
31686 amit.gupta 926
                }
35632 ranu 927
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
928
                lapTime = System.currentTimeMillis();
30330 tejbeer 929
 
35079 vikas 930
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
35632 ranu 931
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
932
                lapTime = System.currentTimeMillis();
30077 tejbeer 933
 
32978 amit.gupta 934
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
31686 amit.gupta 935
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
936
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
35632 ranu 937
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
938
                lapTime = System.currentTimeMillis();
30077 tejbeer 939
 
35415 amit 940
                // Pre-fetch all AuthUsers that might be needed (instead of N+1 queries)
941
                Set<Integer> allAuthIds = new HashSet<>();
942
                collectionMap.values().stream()
943
                        .map(PartnerCollectionPlanModel::getAuthId)
944
                        .filter(id -> id != null && id != authUser.getId())
945
                        .forEach(allAuthIds::add);
946
                partnerSecondaryPlans.values().stream()
947
                        .flatMap(List::stream)
948
                        .map(PartnerSecondaryPlanModel::getAuthId)
949
                        .filter(id -> id != null && id != authUser.getId())
950
                        .forEach(allAuthIds::add);
951
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
952
                if (!allAuthIds.isEmpty()) {
953
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
954
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
955
                }
956
 
35968 ranu 957
                // Fetch BM/ASM/RBM for all partners
958
                Map<Integer, Map<String, Integer>> bmAsmRbmMap = csService.getBmAsmRbmAuthUserIdsByFofoIds(new HashSet<>(fofoIdList));
959
                LOGGER.info("PERF: getBmAsmRbmAuthUserIdsByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
960
                lapTime = System.currentTimeMillis();
961
 
962
                // Collect all BM/ASM/RBM auth IDs to batch fetch AuthUser names
963
                Set<Integer> bmAsmRbmAuthIds = bmAsmRbmMap.values().stream()
964
                        .flatMap(m -> m.values().stream())
965
                        .filter(id -> id != null && id > 0)
966
                        .collect(Collectors.toSet());
967
 
968
                Map<Integer, AuthUser> bmAsmRbmAuthUserMap = new HashMap<>();
969
                if (!bmAsmRbmAuthIds.isEmpty()) {
970
                    bmAsmRbmAuthUserMap = authRepository.selectByIds(new ArrayList<>(bmAsmRbmAuthIds)).stream()
971
                            .collect(Collectors.toMap(AuthUser::getId, x -> x, (a, b) -> a));
972
                }
973
                LOGGER.info("PERF: fetch BM/ASM/RBM AuthUsers took {} ms", System.currentTimeMillis() - lapTime);
974
                lapTime = System.currentTimeMillis();
975
 
32978 amit.gupta 976
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
35968 ranu 977
                final Map<Integer, AuthUser> finalBmAsmRbmAuthUserMap = bmAsmRbmAuthUserMap;
31686 amit.gupta 978
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
979
                    int fofoId = customRetailerEntry.getKey();
980
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
981
                    float totalSecondaryPlan = 0;
982
                    float totalSecondaryAchivement = 0;
30077 tejbeer 983
 
31686 amit.gupta 984
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
985
                    ptam.setFofoId(fofoId);
986
                    ptam.setBusinessName(customRetailer.getBusinessName());
987
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 988
                    ptam.setActivationType(customRetailer.getActivationType());
30087 tejbeer 989
 
35968 ranu 990
                    // Set ASM/RBM/BM names
991
                    Map<String, Integer> roleMap = bmAsmRbmMap.get(fofoId);
992
                    if (roleMap != null) {
993
                        Integer asmId = roleMap.get("ASM");
994
                        if (asmId != null && asmId > 0 && finalBmAsmRbmAuthUserMap.get(asmId) != null) {
995
                            ptam.setAsmName(finalBmAsmRbmAuthUserMap.get(asmId).getFullName());
996
                        }
997
                        Integer rbmId = roleMap.get("RBM");
998
                        if (rbmId != null && rbmId > 0 && finalBmAsmRbmAuthUserMap.get(rbmId) != null) {
999
                            ptam.setRbmName(finalBmAsmRbmAuthUserMap.get(rbmId).getFullName());
1000
                        }
1001
                        Integer bmId = roleMap.get("BM");
1002
                        if (bmId != null && bmId > 0 && finalBmAsmRbmAuthUserMap.get(bmId) != null) {
1003
                            ptam.setBmName(finalBmAsmRbmAuthUserMap.get(bmId).getFullName());
1004
                        }
1005
                    }
1006
 
31686 amit.gupta 1007
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1008
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1009
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1010
                    }
30808 tejbeer 1011
 
32978 amit.gupta 1012
                    if (collectionMap.get(fofoId) != null) {
1013
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
30330 tejbeer 1014
 
31686 amit.gupta 1015
                        ptam.setRemark(collectionPlan.getRemark());
1016
                        ptam.setMessage(collectionPlan.getMessage());
1017
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
35632 ranu 1018
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
35835 ranu 1019
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
31686 amit.gupta 1020
                        ptam.setRank(collectionPlan.getRank());
36267 ranu 1021
 
1022
                        // If remark is SALES_ESCALATION, fetch open escalation ticket activities
1023
                        if (CollectionRemark.SALES_ESCALATION.equals(collectionPlan.getRemark())
1024
                                || CollectionRemark.PARTIAL_RESOLVE.equals(collectionPlan.getRemark())
1025
                                || CollectionRemark.NOT_RESOLVED.equals(collectionPlan.getRemark())) {
1026
                            List<Ticket> openTickets = ticketRepository.selectAllOpenTicketByRetailer(fofoId);
1027
                            for (Ticket ticket : openTickets) {
1028
                                if (ticket.getSubCategoryId() == ProfitMandiConstants.SALES_ESCALATION) {
1029
                                    List<Activity> activities = activityRepository.selectAll(ticket.getId());
1030
                                    ptam.setTicketActivities(activities);
1031
                                    break;
1032
                                }
1033
                            }
1034
                        }
1035
 
31686 amit.gupta 1036
                        Integer authId = collectionPlan.getAuthId();
30330 tejbeer 1037
 
31686 amit.gupta 1038
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
30416 tejbeer 1039
 
31686 amit.gupta 1040
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
30077 tejbeer 1041
 
31686 amit.gupta 1042
                        LOGGER.info("authId" + authId);
30137 tejbeer 1043
 
31686 amit.gupta 1044
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1045
                            float targetCollection = 0;
30330 tejbeer 1046
 
31686 amit.gupta 1047
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1048
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1049
                            } else {
1050
                                targetCollection = collectionPlan.getTargetPlan();
31677 amit.gupta 1051
                            }
30451 tejbeer 1052
 
31677 amit.gupta 1053
                            if (authId != null && authId == authUser.getId()) {
31686 amit.gupta 1054
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1055
                                    totalPartnerTargetCollection += targetCollection;
1056
                                }
31677 amit.gupta 1057
                            }
31686 amit.gupta 1058
                            ptam.setCollectionTarget(targetCollection);
1059
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1060
                                    && collectionPlan.getWalletTimestamp() != null
1061
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1062
                                if (authId != null && authId == authUser.getId()) {
1063
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1064
                                }
1065
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1066
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1067
                                    && collectionPlan.getAchievementPlan() != null) {
1068
                                if (authId != null && authId == authUser.getId()) {
1069
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1070
                                }
1071
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1072
 
31677 amit.gupta 1073
                            }
31686 amit.gupta 1074
                        }
30822 tejbeer 1075
 
31686 amit.gupta 1076
                        if (authId != null && authId != authUser.getId()) {
35415 amit 1077
                            ptam.setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1078
 
31677 amit.gupta 1079
                        }
30087 tejbeer 1080
 
31686 amit.gupta 1081
                        if (collectionPlan.getCommittedDate() != null) {
30087 tejbeer 1082
 
31686 amit.gupta 1083
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1084
                        }
30087 tejbeer 1085
 
31677 amit.gupta 1086
                    }
30821 tejbeer 1087
 
31686 amit.gupta 1088
                    // Secondary
30077 tejbeer 1089
 
31686 amit.gupta 1090
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1091
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
32978 amit.gupta 1092
                    if (partnerSecondaryPlans.get(fofoId) != null) {
31686 amit.gupta 1093
                        long otherBrandSecondary = 0;
32978 amit.gupta 1094
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
31686 amit.gupta 1095
                            Integer authId = pspm.getAuthId();
1096
                            if (!brands.contains(pspm.getBrand())) {
1097
                                if (pspm.getAchievementPlan() != null) {
1098
                                    otherBrandSecondary += pspm.getAchievementPlan();
1099
                                }
1100
                            } else {
1101
                                otherPartnerSecondaryPlanModel = pspm;
1102
                            }
1103
                            if (pspm.getTargetPlan() != null) {
1104
                                totalSecondaryPlan += pspm.getTargetPlan();
1105
                            }
30330 tejbeer 1106
 
31677 amit.gupta 1107
                            if (pspm.getAchievementPlan() != null) {
31686 amit.gupta 1108
                                totalSecondaryAchivement += pspm.getAchievementPlan();
31677 amit.gupta 1109
                            }
30087 tejbeer 1110
 
31686 amit.gupta 1111
                            if (pspm.getCommittedDate() != null) {
30137 tejbeer 1112
 
31686 amit.gupta 1113
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1114
                            }
1115
                            if (authId != null && authId == authUser.getId()) {
30137 tejbeer 1116
 
31686 amit.gupta 1117
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
30087 tejbeer 1118
 
31686 amit.gupta 1119
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1120
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1121
                                    }
1122
                                }
30087 tejbeer 1123
 
31686 amit.gupta 1124
                                if (pspm.getAchievementPlan() != null) {
1125
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
31677 amit.gupta 1126
                                }
31686 amit.gupta 1127
 
31677 amit.gupta 1128
                            }
31686 amit.gupta 1129
                        }
1130
                        if (otherPartnerSecondaryPlanModel != null) {
1131
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1132
                        }
32978 amit.gupta 1133
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
31686 amit.gupta 1134
                                .filter(x -> brands.contains(x.getBrand()))
1135
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30087 tejbeer 1136
 
31686 amit.gupta 1137
                        if (secondaryModelMap.containsKey("Others")) {
1138
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1139
                            psp.setAchievementPlan(otherBrandSecondary);
1140
                        } else {
35079 vikas 1141
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
31686 amit.gupta 1142
                        }
1143
                        for (String brand : brands) {
1144
                            if (!secondaryModelMap.containsKey(brand)) {
35079 vikas 1145
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
31677 amit.gupta 1146
                            }
31686 amit.gupta 1147
                        }
30087 tejbeer 1148
 
31686 amit.gupta 1149
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1150
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1151
                            if (authId != null && authId != authUser.getId()) {
35415 amit 1152
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1153
                                ptam.setSecondaryColor("red");
1154
                            }
1155
 
31677 amit.gupta 1156
                        }
30077 tejbeer 1157
 
31686 amit.gupta 1158
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1159
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1160
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1161
                        // Secondary
1162
 
31677 amit.gupta 1163
                    } else {
31686 amit.gupta 1164
                        for (String brand : brands) {
1165
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1166
                            pspm.setAchievementPlan((long) 0);
1167
                            pspm.setTargetPlan((long) 0);
1168
                            pspm.setBrand(brand);
1169
                            pspm.setFofoId(fofoId);
1170
                            secondaryModelMap.put(brand, pspm);
31677 amit.gupta 1171
                        }
31686 amit.gupta 1172
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
31677 amit.gupta 1173
                    }
30077 tejbeer 1174
 
31686 amit.gupta 1175
                    if (!partnerTicketCount.isEmpty()) {
1176
                        if (partnerTicketCount.get(fofoId) != null) {
1177
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
1178
                        } else {
1179
                            ptam.setTicketCount(0);
1180
 
31677 amit.gupta 1181
                        }
1182
                    }
30087 tejbeer 1183
 
35632 ranu 1184
                    // Category Assignment Logic (Priority: PLAN_TODAY > CARRY_FORWARD > ZERO_BILLED > UNTOUCHED > NORMAL)
1185
                    // Check if partner has credit due (loans > 15 days with pending amount) - just a flag, doesn't affect sorting
1186
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
1187
                    ptam.setHasOverdue(hasCreditDue);
1188
 
1189
                    // Default rank to 5 (Normal) if no collection plan exists
1190
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
1191
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1192
 
1193
                    // Assign category based on rank (overdue is just a flag, doesn't affect category)
1194
                    if (rank == 1) {
1195
                        ptam.setCategory("PLAN_TODAY");
1196
                        ptam.setCategoryPriority(1);
1197
                    } else if (rank == 2) {
1198
                        ptam.setCategory("CARRY_FORWARD");
1199
                        ptam.setCategoryPriority(2);
1200
                    } else if (hasZeroBilling && rank < 5) {
1201
                        // Zero billed only if NOT in normal category (rank 5+)
1202
                        // If rank is 1,2,3,4 and has zero billing, include in ZERO_BILLED
1203
                        ptam.setCategory("ZERO_BILLED");
1204
                        ptam.setCategoryPriority(3);
1205
                    } else if (rank == 3) {
1206
                        ptam.setCategory("UNTOUCHED");
1207
                        ptam.setCategoryPriority(4);
1208
                    } else {
1209
                        // rank 4 (future plan) and rank 5+ (normal) go to NORMAL
1210
                        // Also, zero billing with rank 5+ goes to NORMAL (not ZERO_BILLED)
1211
                        ptam.setCategory("NORMAL");
1212
                        ptam.setCategoryPriority(5);
1213
                    }
1214
 
31686 amit.gupta 1215
                    ptams.add(ptam);
30077 tejbeer 1216
 
31677 amit.gupta 1217
                }
32923 ranu 1218
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
30077 tejbeer 1219
 
32923 ranu 1220
                LOGGER.info("positions {}", positions);
1221
 
35079 vikas 1222
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 1223
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
1224
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35079 vikas 1225
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
32923 ranu 1226
 
36211 ranu 1227
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
32923 ranu 1228
 
35079 vikas 1229
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
32923 ranu 1230
 
31686 amit.gupta 1231
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
1232
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
1233
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
1234
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
1235
                tm.setTodayCollectionCount((int) todayCollectionCount);
32923 ranu 1236
                List<PartnerTargetAchievementModel> filteredPtams;
30416 tejbeer 1237
 
32923 ranu 1238
                if (isRBMAndL1) {
34428 ranu 1239
                    filteredPtams = ptams;
1240
//                    as of now all party is showing to rbm
1241
                    /*filteredPtams = ptams.stream()
32978 amit.gupta 1242
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34428 ranu 1243
                            .collect(Collectors.toList());*/
32923 ranu 1244
                } else if (isRBMAndNotL1) {
34429 ranu 1245
                    filteredPtams = ptams;
1246
                    /*filteredPtams = ptams.stream()
32923 ranu 1247
                            .filter(ptam -> !(CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34429 ranu 1248
                            .collect(Collectors.toList());*/
33041 ranu 1249
                } else if (isSales) {
1250
                    filteredPtams = ptams.stream()
36211 ranu 1251
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
33041 ranu 1252
                            .collect(Collectors.toList());
32923 ranu 1253
                } else {
1254
                    filteredPtams = ptams;
1255
                }
34428 ranu 1256
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 1257
                tm.setRBMAndL2(isRBMAndL2);
1258
                tm.setRBMAndL3(isRBMAndL3);
34428 ranu 1259
                tm.setRBMAndNotL1(isRBMAndNotL1);
1260
                tm.setSales(isSales);
35632 ranu 1261
 
1262
                // Calculate category counts
1263
                Map<String, Long> categoryCounts = filteredPtams.stream()
1264
                        .collect(Collectors.groupingBy(
1265
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
1266
                                Collectors.counting()));
1267
                // Count parties with overdue flag (independent of category)
1268
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
1269
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
1270
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
1271
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
1272
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
1273
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
1274
 
1275
                // Sort by: 1) Partners with today's remark go to bottom of entire list
35835 ranu 1276
                //          EXCEPT: NO_ANSWER/SCHEDULE_CALL with scheduledCallTime reached → comes back up
35853 ranu 1277
                //          EXCEPT: NO_ANSWER without scheduledCallTime older than 4 hours → comes back up
35632 ranu 1278
                //          2) Category Priority (PLAN_TODAY=1, CARRY_FORWARD=2, ZERO_BILLED=3, UNTOUCHED=4, NORMAL=5)
1279
                //          3) Then by rank
35835 ranu 1280
                LocalDateTime now = LocalDateTime.now();
35853 ranu 1281
                LocalDateTime fourHoursAgo = now.minusHours(4);
34796 ranu 1282
                tm.setTargetAchievement(filteredPtams.stream()
1283
                        .sorted(Comparator
35632 ranu 1284
                                .comparing((PartnerTargetAchievementModel p) -> {
1285
                                    if (p.getRemarkTimestamp() == null) {
1286
                                        return false; // No remark → comes first
1287
                                    }
1288
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
1289
                                    if (!remarkDate.equals(LocalDate.now())) {
1290
                                        return false; // Not today's remark → comes first
1291
                                    }
35835 ranu 1292
                                    // Check if SCHEDULE_CALL or NO_ANSWER with scheduledCallTime
1293
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
1294
                                        if (p.getScheduledCallTime() != null) {
1295
                                            // Has scheduled time - come up only when scheduled time is reached
1296
                                            if (!p.getScheduledCallTime().isAfter(now)) {
1297
                                                return false; // Scheduled time reached → comes back up
1298
                                            }
1299
                                            return true; // Scheduled time not reached → stays at bottom
1300
                                        }
35853 ranu 1301
                                        // NO_ANSWER without scheduledCallTime - use 4 hour logic
35835 ranu 1302
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
35853 ranu 1303
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
1304
                                            return false; // NO_ANSWER older than 4 hours → comes back up
35835 ranu 1305
                                        }
35632 ranu 1306
                                    }
1307
                                    return true; // Other today's remarks → goes to bottom
1308
                                }) // false → comes first, true → goes to bottom
1309
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
34796 ranu 1310
                                .thenComparing(PartnerTargetAchievementModel::getRank)
1311
                        )
31686 amit.gupta 1312
                        .collect(Collectors.toList()));
30416 tejbeer 1313
 
34796 ranu 1314
 
31677 amit.gupta 1315
            }
30077 tejbeer 1316
 
31677 amit.gupta 1317
        }
35632 ranu 1318
        LOGGER.info("PERF: Total getPartnerTarget took {} ms", System.currentTimeMillis() - startTime);
31677 amit.gupta 1319
        return responseSender.ok(tm);
30077 tejbeer 1320
 
31677 amit.gupta 1321
    }
32737 amit.gupta 1322
 
35920 ranu 1323
    @RequestMapping(value = "/getInactivePartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1324
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
1325
    public ResponseEntity<?> getInactivePartnerTarget(HttpServletRequest request, @RequestParam String
1326
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
1327
            ProfitMandiBusinessException {
1328
 
1329
        long startTime = System.currentTimeMillis();
1330
        long lapTime = startTime;
1331
 
1332
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
1333
 
1334
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserInactivePartnerIdMapping();
1335
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1336
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
1337
 
1338
        float totalPartnerTargetSecondary = 0;
1339
        float totalPartnerTargetCollection = 0;
1340
        float totalPartnerAchievementSecondary = 0;
1341
        float totalPartnerAchievementCollection = 0;
1342
        TargetModel tm = new TargetModel();
1343
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
1344
        Map<Integer, Long> partnerTicketCount = new HashMap<>();
1345
 
1346
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
1347
 
1348
        if (fofoIds != null && fofoIds.size() > 0) {
1349
            LOGGER.info("fofoIds {}", fofoIds);
1350
            // Get inactive stores for the given retailer IDs
1351
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
1352
                    .filter(x -> (!x.isInternal()))
1353
                    .map(x -> x.getId()).collect(Collectors.toList());
1354
            LOGGER.info("PERF: selectInActiveStore took {} ms", System.currentTimeMillis() - lapTime);
1355
            lapTime = System.currentTimeMillis();
1356
            LOGGER.info("inactive fofoIdList size: {}", fofoIdList.size());
1357
 
1358
            if (!fofoIdList.isEmpty()) {
1359
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
1360
            }
1361
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1362
            lapTime = System.currentTimeMillis();
1363
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
1364
 
1365
            if (dayValue.equals("previous")) {
1366
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
1367
            }
1368
 
1369
            if (fofoIdList.size() > 0) {
1370
 
1371
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
1372
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
1373
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
1374
                lapTime = System.currentTimeMillis();
1375
 
1376
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
1377
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
1378
                long billingThreshold = 1000L;
1379
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
1380
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
1381
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
1382
                lapTime = System.currentTimeMillis();
1383
 
1384
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
1385
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
1386
                lapTime = System.currentTimeMillis();
1387
 
1388
                if (!partnerDailyInvestments.isEmpty()) {
1389
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1390
                }
1391
 
1392
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
1393
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
1394
                lapTime = System.currentTimeMillis();
1395
 
1396
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1397
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
1398
                lapTime = System.currentTimeMillis();
1399
 
1400
                long todayCollectionCount = 0;
1401
                if (!remarkIds.isEmpty()) {
1402
                    todayCollectionCount = partnerCollectionRemarkRepository
1403
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
1404
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
1405
                            .collect(Collectors.counting());
1406
                }
1407
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
1408
                lapTime = System.currentTimeMillis();
1409
 
1410
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
1411
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
1412
                lapTime = System.currentTimeMillis();
1413
 
1414
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
1415
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
1416
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
1417
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
1418
                lapTime = System.currentTimeMillis();
1419
 
1420
                Set<Integer> allAuthIds = new HashSet<>();
1421
                collectionMap.values().stream()
1422
                        .map(PartnerCollectionPlanModel::getAuthId)
1423
                        .filter(id -> id != null && id != authUser.getId())
1424
                        .forEach(allAuthIds::add);
1425
                partnerSecondaryPlans.values().stream()
1426
                        .flatMap(List::stream)
1427
                        .map(PartnerSecondaryPlanModel::getAuthId)
1428
                        .filter(id -> id != null && id != authUser.getId())
1429
                        .forEach(allAuthIds::add);
1430
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
1431
                if (!allAuthIds.isEmpty()) {
1432
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
1433
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
1434
                }
1435
 
1436
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
1437
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
1438
                    int fofoId = customRetailerEntry.getKey();
1439
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
1440
                    float totalSecondaryPlan = 0;
1441
                    float totalSecondaryAchivement = 0;
1442
 
1443
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
1444
                    ptam.setFofoId(fofoId);
1445
                    ptam.setBusinessName(customRetailer.getBusinessName());
1446
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 1447
                    ptam.setActivationType(customRetailer.getActivationType());
35920 ranu 1448
 
1449
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1450
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1451
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1452
                    }
1453
 
1454
                    if (collectionMap.get(fofoId) != null) {
1455
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
1456
 
1457
                        ptam.setRemark(collectionPlan.getRemark());
1458
                        ptam.setMessage(collectionPlan.getMessage());
1459
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
1460
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
1461
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
1462
                        ptam.setRank(collectionPlan.getRank());
1463
                        Integer authId = collectionPlan.getAuthId();
1464
 
1465
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
1466
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
1467
 
1468
                        LOGGER.info("authId" + authId);
1469
 
1470
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1471
                            float targetCollection = 0;
1472
 
1473
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1474
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1475
                            } else {
1476
                                targetCollection = collectionPlan.getTargetPlan();
1477
                            }
1478
 
1479
                            if (authId != null && authId == authUser.getId()) {
1480
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1481
                                    totalPartnerTargetCollection += targetCollection;
1482
                                }
1483
                            }
1484
                            ptam.setCollectionTarget(targetCollection);
1485
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1486
                                    && collectionPlan.getWalletTimestamp() != null
1487
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1488
                                if (authId != null && authId == authUser.getId()) {
1489
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1490
                                }
1491
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1492
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1493
                                    && collectionPlan.getAchievementPlan() != null) {
1494
                                if (authId != null && authId == authUser.getId()) {
1495
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1496
                                }
1497
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1498
                            }
1499
                        }
1500
 
1501
                        if (authId != null && authId != authUser.getId()) {
1502
                            ptam.setAuthUser(authUserMap.get(authId));
1503
                        }
1504
 
1505
                        if (collectionPlan.getCommittedDate() != null) {
1506
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1507
                        }
1508
                    }
1509
 
1510
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1511
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
1512
                    if (partnerSecondaryPlans.get(fofoId) != null) {
1513
                        long otherBrandSecondary = 0;
1514
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
1515
                            Integer authId = pspm.getAuthId();
1516
                            if (!brands.contains(pspm.getBrand())) {
1517
                                if (pspm.getAchievementPlan() != null) {
1518
                                    otherBrandSecondary += pspm.getAchievementPlan();
1519
                                }
1520
                            } else {
1521
                                otherPartnerSecondaryPlanModel = pspm;
1522
                            }
1523
                            if (pspm.getTargetPlan() != null) {
1524
                                totalSecondaryPlan += pspm.getTargetPlan();
1525
                            }
1526
 
1527
                            if (pspm.getAchievementPlan() != null) {
1528
                                totalSecondaryAchivement += pspm.getAchievementPlan();
1529
                            }
1530
 
1531
                            if (pspm.getCommittedDate() != null) {
1532
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1533
                            }
1534
                            if (authId != null && authId == authUser.getId()) {
1535
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
1536
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1537
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1538
                                    }
1539
                                }
1540
 
1541
                                if (pspm.getAchievementPlan() != null) {
1542
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
1543
                                }
1544
                            }
1545
                        }
1546
                        if (otherPartnerSecondaryPlanModel != null) {
1547
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1548
                        }
1549
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
1550
                                .filter(x -> brands.contains(x.getBrand()))
1551
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1552
 
1553
                        if (secondaryModelMap.containsKey("Others")) {
1554
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1555
                            psp.setAchievementPlan(otherBrandSecondary);
1556
                        } else {
1557
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
1558
                        }
1559
                        for (String brand : brands) {
1560
                            if (!secondaryModelMap.containsKey(brand)) {
1561
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
1562
                            }
1563
                        }
1564
 
1565
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1566
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1567
                            if (authId != null && authId != authUser.getId()) {
1568
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
1569
                                ptam.setSecondaryColor("red");
1570
                            }
1571
                        }
1572
 
1573
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1574
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1575
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1576
 
1577
                    } else {
1578
                        for (String brand : brands) {
1579
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1580
                            pspm.setAchievementPlan((long) 0);
1581
                            pspm.setTargetPlan((long) 0);
1582
                            pspm.setBrand(brand);
1583
                            pspm.setFofoId(fofoId);
1584
                            secondaryModelMap.put(brand, pspm);
1585
                        }
1586
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1587
                    }
1588
 
1589
                    if (!partnerTicketCount.isEmpty()) {
1590
                        if (partnerTicketCount.get(fofoId) != null) {
1591
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
1592
                        } else {
1593
                            ptam.setTicketCount(0);
1594
                        }
1595
                    }
1596
 
1597
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
1598
                    ptam.setHasOverdue(hasCreditDue);
1599
 
1600
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
1601
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1602
 
1603
                    if (rank == 1) {
1604
                        ptam.setCategory("PLAN_TODAY");
1605
                        ptam.setCategoryPriority(1);
1606
                    } else if (rank == 2) {
1607
                        ptam.setCategory("CARRY_FORWARD");
1608
                        ptam.setCategoryPriority(2);
1609
                    } else if (hasZeroBilling && rank < 5) {
1610
                        ptam.setCategory("ZERO_BILLED");
1611
                        ptam.setCategoryPriority(3);
1612
                    } else if (rank == 3) {
1613
                        ptam.setCategory("UNTOUCHED");
1614
                        ptam.setCategoryPriority(4);
1615
                    } else {
1616
                        ptam.setCategory("NORMAL");
1617
                        ptam.setCategoryPriority(5);
1618
                    }
1619
 
1620
                    ptams.add(ptam);
1621
                }
1622
 
1623
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
1624
                LOGGER.info("positions {}", positions);
1625
 
1626
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 1627
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
1628
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35920 ranu 1629
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 1630
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
35920 ranu 1631
 
1632
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
1633
 
1634
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
1635
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
1636
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
1637
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
1638
                tm.setTodayCollectionCount((int) todayCollectionCount);
1639
                List<PartnerTargetAchievementModel> filteredPtams;
1640
 
1641
                if (isRBMAndL1) {
1642
                    filteredPtams = ptams;
1643
                } else if (isRBMAndNotL1) {
1644
                    filteredPtams = ptams;
1645
                } else if (isSales) {
1646
                    filteredPtams = ptams.stream()
36211 ranu 1647
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
35920 ranu 1648
                            .collect(Collectors.toList());
1649
                } else {
1650
                    filteredPtams = ptams;
1651
                }
1652
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 1653
                tm.setRBMAndL2(isRBMAndL2);
1654
                tm.setRBMAndL3(isRBMAndL3);
35920 ranu 1655
                tm.setRBMAndNotL1(isRBMAndNotL1);
1656
                tm.setSales(isSales);
1657
 
1658
                Map<String, Long> categoryCounts = filteredPtams.stream()
1659
                        .collect(Collectors.groupingBy(
1660
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
1661
                                Collectors.counting()));
1662
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
1663
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
1664
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
1665
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
1666
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
1667
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
1668
 
1669
                LocalDateTime now = LocalDateTime.now();
1670
                LocalDateTime fourHoursAgo = now.minusHours(4);
1671
                tm.setTargetAchievement(filteredPtams.stream()
1672
                        .sorted(Comparator
1673
                                .comparing((PartnerTargetAchievementModel p) -> {
1674
                                    if (p.getRemarkTimestamp() == null) {
1675
                                        return false;
1676
                                    }
1677
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
1678
                                    if (!remarkDate.equals(LocalDate.now())) {
1679
                                        return false;
1680
                                    }
1681
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
1682
                                        if (p.getScheduledCallTime() != null) {
1683
                                            if (!p.getScheduledCallTime().isAfter(now)) {
1684
                                                return false;
1685
                                            }
1686
                                            return true;
1687
                                        }
1688
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
1689
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
1690
                                            return false;
1691
                                        }
1692
                                    }
1693
                                    return true;
1694
                                })
1695
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
1696
                                .thenComparing(PartnerTargetAchievementModel::getRank)
1697
                        )
1698
                        .collect(Collectors.toList()));
1699
            }
1700
        }
1701
        LOGGER.info("PERF: Total getInactivePartnerTarget took {} ms", System.currentTimeMillis() - startTime);
1702
        return responseSender.ok(tm);
1703
 
1704
    }
1705
 
32737 amit.gupta 1706
    //TODO:Amit
31677 amit.gupta 1707
    @RequestMapping(value = "/target", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1708
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1709
    public ResponseEntity<?> createPartnerTarget(HttpServletRequest request,
1710
                                                 @RequestBody PartnerTargetAchievementModel ptam) throws ProfitMandiBusinessException {
30077 tejbeer 1711
 
31677 amit.gupta 1712
        LOGGER.info("ptam" + ptam);
30089 tejbeer 1713
 
31677 amit.gupta 1714
        AuthUser authUser = authRepository.selectByGmailId(ptam.getCreatedBy());
30077 tejbeer 1715
 
31677 amit.gupta 1716
        if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
1717
                || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
1718
            PartnerCollectionPlan partnerCollectionPlan = partnerCollectionPlanRepository
1719
                    .selectByLocalDate(LocalDate.now(), ptam.getFofoId(), true);
1720
            LOGGER.info("pcp" + partnerCollectionPlan);
30077 tejbeer 1721
 
31677 amit.gupta 1722
            if (partnerCollectionPlan == null) {
1723
                if (ptam.getCollectionTarget() > 0) {
30087 tejbeer 1724
 
31677 amit.gupta 1725
                    partnerCollectionPlan = new PartnerCollectionPlan();
1726
                    partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
1727
                    partnerCollectionPlan.setAuthId(authUser.getId());
1728
                    partnerCollectionPlan.setFofoId(ptam.getFofoId());
1729
                    partnerCollectionPlan.setActive(true);
1730
                    partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1731
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1732
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1733
                    partnerCollectionPlanRepository.persist(partnerCollectionPlan);
30416 tejbeer 1734
 
31677 amit.gupta 1735
                }
30087 tejbeer 1736
 
31677 amit.gupta 1737
            } else {
30087 tejbeer 1738
 
31677 amit.gupta 1739
                if (partnerCollectionPlan.getCollectionPlan() != ptam.getCollectionTarget()) {
1740
                    float totalCollectionPlan = partnerCollectionPlan.getCollectionPlan() + 10000;
1741
                    if (authUser.getId() == partnerCollectionPlan.getAuthId()) {
30087 tejbeer 1742
 
31677 amit.gupta 1743
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1744
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1745
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
1746
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1747
                            partnerCollectionPlan.setActive(true);
1748
                            partnerCollectionPlan
1749
                                    .setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1750
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1751
                        } else {
1752
                            throw new ProfitMandiBusinessException("collection target", "",
1753
                                    "collection target should be more than " + totalCollectionPlan);
1754
                        }
30087 tejbeer 1755
 
31677 amit.gupta 1756
                    } else {
30137 tejbeer 1757
 
31677 amit.gupta 1758
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1759
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1760
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
30137 tejbeer 1761
 
31677 amit.gupta 1762
                            partnerCollectionPlan.setActive(false);
1763
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1764
                            partnerCollectionPlan = new PartnerCollectionPlan();
1765
                            partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
1766
                            partnerCollectionPlan.setAuthId(authUser.getId());
1767
                            partnerCollectionPlan.setFofoId(ptam.getFofoId());
1768
                            partnerCollectionPlan.setActive(true);
1769
                            partnerCollectionPlan
1770
                                    .setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1771
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1772
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1773
                            partnerCollectionPlanRepository.persist(partnerCollectionPlan);
1774
                        } else {
1775
                            throw new ProfitMandiBusinessException("collection target", "",
1776
                                    "collection target should be more than " + totalCollectionPlan);
1777
                        }
1778
                    }
1779
                }
30137 tejbeer 1780
 
31677 amit.gupta 1781
                if ((LocalDate.now().atStartOfDay().equals(ptam.getCollectionCommitmentDate().atStartOfDay())
1782
                        || ptam.getCollectionCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
1783
                        && partnerCollectionPlan.getCollectionPlan() == ptam.getCollectionTarget()) {
1784
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1785
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1786
                }
30416 tejbeer 1787
 
31677 amit.gupta 1788
            }
30433 tejbeer 1789
 
35725 ranu 1790
            long callLogId = recordingService.getLatestAgentCallLog(ptam.getFofoId(),authUser.getId());
1791
 
31677 amit.gupta 1792
            PartnerCollectionRemark pcr = new PartnerCollectionRemark();
1793
            pcr.setFofoId(ptam.getFofoId());
1794
            pcr.setAuthId(authUser.getId());
1795
            pcr.setMessage("Collection plan for" + ptam.getCollectionCommitmentDate());
1796
            pcr.setRemark(CollectionRemark.COLLECTION_PLAN);
35725 ranu 1797
            pcr.setAgentCallLogId(callLogId);
31677 amit.gupta 1798
            pcr.setCreateTimestamp(LocalDateTime.now());
1799
            partnerCollectionRemarkRepository.persist(pcr);
1800
        } else {
1801
            throw new ProfitMandiBusinessException("Date", "",
1802
                    "you can't select the back date " + ptam.getCollectionCommitmentDate());
1803
        }
30077 tejbeer 1804
 
31677 amit.gupta 1805
        for (Entry<String, PartnerSecondaryPlanModel> pspm : ptam.getPartnerSecondaryModel().entrySet()) {
30087 tejbeer 1806
 
31677 amit.gupta 1807
            if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
1808
                    || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
1809
                PartnerSecondaryPlanModel plan = pspm.getValue();
1810
                PartnerSecondaryPlan psp = partnerSecondaryPlanRepository.selectByLocalDateBrand(plan.getBrand(),
1811
                        LocalDate.now(), ptam.getFofoId(), true);
1812
                LOGGER.info("psp" + psp);
30087 tejbeer 1813
 
31677 amit.gupta 1814
                if (psp == null) {
1815
                    if (plan.getTargetPlan() != null && plan.getTargetPlan() > 0) {
30087 tejbeer 1816
 
31677 amit.gupta 1817
                        psp = new PartnerSecondaryPlan();
1818
                        psp.setAuthId(authUser.getId());
1819
                        psp.setBrand(pspm.getKey());
1820
                        psp.setFofoId(pspm.getValue().getFofoId());
1821
                        psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1822
                        psp.setCreateTimestamp(LocalDateTime.now());
1823
                        psp.setUpdatedTimestamp(LocalDateTime.now());
1824
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1825
                        psp.setActive(true);
1826
                        partnerSecondaryPlanRepository.persist(psp);
1827
                    }
30087 tejbeer 1828
 
31677 amit.gupta 1829
                } else {
1830
                    if (plan.getTargetPlan() != psp.getSecondaryPlan()) {
1831
                        float totalSecondaryPlan = psp.getSecondaryPlan() + 10000;
1832
                        if (authUser.getId() == plan.getAuthId()) {
1833
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1834
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1835
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
1836
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1837
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1838
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1839
                                psp.setActive(true);
1840
                            } else {
1841
                                throw new ProfitMandiBusinessException("secondary target", "",
1842
                                        "secondary target should be more than " + totalSecondaryPlan);
1843
                            }
30087 tejbeer 1844
 
31677 amit.gupta 1845
                        } else {
30087 tejbeer 1846
 
31677 amit.gupta 1847
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1848
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1849
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
30087 tejbeer 1850
 
31677 amit.gupta 1851
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1852
                                psp.setActive(false);
1853
                                psp = new PartnerSecondaryPlan();
1854
                                psp.setAuthId(authUser.getId());
1855
                                psp.setBrand(pspm.getKey());
1856
                                psp.setFofoId(pspm.getValue().getFofoId());
1857
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1858
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1859
                                psp.setCreateTimestamp(LocalDateTime.now());
1860
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1861
                                psp.setActive(true);
1862
                                partnerSecondaryPlanRepository.persist(psp);
1863
                            } else {
1864
                                throw new ProfitMandiBusinessException("secondary target", "",
1865
                                        "secondary target should be more than " + totalSecondaryPlan);
1866
                            }
1867
                        }
1868
                    }
30137 tejbeer 1869
 
31677 amit.gupta 1870
                    if ((LocalDate.now().atStartOfDay().equals(ptam.getSecondaryCommitmentDate().atStartOfDay())
1871
                            || ptam.getSecondaryCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
1872
                            && plan.getTargetPlan() == psp.getSecondaryPlan()) {
1873
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1874
                        psp.setUpdatedTimestamp(LocalDateTime.now());
1875
                    }
30137 tejbeer 1876
 
31677 amit.gupta 1877
                }
1878
            } else {
1879
                throw new ProfitMandiBusinessException("Date", "",
1880
                        "you can't select the back date " + ptam.getSecondaryCommitmentDate());
1881
            }
30137 tejbeer 1882
 
31677 amit.gupta 1883
        }
30077 tejbeer 1884
 
31677 amit.gupta 1885
        return responseSender.ok(true);
30137 tejbeer 1886
 
31677 amit.gupta 1887
    }
30077 tejbeer 1888
 
31677 amit.gupta 1889
    @RequestMapping(value = "/uploadFranchiseeVisit", method = RequestMethod.POST)
35288 amit 1890
    public ResponseEntity<?> readCsvFileAndSetLead(HttpServletRequest request, @RequestPart MultipartFile
1891
            multipartFile) throws Throwable {
30433 tejbeer 1892
 
31677 amit.gupta 1893
        int id = (int) request.getAttribute("userId");
30433 tejbeer 1894
 
31677 amit.gupta 1895
        LOGGER.info("id" + id);
30433 tejbeer 1896
 
31677 amit.gupta 1897
        User user = userRepository.selectById(id);
30433 tejbeer 1898
 
31677 amit.gupta 1899
        AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());
30433 tejbeer 1900
 
31677 amit.gupta 1901
        String fileName = multipartFile.getName();
1902
        String fileNames = multipartFile.getOriginalFilename();
30433 tejbeer 1903
 
31677 amit.gupta 1904
        LOGGER.info("fileName" + fileName);
1905
        LOGGER.info("fileNames" + fileNames);
30433 tejbeer 1906
 
31677 amit.gupta 1907
        List<CSVRecord> records = FileUtil.readFile(multipartFile);
30433 tejbeer 1908
 
31677 amit.gupta 1909
        for (CSVRecord record : records) {
1910
            FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
1911
            franchiseeVisit.setFofoId(Integer.parseInt(record.get(0)));
1912
            CustomRetailer customRetailer = retailerService.getFofoRetailer(Integer.parseInt(record.get(0)));
30433 tejbeer 1913
 
31677 amit.gupta 1914
            franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
1915
            franchiseeVisit.setAgenda(record.get(1));
1916
            franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
1917
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1918
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
30433 tejbeer 1919
 
31677 amit.gupta 1920
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
1921
            LOGGER.info(record.get(1));
1922
            LocalDate dateTime = LocalDate.parse(record.get(2), formatter);
30433 tejbeer 1923
 
31677 amit.gupta 1924
            franchiseeVisit.setScheduleTimestamp(dateTime.atStartOfDay());
1925
            // change
30433 tejbeer 1926
 
31677 amit.gupta 1927
            String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
1928
            franchiseeVisit.setCreatedBy(authUserName);
1929
            franchiseeVisit.setAuthId(authUser.getId());
30433 tejbeer 1930
 
31677 amit.gupta 1931
            franchiseeVisitRepository.persist(franchiseeVisit);
30433 tejbeer 1932
 
31677 amit.gupta 1933
            return responseSender.ok(true);
1934
        }
30433 tejbeer 1935
 
31677 amit.gupta 1936
        return responseSender.ok(true);
30433 tejbeer 1937
 
31677 amit.gupta 1938
    }
30487 tejbeer 1939
 
31677 amit.gupta 1940
    @RequestMapping(value = "/downloadFranchiseeVisitTemplate", method = RequestMethod.GET)
1941
    public ResponseEntity<?> downloadFranchiseeVisitTemplate(HttpServletRequest request) throws Exception {
30487 tejbeer 1942
 
31677 amit.gupta 1943
        // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
30487 tejbeer 1944
 
31677 amit.gupta 1945
        List<List<?>> rows = new ArrayList<>();
30487 tejbeer 1946
 
32923 ranu 1947
        ByteArrayOutputStream byteArrayOutputStream = FileUtil
31677 amit.gupta 1948
                .getCSVByteStream(Arrays.asList("Partner Id", "Agenda", "Schedule Timestamp"), rows);
30487 tejbeer 1949
 
31677 amit.gupta 1950
        try {
1951
            byteArrayOutputStream.close();
1952
        } catch (IOException e) {
1953
            // TODO Auto-generated catch block
1954
            e.printStackTrace();
1955
        }
30487 tejbeer 1956
 
31677 amit.gupta 1957
        String filename = "template.csv";
1958
        HttpHeaders headers = new HttpHeaders();
1959
        headers.add("Content-Type", "application/csv");
1960
        headers.setContentDispositionFormData(filename, filename);
30487 tejbeer 1961
 
31677 amit.gupta 1962
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
30487 tejbeer 1963
 
31677 amit.gupta 1964
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
1965
                HttpStatus.OK);
1966
        return response;
30544 tejbeer 1967
 
31677 amit.gupta 1968
    }
30542 tejbeer 1969
 
31677 amit.gupta 1970
    @RequestMapping(value = "/markVisitAttendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1971
    public ResponseEntity<?> markVisitAttendance(HttpServletRequest request, @RequestParam(name = "id") int id)
1972
            throws ProfitMandiBusinessException {
1973
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
30542 tejbeer 1974
 
31677 amit.gupta 1975
        franchiseeVisit.setVisitTimestamp(LocalDateTime.now());
30542 tejbeer 1976
 
31677 amit.gupta 1977
        return responseSender.ok(true);
30542 tejbeer 1978
 
31677 amit.gupta 1979
    }
31249 tejbeer 1980
 
31677 amit.gupta 1981
    @RequestMapping(value = "/getVisitRequests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1982
    public ResponseEntity<?> getVisitRequests(HttpServletRequest request,
1983
                                              @RequestParam(name = "gmailId") String gmailId, Model model) throws Exception {
31249 tejbeer 1984
 
31677 amit.gupta 1985
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 1986
 
31677 amit.gupta 1987
        List<Integer> authUserIds = authService.getAllReportees(authUser.getId());
1988
        List<VisitSummaryModel> visitSummary = new ArrayList<>();
31249 tejbeer 1989
 
31677 amit.gupta 1990
        if (!authUserIds.isEmpty()) {
35397 amit 1991
            List<AuthUser> authUsers = authRepository.selectByIds(authUserIds);
31249 tejbeer 1992
 
31677 amit.gupta 1993
            List<VisitRequest> allVisitRequests = visitRequestRepository.selectByAuthIdsAndDate(authUserIds,
1994
                    LocalDate.now().minusDays(7), Arrays.asList(VisitStatus.approved, VisitStatus.pending));
1995
            LOGGER.info("allVisitRequests {}", allVisitRequests);
31249 tejbeer 1996
 
31677 amit.gupta 1997
            if (!allVisitRequests.isEmpty()) {
31249 tejbeer 1998
 
31677 amit.gupta 1999
                List<Integer> leadIds = allVisitRequests.stream().filter(x -> x.getVisitType().equals("lead"))
2000
                        .map(x -> x.getVisitId()).collect(Collectors.toList());
2001
                List<Lead> leads = new ArrayList<>();
2002
                if (!leadIds.isEmpty()) {
2003
                    leads = leadRepository.selectAllByIds(leadIds);
31249 tejbeer 2004
 
35415 amit 2005
                    // Batch fetch all LeadActivities instead of N+1
2006
                    List<LeadActivity> allLeadActivities = leadActivityRepository.selectAllByleadIds(leadIds);
2007
                    Map<Integer, List<LeadActivity>> leadActivityMap = allLeadActivities.stream()
2008
                            .collect(Collectors.groupingBy(LeadActivity::getLeadId));
2009
 
31677 amit.gupta 2010
                    for (Lead lead : leads) {
35415 amit 2011
                        List<LeadActivity> leadActivities = leadActivityMap.get(lead.getId());
2012
                        if (leadActivities != null && !leadActivities.isEmpty()) {
2013
                            lead.setScheduledTimestamp(leadActivities.get(0).getSchelduleTimestamp());
2014
                            lead.setLeadActivity(leadActivities.get(0));
2015
                        }
31677 amit.gupta 2016
                    }
2017
                }
2018
                List<Integer> franchiseeIds = allVisitRequests.stream()
2019
                        .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2020
                        .collect(Collectors.toList());
2021
                List<FranchiseeVisit> franchiseeVisits = new ArrayList<>();
2022
                if (!franchiseeIds.isEmpty()) {
2023
                    franchiseeVisits = franchiseeVisitRepository.selectAllByIds(franchiseeIds);
2024
                    LOGGER.info("franchiseeVisits {}", franchiseeVisits);
31249 tejbeer 2025
 
35415 amit 2026
                    // Batch fetch all FranchiseeActivities instead of N+1
2027
                    List<FranchiseeActivity> allFranchiseeActivities = franchiseeActivityRepository
2028
                            .selectByFranchiseeVisitIds(franchiseeIds);
2029
                    Map<Integer, List<FranchiseeActivity>> franchiseeActivityMap = allFranchiseeActivities.stream()
2030
                            .collect(Collectors.groupingBy(FranchiseeActivity::getFranchiseeVisitd));
2031
 
31677 amit.gupta 2032
                    for (FranchiseeVisit franchiseeVisit : franchiseeVisits) {
35415 amit 2033
                        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityMap.get(franchiseeVisit.getId());
31677 amit.gupta 2034
                        LOGGER.info("franchiseeActivities {}", franchiseeActivities);
31249 tejbeer 2035
 
35415 amit 2036
                        if (franchiseeActivities != null && !franchiseeActivities.isEmpty()) {
2037
                            franchiseeVisit.setScheduleTimestamp(franchiseeActivities.get(0).getSchelduleTimestamp());
2038
                            franchiseeVisit.setFranchiseeActivity(franchiseeActivities.get(0));
2039
                        }
31677 amit.gupta 2040
                    }
31249 tejbeer 2041
 
31677 amit.gupta 2042
                }
31249 tejbeer 2043
 
35415 amit 2044
                // Pre-fetch all retailers using cached method (instead of N+1 getFofoRetailer calls)
2045
                Map<Integer, CustomRetailer> allRetailersMap = retailerService.getAllFofoRetailers();
2046
 
31677 amit.gupta 2047
                Map<LocalDate, List<VisitRequest>> dateWiseVisitRequest = allVisitRequests.stream()
2048
                        .collect(Collectors.groupingBy(x -> x.getScheduleTimestamp().toLocalDate()));
31249 tejbeer 2049
 
31677 amit.gupta 2050
                for (Entry<LocalDate, List<VisitRequest>> visitEntry : dateWiseVisitRequest.entrySet()) {
31249 tejbeer 2051
 
31677 amit.gupta 2052
                    LocalDate date = visitEntry.getKey();
2053
                    List<VisitRequest> visitRequests = visitEntry.getValue();
31249 tejbeer 2054
 
31677 amit.gupta 2055
                    VisitSummaryModel visitSummaryModel = new VisitSummaryModel();
31249 tejbeer 2056
 
31677 amit.gupta 2057
                    visitSummaryModel.setDate(date);
2058
                    List<Integer> dateWiseLeadEntry = visitRequests.stream()
2059
                            .filter(x -> x.getVisitType().equals("lead")).map(x -> x.getVisitId())
2060
                            .collect(Collectors.toList());
31249 tejbeer 2061
 
31677 amit.gupta 2062
                    List<Integer> dateWiseFranchiseeIds = visitRequests.stream()
2063
                            .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2064
                            .collect(Collectors.toList());
31249 tejbeer 2065
 
31677 amit.gupta 2066
                    Map<Integer, List<Lead>> filteredLeadsMap = null;
2067
                    if (!leads.isEmpty()) {
2068
                        filteredLeadsMap = leads.stream().filter(x -> dateWiseLeadEntry.contains(x.getId()))
2069
                                .collect(Collectors.groupingBy(x -> x.getAssignTo()));
31249 tejbeer 2070
 
31677 amit.gupta 2071
                    }
31249 tejbeer 2072
 
31677 amit.gupta 2073
                    Map<Integer, List<FranchiseeVisit>> filteredFranchiseeVisitsMap = null;
31249 tejbeer 2074
 
31677 amit.gupta 2075
                    if (!franchiseeVisits.isEmpty()) {
2076
                        filteredFranchiseeVisitsMap = franchiseeVisits.stream()
2077
                                .filter(x -> dateWiseFranchiseeIds.contains(x.getId()))
2078
                                .collect(Collectors.groupingBy(x -> x.getAuthId()));
31249 tejbeer 2079
 
31677 amit.gupta 2080
                    }
31249 tejbeer 2081
 
31677 amit.gupta 2082
                    List<UserVisitModel> userVisits = new ArrayList<>();
31249 tejbeer 2083
 
31677 amit.gupta 2084
                    for (AuthUser auth : authUsers) {
2085
                        UserVisitModel userVisitModel = new UserVisitModel();
2086
                        List<VisitDescriptionModel> visitDescriptions = new ArrayList<>();
31249 tejbeer 2087
 
31677 amit.gupta 2088
                        List<Lead> authLeads = new ArrayList<>();
2089
                        if (filteredLeadsMap != null) {
2090
                            authLeads = filteredLeadsMap.get(auth.getId());
31249 tejbeer 2091
 
31677 amit.gupta 2092
                        }
31249 tejbeer 2093
 
31677 amit.gupta 2094
                        if (authLeads != null && !authLeads.isEmpty()) {
2095
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2096
 
31677 amit.gupta 2097
                            for (Lead lead : authLeads) {
31249 tejbeer 2098
 
31677 amit.gupta 2099
                                VisitRequest visitRequest = visitRequests.stream().filter(
2100
                                                x -> x.getVisitId() == lead.getId() && x.getCreatedBy() == lead.getAssignTo())
2101
                                        .findAny().orElse(null);
2102
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2103
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2104
                                visitDescriptionModel.setVisitName(lead.getFirstName());
2105
                                visitDescriptionModel.setCity(lead.getCity());
2106
                                visitDescriptionModel.setState(lead.getState());
2107
                                visitDescriptionModel.setScheduleTime(lead.getScheduledTimestamp());
2108
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2109
                                visitDescriptionModel.setRemarks(lead.getLeadActivity().getRemark());
2110
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
2111
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2112
 
31677 amit.gupta 2113
                            }
2114
                        }
31249 tejbeer 2115
 
31677 amit.gupta 2116
                        List<FranchiseeVisit> authfranchiseeVisit = new ArrayList<>();
2117
                        if (filteredFranchiseeVisitsMap != null) {
2118
                            authfranchiseeVisit = filteredFranchiseeVisitsMap.get(auth.getId());
31249 tejbeer 2119
 
31677 amit.gupta 2120
                        }
31249 tejbeer 2121
 
31677 amit.gupta 2122
                        if (authfranchiseeVisit != null && !authfranchiseeVisit.isEmpty()) {
2123
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2124
 
31677 amit.gupta 2125
                            for (FranchiseeVisit franchiseeVisit : authfranchiseeVisit) {
31249 tejbeer 2126
 
31677 amit.gupta 2127
                                VisitRequest visitRequest = visitRequests.stream()
2128
                                        .filter(x -> x.getVisitId() == franchiseeVisit.getId()
2129
                                                && x.getCreatedBy() == franchiseeVisit.getAuthId())
2130
                                        .findAny().orElse(null);
31249 tejbeer 2131
 
35415 amit 2132
                                CustomRetailer customRetailer = allRetailersMap.get(franchiseeVisit.getFofoId());
31677 amit.gupta 2133
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2134
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2135
                                visitDescriptionModel.setVisitName(franchiseeVisit.getPartnerName());
35415 amit 2136
                                if (customRetailer != null && customRetailer.getAddress() != null) {
2137
                                    visitDescriptionModel.setCity(customRetailer.getAddress().getCity());
2138
                                    visitDescriptionModel.setState(customRetailer.getAddress().getState());
2139
                                }
31677 amit.gupta 2140
                                visitDescriptionModel.setScheduleTime(
2141
                                        franchiseeVisit.getFranchiseeActivity().getSchelduleTimestamp());
2142
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2143
                                visitDescriptionModel.setRemarks(franchiseeVisit.getAgenda());
2144
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
31249 tejbeer 2145
 
31677 amit.gupta 2146
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2147
 
31677 amit.gupta 2148
                            }
2149
                        }
31249 tejbeer 2150
 
31677 amit.gupta 2151
                        userVisitModel.setVisitDescriptions(visitDescriptions);
2152
                        LOGGER.info("userVisit {}", userVisitModel);
31249 tejbeer 2153
 
31677 amit.gupta 2154
                        if (userVisitModel.getAuthUser() != null) {
2155
                            userVisits.add(userVisitModel);
2156
                        }
31249 tejbeer 2157
 
31677 amit.gupta 2158
                    }
31249 tejbeer 2159
 
31677 amit.gupta 2160
                    visitSummaryModel.setUserVisits(userVisits);
31249 tejbeer 2161
 
31677 amit.gupta 2162
                    visitSummary.add(visitSummaryModel);
31249 tejbeer 2163
 
31677 amit.gupta 2164
                }
31249 tejbeer 2165
 
31677 amit.gupta 2166
            }
31249 tejbeer 2167
 
31677 amit.gupta 2168
        }
2169
        return responseSender.ok(visitSummary);
31249 tejbeer 2170
 
31677 amit.gupta 2171
    }
31249 tejbeer 2172
 
31677 amit.gupta 2173
    @RequestMapping(value = "/visitRequest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2174
    public ResponseEntity<?> visitRequest(HttpServletRequest request, @RequestParam(name = "gmailId") String
2175
                                                  gmailId,
31677 amit.gupta 2176
                                          @RequestParam(name = "visitId") int visitId, @RequestParam(name = "status") VisitStatus status, Model model)
2177
            throws Exception {
2178
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 2179
 
31677 amit.gupta 2180
        VisitRequest visitRequest = visitRequestRepository.selectById(visitId);
2181
        visitRequest.setActionedBy(authUser.getId());
2182
        visitRequest.setStatus(status);
2183
        visitRequest.setUpdatedTimestamp(LocalDateTime.now());
2184
        if (status.equals(VisitStatus.approved)) {
2185
            visitRequest.setApprovedTimestamp(LocalDateTime.now());
2186
        }
31249 tejbeer 2187
 
31677 amit.gupta 2188
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
2189
        sendNotificationModel.setCampaignName("Visit Request");
2190
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2191
        sendNotificationModel.setTitle("Visit Request");
2192
        String message = "Visit Request has been " + status + " for scheduled time on "
2193
                + visitRequest.getScheduleTimestamp().toLocalDate();
31249 tejbeer 2194
 
31677 amit.gupta 2195
        sendNotificationModel.setMessage(message);
2196
        sendNotificationModel.setMessageType(MessageType.notification);
2197
        User user = userRepository.selectByEmailId(gmailId);
2198
        sendNotificationModel.setUserIds(new ArrayList<>(user.getId()));
31249 tejbeer 2199
 
31677 amit.gupta 2200
        notificationService.sendNotificationToAll(sendNotificationModel);
31249 tejbeer 2201
 
31677 amit.gupta 2202
        return responseSender.ok(true);
31249 tejbeer 2203
 
31677 amit.gupta 2204
    }
31249 tejbeer 2205
 
34301 ranu 2206
    @Autowired
2207
    RbmRatingRepository rbmRatingRepository;
2208
 
34322 ranu 2209
    @Autowired
2210
    SalesRatingRepository salesRatingRepository;
2211
 
34301 ranu 2212
    @RequestMapping(value = "/rbmRating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2213
    public ResponseEntity<?> rbmRating(HttpServletRequest request, @RequestBody RbmSalesRatingRequest
2214
            rbmSalesRatingRequest, Model model) throws Exception {
34301 ranu 2215
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2216
        UserCart uc = userAccountRepository.getUserCart(userId);
2217
        int fofoId = uc.getUserId();
34322 ranu 2218
 
34301 ranu 2219
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
34322 ranu 2220
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
34301 ranu 2221
 
36114 ranu 2222
        // Calculate current week boundaries (Monday to Sunday)
2223
        LocalDate today = LocalDate.now();
2224
        LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
2225
        LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
2226
        LocalDateTime startOfWeekDateTime = startOfWeek.atStartOfDay();
2227
        LocalDateTime endOfWeekDateTime = endOfWeek.atTime(23, 59, 59);
34301 ranu 2228
 
36114 ranu 2229
        // Check if RBM rating already exists for this week
2230
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfWeekDateTime, endOfWeekDateTime);
34322 ranu 2231
        if (!existingRbmRatings.isEmpty()) {
36114 ranu 2232
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rating for this week already exists.");
34301 ranu 2233
        }
2234
 
36114 ranu 2235
        // Check if Sales Person rating already exists for this week
2236
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfWeekDateTime, endOfWeekDateTime);
34322 ranu 2237
        if (!existingSalesRatings.isEmpty()) {
36114 ranu 2238
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rating for this week already exists.");
34322 ranu 2239
        }
34301 ranu 2240
 
34322 ranu 2241
        // Save RBM rating
34301 ranu 2242
        RbmRating rbmRating = new RbmRating();
34322 ranu 2243
        rbmRating.setComment(rbmSalesRatingRequest.getRbmComment());
2244
        rbmRating.setRating(rbmSalesRatingRequest.getRbmRating());
34301 ranu 2245
        rbmRating.setFofoId(fofoId);
2246
        rbmRating.setRbmId(rbmL1);
2247
        rbmRating.setCreateTimeStamp(LocalDateTime.now());
2248
        rbmRatingRepository.persist(rbmRating);
2249
 
34322 ranu 2250
        // Save Sales Person rating
2251
        SalesRating salesRating = new SalesRating();
2252
        salesRating.setComment(rbmSalesRatingRequest.getSalesComment());
2253
        salesRating.setRating(rbmSalesRatingRequest.getSalesRating());
2254
        salesRating.setFofoId(fofoId);
2255
        salesRating.setSalesL1Id(salesL1Id);
2256
        salesRating.setCreateTimeStamp(LocalDateTime.now());
2257
        salesRatingRepository.persist(salesRating);
2258
 
2259
        return responseSender.ok("Rating submitted successfully.");
34301 ranu 2260
    }
2261
 
2262
 
30077 tejbeer 2263
}