Subversion Repositories SmartDukaan

Rev

Rev 35630 | Rev 35649 | 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
        LOGGER.info("PERF: selectByGmailId took {} ms", System.currentTimeMillis() - lapTime);
838
        lapTime = System.currentTimeMillis();
839
 
840
        // Optimized: get partner IDs only for this specific user instead of ALL users
841
        Set<Integer> fofoIds = csService.getPartnerIdsByAuthUserId(authUser.getId());
842
        LOGGER.info("PERF: getPartnerIdsByAuthUserId took {} ms", System.currentTimeMillis() - lapTime);
843
        lapTime = System.currentTimeMillis();
31677 amit.gupta 844
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
30078 tejbeer 845
 
31677 amit.gupta 846
        float totalPartnerTargetSecondary = 0;
847
        float totalPartnerTargetCollection = 0;
848
        float totalPartnerAchievementSecondary = 0;
849
        float totalPartnerAchievementCollection = 0;
850
        TargetModel tm = new TargetModel();
851
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
35632 ranu 852
        Map<Integer, Long> partnerTicketCount = new HashMap<>(); // Will be populated after we have fofoIdList
30416 tejbeer 853
 
31677 amit.gupta 854
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
30077 tejbeer 855
 
31677 amit.gupta 856
        if (fofoIds != null && fofoIds.size() > 0) {
32737 amit.gupta 857
            LOGGER.info("fofoIds {}", fofoIds);
31727 amit.gupta 858
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
31677 amit.gupta 859
                    .filter(x -> (!x.isInternal() && (activationType == null || x.getActivationType().equals(activationType))))
860
                    .map(x -> x.getId()).collect(Collectors.toList());
35632 ranu 861
            LOGGER.info("PERF: selectByRetailerIds took {} ms", System.currentTimeMillis() - lapTime);
862
            lapTime = System.currentTimeMillis();
863
            LOGGER.info("fofoIdList size: {}", fofoIdList.size());
864
 
865
            // Optimized: fetch ticket counts only for specific fofoIds instead of all retailers
866
            if (!fofoIdList.isEmpty()) {
867
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
868
            }
869
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
870
            lapTime = System.currentTimeMillis();
31677 amit.gupta 871
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
30077 tejbeer 872
 
31677 amit.gupta 873
            if (dayValue.equals("previous")) {
874
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
30138 tejbeer 875
 
31677 amit.gupta 876
            }
30087 tejbeer 877
 
31686 amit.gupta 878
            if (fofoIdList.size() > 0) {
30453 tejbeer 879
 
35632 ranu 880
                // Fetch fofoIds with overdue loans (pending amount > 0 and created > 15 days ago)
881
                // Optimized: returns only fofoIds, not full Loan objects
882
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
883
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
884
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
885
                lapTime = System.currentTimeMillis();
886
 
887
                // Fetch fofoIds with MTD billing above threshold (20000)
888
                // Optimized: direct query on orders table instead of complex RBM query
889
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
890
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
891
                long billingThreshold = 20000L; // Same as RbmWeeklyBillingModel.BILLING_THRESHOLD
892
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
893
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
894
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
895
                lapTime = System.currentTimeMillis();
896
 
35079 vikas 897
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
35632 ranu 898
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
899
                lapTime = System.currentTimeMillis();
30087 tejbeer 900
 
31686 amit.gupta 901
                if (!partnerDailyInvestments.isEmpty()) {
35079 vikas 902
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31686 amit.gupta 903
                }
30077 tejbeer 904
 
35632 ranu 905
                // Optimized: fetch only specific fofoIds instead of all retailers
906
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
907
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
908
                lapTime = System.currentTimeMillis();
30426 tejbeer 909
 
31686 amit.gupta 910
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
35632 ranu 911
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
912
                lapTime = System.currentTimeMillis();
30453 tejbeer 913
 
31686 amit.gupta 914
                long todayCollectionCount = 0;
915
                if (!remarkIds.isEmpty()) {
916
                    todayCollectionCount = partnerCollectionRemarkRepository
917
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
918
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
919
                            .collect(Collectors.counting());
30453 tejbeer 920
 
31686 amit.gupta 921
                }
35632 ranu 922
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
923
                lapTime = System.currentTimeMillis();
30330 tejbeer 924
 
35079 vikas 925
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
35632 ranu 926
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
927
                lapTime = System.currentTimeMillis();
30077 tejbeer 928
 
32978 amit.gupta 929
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
31686 amit.gupta 930
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
931
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
35632 ranu 932
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
933
                lapTime = System.currentTimeMillis();
30077 tejbeer 934
 
35415 amit 935
                // Pre-fetch all AuthUsers that might be needed (instead of N+1 queries)
936
                Set<Integer> allAuthIds = new HashSet<>();
937
                collectionMap.values().stream()
938
                        .map(PartnerCollectionPlanModel::getAuthId)
939
                        .filter(id -> id != null && id != authUser.getId())
940
                        .forEach(allAuthIds::add);
941
                partnerSecondaryPlans.values().stream()
942
                        .flatMap(List::stream)
943
                        .map(PartnerSecondaryPlanModel::getAuthId)
944
                        .filter(id -> id != null && id != authUser.getId())
945
                        .forEach(allAuthIds::add);
946
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
947
                if (!allAuthIds.isEmpty()) {
948
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
949
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
950
                }
951
 
32978 amit.gupta 952
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
31686 amit.gupta 953
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
954
                    int fofoId = customRetailerEntry.getKey();
955
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
956
                    float totalSecondaryPlan = 0;
957
                    float totalSecondaryAchivement = 0;
30077 tejbeer 958
 
31686 amit.gupta 959
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
960
                    ptam.setFofoId(fofoId);
961
                    ptam.setBusinessName(customRetailer.getBusinessName());
962
                    ptam.setMobile(customRetailer.getMobileNumber());
30087 tejbeer 963
 
31686 amit.gupta 964
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
965
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
966
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
967
                    }
30808 tejbeer 968
 
32978 amit.gupta 969
                    if (collectionMap.get(fofoId) != null) {
970
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
30330 tejbeer 971
 
31686 amit.gupta 972
                        ptam.setRemark(collectionPlan.getRemark());
973
                        ptam.setMessage(collectionPlan.getMessage());
974
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
35632 ranu 975
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
31686 amit.gupta 976
                        ptam.setRank(collectionPlan.getRank());
977
                        Integer authId = collectionPlan.getAuthId();
30330 tejbeer 978
 
31686 amit.gupta 979
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
30416 tejbeer 980
 
31686 amit.gupta 981
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
30077 tejbeer 982
 
31686 amit.gupta 983
                        LOGGER.info("authId" + authId);
30137 tejbeer 984
 
31686 amit.gupta 985
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
986
                            float targetCollection = 0;
30330 tejbeer 987
 
31686 amit.gupta 988
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
989
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
990
                            } else {
991
                                targetCollection = collectionPlan.getTargetPlan();
31677 amit.gupta 992
                            }
30451 tejbeer 993
 
31677 amit.gupta 994
                            if (authId != null && authId == authUser.getId()) {
31686 amit.gupta 995
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
996
                                    totalPartnerTargetCollection += targetCollection;
997
                                }
31677 amit.gupta 998
                            }
31686 amit.gupta 999
                            ptam.setCollectionTarget(targetCollection);
1000
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1001
                                    && collectionPlan.getWalletTimestamp() != null
1002
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1003
                                if (authId != null && authId == authUser.getId()) {
1004
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1005
                                }
1006
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1007
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1008
                                    && collectionPlan.getAchievementPlan() != null) {
1009
                                if (authId != null && authId == authUser.getId()) {
1010
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1011
                                }
1012
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1013
 
31677 amit.gupta 1014
                            }
31686 amit.gupta 1015
                        }
30822 tejbeer 1016
 
31686 amit.gupta 1017
                        if (authId != null && authId != authUser.getId()) {
35415 amit 1018
                            ptam.setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1019
 
31677 amit.gupta 1020
                        }
30087 tejbeer 1021
 
31686 amit.gupta 1022
                        if (collectionPlan.getCommittedDate() != null) {
30087 tejbeer 1023
 
31686 amit.gupta 1024
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1025
                        }
30087 tejbeer 1026
 
31677 amit.gupta 1027
                    }
30821 tejbeer 1028
 
31686 amit.gupta 1029
                    // Secondary
30077 tejbeer 1030
 
31686 amit.gupta 1031
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1032
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
32978 amit.gupta 1033
                    if (partnerSecondaryPlans.get(fofoId) != null) {
31686 amit.gupta 1034
                        long otherBrandSecondary = 0;
32978 amit.gupta 1035
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
31686 amit.gupta 1036
                            Integer authId = pspm.getAuthId();
1037
                            if (!brands.contains(pspm.getBrand())) {
1038
                                if (pspm.getAchievementPlan() != null) {
1039
                                    otherBrandSecondary += pspm.getAchievementPlan();
1040
                                }
1041
                            } else {
1042
                                otherPartnerSecondaryPlanModel = pspm;
1043
                            }
1044
                            if (pspm.getTargetPlan() != null) {
1045
                                totalSecondaryPlan += pspm.getTargetPlan();
1046
                            }
30330 tejbeer 1047
 
31677 amit.gupta 1048
                            if (pspm.getAchievementPlan() != null) {
31686 amit.gupta 1049
                                totalSecondaryAchivement += pspm.getAchievementPlan();
31677 amit.gupta 1050
                            }
30087 tejbeer 1051
 
31686 amit.gupta 1052
                            if (pspm.getCommittedDate() != null) {
30137 tejbeer 1053
 
31686 amit.gupta 1054
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1055
                            }
1056
                            if (authId != null && authId == authUser.getId()) {
30137 tejbeer 1057
 
31686 amit.gupta 1058
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
30087 tejbeer 1059
 
31686 amit.gupta 1060
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1061
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1062
                                    }
1063
                                }
30087 tejbeer 1064
 
31686 amit.gupta 1065
                                if (pspm.getAchievementPlan() != null) {
1066
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
31677 amit.gupta 1067
                                }
31686 amit.gupta 1068
 
31677 amit.gupta 1069
                            }
31686 amit.gupta 1070
                        }
1071
                        if (otherPartnerSecondaryPlanModel != null) {
1072
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1073
                        }
32978 amit.gupta 1074
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
31686 amit.gupta 1075
                                .filter(x -> brands.contains(x.getBrand()))
1076
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30087 tejbeer 1077
 
31686 amit.gupta 1078
                        if (secondaryModelMap.containsKey("Others")) {
1079
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1080
                            psp.setAchievementPlan(otherBrandSecondary);
1081
                        } else {
35079 vikas 1082
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
31686 amit.gupta 1083
                        }
1084
                        for (String brand : brands) {
1085
                            if (!secondaryModelMap.containsKey(brand)) {
35079 vikas 1086
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
31677 amit.gupta 1087
                            }
31686 amit.gupta 1088
                        }
30087 tejbeer 1089
 
31686 amit.gupta 1090
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1091
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1092
                            if (authId != null && authId != authUser.getId()) {
35415 amit 1093
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1094
                                ptam.setSecondaryColor("red");
1095
                            }
1096
 
31677 amit.gupta 1097
                        }
30077 tejbeer 1098
 
31686 amit.gupta 1099
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1100
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1101
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1102
                        // Secondary
1103
 
31677 amit.gupta 1104
                    } else {
31686 amit.gupta 1105
                        for (String brand : brands) {
1106
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1107
                            pspm.setAchievementPlan((long) 0);
1108
                            pspm.setTargetPlan((long) 0);
1109
                            pspm.setBrand(brand);
1110
                            pspm.setFofoId(fofoId);
1111
                            secondaryModelMap.put(brand, pspm);
31677 amit.gupta 1112
                        }
31686 amit.gupta 1113
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
31677 amit.gupta 1114
                    }
30077 tejbeer 1115
 
31686 amit.gupta 1116
                    if (!partnerTicketCount.isEmpty()) {
1117
                        if (partnerTicketCount.get(fofoId) != null) {
1118
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
1119
                        } else {
1120
                            ptam.setTicketCount(0);
1121
 
31677 amit.gupta 1122
                        }
1123
                    }
30087 tejbeer 1124
 
35632 ranu 1125
                    // Category Assignment Logic (Priority: PLAN_TODAY > CARRY_FORWARD > ZERO_BILLED > UNTOUCHED > NORMAL)
1126
                    // Check if partner has credit due (loans > 15 days with pending amount) - just a flag, doesn't affect sorting
1127
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
1128
                    ptam.setHasOverdue(hasCreditDue);
1129
 
1130
                    // Default rank to 5 (Normal) if no collection plan exists
1131
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
1132
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1133
 
1134
                    // Assign category based on rank (overdue is just a flag, doesn't affect category)
1135
                    if (rank == 1) {
1136
                        ptam.setCategory("PLAN_TODAY");
1137
                        ptam.setCategoryPriority(1);
1138
                    } else if (rank == 2) {
1139
                        ptam.setCategory("CARRY_FORWARD");
1140
                        ptam.setCategoryPriority(2);
1141
                    } else if (hasZeroBilling && rank < 5) {
1142
                        // Zero billed only if NOT in normal category (rank 5+)
1143
                        // If rank is 1,2,3,4 and has zero billing, include in ZERO_BILLED
1144
                        ptam.setCategory("ZERO_BILLED");
1145
                        ptam.setCategoryPriority(3);
1146
                    } else if (rank == 3) {
1147
                        ptam.setCategory("UNTOUCHED");
1148
                        ptam.setCategoryPriority(4);
1149
                    } else {
1150
                        // rank 4 (future plan) and rank 5+ (normal) go to NORMAL
1151
                        // Also, zero billing with rank 5+ goes to NORMAL (not ZERO_BILLED)
1152
                        ptam.setCategory("NORMAL");
1153
                        ptam.setCategoryPriority(5);
1154
                    }
1155
 
31686 amit.gupta 1156
                    ptams.add(ptam);
30077 tejbeer 1157
 
31677 amit.gupta 1158
                }
32923 ranu 1159
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
30077 tejbeer 1160
 
32923 ranu 1161
                LOGGER.info("positions {}", positions);
1162
 
35079 vikas 1163
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
1164
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
32923 ranu 1165
 
34118 tejus.loha 1166
                LOGGER.info("isRBMAndL1{}", isRBMAndL1);
32923 ranu 1167
 
35079 vikas 1168
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
32923 ranu 1169
 
31686 amit.gupta 1170
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
1171
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
1172
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
1173
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
1174
                tm.setTodayCollectionCount((int) todayCollectionCount);
32923 ranu 1175
                List<PartnerTargetAchievementModel> filteredPtams;
30416 tejbeer 1176
 
32923 ranu 1177
                if (isRBMAndL1) {
34428 ranu 1178
                    filteredPtams = ptams;
1179
//                    as of now all party is showing to rbm
1180
                    /*filteredPtams = ptams.stream()
32978 amit.gupta 1181
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34428 ranu 1182
                            .collect(Collectors.toList());*/
32923 ranu 1183
                } else if (isRBMAndNotL1) {
34429 ranu 1184
                    filteredPtams = ptams;
1185
                    /*filteredPtams = ptams.stream()
32923 ranu 1186
                            .filter(ptam -> !(CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34429 ranu 1187
                            .collect(Collectors.toList());*/
33041 ranu 1188
                } else if (isSales) {
1189
                    filteredPtams = ptams.stream()
1190
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark())))
1191
                            .collect(Collectors.toList());
32923 ranu 1192
                } else {
1193
                    filteredPtams = ptams;
1194
                }
34428 ranu 1195
                tm.setRBMAndL1(isRBMAndL1);
1196
                tm.setRBMAndNotL1(isRBMAndNotL1);
1197
                tm.setSales(isSales);
35632 ranu 1198
 
1199
                // Calculate category counts
1200
                Map<String, Long> categoryCounts = filteredPtams.stream()
1201
                        .collect(Collectors.groupingBy(
1202
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
1203
                                Collectors.counting()));
1204
                // Count parties with overdue flag (independent of category)
1205
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
1206
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
1207
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
1208
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
1209
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
1210
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
1211
 
1212
                // Sort by: 1) Partners with today's remark go to bottom of entire list
1213
                //          EXCEPT: NO_ANSWER remark older than 2 hours comes back to original position
1214
                //          2) Category Priority (PLAN_TODAY=1, CARRY_FORWARD=2, ZERO_BILLED=3, UNTOUCHED=4, NORMAL=5)
1215
                //          3) Then by rank
1216
                LocalDateTime twoHoursAgo = LocalDateTime.now().minusHours(2);
34796 ranu 1217
                tm.setTargetAchievement(filteredPtams.stream()
1218
                        .sorted(Comparator
35632 ranu 1219
                                .comparing((PartnerTargetAchievementModel p) -> {
1220
                                    if (p.getRemarkTimestamp() == null) {
1221
                                        return false; // No remark → comes first
1222
                                    }
1223
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
1224
                                    if (!remarkDate.equals(LocalDate.now())) {
1225
                                        return false; // Not today's remark → comes first
1226
                                    }
1227
                                    // Today's remark - check if NO_ANSWER and older than 2 hours
1228
                                    if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
1229
                                            && p.getRemarkTimestamp().isBefore(twoHoursAgo)) {
1230
                                        return false; // NO_ANSWER older than 2 hours → comes back up
1231
                                    }
1232
                                    return true; // Other today's remarks → goes to bottom
1233
                                }) // false → comes first, true → goes to bottom
1234
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
34796 ranu 1235
                                .thenComparing(PartnerTargetAchievementModel::getRank)
1236
                        )
31686 amit.gupta 1237
                        .collect(Collectors.toList()));
30416 tejbeer 1238
 
34796 ranu 1239
 
31677 amit.gupta 1240
            }
30077 tejbeer 1241
 
31677 amit.gupta 1242
        }
35632 ranu 1243
        LOGGER.info("PERF: Total getPartnerTarget took {} ms", System.currentTimeMillis() - startTime);
31677 amit.gupta 1244
        return responseSender.ok(tm);
30077 tejbeer 1245
 
31677 amit.gupta 1246
    }
32737 amit.gupta 1247
 
1248
    //TODO:Amit
31677 amit.gupta 1249
    @RequestMapping(value = "/target", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1250
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1251
    public ResponseEntity<?> createPartnerTarget(HttpServletRequest request,
1252
                                                 @RequestBody PartnerTargetAchievementModel ptam) throws ProfitMandiBusinessException {
30077 tejbeer 1253
 
31677 amit.gupta 1254
        LOGGER.info("ptam" + ptam);
30089 tejbeer 1255
 
31677 amit.gupta 1256
        AuthUser authUser = authRepository.selectByGmailId(ptam.getCreatedBy());
30077 tejbeer 1257
 
31677 amit.gupta 1258
        if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
1259
                || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
1260
            PartnerCollectionPlan partnerCollectionPlan = partnerCollectionPlanRepository
1261
                    .selectByLocalDate(LocalDate.now(), ptam.getFofoId(), true);
1262
            LOGGER.info("pcp" + partnerCollectionPlan);
30077 tejbeer 1263
 
31677 amit.gupta 1264
            if (partnerCollectionPlan == null) {
1265
                if (ptam.getCollectionTarget() > 0) {
30087 tejbeer 1266
 
31677 amit.gupta 1267
                    partnerCollectionPlan = new PartnerCollectionPlan();
1268
                    partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
1269
                    partnerCollectionPlan.setAuthId(authUser.getId());
1270
                    partnerCollectionPlan.setFofoId(ptam.getFofoId());
1271
                    partnerCollectionPlan.setActive(true);
1272
                    partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1273
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1274
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1275
                    partnerCollectionPlanRepository.persist(partnerCollectionPlan);
30416 tejbeer 1276
 
31677 amit.gupta 1277
                }
30087 tejbeer 1278
 
31677 amit.gupta 1279
            } else {
30087 tejbeer 1280
 
31677 amit.gupta 1281
                if (partnerCollectionPlan.getCollectionPlan() != ptam.getCollectionTarget()) {
1282
                    float totalCollectionPlan = partnerCollectionPlan.getCollectionPlan() + 10000;
1283
                    if (authUser.getId() == partnerCollectionPlan.getAuthId()) {
30087 tejbeer 1284
 
31677 amit.gupta 1285
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1286
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1287
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
1288
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1289
                            partnerCollectionPlan.setActive(true);
1290
                            partnerCollectionPlan
1291
                                    .setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1292
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1293
                        } else {
1294
                            throw new ProfitMandiBusinessException("collection target", "",
1295
                                    "collection target should be more than " + totalCollectionPlan);
1296
                        }
30087 tejbeer 1297
 
31677 amit.gupta 1298
                    } else {
30137 tejbeer 1299
 
31677 amit.gupta 1300
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1301
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1302
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
30137 tejbeer 1303
 
31677 amit.gupta 1304
                            partnerCollectionPlan.setActive(false);
1305
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1306
                            partnerCollectionPlan = new PartnerCollectionPlan();
1307
                            partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
1308
                            partnerCollectionPlan.setAuthId(authUser.getId());
1309
                            partnerCollectionPlan.setFofoId(ptam.getFofoId());
1310
                            partnerCollectionPlan.setActive(true);
1311
                            partnerCollectionPlan
1312
                                    .setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1313
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
1314
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1315
                            partnerCollectionPlanRepository.persist(partnerCollectionPlan);
1316
                        } else {
1317
                            throw new ProfitMandiBusinessException("collection target", "",
1318
                                    "collection target should be more than " + totalCollectionPlan);
1319
                        }
1320
                    }
1321
                }
30137 tejbeer 1322
 
31677 amit.gupta 1323
                if ((LocalDate.now().atStartOfDay().equals(ptam.getCollectionCommitmentDate().atStartOfDay())
1324
                        || ptam.getCollectionCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
1325
                        && partnerCollectionPlan.getCollectionPlan() == ptam.getCollectionTarget()) {
1326
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
1327
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
1328
                }
30416 tejbeer 1329
 
31677 amit.gupta 1330
            }
30433 tejbeer 1331
 
31677 amit.gupta 1332
            PartnerCollectionRemark pcr = new PartnerCollectionRemark();
1333
            pcr.setFofoId(ptam.getFofoId());
1334
            pcr.setAuthId(authUser.getId());
1335
            pcr.setMessage("Collection plan for" + ptam.getCollectionCommitmentDate());
1336
            pcr.setRemark(CollectionRemark.COLLECTION_PLAN);
1337
            pcr.setCreateTimestamp(LocalDateTime.now());
1338
            partnerCollectionRemarkRepository.persist(pcr);
1339
        } else {
1340
            throw new ProfitMandiBusinessException("Date", "",
1341
                    "you can't select the back date " + ptam.getCollectionCommitmentDate());
1342
        }
30077 tejbeer 1343
 
31677 amit.gupta 1344
        for (Entry<String, PartnerSecondaryPlanModel> pspm : ptam.getPartnerSecondaryModel().entrySet()) {
30087 tejbeer 1345
 
31677 amit.gupta 1346
            if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
1347
                    || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
1348
                PartnerSecondaryPlanModel plan = pspm.getValue();
1349
                PartnerSecondaryPlan psp = partnerSecondaryPlanRepository.selectByLocalDateBrand(plan.getBrand(),
1350
                        LocalDate.now(), ptam.getFofoId(), true);
1351
                LOGGER.info("psp" + psp);
30087 tejbeer 1352
 
31677 amit.gupta 1353
                if (psp == null) {
1354
                    if (plan.getTargetPlan() != null && plan.getTargetPlan() > 0) {
30087 tejbeer 1355
 
31677 amit.gupta 1356
                        psp = new PartnerSecondaryPlan();
1357
                        psp.setAuthId(authUser.getId());
1358
                        psp.setBrand(pspm.getKey());
1359
                        psp.setFofoId(pspm.getValue().getFofoId());
1360
                        psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1361
                        psp.setCreateTimestamp(LocalDateTime.now());
1362
                        psp.setUpdatedTimestamp(LocalDateTime.now());
1363
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1364
                        psp.setActive(true);
1365
                        partnerSecondaryPlanRepository.persist(psp);
1366
                    }
30087 tejbeer 1367
 
31677 amit.gupta 1368
                } else {
1369
                    if (plan.getTargetPlan() != psp.getSecondaryPlan()) {
1370
                        float totalSecondaryPlan = psp.getSecondaryPlan() + 10000;
1371
                        if (authUser.getId() == plan.getAuthId()) {
1372
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1373
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1374
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
1375
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1376
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1377
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1378
                                psp.setActive(true);
1379
                            } else {
1380
                                throw new ProfitMandiBusinessException("secondary target", "",
1381
                                        "secondary target should be more than " + totalSecondaryPlan);
1382
                            }
30087 tejbeer 1383
 
31677 amit.gupta 1384
                        } else {
30087 tejbeer 1385
 
31677 amit.gupta 1386
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
1387
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
1388
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
30087 tejbeer 1389
 
31677 amit.gupta 1390
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1391
                                psp.setActive(false);
1392
                                psp = new PartnerSecondaryPlan();
1393
                                psp.setAuthId(authUser.getId());
1394
                                psp.setBrand(pspm.getKey());
1395
                                psp.setFofoId(pspm.getValue().getFofoId());
1396
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
1397
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1398
                                psp.setCreateTimestamp(LocalDateTime.now());
1399
                                psp.setUpdatedTimestamp(LocalDateTime.now());
1400
                                psp.setActive(true);
1401
                                partnerSecondaryPlanRepository.persist(psp);
1402
                            } else {
1403
                                throw new ProfitMandiBusinessException("secondary target", "",
1404
                                        "secondary target should be more than " + totalSecondaryPlan);
1405
                            }
1406
                        }
1407
                    }
30137 tejbeer 1408
 
31677 amit.gupta 1409
                    if ((LocalDate.now().atStartOfDay().equals(ptam.getSecondaryCommitmentDate().atStartOfDay())
1410
                            || ptam.getSecondaryCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
1411
                            && plan.getTargetPlan() == psp.getSecondaryPlan()) {
1412
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
1413
                        psp.setUpdatedTimestamp(LocalDateTime.now());
1414
                    }
30137 tejbeer 1415
 
31677 amit.gupta 1416
                }
1417
            } else {
1418
                throw new ProfitMandiBusinessException("Date", "",
1419
                        "you can't select the back date " + ptam.getSecondaryCommitmentDate());
1420
            }
30137 tejbeer 1421
 
31677 amit.gupta 1422
        }
30077 tejbeer 1423
 
31677 amit.gupta 1424
        return responseSender.ok(true);
30137 tejbeer 1425
 
31677 amit.gupta 1426
    }
30077 tejbeer 1427
 
31677 amit.gupta 1428
    @RequestMapping(value = "/uploadFranchiseeVisit", method = RequestMethod.POST)
35288 amit 1429
    public ResponseEntity<?> readCsvFileAndSetLead(HttpServletRequest request, @RequestPart MultipartFile
1430
            multipartFile) throws Throwable {
30433 tejbeer 1431
 
31677 amit.gupta 1432
        int id = (int) request.getAttribute("userId");
30433 tejbeer 1433
 
31677 amit.gupta 1434
        LOGGER.info("id" + id);
30433 tejbeer 1435
 
31677 amit.gupta 1436
        User user = userRepository.selectById(id);
30433 tejbeer 1437
 
31677 amit.gupta 1438
        AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());
30433 tejbeer 1439
 
31677 amit.gupta 1440
        String fileName = multipartFile.getName();
1441
        String fileNames = multipartFile.getOriginalFilename();
30433 tejbeer 1442
 
31677 amit.gupta 1443
        LOGGER.info("fileName" + fileName);
1444
        LOGGER.info("fileNames" + fileNames);
30433 tejbeer 1445
 
31677 amit.gupta 1446
        List<CSVRecord> records = FileUtil.readFile(multipartFile);
30433 tejbeer 1447
 
31677 amit.gupta 1448
        for (CSVRecord record : records) {
1449
            FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
1450
            franchiseeVisit.setFofoId(Integer.parseInt(record.get(0)));
1451
            CustomRetailer customRetailer = retailerService.getFofoRetailer(Integer.parseInt(record.get(0)));
30433 tejbeer 1452
 
31677 amit.gupta 1453
            franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
1454
            franchiseeVisit.setAgenda(record.get(1));
1455
            franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
1456
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1457
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
30433 tejbeer 1458
 
31677 amit.gupta 1459
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
1460
            LOGGER.info(record.get(1));
1461
            LocalDate dateTime = LocalDate.parse(record.get(2), formatter);
30433 tejbeer 1462
 
31677 amit.gupta 1463
            franchiseeVisit.setScheduleTimestamp(dateTime.atStartOfDay());
1464
            // change
30433 tejbeer 1465
 
31677 amit.gupta 1466
            String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
1467
            franchiseeVisit.setCreatedBy(authUserName);
1468
            franchiseeVisit.setAuthId(authUser.getId());
30433 tejbeer 1469
 
31677 amit.gupta 1470
            franchiseeVisitRepository.persist(franchiseeVisit);
30433 tejbeer 1471
 
31677 amit.gupta 1472
            return responseSender.ok(true);
1473
        }
30433 tejbeer 1474
 
31677 amit.gupta 1475
        return responseSender.ok(true);
30433 tejbeer 1476
 
31677 amit.gupta 1477
    }
30487 tejbeer 1478
 
31677 amit.gupta 1479
    @RequestMapping(value = "/downloadFranchiseeVisitTemplate", method = RequestMethod.GET)
1480
    public ResponseEntity<?> downloadFranchiseeVisitTemplate(HttpServletRequest request) throws Exception {
30487 tejbeer 1481
 
31677 amit.gupta 1482
        // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
30487 tejbeer 1483
 
31677 amit.gupta 1484
        List<List<?>> rows = new ArrayList<>();
30487 tejbeer 1485
 
32923 ranu 1486
        ByteArrayOutputStream byteArrayOutputStream = FileUtil
31677 amit.gupta 1487
                .getCSVByteStream(Arrays.asList("Partner Id", "Agenda", "Schedule Timestamp"), rows);
30487 tejbeer 1488
 
31677 amit.gupta 1489
        try {
1490
            byteArrayOutputStream.close();
1491
        } catch (IOException e) {
1492
            // TODO Auto-generated catch block
1493
            e.printStackTrace();
1494
        }
30487 tejbeer 1495
 
31677 amit.gupta 1496
        String filename = "template.csv";
1497
        HttpHeaders headers = new HttpHeaders();
1498
        headers.add("Content-Type", "application/csv");
1499
        headers.setContentDispositionFormData(filename, filename);
30487 tejbeer 1500
 
31677 amit.gupta 1501
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
30487 tejbeer 1502
 
31677 amit.gupta 1503
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
1504
                HttpStatus.OK);
1505
        return response;
30544 tejbeer 1506
 
31677 amit.gupta 1507
    }
30542 tejbeer 1508
 
31677 amit.gupta 1509
    @RequestMapping(value = "/markVisitAttendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
1510
    public ResponseEntity<?> markVisitAttendance(HttpServletRequest request, @RequestParam(name = "id") int id)
1511
            throws ProfitMandiBusinessException {
1512
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
30542 tejbeer 1513
 
31677 amit.gupta 1514
        franchiseeVisit.setVisitTimestamp(LocalDateTime.now());
30542 tejbeer 1515
 
31677 amit.gupta 1516
        return responseSender.ok(true);
30542 tejbeer 1517
 
31677 amit.gupta 1518
    }
31249 tejbeer 1519
 
31677 amit.gupta 1520
    @RequestMapping(value = "/getVisitRequests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1521
    public ResponseEntity<?> getVisitRequests(HttpServletRequest request,
1522
                                              @RequestParam(name = "gmailId") String gmailId, Model model) throws Exception {
31249 tejbeer 1523
 
31677 amit.gupta 1524
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 1525
 
31677 amit.gupta 1526
        List<Integer> authUserIds = authService.getAllReportees(authUser.getId());
1527
        List<VisitSummaryModel> visitSummary = new ArrayList<>();
31249 tejbeer 1528
 
31677 amit.gupta 1529
        if (!authUserIds.isEmpty()) {
35397 amit 1530
            List<AuthUser> authUsers = authRepository.selectByIds(authUserIds);
31249 tejbeer 1531
 
31677 amit.gupta 1532
            List<VisitRequest> allVisitRequests = visitRequestRepository.selectByAuthIdsAndDate(authUserIds,
1533
                    LocalDate.now().minusDays(7), Arrays.asList(VisitStatus.approved, VisitStatus.pending));
1534
            LOGGER.info("allVisitRequests {}", allVisitRequests);
31249 tejbeer 1535
 
31677 amit.gupta 1536
            if (!allVisitRequests.isEmpty()) {
31249 tejbeer 1537
 
31677 amit.gupta 1538
                List<Integer> leadIds = allVisitRequests.stream().filter(x -> x.getVisitType().equals("lead"))
1539
                        .map(x -> x.getVisitId()).collect(Collectors.toList());
1540
                List<Lead> leads = new ArrayList<>();
1541
                if (!leadIds.isEmpty()) {
1542
                    leads = leadRepository.selectAllByIds(leadIds);
31249 tejbeer 1543
 
35415 amit 1544
                    // Batch fetch all LeadActivities instead of N+1
1545
                    List<LeadActivity> allLeadActivities = leadActivityRepository.selectAllByleadIds(leadIds);
1546
                    Map<Integer, List<LeadActivity>> leadActivityMap = allLeadActivities.stream()
1547
                            .collect(Collectors.groupingBy(LeadActivity::getLeadId));
1548
 
31677 amit.gupta 1549
                    for (Lead lead : leads) {
35415 amit 1550
                        List<LeadActivity> leadActivities = leadActivityMap.get(lead.getId());
1551
                        if (leadActivities != null && !leadActivities.isEmpty()) {
1552
                            lead.setScheduledTimestamp(leadActivities.get(0).getSchelduleTimestamp());
1553
                            lead.setLeadActivity(leadActivities.get(0));
1554
                        }
31677 amit.gupta 1555
                    }
1556
                }
1557
                List<Integer> franchiseeIds = allVisitRequests.stream()
1558
                        .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
1559
                        .collect(Collectors.toList());
1560
                List<FranchiseeVisit> franchiseeVisits = new ArrayList<>();
1561
                if (!franchiseeIds.isEmpty()) {
1562
                    franchiseeVisits = franchiseeVisitRepository.selectAllByIds(franchiseeIds);
1563
                    LOGGER.info("franchiseeVisits {}", franchiseeVisits);
31249 tejbeer 1564
 
35415 amit 1565
                    // Batch fetch all FranchiseeActivities instead of N+1
1566
                    List<FranchiseeActivity> allFranchiseeActivities = franchiseeActivityRepository
1567
                            .selectByFranchiseeVisitIds(franchiseeIds);
1568
                    Map<Integer, List<FranchiseeActivity>> franchiseeActivityMap = allFranchiseeActivities.stream()
1569
                            .collect(Collectors.groupingBy(FranchiseeActivity::getFranchiseeVisitd));
1570
 
31677 amit.gupta 1571
                    for (FranchiseeVisit franchiseeVisit : franchiseeVisits) {
35415 amit 1572
                        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityMap.get(franchiseeVisit.getId());
31677 amit.gupta 1573
                        LOGGER.info("franchiseeActivities {}", franchiseeActivities);
31249 tejbeer 1574
 
35415 amit 1575
                        if (franchiseeActivities != null && !franchiseeActivities.isEmpty()) {
1576
                            franchiseeVisit.setScheduleTimestamp(franchiseeActivities.get(0).getSchelduleTimestamp());
1577
                            franchiseeVisit.setFranchiseeActivity(franchiseeActivities.get(0));
1578
                        }
31677 amit.gupta 1579
                    }
31249 tejbeer 1580
 
31677 amit.gupta 1581
                }
31249 tejbeer 1582
 
35415 amit 1583
                // Pre-fetch all retailers using cached method (instead of N+1 getFofoRetailer calls)
1584
                Map<Integer, CustomRetailer> allRetailersMap = retailerService.getAllFofoRetailers();
1585
 
31677 amit.gupta 1586
                Map<LocalDate, List<VisitRequest>> dateWiseVisitRequest = allVisitRequests.stream()
1587
                        .collect(Collectors.groupingBy(x -> x.getScheduleTimestamp().toLocalDate()));
31249 tejbeer 1588
 
31677 amit.gupta 1589
                for (Entry<LocalDate, List<VisitRequest>> visitEntry : dateWiseVisitRequest.entrySet()) {
31249 tejbeer 1590
 
31677 amit.gupta 1591
                    LocalDate date = visitEntry.getKey();
1592
                    List<VisitRequest> visitRequests = visitEntry.getValue();
31249 tejbeer 1593
 
31677 amit.gupta 1594
                    VisitSummaryModel visitSummaryModel = new VisitSummaryModel();
31249 tejbeer 1595
 
31677 amit.gupta 1596
                    visitSummaryModel.setDate(date);
1597
                    List<Integer> dateWiseLeadEntry = visitRequests.stream()
1598
                            .filter(x -> x.getVisitType().equals("lead")).map(x -> x.getVisitId())
1599
                            .collect(Collectors.toList());
31249 tejbeer 1600
 
31677 amit.gupta 1601
                    List<Integer> dateWiseFranchiseeIds = visitRequests.stream()
1602
                            .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
1603
                            .collect(Collectors.toList());
31249 tejbeer 1604
 
31677 amit.gupta 1605
                    Map<Integer, List<Lead>> filteredLeadsMap = null;
1606
                    if (!leads.isEmpty()) {
1607
                        filteredLeadsMap = leads.stream().filter(x -> dateWiseLeadEntry.contains(x.getId()))
1608
                                .collect(Collectors.groupingBy(x -> x.getAssignTo()));
31249 tejbeer 1609
 
31677 amit.gupta 1610
                    }
31249 tejbeer 1611
 
31677 amit.gupta 1612
                    Map<Integer, List<FranchiseeVisit>> filteredFranchiseeVisitsMap = null;
31249 tejbeer 1613
 
31677 amit.gupta 1614
                    if (!franchiseeVisits.isEmpty()) {
1615
                        filteredFranchiseeVisitsMap = franchiseeVisits.stream()
1616
                                .filter(x -> dateWiseFranchiseeIds.contains(x.getId()))
1617
                                .collect(Collectors.groupingBy(x -> x.getAuthId()));
31249 tejbeer 1618
 
31677 amit.gupta 1619
                    }
31249 tejbeer 1620
 
31677 amit.gupta 1621
                    List<UserVisitModel> userVisits = new ArrayList<>();
31249 tejbeer 1622
 
31677 amit.gupta 1623
                    for (AuthUser auth : authUsers) {
1624
                        UserVisitModel userVisitModel = new UserVisitModel();
1625
                        List<VisitDescriptionModel> visitDescriptions = new ArrayList<>();
31249 tejbeer 1626
 
31677 amit.gupta 1627
                        List<Lead> authLeads = new ArrayList<>();
1628
                        if (filteredLeadsMap != null) {
1629
                            authLeads = filteredLeadsMap.get(auth.getId());
31249 tejbeer 1630
 
31677 amit.gupta 1631
                        }
31249 tejbeer 1632
 
31677 amit.gupta 1633
                        if (authLeads != null && !authLeads.isEmpty()) {
1634
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 1635
 
31677 amit.gupta 1636
                            for (Lead lead : authLeads) {
31249 tejbeer 1637
 
31677 amit.gupta 1638
                                VisitRequest visitRequest = visitRequests.stream().filter(
1639
                                                x -> x.getVisitId() == lead.getId() && x.getCreatedBy() == lead.getAssignTo())
1640
                                        .findAny().orElse(null);
1641
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
1642
                                visitDescriptionModel.setVisitId(visitRequest.getId());
1643
                                visitDescriptionModel.setVisitName(lead.getFirstName());
1644
                                visitDescriptionModel.setCity(lead.getCity());
1645
                                visitDescriptionModel.setState(lead.getState());
1646
                                visitDescriptionModel.setScheduleTime(lead.getScheduledTimestamp());
1647
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
1648
                                visitDescriptionModel.setRemarks(lead.getLeadActivity().getRemark());
1649
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
1650
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 1651
 
31677 amit.gupta 1652
                            }
1653
                        }
31249 tejbeer 1654
 
31677 amit.gupta 1655
                        List<FranchiseeVisit> authfranchiseeVisit = new ArrayList<>();
1656
                        if (filteredFranchiseeVisitsMap != null) {
1657
                            authfranchiseeVisit = filteredFranchiseeVisitsMap.get(auth.getId());
31249 tejbeer 1658
 
31677 amit.gupta 1659
                        }
31249 tejbeer 1660
 
31677 amit.gupta 1661
                        if (authfranchiseeVisit != null && !authfranchiseeVisit.isEmpty()) {
1662
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 1663
 
31677 amit.gupta 1664
                            for (FranchiseeVisit franchiseeVisit : authfranchiseeVisit) {
31249 tejbeer 1665
 
31677 amit.gupta 1666
                                VisitRequest visitRequest = visitRequests.stream()
1667
                                        .filter(x -> x.getVisitId() == franchiseeVisit.getId()
1668
                                                && x.getCreatedBy() == franchiseeVisit.getAuthId())
1669
                                        .findAny().orElse(null);
31249 tejbeer 1670
 
35415 amit 1671
                                CustomRetailer customRetailer = allRetailersMap.get(franchiseeVisit.getFofoId());
31677 amit.gupta 1672
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
1673
                                visitDescriptionModel.setVisitId(visitRequest.getId());
1674
                                visitDescriptionModel.setVisitName(franchiseeVisit.getPartnerName());
35415 amit 1675
                                if (customRetailer != null && customRetailer.getAddress() != null) {
1676
                                    visitDescriptionModel.setCity(customRetailer.getAddress().getCity());
1677
                                    visitDescriptionModel.setState(customRetailer.getAddress().getState());
1678
                                }
31677 amit.gupta 1679
                                visitDescriptionModel.setScheduleTime(
1680
                                        franchiseeVisit.getFranchiseeActivity().getSchelduleTimestamp());
1681
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
1682
                                visitDescriptionModel.setRemarks(franchiseeVisit.getAgenda());
1683
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
31249 tejbeer 1684
 
31677 amit.gupta 1685
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 1686
 
31677 amit.gupta 1687
                            }
1688
                        }
31249 tejbeer 1689
 
31677 amit.gupta 1690
                        userVisitModel.setVisitDescriptions(visitDescriptions);
1691
                        LOGGER.info("userVisit {}", userVisitModel);
31249 tejbeer 1692
 
31677 amit.gupta 1693
                        if (userVisitModel.getAuthUser() != null) {
1694
                            userVisits.add(userVisitModel);
1695
                        }
31249 tejbeer 1696
 
31677 amit.gupta 1697
                    }
31249 tejbeer 1698
 
31677 amit.gupta 1699
                    visitSummaryModel.setUserVisits(userVisits);
31249 tejbeer 1700
 
31677 amit.gupta 1701
                    visitSummary.add(visitSummaryModel);
31249 tejbeer 1702
 
31677 amit.gupta 1703
                }
31249 tejbeer 1704
 
31677 amit.gupta 1705
            }
31249 tejbeer 1706
 
31677 amit.gupta 1707
        }
1708
        return responseSender.ok(visitSummary);
31249 tejbeer 1709
 
31677 amit.gupta 1710
    }
31249 tejbeer 1711
 
31677 amit.gupta 1712
    @RequestMapping(value = "/visitRequest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 1713
    public ResponseEntity<?> visitRequest(HttpServletRequest request, @RequestParam(name = "gmailId") String
1714
                                                  gmailId,
31677 amit.gupta 1715
                                          @RequestParam(name = "visitId") int visitId, @RequestParam(name = "status") VisitStatus status, Model model)
1716
            throws Exception {
1717
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 1718
 
31677 amit.gupta 1719
        VisitRequest visitRequest = visitRequestRepository.selectById(visitId);
1720
        visitRequest.setActionedBy(authUser.getId());
1721
        visitRequest.setStatus(status);
1722
        visitRequest.setUpdatedTimestamp(LocalDateTime.now());
1723
        if (status.equals(VisitStatus.approved)) {
1724
            visitRequest.setApprovedTimestamp(LocalDateTime.now());
1725
        }
31249 tejbeer 1726
 
31677 amit.gupta 1727
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
1728
        sendNotificationModel.setCampaignName("Visit Request");
1729
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
1730
        sendNotificationModel.setTitle("Visit Request");
1731
        String message = "Visit Request has been " + status + " for scheduled time on "
1732
                + visitRequest.getScheduleTimestamp().toLocalDate();
31249 tejbeer 1733
 
31677 amit.gupta 1734
        sendNotificationModel.setMessage(message);
1735
        sendNotificationModel.setMessageType(MessageType.notification);
1736
        User user = userRepository.selectByEmailId(gmailId);
1737
        sendNotificationModel.setUserIds(new ArrayList<>(user.getId()));
31249 tejbeer 1738
 
31677 amit.gupta 1739
        notificationService.sendNotificationToAll(sendNotificationModel);
31249 tejbeer 1740
 
31677 amit.gupta 1741
        return responseSender.ok(true);
31249 tejbeer 1742
 
31677 amit.gupta 1743
    }
31249 tejbeer 1744
 
34301 ranu 1745
    @Autowired
1746
    RbmRatingRepository rbmRatingRepository;
1747
 
34322 ranu 1748
    @Autowired
1749
    SalesRatingRepository salesRatingRepository;
1750
 
34301 ranu 1751
    @RequestMapping(value = "/rbmRating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 1752
    public ResponseEntity<?> rbmRating(HttpServletRequest request, @RequestBody RbmSalesRatingRequest
1753
            rbmSalesRatingRequest, Model model) throws Exception {
34301 ranu 1754
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
1755
        UserCart uc = userAccountRepository.getUserCart(userId);
1756
        int fofoId = uc.getUserId();
34322 ranu 1757
 
34301 ranu 1758
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
34322 ranu 1759
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
34301 ranu 1760
 
1761
        YearMonth currentMonth = YearMonth.now();
1762
        LocalDateTime startOfMonth = currentMonth.atDay(1).atStartOfDay();
1763
        LocalDateTime endOfMonth = currentMonth.atEndOfMonth().atTime(23, 59, 59);
1764
 
34322 ranu 1765
        // Check if RBM rating already exists
1766
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfMonth, endOfMonth);
1767
        if (!existingRbmRatings.isEmpty()) {
34301 ranu 1768
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rating for this month already exists.");
1769
        }
1770
 
34322 ranu 1771
        // Check if Sales Person rating exists (optional check)
1772
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfMonth, endOfMonth);
1773
        if (!existingSalesRatings.isEmpty()) {
1774
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rating for this month already exists.");
1775
        }
34301 ranu 1776
 
34322 ranu 1777
        // Save RBM rating
34301 ranu 1778
        RbmRating rbmRating = new RbmRating();
34322 ranu 1779
        rbmRating.setComment(rbmSalesRatingRequest.getRbmComment());
1780
        rbmRating.setRating(rbmSalesRatingRequest.getRbmRating());
34301 ranu 1781
        rbmRating.setFofoId(fofoId);
1782
        rbmRating.setRbmId(rbmL1);
1783
        rbmRating.setCreateTimeStamp(LocalDateTime.now());
1784
        rbmRatingRepository.persist(rbmRating);
1785
 
34322 ranu 1786
        // Save Sales Person rating
1787
        SalesRating salesRating = new SalesRating();
1788
        salesRating.setComment(rbmSalesRatingRequest.getSalesComment());
1789
        salesRating.setRating(rbmSalesRatingRequest.getSalesRating());
1790
        salesRating.setFofoId(fofoId);
1791
        salesRating.setSalesL1Id(salesL1Id);
1792
        salesRating.setCreateTimeStamp(LocalDateTime.now());
1793
        salesRatingRepository.persist(salesRating);
1794
 
1795
        return responseSender.ok("Rating submitted successfully.");
34301 ranu 1796
    }
1797
 
1798
 
30077 tejbeer 1799
}