Subversion Repositories SmartDukaan

Rev

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

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