Subversion Repositories SmartDukaan

Rev

Rev 37781 | 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;
36267 ranu 16
import com.spice.profitmandi.dao.entity.cs.Activity;
32978 amit.gupta 17
import com.spice.profitmandi.dao.entity.cs.Position;
36267 ranu 18
import com.spice.profitmandi.dao.entity.cs.Ticket;
25899 tejbeer 19
import com.spice.profitmandi.dao.entity.dtr.User;
25952 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
34322 ranu 21
import com.spice.profitmandi.dao.entity.fofo.*;
32978 amit.gupta 22
import com.spice.profitmandi.dao.entity.user.*;
30416 tejbeer 23
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
32978 amit.gupta 24
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
25
import com.spice.profitmandi.dao.enumuration.dtr.*;
26
import com.spice.profitmandi.dao.model.*;
27
import com.spice.profitmandi.dao.repository.auth.*;
28
import com.spice.profitmandi.dao.repository.cs.*;
29
import com.spice.profitmandi.dao.repository.dtr.*;
30087 tejbeer 30
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
35075 aman 31
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
36286 ranu 32
import com.spice.profitmandi.dao.repository.fofo.RatingReminderRepository;
34301 ranu 33
import com.spice.profitmandi.dao.repository.fofo.RbmRatingRepository;
34322 ranu 34
import com.spice.profitmandi.dao.repository.fofo.SalesRatingRepository;
35632 ranu 35
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
30077 tejbeer 36
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
32978 amit.gupta 37
import com.spice.profitmandi.dao.repository.user.AddressRepository;
31249 tejbeer 38
import com.spice.profitmandi.service.AuthService;
39
import com.spice.profitmandi.service.NotificationService;
30348 tejbeer 40
import com.spice.profitmandi.service.PartnerCollectionService;
35725 ranu 41
import com.spice.profitmandi.service.integrations.kommuno.RecordingService;
25952 tejbeer 42
import com.spice.profitmandi.service.user.RetailerService;
28935 tejbeer 43
import com.spice.profitmandi.service.user.StoreTimelineTatService;
25952 tejbeer 44
import com.spice.profitmandi.web.req.CreateFranchiseeRequest;
34322 ranu 45
import com.spice.profitmandi.web.req.RbmSalesRatingRequest;
25952 tejbeer 46
import com.spice.profitmandi.web.res.Partner;
25899 tejbeer 47
import io.swagger.annotations.ApiImplicitParam;
48
import io.swagger.annotations.ApiImplicitParams;
32978 amit.gupta 49
import org.apache.commons.csv.CSVRecord;
50
import org.apache.commons.io.output.ByteArrayOutputStream;
51
import org.apache.logging.log4j.LogManager;
52
import org.apache.logging.log4j.Logger;
53
import org.springframework.beans.factory.annotation.Autowired;
36957 aman 54
import org.springframework.beans.factory.annotation.Value;
32978 amit.gupta 55
import org.springframework.format.annotation.DateTimeFormat;
56
import org.springframework.http.HttpHeaders;
57
import org.springframework.http.HttpStatus;
58
import org.springframework.http.MediaType;
59
import org.springframework.http.ResponseEntity;
60
import org.springframework.mail.javamail.JavaMailSender;
61
import org.springframework.stereotype.Controller;
62
import org.springframework.transaction.annotation.Transactional;
63
import org.springframework.ui.Model;
64
import org.springframework.web.bind.annotation.*;
65
import org.springframework.web.multipart.MultipartFile;
25899 tejbeer 66
 
32978 amit.gupta 67
import javax.servlet.http.HttpServletRequest;
68
import java.io.IOException;
69
import java.time.LocalDate;
70
import java.time.LocalDateTime;
34301 ranu 71
import java.time.YearMonth;
32978 amit.gupta 72
import java.time.format.DateTimeFormatter;
36114 ranu 73
import java.time.temporal.TemporalAdjusters;
32978 amit.gupta 74
import java.util.*;
35415 amit 75
import java.util.HashSet;
32978 amit.gupta 76
import java.util.Map.Entry;
37353 aman 77
import java.util.concurrent.ThreadLocalRandom;
32978 amit.gupta 78
import java.util.stream.Collectors;
79
 
25899 tejbeer 80
@Controller
81
@Transactional(rollbackFor = Throwable.class)
82
public class LeadController {
31677 amit.gupta 83
    private static final Logger LOGGER = LogManager.getLogger(LeadController.class);
36957 aman 84
 
85
    /** Source/createdBy label for leads captured by the AI assistant. */
86
    private static final String AI_LEAD_SOURCE = "AI Assistant";
87
 
37353 aman 88
    /**
37354 aman 89
     * Assignee used for AI leads only when no active BGC L1 can be resolved from cs.position.
37353 aman 90
     * Same auth id the web capture has always routed to, so intake never fails on an empty pool.
91
     */
92
    private static final int AI_LEAD_FALLBACK_ASSIGNEE = 53;
93
 
37893 aman 94
    // Ira channels the AI side sends in AiLeadRequest.source, stored on lead.ai_channel.
95
    private static final String IRA_PHONE = "IRA_PHONE";
96
    private static final String IRA_WEB = "IRA_WEB";
97
 
98
    // AI leads from the Ira toll-free number all go to Meenakshi Mehta, and she is left out of the
99
    // random pool for every other AI lead.
100
    private static final int IRA_PHONE_LEAD_ASSIGNEE = 84;
101
 
31677 amit.gupta 102
    @Autowired
103
    private ResponseSender<?> responseSender;
25899 tejbeer 104
 
36957 aman 105
    @Value("${ai.lead.intake.token}")
106
    private String aiLeadIntakeToken;
107
 
31677 amit.gupta 108
    @Autowired
109
    private AuthRepository authRepository;
25899 tejbeer 110
 
31677 amit.gupta 111
    @Autowired
112
    private LeadRepository leadRepository;
25899 tejbeer 113
 
31677 amit.gupta 114
    @Autowired
37729 amit 115
    private com.spice.profitmandi.dao.service.lead.LeadCreationService leadCreationService;
116
 
117
    @Autowired
32923 ranu 118
    DocumentRepository documentRepository;
119
 
120
    @Autowired
121
    PositionRepository positionRepository;
122
 
123
    @Autowired
124
    private ActivityAttachmentRepository activityAttachmentRepository;
125
 
126
    @Autowired
31677 amit.gupta 127
    private CsService csService;
25952 tejbeer 128
 
31677 amit.gupta 129
    @Autowired
37781 amit 130
    private DemoPartnerAccessService demoPartnerAccessService;
131
 
132
    @Autowired
31677 amit.gupta 133
    private UserRepository userRepository;
25952 tejbeer 134
 
31677 amit.gupta 135
    @Autowired
32923 ranu 136
    private AddressRepository addressRepository;
137
 
138
    @Autowired
139
 
140
    private UserRoleRepository userRoleRepository;
141
 
142
    @Autowired
31677 amit.gupta 143
    private UserAccountRepository userAccountRepository;
25952 tejbeer 144
 
31677 amit.gupta 145
    @Autowired
146
    private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
25952 tejbeer 147
 
31677 amit.gupta 148
    @Autowired
149
    private RetailerService retailerService;
25952 tejbeer 150
 
31677 amit.gupta 151
    @Autowired
152
    private LeadActivityRepository leadActivityRepository;
25899 tejbeer 153
 
31677 amit.gupta 154
    @Autowired
155
    private FranchiseeVisitRepository franchiseeVisitRepository;
25952 tejbeer 156
 
31677 amit.gupta 157
    @Autowired
158
    private FranchiseeActivityRepository franchiseeActivityRepository;
25952 tejbeer 159
 
31677 amit.gupta 160
    @Autowired
161
    private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;
28935 tejbeer 162
 
31677 amit.gupta 163
    @Autowired
164
    private FofoStoreRepository fofoStoreRepository;
28935 tejbeer 165
 
31677 amit.gupta 166
    @Autowired
167
    private StoreTimelineTatService storeTimelineTatService;
28935 tejbeer 168
 
31677 amit.gupta 169
    @Autowired
170
    private PartnerCollectionService partnerCollectionService;
30348 tejbeer 171
 
31677 amit.gupta 172
    @Autowired
173
    private TicketRepository ticketRepository;
30416 tejbeer 174
 
31677 amit.gupta 175
    @Autowired
36267 ranu 176
    private ActivityRepository activityRepository;
177
 
178
    @Autowired
31677 amit.gupta 179
    private TicketCategoryRepository ticketCategoryRepository;
30416 tejbeer 180
 
31677 amit.gupta 181
    @Autowired
182
    private TicketSubCategoryRepository ticketSubCategoryRepository;
30416 tejbeer 183
 
31677 amit.gupta 184
    @Autowired
185
    private PartnerCollectionRemarkRepository partnerCollectionRemarkRepository;
30416 tejbeer 186
 
31677 amit.gupta 187
    @Autowired
188
    private Mongo mongoClient;
30487 tejbeer 189
 
31677 amit.gupta 190
    @Autowired
191
    private OrderRepository orderRepository;
30487 tejbeer 192
 
31677 amit.gupta 193
    @Autowired
194
    private PartnerCollectionPlanRepository partnerCollectionPlanRepository;
30487 tejbeer 195
 
31677 amit.gupta 196
    @Autowired
197
    private PartnerSecondaryPlanRepository partnerSecondaryPlanRepository;
30487 tejbeer 198
 
31677 amit.gupta 199
    @Autowired
200
    private PartnerDailyInvestmentRepository partnerDailyInvestmentRepository;
30487 tejbeer 201
 
31677 amit.gupta 202
    @Autowired
203
    private VisitRequestRepository visitRequestRepository;
31249 tejbeer 204
 
31677 amit.gupta 205
    @Autowired
206
    private AuthService authService;
31249 tejbeer 207
 
31677 amit.gupta 208
    @Autowired
209
    private NotificationService notificationService;
31249 tejbeer 210
 
32923 ranu 211
    @Autowired
36400 amit 212
    JavaMailSender gmailRelaySender;
32923 ranu 213
 
214
    @Autowired
215
    private TicketAssignedRepository ticketAssignedRepository;
216
 
34124 tejus.loha 217
    @Autowired
218
    LeadDetailRepository leadDetailRepository;
219
 
35075 aman 220
    @Autowired
36771 ranu 221
    private com.spice.profitmandi.dao.repository.dtr.BeatRepository beatRepository;
222
 
223
    @Autowired
224
    private com.spice.profitmandi.dao.repository.dtr.BeatScheduleRepository beatScheduleRepository;
225
 
226
    @Autowired
227
    private com.spice.profitmandi.dao.repository.dtr.BeatRouteRepository beatRouteRepository;
228
 
229
    @Autowired
230
    private com.spice.profitmandi.dao.repository.dtr.LeadRouteRepository leadRouteRepository;
231
 
232
    @Autowired
233
    private com.spice.profitmandi.dao.repository.dtr.LeadLiveLocationRepository leadLiveLocationRepository;
234
 
235
    @Autowired
35075 aman 236
    PurchaseRepository purchaseRepository;
237
 
35632 ranu 238
    @Autowired
239
    private LoanRepository loanRepository;
240
 
35725 ranu 241
    @Autowired
242
    private RecordingService recordingService;
243
 
36771 ranu 244
    // Field-staff creates a lead from the planner — they're physically at the lead's
245
    // location, so we mark the geo APPROVED immediately (no link-and-approve cycle).
246
    @RequestMapping(value = "/lead-geo/self-approve", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
247
    @ApiImplicitParams({
248
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
249
    public ResponseEntity<?> selfApproveLeadGeo(javax.servlet.http.HttpServletRequest request,
250
                                                @RequestBody Map<String, Object> req) throws Exception {
251
        Integer leadId = req.get("leadId") instanceof Number ? ((Number) req.get("leadId")).intValue() : null;
252
        if (leadId == null || leadId <= 0) return responseSender.badRequest("leadId required");
253
        Object latObj = req.get("latitude"), lngObj = req.get("longitude");
254
        if (!(latObj instanceof Number) || !(lngObj instanceof Number)) return responseSender.badRequest("latitude/longitude required");
255
        double latitude = ((Number) latObj).doubleValue();
256
        double longitude = ((Number) lngObj).doubleValue();
257
        Lead lead = leadRepository.selectById(leadId);
258
        if (lead == null) return responseSender.badRequest("Lead not found");
259
        // Resolve approver from session, fall back to request body.
260
        int approverAuthId = 0;
261
        com.spice.profitmandi.common.model.UserInfo userInfo =
262
                (com.spice.profitmandi.common.model.UserInfo) request.getAttribute("userInfo");
263
        if (userInfo != null && userInfo.getEmail() != null) {
264
            AuthUser sessionAuth = authRepository.selectByGmailId(userInfo.getEmail());
265
            if (sessionAuth != null) approverAuthId = sessionAuth.getId();
266
        }
267
        if (approverAuthId == 0 && req.get("authUserId") instanceof Number) {
268
            approverAuthId = ((Number) req.get("authUserId")).intValue();
269
        }
270
 
271
        int imageDocumentId = 0;
272
        if (req.get("imageDocumentId") instanceof Number) {
273
            imageDocumentId = ((Number) req.get("imageDocumentId")).intValue();
274
        }
275
 
276
        LocalDateTime now = LocalDateTime.now();
277
        com.spice.profitmandi.dao.entity.user.LeadLiveLocation existing = leadLiveLocationRepository.selectByLeadId(leadId);
278
        if (existing != null) {
279
            existing.setLatitude(latitude);
280
            existing.setLongitude(longitude);
281
            existing.setStatus(com.spice.profitmandi.dao.enumuration.dtr.GeoLocationStatus.APPROVED);
282
            existing.setReviewedBy(approverAuthId);
283
            existing.setReviewedTimestamp(now);
284
            existing.setSubmissionCount(existing.getSubmissionCount() + 1);
285
            existing.setMobileNumber(lead.getLeadMobile());
286
            if (imageDocumentId > 0) existing.setImageDocumentId(imageDocumentId);
287
            existing.setUpdatedTimestamp(now);
288
            existing.setRemark("Self-approved by field creator");
289
        } else {
290
            com.spice.profitmandi.dao.entity.user.LeadLiveLocation loc = new com.spice.profitmandi.dao.entity.user.LeadLiveLocation();
291
            loc.setLeadId(leadId);
292
            loc.setLatitude(latitude);
293
            loc.setLongitude(longitude);
294
            loc.setMobileNumber(lead.getLeadMobile());
295
            loc.setImageDocumentId(imageDocumentId);
296
            loc.setStatus(com.spice.profitmandi.dao.enumuration.dtr.GeoLocationStatus.APPROVED);
297
            loc.setReviewedBy(approverAuthId);
298
            loc.setReviewedTimestamp(now);
299
            loc.setSubmissionCount(1);
300
            loc.setRemark("Self-approved by field creator");
301
            loc.setCreatedTimestamp(now);
302
            loc.setUpdatedTimestamp(now);
303
            leadLiveLocationRepository.persist(loc);
304
        }
305
 
306
        LeadActivity activity = new LeadActivity();
307
        activity.setLeadId(leadId);
308
        activity.setRemark("Geolocation self-approved by field creator");
309
        activity.setAuthId(approverAuthId);
310
        activity.setCreatedTimestamp(now);
311
        leadActivityRepository.persist(activity);
312
 
313
        Map<String, Object> result = new HashMap<>();
314
        result.put("status", "approved");
315
        result.put("leadId", leadId);
316
        return responseSender.ok(result);
317
    }
318
 
319
    // Returns the field-staff person's upcoming beat-day chips (today + next N days) so
320
    // the partner app can present "Schedule on today vs future" right after a self-create.
321
    // The auth user is resolved from the session — matches the existing
322
    // BeatTrackingController.listBeats pattern (the client `userId` is unreliable).
323
    public ResponseEntity<?> upcomingBeatsForUser(javax.servlet.http.HttpServletRequest request, int days) throws Exception {
324
        com.spice.profitmandi.common.model.UserInfo userInfo =
325
                (com.spice.profitmandi.common.model.UserInfo) request.getAttribute("userInfo");
326
        if (userInfo == null || userInfo.getEmail() == null) {
327
            return responseSender.badRequest("Auth session not found");
328
        }
329
        AuthUser authUser = authRepository.selectByGmailId(userInfo.getEmail());
330
        if (authUser == null) return responseSender.badRequest("Auth user not found");
331
        int authUserId = authUser.getId();
332
        LOGGER.info("upcomingBeatsForUser resolved authUserId={} from session email={}", authUserId, userInfo.getEmail());
333
        LocalDate today = LocalDate.now();
334
        LocalDate end = today.plusDays(days);
335
        List<com.spice.profitmandi.dao.entity.user.Beat> beats = beatRepository.selectActiveByAuthUserId(authUserId);
336
        List<Map<String, Object>> out = new ArrayList<>();
337
        for (com.spice.profitmandi.dao.entity.user.Beat b : beats) {
338
            List<com.spice.profitmandi.dao.entity.user.BeatSchedule> schedules =
339
                    beatScheduleRepository.selectByBeatIdAndDateRange(b.getId(), today, end);
340
            for (com.spice.profitmandi.dao.entity.user.BeatSchedule s : schedules) {
341
                if (s.getStartDate() == null || s.getStartDate().getYear() == 9999) continue;
342
                Map<String, Object> row = new HashMap<>();
343
                row.put("beatId", b.getId());
344
                row.put("beatName", b.getName());
345
                row.put("beatColor", b.getBeatColor());
346
                row.put("scheduleDate", s.getStartDate().toString());
347
                row.put("dayNumber", s.getDayNumber());
348
                row.put("isToday", today.equals(s.getStartDate()));
349
                out.add(row);
350
            }
351
        }
352
        out.sort(Comparator.comparing(r -> (String) r.get("scheduleDate")));
353
        return responseSender.ok(out);
354
    }
355
 
356
    // Attaches a (just-created, self-approved) lead to a sales user's beat on a given
357
    // date. Inserts a LeadRoute row with status=APPROVED; idempotent on re-call.
358
    // The auth user is resolved from the session token, not the request body.
359
    public ResponseEntity<?> scheduleLeadOnBeat(javax.servlet.http.HttpServletRequest request,
360
                                                Map<String, Object> req) throws Exception {
361
        com.spice.profitmandi.common.model.UserInfo userInfo =
362
                (com.spice.profitmandi.common.model.UserInfo) request.getAttribute("userInfo");
363
        if (userInfo == null || userInfo.getEmail() == null) {
364
            return responseSender.badRequest("Auth session not found");
365
        }
366
        AuthUser sessionAuth = authRepository.selectByGmailId(userInfo.getEmail());
367
        if (sessionAuth == null) return responseSender.badRequest("Auth user not found");
368
        int authUserId = sessionAuth.getId();
369
 
370
        Integer leadId = req.get("leadId") instanceof Number ? ((Number) req.get("leadId")).intValue() : null;
371
        Integer beatId = req.get("beatId") instanceof Number ? ((Number) req.get("beatId")).intValue() : null;
372
        Object dateObj = req.get("scheduleDate");
373
        if (leadId == null || beatId == null || dateObj == null) {
374
            return responseSender.badRequest("leadId, beatId and scheduleDate are required");
375
        }
376
        LocalDate scheduleDate;
377
        try {
378
            scheduleDate = LocalDate.parse(dateObj.toString());
379
        } catch (Exception e) {
380
            return responseSender.badRequest("scheduleDate must be yyyy-MM-dd");
381
        }
382
 
383
        Lead lead = leadRepository.selectById(leadId);
384
        if (lead == null) return responseSender.badRequest("Lead not found");
385
 
386
        // Beat must actually run on the chosen date — same guard as the panel-side flow.
387
        List<com.spice.profitmandi.dao.entity.user.BeatSchedule> match =
388
                beatScheduleRepository.selectByBeatIdAndDateRange(beatId, scheduleDate, scheduleDate);
389
        if (match.isEmpty()) return responseSender.badRequest("Beat is not scheduled on " + scheduleDate);
390
 
391
        // Idempotency: skip if the same lead is already pinned to this beat-day.
392
        boolean exists = leadRouteRepository.selectByBeatId(beatId).stream()
393
                .anyMatch(lr -> lr.getLeadId() == leadId
394
                        && scheduleDate.equals(lr.getScheduleDate())
395
                        && !"CANCELLED".equals(lr.getStatus()));
396
        if (exists) {
397
            return responseSender.ok(Collections.singletonMap("status", "already_scheduled"));
398
        }
399
 
400
        // Append at the end of the day's existing stops.
401
        int seq = beatRouteRepository.selectByBeatId(beatId).size() + 1;
402
 
403
        com.spice.profitmandi.dao.entity.user.LeadRoute lr = new com.spice.profitmandi.dao.entity.user.LeadRoute();
404
        lr.setBeatId(beatId);
405
        lr.setLeadId(leadId);
406
        lr.setScheduleDate(scheduleDate);
407
        lr.setSequenceOrder(seq);
408
        lr.setStatus("APPROVED");
409
        lr.setRequestedBy(authUserId);
410
        lr.setApprovedBy(authUserId);
411
        LocalDateTime now = LocalDateTime.now();
412
        lr.setApprovedTimestamp(now);
413
        lr.setCreatedTimestamp(now);
414
        lr.setUpdatedTimestamp(now);
415
        leadRouteRepository.persist(lr);
416
 
417
        Map<String, Object> result = new HashMap<>();
418
        result.put("status", "scheduled");
419
        result.put("scheduleDate", scheduleDate.toString());
420
        return responseSender.ok(result);
421
    }
422
 
31677 amit.gupta 423
    @RequestMapping(value = "/lead", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
424
    @ApiImplicitParams({
425
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
34118 tejus.loha 426
 
427
    public ResponseEntity<?> LeadUser(@RequestBody CreateRefferalRequest createRefferalRequest) throws Exception {
35079 vikas 428
        LOGGER.info("CreateReferralRequest - " + createRefferalRequest);
34394 tejus.loha 429
        if (createRefferalRequest.getOutletName() == null || createRefferalRequest.getPotential() == 0) {
35079 vikas 430
            throw new Exception("Outlet should not be empty and potential should be greater > 0");
34386 ranu 431
        }
35288 amit 432
        Lead lead;
433
        AuthUser authUser = authRepository.selectByGmailId(createRefferalRequest.getReffereeEmail());
434
        if (createRefferalRequest.getId() > 0) {
435
            lead = leadRepository.selectById(createRefferalRequest.getId());
436
            lead.setAssignTo(authUser.getId());
31677 amit.gupta 437
        } else {
35288 amit 438
            lead = new Lead();
439
            lead.setFirstName(createRefferalRequest.getFirstName());
440
            lead.setLastName(createRefferalRequest.getLastName());
441
            lead.setLeadMobile(createRefferalRequest.getMobile());
442
            lead.setState(createRefferalRequest.getState());
443
            lead.setCity(createRefferalRequest.getCity());
444
            lead.setAddress(createRefferalRequest.getAddress());
445
            lead.setCreatedTimestamp(LocalDateTime.now());
446
            lead.setOutLetName(createRefferalRequest.getOutletName());
447
            lead.setUpdatedTimestamp(LocalDateTime.now());
448
            lead.setStatus(createRefferalRequest.getStatus());
449
            lead.setSource(createRefferalRequest.getSource());
450
            lead.setNotinterestedReason(createRefferalRequest.getReason());
451
            lead.setPotential(createRefferalRequest.getPotential());
452
            if (createRefferalRequest.getColorCheck() == true) {
453
                lead.setColor("Green");
454
            } else {
455
                lead.setColor("Yellow");
456
            }
457
            String authUserName = authUser.getFullName();
458
            lead.setAuthId(authUser.getId());
459
            lead.setAssignTo(authUser.getId());
35079 vikas 460
            lead.setCreatedBy(authUserName);
37729 amit 461
            // One workable lead per number -- see LeadCreationService.
462
            leadCreationService.create(lead, authUser.getId(), createRefferalRequest.isOverrideDuplicate());
35288 amit 463
 
35079 vikas 464
        }
34118 tejus.loha 465
 
31677 amit.gupta 466
        LeadActivity leadActivity = new LeadActivity();
467
        leadActivity.setLeadId(lead.getId());
35288 amit 468
        leadActivity.setRemark((createRefferalRequest.getId() > 0 ? "Self Assigned." : "") + createRefferalRequest.getRemark());
31677 amit.gupta 469
        leadActivity.setAuthId(authUser.getId());
31249 tejbeer 470
 
31677 amit.gupta 471
        if (createRefferalRequest.getStatus().equals(LeadStatus.followUp)) {
472
            leadActivity.setSchelduleTimestamp(createRefferalRequest.getSchelduleTimestamp());
473
            leadActivity.setCommunicationType(createRefferalRequest.getCommunicationType());
31249 tejbeer 474
 
31677 amit.gupta 475
            if (leadActivity.getCommunicationType().equals(CommunicationType.VISIT)) {
31249 tejbeer 476
 
31677 amit.gupta 477
                visitRequestRepository.createVisitRequest(lead.getId(), "lead", lead.getAssignTo(),
478
                        createRefferalRequest.getSchelduleTimestamp());
479
            }
480
            //
481
            leadActivity.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
482
            lead.setClosureTimestamp(createRefferalRequest.getClosureTimestamp());
483
        } else {
484
            leadActivity.setSchelduleTimestamp(null);
485
            leadActivity.setClosureTimestamp(null);
486
            lead.setClosureTimestamp(null);
487
        }
488
        leadActivity.setCreatedTimestamp(LocalDateTime.now());
489
        leadActivityRepository.persist(leadActivity);
25899 tejbeer 490
 
36771 ranu 491
        // Return the new lead's id alongside the legacy `success: true` flag so callers
492
        // that need to chain follow-up actions (e.g., the partner app's self-create →
493
        // self-approve geo → schedule on beat flow) can do so without an extra lookup.
494
        Map<String, Object> body = new HashMap<>();
495
        body.put("success", true);
496
        body.put("leadId", lead.getId());
497
        return responseSender.ok(body);
31677 amit.gupta 498
    }
25899 tejbeer 499
 
31677 amit.gupta 500
    @RequestMapping(value = "/lead-description", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
501
    @ApiImplicitParams({
502
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 503
    public ResponseEntity<?> leadDescription(HttpServletRequest request, @RequestParam(name = "gmailId") String
504
                                                     gmailId,
31677 amit.gupta 505
                                             @RequestParam(name = "status") LeadStatus status) throws ProfitMandiBusinessException {
506
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
507
        List<Lead> leads = null;
508
        LOGGER.info("emails" + status);
31249 tejbeer 509
 
35469 vikas 510
        List<VisitRequest> visitRequests = visitRequestRepository.selectByAuthIdAndDate(authUser.getId(),
511
                LocalDate.now());
512
        Map<Integer, List<VisitRequest>> visitRequestMap = null;
513
        if (!visitRequests.isEmpty()) {
514
            visitRequestMap = visitRequests.stream().collect(Collectors.groupingBy(x -> x.getVisitId()));
515
        }
36827 ranu 516
 
517
        // Hierarchy expansion (Sales only):
518
        //   L1 → just self
519
        //   L2 → self + every L1 reportee
520
        //   L3 → self + L1 + L2 reportees
521
        //   L4 → self + L1 + L2 + L3 reportees
522
        // Non-Sales callers stay at "just self" — same as today.
523
        List<Integer> visibleAuthIds = visibleAuthIdsForLeads(authUser.getId());
524
 
31677 amit.gupta 525
        if (status.equals(LeadStatus.followUp)) {
35469 vikas 526
 
36853 ranu 527
            // Show every lead assigned to the caller (or downline for Sales heads)
528
            // whose status is followUp. The old call,
529
            //   selectLeadsScheduledBetweenDate(visibleAuthIds, null, null)
530
            // silently dropped any lead whose LATEST lead_activity row did not
531
            // carry a schedule_timestamp — which excludes leads that were
532
            // assigned but never scheduled, and leads whose most recent activity
533
            // was a visit-request action (create / reject / reassign / cancel)
534
            // that doesn't set schedule_timestamp. Result: most assigned leads
535
            // disappeared from the mobile "All Leads → Follow Up" tab.
536
            leads = leadRepository.selectByAssignAuthIdsAndStatus(visibleAuthIds, LeadStatus.followUp);
31249 tejbeer 537
 
36860 ranu 538
            // Hydrate Lead.scheduledTimestamp for the card date + sort order.
539
            // One batched lookup: lead_id → latest non-null schedule_timestamp.
540
            // Leads with no scheduled activity get null (still shown, just no date).
541
            if (leads != null && !leads.isEmpty()) {
542
                List<Integer> leadIds = leads.stream().map(Lead::getId).collect(Collectors.toList());
543
                Map<Integer, LocalDateTime> scheduleByLead =
544
                        leadActivityRepository.latestScheduleTimestampByLeadIds(leadIds);
545
                leads.forEach(l -> l.setScheduledTimestamp(scheduleByLead.get(l.getId())));
546
            }
547
 
35469 vikas 548
            if (visitRequestMap != null) {
31677 amit.gupta 549
                for (Lead lead : leads) {
550
                    List<VisitRequest> visitRequest = visitRequestMap.get(lead.getId());
35469 vikas 551
 
31677 amit.gupta 552
                    if (visitRequest != null) {
553
                        if (visitRequest.size() > 1) {
35469 vikas 554
 
555
                            Comparator<VisitRequest> visitComparato = Comparator
556
                                    .comparing(VisitRequest::getCreatedTimestamp);
557
 
558
                            VisitRequest youngestVisit = visitRequest.stream().max(visitComparato).get();
31677 amit.gupta 559
                            lead.setVisitStatus(youngestVisit.getStatus());
35469 vikas 560
 
31677 amit.gupta 561
                        } else {
562
                            lead.setVisitStatus(visitRequest.get(0).getStatus());
35469 vikas 563
 
31677 amit.gupta 564
                        }
565
                    }
35469 vikas 566
 
31677 amit.gupta 567
                }
568
            }
31249 tejbeer 569
 
31677 amit.gupta 570
            leads = leads.stream()
35079 vikas 571
                    .sorted(Comparator.comparing(Lead::getScheduledTimestamp, Comparator.nullsFirst(Comparator.reverseOrder())))
572
                    .collect(Collectors.toList());
35469 vikas 573
            /*
574
             * Collections.sort(leads, (o1, o2) -> { if (o1.getScheduledTimestamp() != null
575
             * && o2.getScheduledTimestamp() != null) { return
576
             * o1.getScheduledTimestamp().isBefore(o2.getScheduledTimestamp()) ? -1 : 1; }
577
             * else if (o1.getScheduledTimestamp() != null) { return 1; } else { return -1;
578
             * } });
579
             */
580
 
31677 amit.gupta 581
        } else {
36827 ranu 582
            // Same hierarchy expansion as the followUp branch — Sales heads see their
583
            // downline's leads alongside their own.
584
            leads = leadRepository.selectByAssignAuthIdsAndStatus(visibleAuthIds, status);
35469 vikas 585
 
31677 amit.gupta 586
        }
25979 tejbeer 587
 
31677 amit.gupta 588
        return responseSender.ok(leads);
35469 vikas 589
 
31677 amit.gupta 590
    }
25899 tejbeer 591
 
36827 ranu 592
    // Returns the auth-user IDs whose leads are visible to `authUserId` on the
593
    // mobile "My Leads" screen. Sales heads see their full downline; everyone
594
    // else (incl. non-Sales) sees only themselves.
595
    private List<Integer> visibleAuthIdsForLeads(int authUserId) {
596
        List<Integer> ids = new ArrayList<>();
597
        ids.add(authUserId);
598
 
599
        EscalationType highestSales = null;
600
        try {
601
            for (Position p : positionRepository.selectPositionByAuthId(authUserId)) {
602
                if (p.getCategoryId() == ProfitMandiConstants.TICKET_CATEGORY_SALES) {
603
                    if (highestSales == null || p.getEscalationType().isGreaterThanEqualTo(highestSales)) {
604
                        highestSales = p.getEscalationType();
605
                    }
606
                }
607
            }
608
        } catch (Exception ignored) {
609
        }
610
 
611
        // Only sales heads (L2+) get the downline expansion. L1 / non-Sales stay at self.
612
        if (highestSales != null && highestSales.isGreaterThanEqualTo(EscalationType.L2)) {
613
            try {
614
                List<Integer> reportees = authService.getAllReportees(authUserId);
615
                if (reportees != null) {
616
                    for (Integer r : reportees) {
617
                        if (r != null && !ids.contains(r)) ids.add(r);
618
                    }
619
                }
620
            } catch (Exception ignored) {
621
            }
622
        }
623
        return ids;
624
    }
625
 
31677 amit.gupta 626
    @RequestMapping(value = "/getlead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 627
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
628
    public ResponseEntity<?> getLead(HttpServletRequest request, @RequestParam(name = "id") int id) throws
629
            ProfitMandiBusinessException {
25899 tejbeer 630
 
31677 amit.gupta 631
        List<LeadActivity> leadActivities = leadActivityRepository.selectBYLeadId(id);
632
        Lead lead = leadRepository.selectById(id);
633
        lead.setLeadActivities(leadActivities);
634
        return responseSender.ok(lead);
25899 tejbeer 635
 
31677 amit.gupta 636
    }
25899 tejbeer 637
 
35079 vikas 638
    @RequestMapping(value = "/check-existing-lead", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 639
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
640
    public ResponseEntity<?> getLeadByMobile(HttpServletRequest request, @RequestParam(name = "mobile") String
641
            mobile) throws ProfitMandiBusinessException {
35079 vikas 642
        int userId = (int) request.getAttribute("userId");
643
        LOGGER.info("userId: " + userId);
644
        Lead lead = leadRepository.selectByMobileNumber(mobile);
645
        return responseSender.ok(lead);
646
 
647
    }
648
 
31677 amit.gupta 649
    @RequestMapping(value = "/leadUpdate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 650
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 651
    public ResponseEntity<?> leadUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
35288 amit 652
                                        @RequestParam(name = "status") LeadStatus status, @RequestParam(name = "colorCheck") Boolean colorCheck,
653
                                        @RequestParam(name = "remark") String remark, @RequestParam(name = "reason") String reason,
654
                                        @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp,
655
                                        @RequestParam(name = "closureTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime closureTimestamp,
656
                                        @RequestParam(name = "communicationType") CommunicationType communicationType) throws
657
            ProfitMandiBusinessException {
25899 tejbeer 658
 
31677 amit.gupta 659
        Lead lead = leadRepository.selectById(id);
25899 tejbeer 660
 
31677 amit.gupta 661
        LeadActivity leadActivity = new LeadActivity();
662
        lead.setStatus(status);
663
        lead.setNotinterestedReason(reason);
664
        leadActivity.setRemark(remark);
665
        leadActivity.setLeadId(id);
34394 tejus.loha 666
        leadActivity.setOutletName(lead.getOutLetName());
667
        leadActivity.setPotential(lead.getPotential());
31677 amit.gupta 668
        leadActivity.setCreatedTimestamp(LocalDateTime.now());
669
        leadActivity.setSchelduleTimestamp(null);
670
        leadActivity.setClosureTimestamp(null);
671
        leadActivity.setAuthId(lead.getAssignTo());
672
        lead.setUpdatedTimestamp(LocalDateTime.now());
673
        if (colorCheck == true) {
674
            lead.setColor("Green");
675
        } else {
676
            lead.setColor("Yellow");
677
        }
678
        if (status == LeadStatus.followUp) {
25899 tejbeer 679
 
31677 amit.gupta 680
            if (schelduleTimestamp != null) {
31249 tejbeer 681
 
31677 amit.gupta 682
                leadActivity.setCommunicationType(communicationType);
31249 tejbeer 683
 
31677 amit.gupta 684
                if (leadActivity.getCommunicationType().equals(CommunicationType.VISIT)) {
31249 tejbeer 685
 
35079 vikas 686
                    visitRequestRepository.createVisitRequest(lead.getId(), "lead", lead.getAssignTo(), schelduleTimestamp);
31677 amit.gupta 687
                }
31249 tejbeer 688
 
31677 amit.gupta 689
            }
690
            leadActivity.setSchelduleTimestamp(schelduleTimestamp);
691
            leadActivity.setClosureTimestamp(closureTimestamp);
692
            lead.setClosureTimestamp(closureTimestamp);
26250 tejbeer 693
 
31677 amit.gupta 694
        } else {
26250 tejbeer 695
 
31677 amit.gupta 696
            leadActivity.setSchelduleTimestamp(null);
697
            leadActivity.setClosureTimestamp(null);
698
            lead.setClosureTimestamp(null);
26244 tejbeer 699
 
31677 amit.gupta 700
        }
701
        leadActivityRepository.persist(leadActivity);
702
        return responseSender.ok(true);
25899 tejbeer 703
 
31677 amit.gupta 704
    }
25952 tejbeer 705
 
31677 amit.gupta 706
    @RequestMapping(value = ProfitMandiConstants.URL_NEW_LEAD, method = RequestMethod.POST)
35288 amit 707
    public ResponseEntity<?> newLead(HttpServletRequest request, @RequestBody CreateRefferalRequest
708
            createRefferalRequest) throws ProfitMandiBusinessException {
31677 amit.gupta 709
        LOGGER.info("requested url : " + request.getRequestURL().toString());
710
        Lead lead = new Lead();
711
        lead.setAddress(createRefferalRequest.getCity());
712
        Long.parseLong(createRefferalRequest.getMobile());
713
        if (createRefferalRequest.getMobile().length() != 10) {
35079 vikas 714
            throw new ProfitMandiBusinessException("Mobile Number", createRefferalRequest.getMobile(), "Number should be of 10 digits");
31677 amit.gupta 715
        }
716
        lead.setLeadMobile(createRefferalRequest.getMobile());
717
        lead.setCity(createRefferalRequest.getCity());
718
        lead.setState(createRefferalRequest.getState());
719
        lead.setLastName(createRefferalRequest.getLastName());
720
        if (lead.getState().equals("Uttar Pradesh")) {
721
            lead.setAssignTo(53);
722
        } else if (lead.getState().equals("Haryana")) {
723
            lead.setAssignTo(53);
724
        } else if (lead.getState().equals("Delhi")) {
725
            lead.setAssignTo(53);
726
        } else {
727
            // Assign to sm
728
            lead.setAssignTo(53);
729
            // Assign to neha
730
            // lead.setAssignTo(1);
731
        }
732
        lead.setAuthId(lead.getAssignTo());
733
        lead.setCreatedBy("daily-sync");
734
        lead.setSource("SD-WEB");
735
        lead.setFirstName(createRefferalRequest.getFirstName());
736
        lead.setStatus(LeadStatus.followUp);
737
        lead.setColor("yellow");
738
        lead.setCreatedTimestamp(LocalDateTime.now());
739
        lead.setUpdatedTimestamp(LocalDateTime.now());
37729 amit 740
        // Unattended: SD-WEB capture has no interactive user to offer an override to.
741
        leadCreationService.createUnattended(lead);
27117 tejbeer 742
 
31677 amit.gupta 743
        return responseSender.ok(true);
27117 tejbeer 744
 
31677 amit.gupta 745
    }
27117 tejbeer 746
 
36957 aman 747
    /**
748
     * Intake endpoint for leads captured by the AI assistant (chat + voice flows, external system).
749
     * <p>
750
     * The source is stamped server-side as {@value #AI_LEAD_SOURCE} so the caller cannot spoof it.
751
     * Authenticated with a shared secret sent in the standard {@code Auth-Token} header; this path is
752
     * excluded from the JWT {@code AuthenticationInterceptor} (see WebMVCConfig) so the secret is not
753
     * treated as a user token. The call is idempotent: the AI side fires fire-and-forget with retry,
754
     * so a repeat POST for a mobile that already has an AI lead returns OK without creating a
755
     * duplicate. Leads from other sources (SD-WEB, manual) for the same mobile do not block creation.
756
     */
757
    @RequestMapping(value = ProfitMandiConstants.URL_AI_LEAD_INTAKE, method = RequestMethod.POST)
758
    public ResponseEntity<?> aiLead(HttpServletRequest request,
759
                                    @RequestHeader(name = "Auth-Token", required = false) String authToken,
760
                                    @RequestBody AiLeadRequest aiLeadRequest)
761
            throws ProfitMandiBusinessException {
762
        LOGGER.info("AI lead intake request: {}", aiLeadRequest);
763
 
764
        if (aiLeadIntakeToken == null || aiLeadIntakeToken.trim().isEmpty()
765
                || authToken == null || !aiLeadIntakeToken.equals(authToken)) {
766
            LOGGER.warn("AI lead intake rejected: invalid or missing Auth-Token");
37029 aman 767
            return responseSender.unauthorized(null);
36957 aman 768
        }
769
 
770
        // Normalise mobile to the 10-digit number the lead table stores (mobile column is length 10).
771
        // The AI side sends digits-only 10-12 chars; strip any stray non-digits and drop a leading
772
        // country code (e.g. 91) when present.
773
        String rawMobile = aiLeadRequest.getMobile();
774
        String mobile = rawMobile == null ? "" : rawMobile.replaceAll("\\D", "");
775
        if (mobile.length() > 10) {
776
            mobile = mobile.substring(mobile.length() - 10);
777
        }
778
        if (mobile.length() != 10) {
779
            throw new ProfitMandiBusinessException("Mobile Number", String.valueOf(rawMobile),
780
                    "Mobile number must contain 10 digits");
781
        }
782
 
783
        String firstName = aiLeadRequest.getFirstName();
784
        if (firstName == null || firstName.trim().isEmpty()) {
785
            throw new ProfitMandiBusinessException("First Name", firstName, "First name is required");
786
        }
787
 
788
        // Idempotency: scoped to AI leads only - the AI side retries fire-and-forget posts. A lead
789
        // for the same mobile under another source (e.g. SD-WEB, manual) does NOT block creation.
790
        Lead existing = leadRepository.selectByMobileNumberAndSource(mobile, AI_LEAD_SOURCE);
791
        if (existing != null) {
792
            LOGGER.info("AI lead intake: AI lead already exists for mobile {} (id={}), skipping create",
793
                    mobile, existing.getId());
794
            return responseSender.ok(existing.getId());
795
        }
796
 
797
        Lead lead = new Lead();
798
        lead.setLeadMobile(mobile);
799
        lead.setFirstName(firstName.trim());
37027 aman 800
        // last_name / city / address / state are NOT NULL (no default) in user.lead; a minimal
801
        // name+number lead from the AI omits them, so coalesce nulls to "" to avoid an insert crash.
802
        lead.setLastName(aiLeadRequest.getLastName() == null ? "" : aiLeadRequest.getLastName().trim());
803
        String city = aiLeadRequest.getCity() == null ? "" : aiLeadRequest.getCity().trim();
804
        lead.setCity(city);
36957 aman 805
        lead.setOutLetName(aiLeadRequest.getOutletName());
806
        // AI flow does not collect a separate address; mirror web capture and fall back to city
37027 aman 807
        lead.setAddress(city);
37029 aman 808
        // AI now sends state (auto-detected from the city; may be absent). Column is NOT NULL - coalesce to "".
809
        String state = aiLeadRequest.getState();
810
        lead.setState(state == null ? "" : state.trim());
36957 aman 811
 
812
        // Source is stamped server-side; the caller cannot override it
813
        lead.setSource(AI_LEAD_SOURCE);
814
        lead.setCreatedBy(AI_LEAD_SOURCE);
37029 aman 815
        // "NEW" in the AI contract maps to the standard open-lead status (same as web capture) so the
816
        // lead lands in the Open / New leads view, not the separate follow-up bucket.
817
        lead.setStatus(LeadStatus.pending);
36957 aman 818
        lead.setColor("yellow");
819
 
37027 aman 820
        // Optional call-recording URL - voice leads only. Store null when absent so chat leads stay empty.
821
        String recordingUrl = aiLeadRequest.getRecordingUrl();
822
        if (recordingUrl != null && !recordingUrl.trim().isEmpty()) {
823
            lead.setRecordingUrl(recordingUrl.trim());
824
        }
825
 
37893 aman 826
        // Ira channel: IRA_PHONE from the toll-free number, everything else (IRA_WEB, no source, or an
827
        // unknown value) is a web lead. A missing source is still accepted, as before.
828
        String channel = aiLeadRequest.getSource() == null ? "" : aiLeadRequest.getSource().trim().toUpperCase();
829
        if (!channel.isEmpty() && !IRA_PHONE.equals(channel) && !IRA_WEB.equals(channel)) {
830
            LOGGER.warn("AI lead intake: unknown source '{}' for mobile {}, treating as web", aiLeadRequest.getSource(), mobile);
831
        }
832
        lead.setAiChannel(IRA_PHONE.equals(channel) ? IRA_PHONE : IRA_WEB);
833
 
834
        lead.setAssignTo(resolveAiLeadAssignee(lead));
36957 aman 835
        lead.setAuthId(lead.getAssignTo());
836
 
837
        lead.setCreatedTimestamp(LocalDateTime.now());
838
        lead.setUpdatedTimestamp(LocalDateTime.now());
37729 amit 839
        // Unattended: the AI intake is a bot; a collision is skipped and mailed, not thrown.
840
        leadCreationService.createUnattended(lead);
36957 aman 841
 
842
        LOGGER.info("AI lead intake: created lead id={} for mobile {}", lead.getId(), mobile);
843
        return responseSender.ok(lead.getId());
844
 
845
    }
846
 
37353 aman 847
    /**
37354 aman 848
     * Picks the owner for an incoming AI lead: a uniformly random <b>active</b> BGC L1 from
849
     * cs.position (category {@link ProfitMandiConstants#TICKET_CATEGORY_BGC}, escalation L1).
37353 aman 850
     * <p>
37354 aman 851
     * BGC is the desk that works AI/inbound leads before they reach field sales, and BGC L1-L3 is
852
     * already one of the groups offered in the Lead Management "Assign To" list, so a BGC L1 owner
853
     * is a valid assignee the team can see and reassign. Field Sales (category
854
     * {@link ProfitMandiConstants#TICKET_CATEGORY_SALES}) is deliberately NOT the pool here.
855
     * <p>
856
     * Inactive users are filtered out because {@code getAuthUserByCategoryId(int, EscalationType)}
857
     * does not filter on active, and an inactive owner would strand the lead. Ids are already
858
     * distinct per user, so holding several regional positions does not raise a person's odds.
37353 aman 859
     */
860
    private int resolveAiLeadAssignee() {
37354 aman 861
        List<AuthUser> bgcL1 = csService.getAuthUserByCategoryId(
862
                ProfitMandiConstants.TICKET_CATEGORY_BGC, EscalationType.L1);
37353 aman 863
 
37354 aman 864
        List<AuthUser> eligible = bgcL1 == null ? Collections.<AuthUser>emptyList()
865
                : bgcL1.stream()
37353 aman 866
                        .filter(x -> Boolean.TRUE.equals(x.isActive()))
37893 aman 867
                        .filter(x -> x.getId() != IRA_PHONE_LEAD_ASSIGNEE)
37353 aman 868
                        .collect(Collectors.toList());
869
 
870
        if (eligible.isEmpty()) {
37354 aman 871
            LOGGER.warn("AI lead intake: no active BGC L1 in cs.position, falling back to auth id {}",
37353 aman 872
                    AI_LEAD_FALLBACK_ASSIGNEE);
873
            return AI_LEAD_FALLBACK_ASSIGNEE;
874
        }
875
 
876
        AuthUser assignee = eligible.get(ThreadLocalRandom.current().nextInt(eligible.size()));
37354 aman 877
        LOGGER.info("AI lead intake: assigned to BGC L1 {} ({}) picked from {} eligible",
37353 aman 878
                assignee.getId(), assignee.getFullName(), eligible.size());
879
        return assignee.getId();
880
    }
881
 
37893 aman 882
    /**
883
     * Ira phone leads go to Meenakshi; every other AI lead to a random active BGC L1. If she is ever
884
     * deactivated, phone leads fall back to the pool rather than stranding with an inactive owner.
885
     */
886
    private int resolveAiLeadAssignee(Lead lead) {
887
        if (IRA_PHONE.equals(lead.getAiChannel())) {
888
            AuthUser phoneOwner = authRepository.selectById(IRA_PHONE_LEAD_ASSIGNEE);
889
            if (phoneOwner != null && Boolean.TRUE.equals(phoneOwner.isActive())) {
890
                return IRA_PHONE_LEAD_ASSIGNEE;
891
            }
892
            LOGGER.warn("AI lead intake: Ira phone owner {} is inactive, using the BGC L1 pool", IRA_PHONE_LEAD_ASSIGNEE);
893
        }
894
        return resolveAiLeadAssignee();
895
    }
896
 
31677 amit.gupta 897
    @RequestMapping(value = "/getPartnersList", method = RequestMethod.GET)
35079 vikas 898
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 899
    public ResponseEntity<?> getPartners(HttpServletRequest request, @RequestParam(name = "gmailId") String gmailId)
900
            throws ProfitMandiBusinessException {
25952 tejbeer 901
 
31677 amit.gupta 902
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35630 aman 903
        if (authUser == null) {
904
            LOGGER.warn("No auth user found for gmailId: {}", gmailId);
905
            return responseSender.badRequest("No user found for the provided email");
906
        }
25952 tejbeer 907
 
31677 amit.gupta 908
        Map<String, Set<String>> storeGuyMap = csService.getAuthUserPartnerEmailMapping();
25952 tejbeer 909
 
37781 amit 910
        // Copy: the mapping is a shared cached object and must not carry demo partners.
911
        Set<String> emails = new HashSet<>();
912
        if (storeGuyMap.get(authUser.getEmailId()) != null) {
913
            emails.addAll(storeGuyMap.get(authUser.getEmailId()));
914
        }
915
        emails.addAll(demoPartnerAccessService.getDemoPartnerEmails(authUser.getId()));
35630 aman 916
        LOGGER.info("emails: {}", emails);
917
        if (emails == null || emails.isEmpty()) {
918
            LOGGER.info("No partner emails found for user: {}", gmailId);
919
            return responseSender.ok(new ArrayList<>());
920
        }
31677 amit.gupta 921
        List<User> users = userRepository.selectAllByEmailIds(new ArrayList<>(emails));
922
        List<Partner> partners = new ArrayList<>();
923
        for (User user : users) {
35630 aman 924
            try {
925
                UserAccount uc = userAccountRepository.selectSaholicByUserId(user.getId());
926
                if (uc == null) {
927
                    LOGGER.warn("No user account found for userId: {}", user.getId());
928
                    continue;
929
                }
930
                com.spice.profitmandi.dao.entity.user.User userInfo = userUserRepository.selectById(uc.getAccountKey());
931
                if (userInfo == null) {
932
                    LOGGER.warn("No user info found for accountKey: {}", uc.getAccountKey());
933
                    continue;
934
                }
935
                CustomRetailer customRetailer = retailerService.getFofoRetailer(userInfo.getId());
936
                if (customRetailer == null) {
937
                    LOGGER.warn("No custom retailer found for userInfoId: {}", userInfo.getId());
938
                    continue;
939
                }
25952 tejbeer 940
 
35630 aman 941
                Partner partner = new Partner();
942
                partner.setBusinessName(customRetailer.getBusinessName());
943
                partner.setPartnerId(customRetailer.getPartnerId());
944
                partner.setCartId(customRetailer.getCartId());
945
                partner.setEmail(customRetailer.getEmail());
946
                partner.setGstNumber(customRetailer.getGstNumber());
947
                partner.setDisplayName(customRetailer.getDisplayName());
948
                partner.setCity(customRetailer.getAddress() != null ? customRetailer.getAddress().getCity() : null);
949
                partner.setUserId(user.getId());
950
                partners.add(partner);
951
            } catch (Exception e) {
952
                LOGGER.error("Error processing partner for userId: {}", user.getId(), e);
953
            }
31677 amit.gupta 954
        }
35630 aman 955
        LOGGER.info("partners: {}", partners);
31677 amit.gupta 956
        return responseSender.ok(partners);
957
    }
25952 tejbeer 958
 
31677 amit.gupta 959
    @RequestMapping(value = "/franchise-first-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 960
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 961
    public ResponseEntity<?> FranchiseFirstVisit(HttpServletRequest request, @RequestBody CreateFranchiseeRequest
962
            createFranchiseeRequest) throws Exception {
25952 tejbeer 963
 
31677 amit.gupta 964
        FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
965
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
966
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
25952 tejbeer 967
 
31677 amit.gupta 968
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
969
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
970
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
971
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
972
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
973
        franchiseeVisit.setScheduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
974
        // change
975
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 976
 
31677 amit.gupta 977
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
978
        franchiseeVisit.setCreatedBy(authUserName);
979
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 980
 
31677 amit.gupta 981
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 982
 
31677 amit.gupta 983
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
984
        franchiseeActivity.setAction(FranchiseeActivityStatus.FOLLOWUP);
985
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
986
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
987
        franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 988
 
31677 amit.gupta 989
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
990
        franchiseeActivityRepository.persist(franchiseeActivity);
31249 tejbeer 991
 
31677 amit.gupta 992
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
31249 tejbeer 993
 
35079 vikas 994
        visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit", authUser.getId(), createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 995
 
31677 amit.gupta 996
        return responseSender.ok(true);
997
    }
25952 tejbeer 998
 
31677 amit.gupta 999
    @RequestMapping(value = "/franchise-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1000
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1001
    public ResponseEntity<?> FranchiseVisit(HttpServletRequest request,
1002
                                            @RequestBody CreateFranchiseeRequest createFranchiseeRequest) throws Exception {
25952 tejbeer 1003
 
34394 tejus.loha 1004
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, createFranchiseeRequest.getFofoId());
34276 ranu 1005
 
36677 vikas 1006
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectAllByFofoId(createFranchiseeRequest.getFofoId());
36723 vikas 1007
        FranchiseeVisit franchiseeVisit = franchiseeVisits.isEmpty() ? new FranchiseeVisit() : franchiseeVisits.get(0);
31677 amit.gupta 1008
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
1009
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
34394 tejus.loha 1010
        LOGGER.info("rbmL1 {}", rbmL1);
31677 amit.gupta 1011
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
1012
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
1013
        franchiseeVisit.setPartnerRemark(createFranchiseeRequest.getPartnerRemark());
1014
        franchiseeVisit.setOutsideVisibity(createFranchiseeRequest.getOutsideVisibity());
1015
        franchiseeVisit.setInstoreVisibility(createFranchiseeRequest.getInstoreVisibility());
1016
        franchiseeVisit.setOutsideStock(createFranchiseeRequest.getOutsideStock());
1017
        franchiseeVisit.setSystemKnowledge(createFranchiseeRequest.getSystemKnowledge());
1018
        franchiseeVisit.setWorkingDevice(createFranchiseeRequest.getWorkingDevice());
1019
        franchiseeVisit.setWorkingPrinter(createFranchiseeRequest.getWorkingPrinter());
1020
        franchiseeVisit.setCarryBags(createFranchiseeRequest.getCarryBags());
1021
        franchiseeVisit.setSmartdukaanTshirt(createFranchiseeRequest.getSmartdukaanTshirt());
1022
        franchiseeVisit.setLatestDummies(createFranchiseeRequest.getLatestDummies());
1023
        franchiseeVisit.setInvestment(createFranchiseeRequest.getInvestment());
1024
        franchiseeVisit.setMtd(createFranchiseeRequest.getMtd());
1025
        franchiseeVisit.setHygiene(createFranchiseeRequest.getHygiene());
1026
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
1027
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1028
        franchiseeVisit.setInformedAboutOnline(createFranchiseeRequest.getOnline());
1029
        franchiseeVisit.setPendingBilling(createFranchiseeRequest.getPendingBilling());
34276 ranu 1030
        franchiseeVisit.setRbmId(rbmL1);
1031
        franchiseeVisit.setRbmRating(createFranchiseeRequest.getRbmRating());
31677 amit.gupta 1032
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
1033
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
1034
        } else {
1035
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
1036
        }
25952 tejbeer 1037
 
31677 amit.gupta 1038
        // AuthUser authUser =
1039
        // authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
1040
        // change
1041
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 1042
 
31677 amit.gupta 1043
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
1044
        franchiseeVisit.setCreatedBy(authUserName);
1045
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 1046
 
31677 amit.gupta 1047
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1048
 
31677 amit.gupta 1049
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
1050
        franchiseeActivity.setAction(createFranchiseeRequest.getAction());
1051
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
1052
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
1053
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
1054
            franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getSchelduleTimestamp());
31249 tejbeer 1055
 
31677 amit.gupta 1056
            visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
1057
                    franchiseeVisit.getAuthId(), createFranchiseeRequest.getSchelduleTimestamp());
1058
        } else {
1059
            franchiseeActivity.setSchelduleTimestamp(null);
1060
        }
1061
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
1062
        franchiseeActivityRepository.persist(franchiseeActivity);
25952 tejbeer 1063
 
31677 amit.gupta 1064
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
34276 ranu 1065
 
34394 tejus.loha 1066
        if (!createFranchiseeRequest.getOutsideVisibityReason().isEmpty()) {
34288 ranu 1067
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_EXTERNAL_VISIBILITY, createFranchiseeRequest.getOutsideVisibityReason(), authUser.getId());
34276 ranu 1068
        }
1069
 
34394 tejus.loha 1070
        if (!createFranchiseeRequest.getInstoreVisibilityReason().isEmpty()) {
34288 ranu 1071
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_INTERNAL_VISIBILITY, createFranchiseeRequest.getInstoreVisibilityReason(), authUser.getId());
34276 ranu 1072
        }
1073
 
34394 tejus.loha 1074
        if (!createFranchiseeRequest.getOutsideStockReason().isEmpty()) {
34288 ranu 1075
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_OUTSIDE_STOCK, createFranchiseeRequest.getOutsideStockReason(), authUser.getId());
34276 ranu 1076
        }
1077
 
34394 tejus.loha 1078
        if (!createFranchiseeRequest.getSystemKnowledgeReason().isEmpty()) {
34288 ranu 1079
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_TRAINING, ProfitMandiConstants.TICKET_CATEGORY_TRAINING_NEED, createFranchiseeRequest.getSystemKnowledgeReason(), authUser.getId());
34276 ranu 1080
        }
1081
 
34394 tejus.loha 1082
        if (!createFranchiseeRequest.getLatestDummiesReason().isEmpty()) {
34288 ranu 1083
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_MARKETING_DUMMIES, createFranchiseeRequest.getLatestDummiesReason(), authUser.getId());
34276 ranu 1084
        }
1085
 
34394 tejus.loha 1086
        if (!createFranchiseeRequest.getInvestmentReason().isEmpty()) {
34288 ranu 1087
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_INVESTMENT, createFranchiseeRequest.getInvestmentReason(), authUser.getId());
34276 ranu 1088
        }
1089
 
34394 tejus.loha 1090
        if (!createFranchiseeRequest.getHygieneReason().isEmpty()) {
34288 ranu 1091
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_DATA_ACCURACY, createFranchiseeRequest.getHygieneReason(), authUser.getId());
1092
        }
34276 ranu 1093
 
31677 amit.gupta 1094
        return responseSender.ok(true);
34276 ranu 1095
 
31677 amit.gupta 1096
    }
25952 tejbeer 1097
 
31677 amit.gupta 1098
    @RequestMapping(value = "/getFranchiseVisit", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1099
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1100
    public ResponseEntity<?> getFranchiseVisit(HttpServletRequest request,
35288 amit 1101
                                               @RequestParam(name = "gmailId") String gmailId, @RequestParam(name = "status") FranchiseeVisitStatus
1102
                                                       status,
31677 amit.gupta 1103
                                               @RequestParam(name = "offset", defaultValue = "0") int offset,
1104
                                               @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
1105
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35079 vikas 1106
        List<VisitRequest> visitRequests = visitRequestRepository.selectByAuthIdAndDate(authUser.getId(), LocalDate.now());
31677 amit.gupta 1107
        Map<Integer, List<VisitRequest>> visitRequestMap = null;
1108
        if (!visitRequests.isEmpty()) {
1109
            visitRequestMap = visitRequests.stream().collect(Collectors.groupingBy(x -> x.getVisitId()));
1110
        }
35079 vikas 1111
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectByAuthIdAndStatus(authUser.getId(), status, offset, limit);
25952 tejbeer 1112
 
35415 amit 1113
        // Batch fetch all FranchiseeActivity in one query instead of N+1
1114
        List<Integer> activityIds = franchiseeVisits.stream()
1115
                .filter(fv -> fv.getFranchiseActivityId() != 0)
1116
                .map(FranchiseeVisit::getFranchiseActivityId)
1117
                .collect(Collectors.toList());
1118
        Map<Integer, FranchiseeActivity> activityMap = new HashMap<>();
1119
        if (!activityIds.isEmpty()) {
1120
            activityMap = franchiseeActivityRepository.selectByIds(activityIds).stream()
1121
                    .collect(Collectors.toMap(FranchiseeActivity::getId, x -> x));
1122
        }
1123
 
31677 amit.gupta 1124
        for (FranchiseeVisit fv : franchiseeVisits) {
1125
            if (visitRequestMap != null) {
31249 tejbeer 1126
 
31677 amit.gupta 1127
                List<VisitRequest> visitRequest = visitRequestMap.get(fv.getId());
1128
                if (visitRequest != null) {
1129
                    if (visitRequest.size() > 1) {
31249 tejbeer 1130
 
35079 vikas 1131
                        Comparator<VisitRequest> visitComparato = Comparator.comparing(VisitRequest::getCreatedTimestamp);
31249 tejbeer 1132
 
31677 amit.gupta 1133
                        VisitRequest youngestVisit = visitRequest.stream().max(visitComparato).get();
1134
                        fv.setVisitStatus(youngestVisit.getStatus());
31249 tejbeer 1135
 
31677 amit.gupta 1136
                    } else {
1137
                        fv.setVisitStatus(visitRequest.get(0).getStatus());
31249 tejbeer 1138
 
31677 amit.gupta 1139
                    }
1140
                }
1141
            }
1142
            if (fv.getFranchiseActivityId() != 0) {
35415 amit 1143
                FranchiseeActivity fA = activityMap.get(fv.getFranchiseActivityId());
31677 amit.gupta 1144
                fv.setFranchiseeActivity(fA);
1145
            }
31249 tejbeer 1146
 
31677 amit.gupta 1147
        }
25952 tejbeer 1148
 
31677 amit.gupta 1149
        return responseSender.ok(franchiseeVisits);
25952 tejbeer 1150
 
31677 amit.gupta 1151
    }
25952 tejbeer 1152
 
31677 amit.gupta 1153
    @RequestMapping(value = "/getFranchiseActivity", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1154
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1155
    public ResponseEntity<?> getFranchiseActivity(HttpServletRequest request, @RequestParam(name = "id") int id) throws
1156
            ProfitMandiBusinessException {
25952 tejbeer 1157
 
31677 amit.gupta 1158
        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityRepository.selectByFranchiseeVisitId(id);
1159
        return responseSender.ok(franchiseeActivities);
25952 tejbeer 1160
 
31677 amit.gupta 1161
    }
25952 tejbeer 1162
 
31677 amit.gupta 1163
    @RequestMapping(value = "/getFranchiseeInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1164
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1165
    public ResponseEntity<?> getFranchiseeInfo(HttpServletRequest request, @RequestParam(name = "id") int id) throws
1166
            ProfitMandiBusinessException {
36678 vikas 1167
        FranchiseeVisit franchiseeVisit;
1168
        if (String.valueOf(id).length() < 9) {
1169
            franchiseeVisit = franchiseeVisitRepository.selectById(id);
1170
        } else {
1171
            List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectAllByFofoId(id);
36722 vikas 1172
            if (franchiseeVisits.isEmpty()) {
1173
                return responseSender.ok(null);
1174
            }
36678 vikas 1175
            franchiseeVisit = franchiseeVisits.get(0);
1176
        }
25952 tejbeer 1177
 
31677 amit.gupta 1178
        List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
30487 tejbeer 1179
 
31677 amit.gupta 1180
        List<String> brands = mobileBrands.stream().filter(x -> (boolean) x.get("active"))
1181
                .map(x -> (String) x.get("name")).collect(Collectors.toList());
30487 tejbeer 1182
 
31677 amit.gupta 1183
        franchiseeVisit.setBrands(brands);
30487 tejbeer 1184
 
31677 amit.gupta 1185
        return responseSender.ok(franchiseeVisit);
25952 tejbeer 1186
 
31677 amit.gupta 1187
    }
25952 tejbeer 1188
 
31677 amit.gupta 1189
    @RequestMapping(value = "/franchise-visit-update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1190
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1191
    public ResponseEntity<?> franchiseVisitUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
1192
                                                  @RequestParam(name = "action") FranchiseeActivityStatus action,
1193
                                                  @RequestParam(name = "resolution") String resolution,
1194
                                                  @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp)
31677 amit.gupta 1195
            throws ProfitMandiBusinessException {
1196
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
25952 tejbeer 1197
 
31677 amit.gupta 1198
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
25952 tejbeer 1199
 
31677 amit.gupta 1200
        if (action == FranchiseeActivityStatus.FOLLOWUP) {
30487 tejbeer 1201
 
31677 amit.gupta 1202
            if (schelduleTimestamp != null) {
31249 tejbeer 1203
 
31677 amit.gupta 1204
                visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
1205
                        franchiseeVisit.getAuthId(), schelduleTimestamp);
1206
            }
31249 tejbeer 1207
 
31677 amit.gupta 1208
            franchiseeActivity.setSchelduleTimestamp(schelduleTimestamp);
1209
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
1210
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1211
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1212
 
31677 amit.gupta 1213
        } else {
30487 tejbeer 1214
 
31677 amit.gupta 1215
            franchiseeActivity.setSchelduleTimestamp(null);
1216
            franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
1217
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
1218
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1219
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1220
 
31677 amit.gupta 1221
        }
25952 tejbeer 1222
 
31677 amit.gupta 1223
        franchiseeActivity.setResolution(resolution);
1224
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
1225
        franchiseeActivity.setAction(action);
30487 tejbeer 1226
 
31677 amit.gupta 1227
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
1228
        franchiseeActivityRepository.persist(franchiseeActivity);
30487 tejbeer 1229
 
31677 amit.gupta 1230
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
1231
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
1232
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1233
        franchiseeVisitRepository.persist(franchiseeVisit);
30487 tejbeer 1234
 
31677 amit.gupta 1235
        return responseSender.ok(true);
25952 tejbeer 1236
 
31677 amit.gupta 1237
    }
28935 tejbeer 1238
 
31677 amit.gupta 1239
    @RequestMapping(value = "/onBoardingTimelineStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1240
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1241
    public ResponseEntity<?> onBoardingTimelineStatus(HttpServletRequest request, Model model)
1242
            throws ProfitMandiBusinessException {
35075 aman 1243
        //This userId is of dtr.users
31677 amit.gupta 1244
        int userId = (int) request.getAttribute("userId");
35075 aman 1245
 
1246
        //UserCart contains userId/retailerId in context of user.user as
1247
        //uc contains retailerId and cartId of the retailerId that belongs to user schema
31677 amit.gupta 1248
        UserCart uc = userAccountRepository.getUserCart(userId);
1249
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
1250
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1251
        Map<StoreTimeline, OnBoardingTimelineModel> timelineStatus = null;
1252
        LOGGER.info("partnerOnBoardingPanel" + partnerOnBoardingPanel);
1253
        if (partnerOnBoardingPanel != null) {
28935 tejbeer 1254
 
31677 amit.gupta 1255
            timelineStatus = storeTimelineTatService.getTimeline(partnerOnBoardingPanel.getId());
1256
        }
1257
        List<OnBoardingTimelineModel> onBoardingModel = new ArrayList<>();
1258
        if (timelineStatus != null) {
1259
            onBoardingModel = timelineStatus.values().stream().skip(2).map(x -> x).collect(Collectors.toList());
1260
        }
1261
        return responseSender.ok(onBoardingModel);
28935 tejbeer 1262
 
31677 amit.gupta 1263
    }
35288 amit 1264
 
35075 aman 1265
    @RequestMapping(value = "/purchaseExist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1266
    @ApiImplicitParams({
1267
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35415 amit 1268
    public ResponseEntity<?> purchaseExist(HttpServletRequest request) throws ProfitMandiBusinessException {
35075 aman 1269
        int userId = (int) request.getAttribute("userId");
1270
        UserCart uc = userAccountRepository.getUserCart(userId);
35415 amit 1271
        return responseSender.ok(purchaseRepository.hasPurchaseForFofoId(uc.getUserId()));
35075 aman 1272
    }
35288 amit 1273
 
31677 amit.gupta 1274
    @RequestMapping(value = "/onBoardingTimelineVisibility", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1275
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1276
    public ResponseEntity<?> onBoardingTimelineVisibility(HttpServletRequest request, Model model)
1277
            throws ProfitMandiBusinessException {
1278
        int userId = (int) request.getAttribute("userId");
1279
        UserCart uc = userAccountRepository.getUserCart(userId);
28982 tejbeer 1280
 
31677 amit.gupta 1281
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
1282
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1283
        boolean status = true;
1284
        if (partnerOnBoardingPanel != null) {
28982 tejbeer 1285
 
31677 amit.gupta 1286
            status = storeTimelineTatService.getTimelineCompleted(partnerOnBoardingPanel.getId());
1287
        }
28982 tejbeer 1288
 
31677 amit.gupta 1289
        LOGGER.info("status" + status);
28983 tejbeer 1290
 
31677 amit.gupta 1291
        return responseSender.ok(status);
28982 tejbeer 1292
 
31677 amit.gupta 1293
    }
30077 tejbeer 1294
 
31677 amit.gupta 1295
    @RequestMapping(value = "/getPartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1296
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1297
    public ResponseEntity<?> getPartnerTarget(HttpServletRequest request, @RequestParam String
1298
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
1299
            ProfitMandiBusinessException {
30077 tejbeer 1300
 
35632 ranu 1301
        long startTime = System.currentTimeMillis();
1302
        long lapTime = startTime;
1303
 
31677 amit.gupta 1304
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35632 ranu 1305
 
35649 ranu 1306
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1307
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
31677 amit.gupta 1308
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
30078 tejbeer 1309
 
35649 ranu 1310
 
31677 amit.gupta 1311
        float totalPartnerTargetSecondary = 0;
1312
        float totalPartnerTargetCollection = 0;
1313
        float totalPartnerAchievementSecondary = 0;
1314
        float totalPartnerAchievementCollection = 0;
1315
        TargetModel tm = new TargetModel();
1316
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
35632 ranu 1317
        Map<Integer, Long> partnerTicketCount = new HashMap<>(); // Will be populated after we have fofoIdList
30416 tejbeer 1318
 
31677 amit.gupta 1319
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
30077 tejbeer 1320
 
31677 amit.gupta 1321
        if (fofoIds != null && fofoIds.size() > 0) {
32737 amit.gupta 1322
            LOGGER.info("fofoIds {}", fofoIds);
31727 amit.gupta 1323
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
31677 amit.gupta 1324
                    .filter(x -> (!x.isInternal() && (activationType == null || x.getActivationType().equals(activationType))))
1325
                    .map(x -> x.getId()).collect(Collectors.toList());
35632 ranu 1326
            LOGGER.info("PERF: selectByRetailerIds took {} ms", System.currentTimeMillis() - lapTime);
1327
            lapTime = System.currentTimeMillis();
1328
            LOGGER.info("fofoIdList size: {}", fofoIdList.size());
1329
 
1330
            // Optimized: fetch ticket counts only for specific fofoIds instead of all retailers
1331
            if (!fofoIdList.isEmpty()) {
1332
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
1333
            }
1334
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1335
            lapTime = System.currentTimeMillis();
31677 amit.gupta 1336
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
30077 tejbeer 1337
 
31677 amit.gupta 1338
            if (dayValue.equals("previous")) {
1339
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
30138 tejbeer 1340
 
31677 amit.gupta 1341
            }
30087 tejbeer 1342
 
31686 amit.gupta 1343
            if (fofoIdList.size() > 0) {
30453 tejbeer 1344
 
35632 ranu 1345
                // Fetch fofoIds with overdue loans (pending amount > 0 and created > 15 days ago)
1346
                // Optimized: returns only fofoIds, not full Loan objects
1347
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
1348
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
1349
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
1350
                lapTime = System.currentTimeMillis();
1351
 
1352
                // Fetch fofoIds with MTD billing above threshold (20000)
1353
                // Optimized: direct query on orders table instead of complex RBM query
1354
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
1355
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
35650 ranu 1356
                long billingThreshold = 1000L; // Same as RbmWeeklyBillingModel.BILLING_THRESHOLD
35632 ranu 1357
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
1358
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
1359
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
1360
                lapTime = System.currentTimeMillis();
1361
 
35079 vikas 1362
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
35632 ranu 1363
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
1364
                lapTime = System.currentTimeMillis();
30087 tejbeer 1365
 
31686 amit.gupta 1366
                if (!partnerDailyInvestments.isEmpty()) {
35079 vikas 1367
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31686 amit.gupta 1368
                }
30077 tejbeer 1369
 
35632 ranu 1370
                // Optimized: fetch only specific fofoIds instead of all retailers
1371
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
1372
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
1373
                lapTime = System.currentTimeMillis();
30426 tejbeer 1374
 
31686 amit.gupta 1375
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
35632 ranu 1376
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
1377
                lapTime = System.currentTimeMillis();
30453 tejbeer 1378
 
31686 amit.gupta 1379
                long todayCollectionCount = 0;
1380
                if (!remarkIds.isEmpty()) {
1381
                    todayCollectionCount = partnerCollectionRemarkRepository
1382
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
1383
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
1384
                            .collect(Collectors.counting());
30453 tejbeer 1385
 
31686 amit.gupta 1386
                }
35632 ranu 1387
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
1388
                lapTime = System.currentTimeMillis();
30330 tejbeer 1389
 
35079 vikas 1390
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
35632 ranu 1391
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
1392
                lapTime = System.currentTimeMillis();
30077 tejbeer 1393
 
32978 amit.gupta 1394
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
31686 amit.gupta 1395
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
1396
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
35632 ranu 1397
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
1398
                lapTime = System.currentTimeMillis();
30077 tejbeer 1399
 
35415 amit 1400
                // Pre-fetch all AuthUsers that might be needed (instead of N+1 queries)
1401
                Set<Integer> allAuthIds = new HashSet<>();
1402
                collectionMap.values().stream()
1403
                        .map(PartnerCollectionPlanModel::getAuthId)
1404
                        .filter(id -> id != null && id != authUser.getId())
1405
                        .forEach(allAuthIds::add);
1406
                partnerSecondaryPlans.values().stream()
1407
                        .flatMap(List::stream)
1408
                        .map(PartnerSecondaryPlanModel::getAuthId)
1409
                        .filter(id -> id != null && id != authUser.getId())
1410
                        .forEach(allAuthIds::add);
1411
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
1412
                if (!allAuthIds.isEmpty()) {
1413
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
1414
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
1415
                }
1416
 
35968 ranu 1417
                // Fetch BM/ASM/RBM for all partners
1418
                Map<Integer, Map<String, Integer>> bmAsmRbmMap = csService.getBmAsmRbmAuthUserIdsByFofoIds(new HashSet<>(fofoIdList));
1419
                LOGGER.info("PERF: getBmAsmRbmAuthUserIdsByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1420
                lapTime = System.currentTimeMillis();
1421
 
1422
                // Collect all BM/ASM/RBM auth IDs to batch fetch AuthUser names
1423
                Set<Integer> bmAsmRbmAuthIds = bmAsmRbmMap.values().stream()
1424
                        .flatMap(m -> m.values().stream())
1425
                        .filter(id -> id != null && id > 0)
1426
                        .collect(Collectors.toSet());
1427
 
1428
                Map<Integer, AuthUser> bmAsmRbmAuthUserMap = new HashMap<>();
1429
                if (!bmAsmRbmAuthIds.isEmpty()) {
1430
                    bmAsmRbmAuthUserMap = authRepository.selectByIds(new ArrayList<>(bmAsmRbmAuthIds)).stream()
1431
                            .collect(Collectors.toMap(AuthUser::getId, x -> x, (a, b) -> a));
1432
                }
1433
                LOGGER.info("PERF: fetch BM/ASM/RBM AuthUsers took {} ms", System.currentTimeMillis() - lapTime);
1434
                lapTime = System.currentTimeMillis();
1435
 
32978 amit.gupta 1436
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
35968 ranu 1437
                final Map<Integer, AuthUser> finalBmAsmRbmAuthUserMap = bmAsmRbmAuthUserMap;
31686 amit.gupta 1438
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
1439
                    int fofoId = customRetailerEntry.getKey();
1440
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
1441
                    float totalSecondaryPlan = 0;
1442
                    float totalSecondaryAchivement = 0;
30077 tejbeer 1443
 
31686 amit.gupta 1444
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
1445
                    ptam.setFofoId(fofoId);
1446
                    ptam.setBusinessName(customRetailer.getBusinessName());
1447
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 1448
                    ptam.setActivationType(customRetailer.getActivationType());
30087 tejbeer 1449
 
35968 ranu 1450
                    // Set ASM/RBM/BM names
1451
                    Map<String, Integer> roleMap = bmAsmRbmMap.get(fofoId);
1452
                    if (roleMap != null) {
1453
                        Integer asmId = roleMap.get("ASM");
1454
                        if (asmId != null && asmId > 0 && finalBmAsmRbmAuthUserMap.get(asmId) != null) {
1455
                            ptam.setAsmName(finalBmAsmRbmAuthUserMap.get(asmId).getFullName());
1456
                        }
1457
                        Integer rbmId = roleMap.get("RBM");
1458
                        if (rbmId != null && rbmId > 0 && finalBmAsmRbmAuthUserMap.get(rbmId) != null) {
1459
                            ptam.setRbmName(finalBmAsmRbmAuthUserMap.get(rbmId).getFullName());
1460
                        }
1461
                        Integer bmId = roleMap.get("BM");
1462
                        if (bmId != null && bmId > 0 && finalBmAsmRbmAuthUserMap.get(bmId) != null) {
1463
                            ptam.setBmName(finalBmAsmRbmAuthUserMap.get(bmId).getFullName());
1464
                        }
1465
                    }
1466
 
31686 amit.gupta 1467
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1468
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1469
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1470
                    }
30808 tejbeer 1471
 
32978 amit.gupta 1472
                    if (collectionMap.get(fofoId) != null) {
1473
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
30330 tejbeer 1474
 
31686 amit.gupta 1475
                        ptam.setRemark(collectionPlan.getRemark());
1476
                        ptam.setMessage(collectionPlan.getMessage());
1477
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
35632 ranu 1478
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
35835 ranu 1479
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
31686 amit.gupta 1480
                        ptam.setRank(collectionPlan.getRank());
36267 ranu 1481
 
1482
                        // If remark is SALES_ESCALATION, fetch open escalation ticket activities
1483
                        if (CollectionRemark.SALES_ESCALATION.equals(collectionPlan.getRemark())
1484
                                || CollectionRemark.PARTIAL_RESOLVE.equals(collectionPlan.getRemark())
1485
                                || CollectionRemark.NOT_RESOLVED.equals(collectionPlan.getRemark())) {
1486
                            List<Ticket> openTickets = ticketRepository.selectAllOpenTicketByRetailer(fofoId);
1487
                            for (Ticket ticket : openTickets) {
1488
                                if (ticket.getSubCategoryId() == ProfitMandiConstants.SALES_ESCALATION) {
1489
                                    List<Activity> activities = activityRepository.selectAll(ticket.getId());
1490
                                    ptam.setTicketActivities(activities);
1491
                                    break;
1492
                                }
1493
                            }
1494
                        }
1495
 
31686 amit.gupta 1496
                        Integer authId = collectionPlan.getAuthId();
30330 tejbeer 1497
 
31686 amit.gupta 1498
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
30416 tejbeer 1499
 
31686 amit.gupta 1500
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
30077 tejbeer 1501
 
31686 amit.gupta 1502
                        LOGGER.info("authId" + authId);
30137 tejbeer 1503
 
31686 amit.gupta 1504
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1505
                            float targetCollection = 0;
30330 tejbeer 1506
 
31686 amit.gupta 1507
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1508
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1509
                            } else {
1510
                                targetCollection = collectionPlan.getTargetPlan();
31677 amit.gupta 1511
                            }
30451 tejbeer 1512
 
31677 amit.gupta 1513
                            if (authId != null && authId == authUser.getId()) {
31686 amit.gupta 1514
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1515
                                    totalPartnerTargetCollection += targetCollection;
1516
                                }
31677 amit.gupta 1517
                            }
31686 amit.gupta 1518
                            ptam.setCollectionTarget(targetCollection);
1519
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1520
                                    && collectionPlan.getWalletTimestamp() != null
1521
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1522
                                if (authId != null && authId == authUser.getId()) {
1523
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1524
                                }
1525
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1526
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1527
                                    && collectionPlan.getAchievementPlan() != null) {
1528
                                if (authId != null && authId == authUser.getId()) {
1529
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1530
                                }
1531
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1532
 
31677 amit.gupta 1533
                            }
31686 amit.gupta 1534
                        }
30822 tejbeer 1535
 
31686 amit.gupta 1536
                        if (authId != null && authId != authUser.getId()) {
35415 amit 1537
                            ptam.setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1538
 
31677 amit.gupta 1539
                        }
30087 tejbeer 1540
 
31686 amit.gupta 1541
                        if (collectionPlan.getCommittedDate() != null) {
30087 tejbeer 1542
 
31686 amit.gupta 1543
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1544
                        }
30087 tejbeer 1545
 
31677 amit.gupta 1546
                    }
30821 tejbeer 1547
 
31686 amit.gupta 1548
                    // Secondary
30077 tejbeer 1549
 
31686 amit.gupta 1550
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1551
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
32978 amit.gupta 1552
                    if (partnerSecondaryPlans.get(fofoId) != null) {
31686 amit.gupta 1553
                        long otherBrandSecondary = 0;
32978 amit.gupta 1554
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
31686 amit.gupta 1555
                            Integer authId = pspm.getAuthId();
1556
                            if (!brands.contains(pspm.getBrand())) {
1557
                                if (pspm.getAchievementPlan() != null) {
1558
                                    otherBrandSecondary += pspm.getAchievementPlan();
1559
                                }
1560
                            } else {
1561
                                otherPartnerSecondaryPlanModel = pspm;
1562
                            }
1563
                            if (pspm.getTargetPlan() != null) {
1564
                                totalSecondaryPlan += pspm.getTargetPlan();
1565
                            }
30330 tejbeer 1566
 
31677 amit.gupta 1567
                            if (pspm.getAchievementPlan() != null) {
31686 amit.gupta 1568
                                totalSecondaryAchivement += pspm.getAchievementPlan();
31677 amit.gupta 1569
                            }
30087 tejbeer 1570
 
31686 amit.gupta 1571
                            if (pspm.getCommittedDate() != null) {
30137 tejbeer 1572
 
31686 amit.gupta 1573
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1574
                            }
1575
                            if (authId != null && authId == authUser.getId()) {
30137 tejbeer 1576
 
31686 amit.gupta 1577
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
30087 tejbeer 1578
 
31686 amit.gupta 1579
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1580
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1581
                                    }
1582
                                }
30087 tejbeer 1583
 
31686 amit.gupta 1584
                                if (pspm.getAchievementPlan() != null) {
1585
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
31677 amit.gupta 1586
                                }
31686 amit.gupta 1587
 
31677 amit.gupta 1588
                            }
31686 amit.gupta 1589
                        }
1590
                        if (otherPartnerSecondaryPlanModel != null) {
1591
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1592
                        }
32978 amit.gupta 1593
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
31686 amit.gupta 1594
                                .filter(x -> brands.contains(x.getBrand()))
1595
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30087 tejbeer 1596
 
31686 amit.gupta 1597
                        if (secondaryModelMap.containsKey("Others")) {
1598
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1599
                            psp.setAchievementPlan(otherBrandSecondary);
1600
                        } else {
35079 vikas 1601
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
31686 amit.gupta 1602
                        }
1603
                        for (String brand : brands) {
1604
                            if (!secondaryModelMap.containsKey(brand)) {
35079 vikas 1605
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
31677 amit.gupta 1606
                            }
31686 amit.gupta 1607
                        }
30087 tejbeer 1608
 
31686 amit.gupta 1609
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1610
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1611
                            if (authId != null && authId != authUser.getId()) {
35415 amit 1612
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1613
                                ptam.setSecondaryColor("red");
1614
                            }
1615
 
31677 amit.gupta 1616
                        }
30077 tejbeer 1617
 
31686 amit.gupta 1618
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1619
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1620
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1621
                        // Secondary
1622
 
31677 amit.gupta 1623
                    } else {
31686 amit.gupta 1624
                        for (String brand : brands) {
1625
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1626
                            pspm.setAchievementPlan((long) 0);
1627
                            pspm.setTargetPlan((long) 0);
1628
                            pspm.setBrand(brand);
1629
                            pspm.setFofoId(fofoId);
1630
                            secondaryModelMap.put(brand, pspm);
31677 amit.gupta 1631
                        }
31686 amit.gupta 1632
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
31677 amit.gupta 1633
                    }
30077 tejbeer 1634
 
31686 amit.gupta 1635
                    if (!partnerTicketCount.isEmpty()) {
1636
                        if (partnerTicketCount.get(fofoId) != null) {
1637
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
1638
                        } else {
1639
                            ptam.setTicketCount(0);
1640
 
31677 amit.gupta 1641
                        }
1642
                    }
30087 tejbeer 1643
 
35632 ranu 1644
                    // Category Assignment Logic (Priority: PLAN_TODAY > CARRY_FORWARD > ZERO_BILLED > UNTOUCHED > NORMAL)
1645
                    // Check if partner has credit due (loans > 15 days with pending amount) - just a flag, doesn't affect sorting
1646
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
1647
                    ptam.setHasOverdue(hasCreditDue);
1648
 
1649
                    // Default rank to 5 (Normal) if no collection plan exists
1650
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
1651
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1652
 
1653
                    // Assign category based on rank (overdue is just a flag, doesn't affect category)
1654
                    if (rank == 1) {
1655
                        ptam.setCategory("PLAN_TODAY");
1656
                        ptam.setCategoryPriority(1);
1657
                    } else if (rank == 2) {
1658
                        ptam.setCategory("CARRY_FORWARD");
1659
                        ptam.setCategoryPriority(2);
1660
                    } else if (hasZeroBilling && rank < 5) {
1661
                        // Zero billed only if NOT in normal category (rank 5+)
1662
                        // If rank is 1,2,3,4 and has zero billing, include in ZERO_BILLED
1663
                        ptam.setCategory("ZERO_BILLED");
1664
                        ptam.setCategoryPriority(3);
1665
                    } else if (rank == 3) {
1666
                        ptam.setCategory("UNTOUCHED");
1667
                        ptam.setCategoryPriority(4);
1668
                    } else {
1669
                        // rank 4 (future plan) and rank 5+ (normal) go to NORMAL
1670
                        // Also, zero billing with rank 5+ goes to NORMAL (not ZERO_BILLED)
1671
                        ptam.setCategory("NORMAL");
1672
                        ptam.setCategoryPriority(5);
1673
                    }
1674
 
31686 amit.gupta 1675
                    ptams.add(ptam);
30077 tejbeer 1676
 
31677 amit.gupta 1677
                }
32923 ranu 1678
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
30077 tejbeer 1679
 
32923 ranu 1680
                LOGGER.info("positions {}", positions);
1681
 
35079 vikas 1682
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 1683
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
1684
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35079 vikas 1685
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
32923 ranu 1686
 
36211 ranu 1687
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
32923 ranu 1688
 
35079 vikas 1689
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
32923 ranu 1690
 
31686 amit.gupta 1691
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
1692
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
1693
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
1694
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
1695
                tm.setTodayCollectionCount((int) todayCollectionCount);
32923 ranu 1696
                List<PartnerTargetAchievementModel> filteredPtams;
30416 tejbeer 1697
 
32923 ranu 1698
                if (isRBMAndL1) {
34428 ranu 1699
                    filteredPtams = ptams;
1700
//                    as of now all party is showing to rbm
1701
                    /*filteredPtams = ptams.stream()
32978 amit.gupta 1702
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34428 ranu 1703
                            .collect(Collectors.toList());*/
32923 ranu 1704
                } else if (isRBMAndNotL1) {
34429 ranu 1705
                    filteredPtams = ptams;
1706
                    /*filteredPtams = ptams.stream()
32923 ranu 1707
                            .filter(ptam -> !(CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34429 ranu 1708
                            .collect(Collectors.toList());*/
33041 ranu 1709
                } else if (isSales) {
1710
                    filteredPtams = ptams.stream()
36211 ranu 1711
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
33041 ranu 1712
                            .collect(Collectors.toList());
32923 ranu 1713
                } else {
1714
                    filteredPtams = ptams;
1715
                }
34428 ranu 1716
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 1717
                tm.setRBMAndL2(isRBMAndL2);
1718
                tm.setRBMAndL3(isRBMAndL3);
34428 ranu 1719
                tm.setRBMAndNotL1(isRBMAndNotL1);
1720
                tm.setSales(isSales);
35632 ranu 1721
 
1722
                // Calculate category counts
1723
                Map<String, Long> categoryCounts = filteredPtams.stream()
1724
                        .collect(Collectors.groupingBy(
1725
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
1726
                                Collectors.counting()));
1727
                // Count parties with overdue flag (independent of category)
1728
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
1729
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
1730
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
1731
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
1732
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
1733
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
1734
 
1735
                // Sort by: 1) Partners with today's remark go to bottom of entire list
35835 ranu 1736
                //          EXCEPT: NO_ANSWER/SCHEDULE_CALL with scheduledCallTime reached → comes back up
35853 ranu 1737
                //          EXCEPT: NO_ANSWER without scheduledCallTime older than 4 hours → comes back up
35632 ranu 1738
                //          2) Category Priority (PLAN_TODAY=1, CARRY_FORWARD=2, ZERO_BILLED=3, UNTOUCHED=4, NORMAL=5)
1739
                //          3) Then by rank
35835 ranu 1740
                LocalDateTime now = LocalDateTime.now();
35853 ranu 1741
                LocalDateTime fourHoursAgo = now.minusHours(4);
34796 ranu 1742
                tm.setTargetAchievement(filteredPtams.stream()
1743
                        .sorted(Comparator
35632 ranu 1744
                                .comparing((PartnerTargetAchievementModel p) -> {
1745
                                    if (p.getRemarkTimestamp() == null) {
1746
                                        return false; // No remark → comes first
1747
                                    }
1748
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
1749
                                    if (!remarkDate.equals(LocalDate.now())) {
1750
                                        return false; // Not today's remark → comes first
1751
                                    }
35835 ranu 1752
                                    // Check if SCHEDULE_CALL or NO_ANSWER with scheduledCallTime
1753
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
1754
                                        if (p.getScheduledCallTime() != null) {
1755
                                            // Has scheduled time - come up only when scheduled time is reached
1756
                                            if (!p.getScheduledCallTime().isAfter(now)) {
1757
                                                return false; // Scheduled time reached → comes back up
1758
                                            }
1759
                                            return true; // Scheduled time not reached → stays at bottom
1760
                                        }
35853 ranu 1761
                                        // NO_ANSWER without scheduledCallTime - use 4 hour logic
35835 ranu 1762
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
35853 ranu 1763
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
1764
                                            return false; // NO_ANSWER older than 4 hours → comes back up
35835 ranu 1765
                                        }
35632 ranu 1766
                                    }
1767
                                    return true; // Other today's remarks → goes to bottom
1768
                                }) // false → comes first, true → goes to bottom
1769
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
34796 ranu 1770
                                .thenComparing(PartnerTargetAchievementModel::getRank)
1771
                        )
31686 amit.gupta 1772
                        .collect(Collectors.toList()));
30416 tejbeer 1773
 
34796 ranu 1774
 
31677 amit.gupta 1775
            }
30077 tejbeer 1776
 
31677 amit.gupta 1777
        }
35632 ranu 1778
        LOGGER.info("PERF: Total getPartnerTarget took {} ms", System.currentTimeMillis() - startTime);
31677 amit.gupta 1779
        return responseSender.ok(tm);
30077 tejbeer 1780
 
31677 amit.gupta 1781
    }
32737 amit.gupta 1782
 
35920 ranu 1783
    @RequestMapping(value = "/getInactivePartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1784
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
1785
    public ResponseEntity<?> getInactivePartnerTarget(HttpServletRequest request, @RequestParam String
1786
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
1787
            ProfitMandiBusinessException {
1788
 
1789
        long startTime = System.currentTimeMillis();
1790
        long lapTime = startTime;
1791
 
1792
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
1793
 
1794
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserInactivePartnerIdMapping();
1795
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1796
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
1797
 
1798
        float totalPartnerTargetSecondary = 0;
1799
        float totalPartnerTargetCollection = 0;
1800
        float totalPartnerAchievementSecondary = 0;
1801
        float totalPartnerAchievementCollection = 0;
1802
        TargetModel tm = new TargetModel();
1803
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
1804
        Map<Integer, Long> partnerTicketCount = new HashMap<>();
1805
 
1806
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
1807
 
1808
        if (fofoIds != null && fofoIds.size() > 0) {
1809
            LOGGER.info("fofoIds {}", fofoIds);
1810
            // Get inactive stores for the given retailer IDs
1811
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
1812
                    .filter(x -> (!x.isInternal()))
1813
                    .map(x -> x.getId()).collect(Collectors.toList());
1814
            LOGGER.info("PERF: selectInActiveStore took {} ms", System.currentTimeMillis() - lapTime);
1815
            lapTime = System.currentTimeMillis();
1816
            LOGGER.info("inactive fofoIdList size: {}", fofoIdList.size());
1817
 
1818
            if (!fofoIdList.isEmpty()) {
1819
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
1820
            }
1821
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1822
            lapTime = System.currentTimeMillis();
1823
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
1824
 
1825
            if (dayValue.equals("previous")) {
1826
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
1827
            }
1828
 
1829
            if (fofoIdList.size() > 0) {
1830
 
1831
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
1832
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
1833
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
1834
                lapTime = System.currentTimeMillis();
1835
 
1836
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
1837
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
1838
                long billingThreshold = 1000L;
1839
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
1840
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
1841
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
1842
                lapTime = System.currentTimeMillis();
1843
 
1844
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
1845
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
1846
                lapTime = System.currentTimeMillis();
1847
 
1848
                if (!partnerDailyInvestments.isEmpty()) {
1849
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1850
                }
1851
 
1852
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
1853
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
1854
                lapTime = System.currentTimeMillis();
1855
 
1856
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1857
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
1858
                lapTime = System.currentTimeMillis();
1859
 
1860
                long todayCollectionCount = 0;
1861
                if (!remarkIds.isEmpty()) {
1862
                    todayCollectionCount = partnerCollectionRemarkRepository
1863
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
1864
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
1865
                            .collect(Collectors.counting());
1866
                }
1867
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
1868
                lapTime = System.currentTimeMillis();
1869
 
1870
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
1871
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
1872
                lapTime = System.currentTimeMillis();
1873
 
1874
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
1875
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
1876
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
1877
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
1878
                lapTime = System.currentTimeMillis();
1879
 
1880
                Set<Integer> allAuthIds = new HashSet<>();
1881
                collectionMap.values().stream()
1882
                        .map(PartnerCollectionPlanModel::getAuthId)
1883
                        .filter(id -> id != null && id != authUser.getId())
1884
                        .forEach(allAuthIds::add);
1885
                partnerSecondaryPlans.values().stream()
1886
                        .flatMap(List::stream)
1887
                        .map(PartnerSecondaryPlanModel::getAuthId)
1888
                        .filter(id -> id != null && id != authUser.getId())
1889
                        .forEach(allAuthIds::add);
1890
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
1891
                if (!allAuthIds.isEmpty()) {
1892
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
1893
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
1894
                }
1895
 
1896
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
1897
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
1898
                    int fofoId = customRetailerEntry.getKey();
1899
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
1900
                    float totalSecondaryPlan = 0;
1901
                    float totalSecondaryAchivement = 0;
1902
 
1903
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
1904
                    ptam.setFofoId(fofoId);
1905
                    ptam.setBusinessName(customRetailer.getBusinessName());
1906
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 1907
                    ptam.setActivationType(customRetailer.getActivationType());
35920 ranu 1908
 
1909
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1910
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1911
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1912
                    }
1913
 
1914
                    if (collectionMap.get(fofoId) != null) {
1915
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
1916
 
1917
                        ptam.setRemark(collectionPlan.getRemark());
1918
                        ptam.setMessage(collectionPlan.getMessage());
1919
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
1920
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
1921
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
1922
                        ptam.setRank(collectionPlan.getRank());
1923
                        Integer authId = collectionPlan.getAuthId();
1924
 
1925
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
1926
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
1927
 
1928
                        LOGGER.info("authId" + authId);
1929
 
1930
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1931
                            float targetCollection = 0;
1932
 
1933
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1934
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1935
                            } else {
1936
                                targetCollection = collectionPlan.getTargetPlan();
1937
                            }
1938
 
1939
                            if (authId != null && authId == authUser.getId()) {
1940
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1941
                                    totalPartnerTargetCollection += targetCollection;
1942
                                }
1943
                            }
1944
                            ptam.setCollectionTarget(targetCollection);
1945
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1946
                                    && collectionPlan.getWalletTimestamp() != null
1947
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1948
                                if (authId != null && authId == authUser.getId()) {
1949
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1950
                                }
1951
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1952
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1953
                                    && collectionPlan.getAchievementPlan() != null) {
1954
                                if (authId != null && authId == authUser.getId()) {
1955
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1956
                                }
1957
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1958
                            }
1959
                        }
1960
 
1961
                        if (authId != null && authId != authUser.getId()) {
1962
                            ptam.setAuthUser(authUserMap.get(authId));
1963
                        }
1964
 
1965
                        if (collectionPlan.getCommittedDate() != null) {
1966
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1967
                        }
1968
                    }
1969
 
1970
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1971
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
1972
                    if (partnerSecondaryPlans.get(fofoId) != null) {
1973
                        long otherBrandSecondary = 0;
1974
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
1975
                            Integer authId = pspm.getAuthId();
1976
                            if (!brands.contains(pspm.getBrand())) {
1977
                                if (pspm.getAchievementPlan() != null) {
1978
                                    otherBrandSecondary += pspm.getAchievementPlan();
1979
                                }
1980
                            } else {
1981
                                otherPartnerSecondaryPlanModel = pspm;
1982
                            }
1983
                            if (pspm.getTargetPlan() != null) {
1984
                                totalSecondaryPlan += pspm.getTargetPlan();
1985
                            }
1986
 
1987
                            if (pspm.getAchievementPlan() != null) {
1988
                                totalSecondaryAchivement += pspm.getAchievementPlan();
1989
                            }
1990
 
1991
                            if (pspm.getCommittedDate() != null) {
1992
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1993
                            }
1994
                            if (authId != null && authId == authUser.getId()) {
1995
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
1996
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1997
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1998
                                    }
1999
                                }
2000
 
2001
                                if (pspm.getAchievementPlan() != null) {
2002
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
2003
                                }
2004
                            }
2005
                        }
2006
                        if (otherPartnerSecondaryPlanModel != null) {
2007
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
2008
                        }
2009
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
2010
                                .filter(x -> brands.contains(x.getBrand()))
2011
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
2012
 
2013
                        if (secondaryModelMap.containsKey("Others")) {
2014
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
2015
                            psp.setAchievementPlan(otherBrandSecondary);
2016
                        } else {
2017
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
2018
                        }
2019
                        for (String brand : brands) {
2020
                            if (!secondaryModelMap.containsKey(brand)) {
2021
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
2022
                            }
2023
                        }
2024
 
2025
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
2026
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
2027
                            if (authId != null && authId != authUser.getId()) {
2028
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
2029
                                ptam.setSecondaryColor("red");
2030
                            }
2031
                        }
2032
 
2033
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
2034
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
2035
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
2036
 
2037
                    } else {
2038
                        for (String brand : brands) {
2039
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
2040
                            pspm.setAchievementPlan((long) 0);
2041
                            pspm.setTargetPlan((long) 0);
2042
                            pspm.setBrand(brand);
2043
                            pspm.setFofoId(fofoId);
2044
                            secondaryModelMap.put(brand, pspm);
2045
                        }
2046
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
2047
                    }
2048
 
2049
                    if (!partnerTicketCount.isEmpty()) {
2050
                        if (partnerTicketCount.get(fofoId) != null) {
2051
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
2052
                        } else {
2053
                            ptam.setTicketCount(0);
2054
                        }
2055
                    }
2056
 
2057
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
2058
                    ptam.setHasOverdue(hasCreditDue);
2059
 
2060
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
2061
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
2062
 
2063
                    if (rank == 1) {
2064
                        ptam.setCategory("PLAN_TODAY");
2065
                        ptam.setCategoryPriority(1);
2066
                    } else if (rank == 2) {
2067
                        ptam.setCategory("CARRY_FORWARD");
2068
                        ptam.setCategoryPriority(2);
2069
                    } else if (hasZeroBilling && rank < 5) {
2070
                        ptam.setCategory("ZERO_BILLED");
2071
                        ptam.setCategoryPriority(3);
2072
                    } else if (rank == 3) {
2073
                        ptam.setCategory("UNTOUCHED");
2074
                        ptam.setCategoryPriority(4);
2075
                    } else {
2076
                        ptam.setCategory("NORMAL");
2077
                        ptam.setCategoryPriority(5);
2078
                    }
2079
 
2080
                    ptams.add(ptam);
2081
                }
2082
 
2083
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
2084
                LOGGER.info("positions {}", positions);
2085
 
2086
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 2087
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
2088
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35920 ranu 2089
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 2090
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
35920 ranu 2091
 
2092
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
2093
 
2094
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
2095
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
2096
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
2097
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
2098
                tm.setTodayCollectionCount((int) todayCollectionCount);
2099
                List<PartnerTargetAchievementModel> filteredPtams;
2100
 
2101
                if (isRBMAndL1) {
2102
                    filteredPtams = ptams;
2103
                } else if (isRBMAndNotL1) {
2104
                    filteredPtams = ptams;
2105
                } else if (isSales) {
2106
                    filteredPtams = ptams.stream()
36211 ranu 2107
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
35920 ranu 2108
                            .collect(Collectors.toList());
2109
                } else {
2110
                    filteredPtams = ptams;
2111
                }
2112
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 2113
                tm.setRBMAndL2(isRBMAndL2);
2114
                tm.setRBMAndL3(isRBMAndL3);
35920 ranu 2115
                tm.setRBMAndNotL1(isRBMAndNotL1);
2116
                tm.setSales(isSales);
2117
 
2118
                Map<String, Long> categoryCounts = filteredPtams.stream()
2119
                        .collect(Collectors.groupingBy(
2120
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
2121
                                Collectors.counting()));
2122
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
2123
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
2124
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
2125
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
2126
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
2127
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
2128
 
2129
                LocalDateTime now = LocalDateTime.now();
2130
                LocalDateTime fourHoursAgo = now.minusHours(4);
2131
                tm.setTargetAchievement(filteredPtams.stream()
2132
                        .sorted(Comparator
2133
                                .comparing((PartnerTargetAchievementModel p) -> {
2134
                                    if (p.getRemarkTimestamp() == null) {
2135
                                        return false;
2136
                                    }
2137
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
2138
                                    if (!remarkDate.equals(LocalDate.now())) {
2139
                                        return false;
2140
                                    }
2141
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
2142
                                        if (p.getScheduledCallTime() != null) {
2143
                                            if (!p.getScheduledCallTime().isAfter(now)) {
2144
                                                return false;
2145
                                            }
2146
                                            return true;
2147
                                        }
2148
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
2149
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
2150
                                            return false;
2151
                                        }
2152
                                    }
2153
                                    return true;
2154
                                })
2155
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
2156
                                .thenComparing(PartnerTargetAchievementModel::getRank)
2157
                        )
2158
                        .collect(Collectors.toList()));
2159
            }
2160
        }
2161
        LOGGER.info("PERF: Total getInactivePartnerTarget took {} ms", System.currentTimeMillis() - startTime);
2162
        return responseSender.ok(tm);
2163
 
2164
    }
2165
 
32737 amit.gupta 2166
    //TODO:Amit
31677 amit.gupta 2167
    @RequestMapping(value = "/target", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 2168
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 2169
    public ResponseEntity<?> createPartnerTarget(HttpServletRequest request,
2170
                                                 @RequestBody PartnerTargetAchievementModel ptam) throws ProfitMandiBusinessException {
30077 tejbeer 2171
 
31677 amit.gupta 2172
        LOGGER.info("ptam" + ptam);
30089 tejbeer 2173
 
31677 amit.gupta 2174
        AuthUser authUser = authRepository.selectByGmailId(ptam.getCreatedBy());
30077 tejbeer 2175
 
31677 amit.gupta 2176
        if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
2177
                || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
2178
            PartnerCollectionPlan partnerCollectionPlan = partnerCollectionPlanRepository
2179
                    .selectByLocalDate(LocalDate.now(), ptam.getFofoId(), true);
2180
            LOGGER.info("pcp" + partnerCollectionPlan);
30077 tejbeer 2181
 
31677 amit.gupta 2182
            if (partnerCollectionPlan == null) {
2183
                if (ptam.getCollectionTarget() > 0) {
30087 tejbeer 2184
 
31677 amit.gupta 2185
                    partnerCollectionPlan = new PartnerCollectionPlan();
2186
                    partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
2187
                    partnerCollectionPlan.setAuthId(authUser.getId());
2188
                    partnerCollectionPlan.setFofoId(ptam.getFofoId());
2189
                    partnerCollectionPlan.setActive(true);
2190
                    partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2191
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2192
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2193
                    partnerCollectionPlanRepository.persist(partnerCollectionPlan);
30416 tejbeer 2194
 
31677 amit.gupta 2195
                }
30087 tejbeer 2196
 
31677 amit.gupta 2197
            } else {
30087 tejbeer 2198
 
31677 amit.gupta 2199
                if (partnerCollectionPlan.getCollectionPlan() != ptam.getCollectionTarget()) {
2200
                    float totalCollectionPlan = partnerCollectionPlan.getCollectionPlan() + 10000;
2201
                    if (authUser.getId() == partnerCollectionPlan.getAuthId()) {
30087 tejbeer 2202
 
31677 amit.gupta 2203
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2204
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
2205
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2206
                            partnerCollectionPlan.setActive(true);
2207
                            partnerCollectionPlan
2208
                                    .setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2209
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2210
                        } else {
2211
                            throw new ProfitMandiBusinessException("collection target", "",
2212
                                    "collection target should be more than " + totalCollectionPlan);
2213
                        }
30087 tejbeer 2214
 
31677 amit.gupta 2215
                    } else {
30137 tejbeer 2216
 
31677 amit.gupta 2217
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2218
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
30137 tejbeer 2219
 
31677 amit.gupta 2220
                            partnerCollectionPlan.setActive(false);
2221
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2222
                            partnerCollectionPlan = new PartnerCollectionPlan();
2223
                            partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
2224
                            partnerCollectionPlan.setAuthId(authUser.getId());
2225
                            partnerCollectionPlan.setFofoId(ptam.getFofoId());
2226
                            partnerCollectionPlan.setActive(true);
2227
                            partnerCollectionPlan
2228
                                    .setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2229
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2230
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2231
                            partnerCollectionPlanRepository.persist(partnerCollectionPlan);
2232
                        } else {
2233
                            throw new ProfitMandiBusinessException("collection target", "",
2234
                                    "collection target should be more than " + totalCollectionPlan);
2235
                        }
2236
                    }
2237
                }
30137 tejbeer 2238
 
31677 amit.gupta 2239
                if ((LocalDate.now().atStartOfDay().equals(ptam.getCollectionCommitmentDate().atStartOfDay())
2240
                        || ptam.getCollectionCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
2241
                        && partnerCollectionPlan.getCollectionPlan() == ptam.getCollectionTarget()) {
2242
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2243
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2244
                }
30416 tejbeer 2245
 
31677 amit.gupta 2246
            }
30433 tejbeer 2247
 
35725 ranu 2248
            long callLogId = recordingService.getLatestAgentCallLog(ptam.getFofoId(),authUser.getId());
2249
 
31677 amit.gupta 2250
            PartnerCollectionRemark pcr = new PartnerCollectionRemark();
2251
            pcr.setFofoId(ptam.getFofoId());
2252
            pcr.setAuthId(authUser.getId());
2253
            pcr.setMessage("Collection plan for" + ptam.getCollectionCommitmentDate());
2254
            pcr.setRemark(CollectionRemark.COLLECTION_PLAN);
35725 ranu 2255
            pcr.setAgentCallLogId(callLogId);
31677 amit.gupta 2256
            pcr.setCreateTimestamp(LocalDateTime.now());
2257
            partnerCollectionRemarkRepository.persist(pcr);
2258
        } else {
2259
            throw new ProfitMandiBusinessException("Date", "",
2260
                    "you can't select the back date " + ptam.getCollectionCommitmentDate());
2261
        }
30077 tejbeer 2262
 
31677 amit.gupta 2263
        for (Entry<String, PartnerSecondaryPlanModel> pspm : ptam.getPartnerSecondaryModel().entrySet()) {
30087 tejbeer 2264
 
31677 amit.gupta 2265
            if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
2266
                    || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
2267
                PartnerSecondaryPlanModel plan = pspm.getValue();
2268
                PartnerSecondaryPlan psp = partnerSecondaryPlanRepository.selectByLocalDateBrand(plan.getBrand(),
2269
                        LocalDate.now(), ptam.getFofoId(), true);
2270
                LOGGER.info("psp" + psp);
30087 tejbeer 2271
 
31677 amit.gupta 2272
                if (psp == null) {
2273
                    if (plan.getTargetPlan() != null && plan.getTargetPlan() > 0) {
30087 tejbeer 2274
 
31677 amit.gupta 2275
                        psp = new PartnerSecondaryPlan();
2276
                        psp.setAuthId(authUser.getId());
2277
                        psp.setBrand(pspm.getKey());
2278
                        psp.setFofoId(pspm.getValue().getFofoId());
2279
                        psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2280
                        psp.setCreateTimestamp(LocalDateTime.now());
2281
                        psp.setUpdatedTimestamp(LocalDateTime.now());
2282
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2283
                        psp.setActive(true);
2284
                        partnerSecondaryPlanRepository.persist(psp);
2285
                    }
30087 tejbeer 2286
 
31677 amit.gupta 2287
                } else {
2288
                    if (plan.getTargetPlan() != psp.getSecondaryPlan()) {
2289
                        float totalSecondaryPlan = psp.getSecondaryPlan() + 10000;
2290
                        if (authUser.getId() == plan.getAuthId()) {
2291
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2292
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
2293
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2294
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2295
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2296
                                psp.setActive(true);
2297
                            } else {
2298
                                throw new ProfitMandiBusinessException("secondary target", "",
2299
                                        "secondary target should be more than " + totalSecondaryPlan);
2300
                            }
30087 tejbeer 2301
 
31677 amit.gupta 2302
                        } else {
30087 tejbeer 2303
 
31677 amit.gupta 2304
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2305
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
30087 tejbeer 2306
 
31677 amit.gupta 2307
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2308
                                psp.setActive(false);
2309
                                psp = new PartnerSecondaryPlan();
2310
                                psp.setAuthId(authUser.getId());
2311
                                psp.setBrand(pspm.getKey());
2312
                                psp.setFofoId(pspm.getValue().getFofoId());
2313
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2314
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2315
                                psp.setCreateTimestamp(LocalDateTime.now());
2316
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2317
                                psp.setActive(true);
2318
                                partnerSecondaryPlanRepository.persist(psp);
2319
                            } else {
2320
                                throw new ProfitMandiBusinessException("secondary target", "",
2321
                                        "secondary target should be more than " + totalSecondaryPlan);
2322
                            }
2323
                        }
2324
                    }
30137 tejbeer 2325
 
31677 amit.gupta 2326
                    if ((LocalDate.now().atStartOfDay().equals(ptam.getSecondaryCommitmentDate().atStartOfDay())
2327
                            || ptam.getSecondaryCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
2328
                            && plan.getTargetPlan() == psp.getSecondaryPlan()) {
2329
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2330
                        psp.setUpdatedTimestamp(LocalDateTime.now());
2331
                    }
30137 tejbeer 2332
 
31677 amit.gupta 2333
                }
2334
            } else {
2335
                throw new ProfitMandiBusinessException("Date", "",
2336
                        "you can't select the back date " + ptam.getSecondaryCommitmentDate());
2337
            }
30137 tejbeer 2338
 
31677 amit.gupta 2339
        }
30077 tejbeer 2340
 
31677 amit.gupta 2341
        return responseSender.ok(true);
30137 tejbeer 2342
 
31677 amit.gupta 2343
    }
30077 tejbeer 2344
 
31677 amit.gupta 2345
    @RequestMapping(value = "/uploadFranchiseeVisit", method = RequestMethod.POST)
35288 amit 2346
    public ResponseEntity<?> readCsvFileAndSetLead(HttpServletRequest request, @RequestPart MultipartFile
2347
            multipartFile) throws Throwable {
30433 tejbeer 2348
 
31677 amit.gupta 2349
        int id = (int) request.getAttribute("userId");
30433 tejbeer 2350
 
31677 amit.gupta 2351
        LOGGER.info("id" + id);
30433 tejbeer 2352
 
31677 amit.gupta 2353
        User user = userRepository.selectById(id);
30433 tejbeer 2354
 
31677 amit.gupta 2355
        AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());
30433 tejbeer 2356
 
31677 amit.gupta 2357
        String fileName = multipartFile.getName();
2358
        String fileNames = multipartFile.getOriginalFilename();
30433 tejbeer 2359
 
31677 amit.gupta 2360
        LOGGER.info("fileName" + fileName);
2361
        LOGGER.info("fileNames" + fileNames);
30433 tejbeer 2362
 
31677 amit.gupta 2363
        List<CSVRecord> records = FileUtil.readFile(multipartFile);
30433 tejbeer 2364
 
31677 amit.gupta 2365
        for (CSVRecord record : records) {
2366
            FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
2367
            franchiseeVisit.setFofoId(Integer.parseInt(record.get(0)));
2368
            CustomRetailer customRetailer = retailerService.getFofoRetailer(Integer.parseInt(record.get(0)));
30433 tejbeer 2369
 
31677 amit.gupta 2370
            franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
2371
            franchiseeVisit.setAgenda(record.get(1));
2372
            franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
2373
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
2374
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
30433 tejbeer 2375
 
31677 amit.gupta 2376
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
2377
            LOGGER.info(record.get(1));
2378
            LocalDate dateTime = LocalDate.parse(record.get(2), formatter);
30433 tejbeer 2379
 
31677 amit.gupta 2380
            franchiseeVisit.setScheduleTimestamp(dateTime.atStartOfDay());
2381
            // change
30433 tejbeer 2382
 
31677 amit.gupta 2383
            String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
2384
            franchiseeVisit.setCreatedBy(authUserName);
2385
            franchiseeVisit.setAuthId(authUser.getId());
30433 tejbeer 2386
 
31677 amit.gupta 2387
            franchiseeVisitRepository.persist(franchiseeVisit);
30433 tejbeer 2388
 
31677 amit.gupta 2389
            return responseSender.ok(true);
2390
        }
30433 tejbeer 2391
 
31677 amit.gupta 2392
        return responseSender.ok(true);
30433 tejbeer 2393
 
31677 amit.gupta 2394
    }
30487 tejbeer 2395
 
31677 amit.gupta 2396
    @RequestMapping(value = "/downloadFranchiseeVisitTemplate", method = RequestMethod.GET)
2397
    public ResponseEntity<?> downloadFranchiseeVisitTemplate(HttpServletRequest request) throws Exception {
30487 tejbeer 2398
 
31677 amit.gupta 2399
        // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
30487 tejbeer 2400
 
31677 amit.gupta 2401
        List<List<?>> rows = new ArrayList<>();
30487 tejbeer 2402
 
32923 ranu 2403
        ByteArrayOutputStream byteArrayOutputStream = FileUtil
31677 amit.gupta 2404
                .getCSVByteStream(Arrays.asList("Partner Id", "Agenda", "Schedule Timestamp"), rows);
30487 tejbeer 2405
 
31677 amit.gupta 2406
        try {
2407
            byteArrayOutputStream.close();
2408
        } catch (IOException e) {
2409
            // TODO Auto-generated catch block
2410
            e.printStackTrace();
2411
        }
30487 tejbeer 2412
 
31677 amit.gupta 2413
        String filename = "template.csv";
2414
        HttpHeaders headers = new HttpHeaders();
2415
        headers.add("Content-Type", "application/csv");
2416
        headers.setContentDispositionFormData(filename, filename);
30487 tejbeer 2417
 
31677 amit.gupta 2418
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
30487 tejbeer 2419
 
31677 amit.gupta 2420
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
2421
                HttpStatus.OK);
2422
        return response;
30544 tejbeer 2423
 
31677 amit.gupta 2424
    }
30542 tejbeer 2425
 
31677 amit.gupta 2426
    @RequestMapping(value = "/markVisitAttendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
2427
    public ResponseEntity<?> markVisitAttendance(HttpServletRequest request, @RequestParam(name = "id") int id)
2428
            throws ProfitMandiBusinessException {
2429
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
30542 tejbeer 2430
 
31677 amit.gupta 2431
        franchiseeVisit.setVisitTimestamp(LocalDateTime.now());
30542 tejbeer 2432
 
31677 amit.gupta 2433
        return responseSender.ok(true);
30542 tejbeer 2434
 
31677 amit.gupta 2435
    }
31249 tejbeer 2436
 
31677 amit.gupta 2437
    @RequestMapping(value = "/getVisitRequests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2438
    public ResponseEntity<?> getVisitRequests(HttpServletRequest request,
2439
                                              @RequestParam(name = "gmailId") String gmailId, Model model) throws Exception {
31249 tejbeer 2440
 
31677 amit.gupta 2441
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 2442
 
31677 amit.gupta 2443
        List<Integer> authUserIds = authService.getAllReportees(authUser.getId());
2444
        List<VisitSummaryModel> visitSummary = new ArrayList<>();
31249 tejbeer 2445
 
31677 amit.gupta 2446
        if (!authUserIds.isEmpty()) {
35397 amit 2447
            List<AuthUser> authUsers = authRepository.selectByIds(authUserIds);
31249 tejbeer 2448
 
31677 amit.gupta 2449
            List<VisitRequest> allVisitRequests = visitRequestRepository.selectByAuthIdsAndDate(authUserIds,
2450
                    LocalDate.now().minusDays(7), Arrays.asList(VisitStatus.approved, VisitStatus.pending));
2451
            LOGGER.info("allVisitRequests {}", allVisitRequests);
31249 tejbeer 2452
 
31677 amit.gupta 2453
            if (!allVisitRequests.isEmpty()) {
31249 tejbeer 2454
 
31677 amit.gupta 2455
                List<Integer> leadIds = allVisitRequests.stream().filter(x -> x.getVisitType().equals("lead"))
2456
                        .map(x -> x.getVisitId()).collect(Collectors.toList());
2457
                List<Lead> leads = new ArrayList<>();
2458
                if (!leadIds.isEmpty()) {
2459
                    leads = leadRepository.selectAllByIds(leadIds);
31249 tejbeer 2460
 
35415 amit 2461
                    // Batch fetch all LeadActivities instead of N+1
2462
                    List<LeadActivity> allLeadActivities = leadActivityRepository.selectAllByleadIds(leadIds);
2463
                    Map<Integer, List<LeadActivity>> leadActivityMap = allLeadActivities.stream()
2464
                            .collect(Collectors.groupingBy(LeadActivity::getLeadId));
2465
 
31677 amit.gupta 2466
                    for (Lead lead : leads) {
35415 amit 2467
                        List<LeadActivity> leadActivities = leadActivityMap.get(lead.getId());
2468
                        if (leadActivities != null && !leadActivities.isEmpty()) {
2469
                            lead.setScheduledTimestamp(leadActivities.get(0).getSchelduleTimestamp());
2470
                            lead.setLeadActivity(leadActivities.get(0));
2471
                        }
31677 amit.gupta 2472
                    }
2473
                }
2474
                List<Integer> franchiseeIds = allVisitRequests.stream()
2475
                        .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2476
                        .collect(Collectors.toList());
2477
                List<FranchiseeVisit> franchiseeVisits = new ArrayList<>();
2478
                if (!franchiseeIds.isEmpty()) {
2479
                    franchiseeVisits = franchiseeVisitRepository.selectAllByIds(franchiseeIds);
2480
                    LOGGER.info("franchiseeVisits {}", franchiseeVisits);
31249 tejbeer 2481
 
35415 amit 2482
                    // Batch fetch all FranchiseeActivities instead of N+1
2483
                    List<FranchiseeActivity> allFranchiseeActivities = franchiseeActivityRepository
2484
                            .selectByFranchiseeVisitIds(franchiseeIds);
2485
                    Map<Integer, List<FranchiseeActivity>> franchiseeActivityMap = allFranchiseeActivities.stream()
2486
                            .collect(Collectors.groupingBy(FranchiseeActivity::getFranchiseeVisitd));
2487
 
31677 amit.gupta 2488
                    for (FranchiseeVisit franchiseeVisit : franchiseeVisits) {
35415 amit 2489
                        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityMap.get(franchiseeVisit.getId());
31677 amit.gupta 2490
                        LOGGER.info("franchiseeActivities {}", franchiseeActivities);
31249 tejbeer 2491
 
35415 amit 2492
                        if (franchiseeActivities != null && !franchiseeActivities.isEmpty()) {
2493
                            franchiseeVisit.setScheduleTimestamp(franchiseeActivities.get(0).getSchelduleTimestamp());
2494
                            franchiseeVisit.setFranchiseeActivity(franchiseeActivities.get(0));
2495
                        }
31677 amit.gupta 2496
                    }
31249 tejbeer 2497
 
31677 amit.gupta 2498
                }
31249 tejbeer 2499
 
35415 amit 2500
                // Pre-fetch all retailers using cached method (instead of N+1 getFofoRetailer calls)
2501
                Map<Integer, CustomRetailer> allRetailersMap = retailerService.getAllFofoRetailers();
2502
 
31677 amit.gupta 2503
                Map<LocalDate, List<VisitRequest>> dateWiseVisitRequest = allVisitRequests.stream()
2504
                        .collect(Collectors.groupingBy(x -> x.getScheduleTimestamp().toLocalDate()));
31249 tejbeer 2505
 
31677 amit.gupta 2506
                for (Entry<LocalDate, List<VisitRequest>> visitEntry : dateWiseVisitRequest.entrySet()) {
31249 tejbeer 2507
 
31677 amit.gupta 2508
                    LocalDate date = visitEntry.getKey();
2509
                    List<VisitRequest> visitRequests = visitEntry.getValue();
31249 tejbeer 2510
 
31677 amit.gupta 2511
                    VisitSummaryModel visitSummaryModel = new VisitSummaryModel();
31249 tejbeer 2512
 
31677 amit.gupta 2513
                    visitSummaryModel.setDate(date);
2514
                    List<Integer> dateWiseLeadEntry = visitRequests.stream()
2515
                            .filter(x -> x.getVisitType().equals("lead")).map(x -> x.getVisitId())
2516
                            .collect(Collectors.toList());
31249 tejbeer 2517
 
31677 amit.gupta 2518
                    List<Integer> dateWiseFranchiseeIds = visitRequests.stream()
2519
                            .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2520
                            .collect(Collectors.toList());
31249 tejbeer 2521
 
31677 amit.gupta 2522
                    Map<Integer, List<Lead>> filteredLeadsMap = null;
2523
                    if (!leads.isEmpty()) {
2524
                        filteredLeadsMap = leads.stream().filter(x -> dateWiseLeadEntry.contains(x.getId()))
2525
                                .collect(Collectors.groupingBy(x -> x.getAssignTo()));
31249 tejbeer 2526
 
31677 amit.gupta 2527
                    }
31249 tejbeer 2528
 
31677 amit.gupta 2529
                    Map<Integer, List<FranchiseeVisit>> filteredFranchiseeVisitsMap = null;
31249 tejbeer 2530
 
31677 amit.gupta 2531
                    if (!franchiseeVisits.isEmpty()) {
2532
                        filteredFranchiseeVisitsMap = franchiseeVisits.stream()
2533
                                .filter(x -> dateWiseFranchiseeIds.contains(x.getId()))
2534
                                .collect(Collectors.groupingBy(x -> x.getAuthId()));
31249 tejbeer 2535
 
31677 amit.gupta 2536
                    }
31249 tejbeer 2537
 
31677 amit.gupta 2538
                    List<UserVisitModel> userVisits = new ArrayList<>();
31249 tejbeer 2539
 
31677 amit.gupta 2540
                    for (AuthUser auth : authUsers) {
2541
                        UserVisitModel userVisitModel = new UserVisitModel();
2542
                        List<VisitDescriptionModel> visitDescriptions = new ArrayList<>();
31249 tejbeer 2543
 
31677 amit.gupta 2544
                        List<Lead> authLeads = new ArrayList<>();
2545
                        if (filteredLeadsMap != null) {
2546
                            authLeads = filteredLeadsMap.get(auth.getId());
31249 tejbeer 2547
 
31677 amit.gupta 2548
                        }
31249 tejbeer 2549
 
31677 amit.gupta 2550
                        if (authLeads != null && !authLeads.isEmpty()) {
2551
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2552
 
31677 amit.gupta 2553
                            for (Lead lead : authLeads) {
31249 tejbeer 2554
 
31677 amit.gupta 2555
                                VisitRequest visitRequest = visitRequests.stream().filter(
2556
                                                x -> x.getVisitId() == lead.getId() && x.getCreatedBy() == lead.getAssignTo())
2557
                                        .findAny().orElse(null);
2558
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2559
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2560
                                visitDescriptionModel.setVisitName(lead.getFirstName());
2561
                                visitDescriptionModel.setCity(lead.getCity());
2562
                                visitDescriptionModel.setState(lead.getState());
2563
                                visitDescriptionModel.setScheduleTime(lead.getScheduledTimestamp());
2564
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2565
                                visitDescriptionModel.setRemarks(lead.getLeadActivity().getRemark());
2566
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
2567
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2568
 
31677 amit.gupta 2569
                            }
2570
                        }
31249 tejbeer 2571
 
31677 amit.gupta 2572
                        List<FranchiseeVisit> authfranchiseeVisit = new ArrayList<>();
2573
                        if (filteredFranchiseeVisitsMap != null) {
2574
                            authfranchiseeVisit = filteredFranchiseeVisitsMap.get(auth.getId());
31249 tejbeer 2575
 
31677 amit.gupta 2576
                        }
31249 tejbeer 2577
 
31677 amit.gupta 2578
                        if (authfranchiseeVisit != null && !authfranchiseeVisit.isEmpty()) {
2579
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2580
 
31677 amit.gupta 2581
                            for (FranchiseeVisit franchiseeVisit : authfranchiseeVisit) {
31249 tejbeer 2582
 
31677 amit.gupta 2583
                                VisitRequest visitRequest = visitRequests.stream()
2584
                                        .filter(x -> x.getVisitId() == franchiseeVisit.getId()
2585
                                                && x.getCreatedBy() == franchiseeVisit.getAuthId())
2586
                                        .findAny().orElse(null);
31249 tejbeer 2587
 
35415 amit 2588
                                CustomRetailer customRetailer = allRetailersMap.get(franchiseeVisit.getFofoId());
31677 amit.gupta 2589
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2590
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2591
                                visitDescriptionModel.setVisitName(franchiseeVisit.getPartnerName());
35415 amit 2592
                                if (customRetailer != null && customRetailer.getAddress() != null) {
2593
                                    visitDescriptionModel.setCity(customRetailer.getAddress().getCity());
2594
                                    visitDescriptionModel.setState(customRetailer.getAddress().getState());
2595
                                }
31677 amit.gupta 2596
                                visitDescriptionModel.setScheduleTime(
2597
                                        franchiseeVisit.getFranchiseeActivity().getSchelduleTimestamp());
2598
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2599
                                visitDescriptionModel.setRemarks(franchiseeVisit.getAgenda());
2600
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
31249 tejbeer 2601
 
31677 amit.gupta 2602
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2603
 
31677 amit.gupta 2604
                            }
2605
                        }
31249 tejbeer 2606
 
31677 amit.gupta 2607
                        userVisitModel.setVisitDescriptions(visitDescriptions);
2608
                        LOGGER.info("userVisit {}", userVisitModel);
31249 tejbeer 2609
 
31677 amit.gupta 2610
                        if (userVisitModel.getAuthUser() != null) {
2611
                            userVisits.add(userVisitModel);
2612
                        }
31249 tejbeer 2613
 
31677 amit.gupta 2614
                    }
31249 tejbeer 2615
 
31677 amit.gupta 2616
                    visitSummaryModel.setUserVisits(userVisits);
31249 tejbeer 2617
 
31677 amit.gupta 2618
                    visitSummary.add(visitSummaryModel);
31249 tejbeer 2619
 
31677 amit.gupta 2620
                }
31249 tejbeer 2621
 
31677 amit.gupta 2622
            }
31249 tejbeer 2623
 
31677 amit.gupta 2624
        }
2625
        return responseSender.ok(visitSummary);
31249 tejbeer 2626
 
31677 amit.gupta 2627
    }
31249 tejbeer 2628
 
31677 amit.gupta 2629
    @RequestMapping(value = "/visitRequest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2630
    public ResponseEntity<?> visitRequest(HttpServletRequest request, @RequestParam(name = "gmailId") String
2631
                                                  gmailId,
31677 amit.gupta 2632
                                          @RequestParam(name = "visitId") int visitId, @RequestParam(name = "status") VisitStatus status, Model model)
2633
            throws Exception {
2634
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 2635
 
31677 amit.gupta 2636
        VisitRequest visitRequest = visitRequestRepository.selectById(visitId);
2637
        visitRequest.setActionedBy(authUser.getId());
2638
        visitRequest.setStatus(status);
2639
        visitRequest.setUpdatedTimestamp(LocalDateTime.now());
2640
        if (status.equals(VisitStatus.approved)) {
2641
            visitRequest.setApprovedTimestamp(LocalDateTime.now());
2642
        }
31249 tejbeer 2643
 
31677 amit.gupta 2644
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
2645
        sendNotificationModel.setCampaignName("Visit Request");
2646
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2647
        sendNotificationModel.setTitle("Visit Request");
2648
        String message = "Visit Request has been " + status + " for scheduled time on "
2649
                + visitRequest.getScheduleTimestamp().toLocalDate();
31249 tejbeer 2650
 
31677 amit.gupta 2651
        sendNotificationModel.setMessage(message);
2652
        sendNotificationModel.setMessageType(MessageType.notification);
2653
        User user = userRepository.selectByEmailId(gmailId);
2654
        sendNotificationModel.setUserIds(new ArrayList<>(user.getId()));
31249 tejbeer 2655
 
31677 amit.gupta 2656
        notificationService.sendNotificationToAll(sendNotificationModel);
31249 tejbeer 2657
 
31677 amit.gupta 2658
        return responseSender.ok(true);
31249 tejbeer 2659
 
31677 amit.gupta 2660
    }
31249 tejbeer 2661
 
34301 ranu 2662
    @Autowired
2663
    RbmRatingRepository rbmRatingRepository;
2664
 
34322 ranu 2665
    @Autowired
2666
    SalesRatingRepository salesRatingRepository;
2667
 
34301 ranu 2668
    @RequestMapping(value = "/rbmRating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2669
    public ResponseEntity<?> rbmRating(HttpServletRequest request, @RequestBody RbmSalesRatingRequest
2670
            rbmSalesRatingRequest, Model model) throws Exception {
34301 ranu 2671
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2672
        UserCart uc = userAccountRepository.getUserCart(userId);
2673
        int fofoId = uc.getUserId();
34322 ranu 2674
 
34301 ranu 2675
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
34322 ranu 2676
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
34301 ranu 2677
 
36114 ranu 2678
        LocalDate today = LocalDate.now();
36930 ranu 2679
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2680
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2681
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2682
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
34301 ranu 2683
 
37130 ranu 2684
        // JSON error body so Angular's HttpClient (produces = APPLICATION_JSON)
2685
        // doesn't add a "parse error" alongside the 400. Was returning a plain
2686
        // string which caused the "Http failure response … 400 Bad Request
2687
        // (2 errors)" toast for partners who tried to re-submit a rating in
2688
        // the same month.
36930 ranu 2689
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfMonthDateTime, endOfMonthDateTime);
34322 ranu 2690
        if (!existingRbmRatings.isEmpty()) {
37130 ranu 2691
            Map<String, Object> body = new HashMap<>();
2692
            body.put("code", "RATING_ALREADY_EXISTS");
2693
            body.put("message", "Rating for this month already exists.");
2694
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
34301 ranu 2695
        }
2696
 
36930 ranu 2697
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfMonthDateTime, endOfMonthDateTime);
34322 ranu 2698
        if (!existingSalesRatings.isEmpty()) {
37130 ranu 2699
            Map<String, Object> body = new HashMap<>();
2700
            body.put("code", "RATING_ALREADY_EXISTS");
2701
            body.put("message", "Rating for this month already exists.");
2702
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
34322 ranu 2703
        }
34301 ranu 2704
 
34322 ranu 2705
        // Save RBM rating
34301 ranu 2706
        RbmRating rbmRating = new RbmRating();
34322 ranu 2707
        rbmRating.setComment(rbmSalesRatingRequest.getRbmComment());
2708
        rbmRating.setRating(rbmSalesRatingRequest.getRbmRating());
34301 ranu 2709
        rbmRating.setFofoId(fofoId);
2710
        rbmRating.setRbmId(rbmL1);
2711
        rbmRating.setCreateTimeStamp(LocalDateTime.now());
2712
        rbmRatingRepository.persist(rbmRating);
2713
 
34322 ranu 2714
        // Save Sales Person rating
2715
        SalesRating salesRating = new SalesRating();
2716
        salesRating.setComment(rbmSalesRatingRequest.getSalesComment());
2717
        salesRating.setRating(rbmSalesRatingRequest.getSalesRating());
2718
        salesRating.setFofoId(fofoId);
2719
        salesRating.setSalesL1Id(salesL1Id);
2720
        salesRating.setCreateTimeStamp(LocalDateTime.now());
2721
        salesRatingRepository.persist(salesRating);
2722
 
37130 ranu 2723
        Map<String, Object> ok = new HashMap<>();
2724
        ok.put("code", "OK");
2725
        ok.put("message", "Rating submitted successfully.");
2726
        return responseSender.ok(ok);
34301 ranu 2727
    }
2728
 
37130 ranu 2729
    /**
2730
     * GET /rbmRating/exists-this-month — quick precheck so the client can
2731
     * hide/disable the rating popup when a rating for the current month
2732
     * already exists. Returns per-side booleans so the UI can distinguish
2733
     * "only RBM done" vs "only Sales done" vs "both done" if it wants.
2734
     *
2735
     * Response:
2736
     *   {
2737
     *     "rbmRated":   true|false,
2738
     *     "salesRated": true|false,
2739
     *     "canSubmit":  true|false,   // true only when NEITHER rating exists
2740
     *     "monthStart": "yyyy-MM-dd",
2741
     *     "monthEnd":   "yyyy-MM-dd"
2742
     *   }
2743
     */
2744
    @RequestMapping(value = "/rbmRating/exists-this-month", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2745
    public ResponseEntity<?> rbmRatingExistsThisMonth(HttpServletRequest request) throws Exception {
2746
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2747
        UserCart uc = userAccountRepository.getUserCart(userId);
2748
        int fofoId = uc.getUserId();
2749
 
2750
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
2751
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
2752
 
2753
        LocalDate today = LocalDate.now();
2754
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2755
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2756
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2757
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
2758
 
2759
        boolean rbmRated = !rbmRatingRepository
2760
                .findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfMonthDateTime, endOfMonthDateTime)
2761
                .isEmpty();
2762
        boolean salesRated = !salesRatingRepository
2763
                .findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfMonthDateTime, endOfMonthDateTime)
2764
                .isEmpty();
2765
 
2766
        Map<String, Object> body = new HashMap<>();
2767
        body.put("rbmRated", rbmRated);
2768
        body.put("salesRated", salesRated);
2769
        // POST /rbmRating rejects when EITHER side already exists, so canSubmit
2770
        // mirrors that gate rather than a per-side flag.
2771
        body.put("canSubmit", !rbmRated && !salesRated);
2772
        body.put("monthStart", startOfMonth.toString());
2773
        body.put("monthEnd", endOfMonth.toString());
2774
        return responseSender.ok(body);
2775
    }
2776
 
36286 ranu 2777
    @RequestMapping(value = "/rbmRating/weekly-status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2778
    public ResponseEntity<?> rbmRatingWeeklyStatus(HttpServletRequest request) throws Exception {
2779
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2780
        UserCart uc = userAccountRepository.getUserCart(userId);
2781
        int fofoId = uc.getUserId();
34301 ranu 2782
 
36286 ranu 2783
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
2784
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
2785
 
2786
        LocalDate today = LocalDate.now();
36930 ranu 2787
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2788
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2789
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2790
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
36286 ranu 2791
 
36930 ranu 2792
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdForCurrentWeek(fofoId, startOfMonthDateTime, endOfMonthDateTime);
2793
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdForCurrentWeek(fofoId, startOfMonthDateTime, endOfMonthDateTime);
36286 ranu 2794
 
2795
        boolean pending = existingRbmRatings.isEmpty() || existingSalesRatings.isEmpty();
2796
 
2797
        Map<String, Object> response = new HashMap<>();
2798
        response.put("pending", pending);
36930 ranu 2799
        response.put("weekStart", startOfMonth.toString());
2800
        response.put("weekEnd", endOfMonth.toString());
36286 ranu 2801
 
2802
        if (rbmL1 > 0) {
2803
            AuthUser rbmUser = authRepository.selectById(rbmL1);
2804
            if (rbmUser != null) {
2805
                response.put("rbmName", rbmUser.getFullName());
2806
            }
2807
        }
2808
        if (salesL1Id > 0) {
2809
            AuthUser salesUser = authRepository.selectById(salesL1Id);
2810
            if (salesUser != null) {
2811
                response.put("salesPersonName", salesUser.getFullName());
2812
            }
2813
        }
2814
 
2815
        return responseSender.ok(response);
2816
    }
2817
 
2818
    @Autowired
2819
    private RatingReminderRepository ratingReminderRepository;
2820
 
2821
    @RequestMapping(value = "/rbmRating/reminder", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2822
    public ResponseEntity<?> rbmRatingReminder(HttpServletRequest request) throws Exception {
2823
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2824
        UserCart uc = userAccountRepository.getUserCart(userId);
2825
        int fofoId = uc.getUserId();
2826
 
2827
        LocalDate today = LocalDate.now();
36930 ranu 2828
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2829
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
36286 ranu 2830
 
36930 ranu 2831
        RatingReminder reminder = ratingReminderRepository.findByFofoIdAndWeek(fofoId, startOfMonth);
36286 ranu 2832
 
2833
        int attemptsRemaining;
2834
        if (reminder == null) {
2835
            reminder = new RatingReminder();
2836
            reminder.setFofoId(fofoId);
36930 ranu 2837
            reminder.setWeekStart(startOfMonth);
2838
            reminder.setWeekEnd(endOfMonth);
36286 ranu 2839
            reminder.setAttemptsRemaining(RatingReminder.MAX_ATTEMPTS_PER_WEEK);
2840
            reminder.setCreateTimestamp(LocalDateTime.now());
2841
            ratingReminderRepository.persist(reminder);
2842
            attemptsRemaining = RatingReminder.MAX_ATTEMPTS_PER_WEEK;
2843
        } else {
2844
            ratingReminderRepository.decrementRemaining(reminder.getId());
36930 ranu 2845
            reminder = ratingReminderRepository.findByFofoIdAndWeek(fofoId, startOfMonth);
36286 ranu 2846
            attemptsRemaining = reminder.getAttemptsRemaining();
2847
        }
2848
 
2849
        Map<String, Object> response = new HashMap<>();
2850
        response.put("partnerId", fofoId);
2851
        response.put("attemptsRemaining", attemptsRemaining);
2852
 
2853
        return responseSender.ok(response);
2854
    }
2855
 
2856
 
30077 tejbeer 2857
}