Subversion Repositories SmartDukaan

Rev

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