Subversion Repositories SmartDukaan

Rev

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

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