Subversion Repositories SmartDukaan

Rev

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