Subversion Repositories SmartDukaan

Rev

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