Subversion Repositories SmartDukaan

Rev

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