Subversion Repositories SmartDukaan

Rev

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