Subversion Repositories SmartDukaan

Rev

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

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