Subversion Repositories SmartDukaan

Rev

Rev 37353 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
25899 tejbeer 1
package com.spice.profitmandi.web.controller;
2
 
32978 amit.gupta 3
import com.mongodb.DBObject;
31677 amit.gupta 4
import com.spice.profitmandi.common.enumuration.ActivationType;
31249 tejbeer 5
import com.spice.profitmandi.common.enumuration.MessageType;
25899 tejbeer 6
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
25952 tejbeer 7
import com.spice.profitmandi.common.model.CustomRetailer;
27117 tejbeer 8
import com.spice.profitmandi.common.model.ProfitMandiConstants;
31249 tejbeer 9
import com.spice.profitmandi.common.model.SendNotificationModel;
30433 tejbeer 10
import com.spice.profitmandi.common.util.FileUtil;
25899 tejbeer 11
import com.spice.profitmandi.common.web.util.ResponseSender;
12
import com.spice.profitmandi.dao.entity.auth.AuthUser;
30077 tejbeer 13
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionPlan;
30416 tejbeer 14
import com.spice.profitmandi.dao.entity.auth.PartnerCollectionRemark;
30077 tejbeer 15
import com.spice.profitmandi.dao.entity.auth.PartnerSecondaryPlan;
36267 ranu 16
import com.spice.profitmandi.dao.entity.cs.Activity;
32978 amit.gupta 17
import com.spice.profitmandi.dao.entity.cs.Position;
36267 ranu 18
import com.spice.profitmandi.dao.entity.cs.Ticket;
25899 tejbeer 19
import com.spice.profitmandi.dao.entity.dtr.User;
25952 tejbeer 20
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
34322 ranu 21
import com.spice.profitmandi.dao.entity.fofo.*;
32978 amit.gupta 22
import com.spice.profitmandi.dao.entity.user.*;
30416 tejbeer 23
import com.spice.profitmandi.dao.enumuration.auth.CollectionRemark;
32978 amit.gupta 24
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
25
import com.spice.profitmandi.dao.enumuration.dtr.*;
26
import com.spice.profitmandi.dao.model.*;
27
import com.spice.profitmandi.dao.repository.auth.*;
28
import com.spice.profitmandi.dao.repository.cs.*;
29
import com.spice.profitmandi.dao.repository.dtr.*;
30087 tejbeer 30
import com.spice.profitmandi.dao.repository.fofo.PartnerDailyInvestmentRepository;
35075 aman 31
import com.spice.profitmandi.dao.repository.fofo.PurchaseRepository;
36286 ranu 32
import com.spice.profitmandi.dao.repository.fofo.RatingReminderRepository;
34301 ranu 33
import com.spice.profitmandi.dao.repository.fofo.RbmRatingRepository;
34322 ranu 34
import com.spice.profitmandi.dao.repository.fofo.SalesRatingRepository;
35632 ranu 35
import com.spice.profitmandi.dao.repository.transaction.LoanRepository;
30077 tejbeer 36
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
32978 amit.gupta 37
import com.spice.profitmandi.dao.repository.user.AddressRepository;
31249 tejbeer 38
import com.spice.profitmandi.service.AuthService;
39
import com.spice.profitmandi.service.NotificationService;
30348 tejbeer 40
import com.spice.profitmandi.service.PartnerCollectionService;
35725 ranu 41
import com.spice.profitmandi.service.integrations.kommuno.RecordingService;
25952 tejbeer 42
import com.spice.profitmandi.service.user.RetailerService;
28935 tejbeer 43
import com.spice.profitmandi.service.user.StoreTimelineTatService;
25952 tejbeer 44
import com.spice.profitmandi.web.req.CreateFranchiseeRequest;
34322 ranu 45
import com.spice.profitmandi.web.req.RbmSalesRatingRequest;
25952 tejbeer 46
import com.spice.profitmandi.web.res.Partner;
25899 tejbeer 47
import io.swagger.annotations.ApiImplicitParam;
48
import io.swagger.annotations.ApiImplicitParams;
32978 amit.gupta 49
import org.apache.commons.csv.CSVRecord;
50
import org.apache.commons.io.output.ByteArrayOutputStream;
51
import org.apache.logging.log4j.LogManager;
52
import org.apache.logging.log4j.Logger;
53
import org.springframework.beans.factory.annotation.Autowired;
36957 aman 54
import org.springframework.beans.factory.annotation.Value;
32978 amit.gupta 55
import org.springframework.format.annotation.DateTimeFormat;
56
import org.springframework.http.HttpHeaders;
57
import org.springframework.http.HttpStatus;
58
import org.springframework.http.MediaType;
59
import org.springframework.http.ResponseEntity;
60
import org.springframework.mail.javamail.JavaMailSender;
61
import org.springframework.stereotype.Controller;
62
import org.springframework.transaction.annotation.Transactional;
63
import org.springframework.ui.Model;
64
import org.springframework.web.bind.annotation.*;
65
import org.springframework.web.multipart.MultipartFile;
25899 tejbeer 66
 
32978 amit.gupta 67
import javax.servlet.http.HttpServletRequest;
68
import java.io.IOException;
69
import java.time.LocalDate;
70
import java.time.LocalDateTime;
34301 ranu 71
import java.time.YearMonth;
32978 amit.gupta 72
import java.time.format.DateTimeFormatter;
36114 ranu 73
import java.time.temporal.TemporalAdjusters;
32978 amit.gupta 74
import java.util.*;
35415 amit 75
import java.util.HashSet;
32978 amit.gupta 76
import java.util.Map.Entry;
37353 aman 77
import java.util.concurrent.ThreadLocalRandom;
32978 amit.gupta 78
import java.util.stream.Collectors;
79
 
25899 tejbeer 80
@Controller
81
@Transactional(rollbackFor = Throwable.class)
82
public class LeadController {
31677 amit.gupta 83
    private static final Logger LOGGER = LogManager.getLogger(LeadController.class);
36957 aman 84
 
85
    /** Source/createdBy label for leads captured by the AI assistant. */
86
    private static final String AI_LEAD_SOURCE = "AI Assistant";
87
 
37353 aman 88
    /**
37354 aman 89
     * Assignee used for AI leads only when no active BGC L1 can be resolved from cs.position.
37353 aman 90
     * Same auth id the web capture has always routed to, so intake never fails on an empty pool.
91
     */
92
    private static final int AI_LEAD_FALLBACK_ASSIGNEE = 53;
93
 
31677 amit.gupta 94
    @Autowired
95
    private ResponseSender<?> responseSender;
25899 tejbeer 96
 
36957 aman 97
    @Value("${ai.lead.intake.token}")
98
    private String aiLeadIntakeToken;
99
 
31677 amit.gupta 100
    @Autowired
101
    private AuthRepository authRepository;
25899 tejbeer 102
 
31677 amit.gupta 103
    @Autowired
104
    private LeadRepository leadRepository;
25899 tejbeer 105
 
31677 amit.gupta 106
    @Autowired
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
 
37354 aman 810
        // Auto-assign to a randomly picked active BGC L1 so AI leads spread across the lead desk
37353 aman 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
    /**
37354 aman 824
     * Picks the owner for an incoming AI lead: a uniformly random <b>active</b> BGC L1 from
825
     * cs.position (category {@link ProfitMandiConstants#TICKET_CATEGORY_BGC}, escalation L1).
37353 aman 826
     * <p>
37354 aman 827
     * BGC is the desk that works AI/inbound leads before they reach field sales, and BGC L1-L3 is
828
     * already one of the groups offered in the Lead Management "Assign To" list, so a BGC L1 owner
829
     * is a valid assignee the team can see and reassign. Field Sales (category
830
     * {@link ProfitMandiConstants#TICKET_CATEGORY_SALES}) is deliberately NOT the pool here.
831
     * <p>
832
     * Inactive users are filtered out because {@code getAuthUserByCategoryId(int, EscalationType)}
833
     * does not filter on active, and an inactive owner would strand the lead. Ids are already
834
     * distinct per user, so holding several regional positions does not raise a person's odds.
37353 aman 835
     */
836
    private int resolveAiLeadAssignee() {
37354 aman 837
        List<AuthUser> bgcL1 = csService.getAuthUserByCategoryId(
838
                ProfitMandiConstants.TICKET_CATEGORY_BGC, EscalationType.L1);
37353 aman 839
 
37354 aman 840
        List<AuthUser> eligible = bgcL1 == null ? Collections.<AuthUser>emptyList()
841
                : bgcL1.stream()
37353 aman 842
                        .filter(x -> Boolean.TRUE.equals(x.isActive()))
843
                        .collect(Collectors.toList());
844
 
845
        if (eligible.isEmpty()) {
37354 aman 846
            LOGGER.warn("AI lead intake: no active BGC L1 in cs.position, falling back to auth id {}",
37353 aman 847
                    AI_LEAD_FALLBACK_ASSIGNEE);
848
            return AI_LEAD_FALLBACK_ASSIGNEE;
849
        }
850
 
851
        AuthUser assignee = eligible.get(ThreadLocalRandom.current().nextInt(eligible.size()));
37354 aman 852
        LOGGER.info("AI lead intake: assigned to BGC L1 {} ({}) picked from {} eligible",
37353 aman 853
                assignee.getId(), assignee.getFullName(), eligible.size());
854
        return assignee.getId();
855
    }
856
 
31677 amit.gupta 857
    @RequestMapping(value = "/getPartnersList", method = RequestMethod.GET)
35079 vikas 858
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 859
    public ResponseEntity<?> getPartners(HttpServletRequest request, @RequestParam(name = "gmailId") String gmailId)
860
            throws ProfitMandiBusinessException {
25952 tejbeer 861
 
31677 amit.gupta 862
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35630 aman 863
        if (authUser == null) {
864
            LOGGER.warn("No auth user found for gmailId: {}", gmailId);
865
            return responseSender.badRequest("No user found for the provided email");
866
        }
25952 tejbeer 867
 
31677 amit.gupta 868
        Map<String, Set<String>> storeGuyMap = csService.getAuthUserPartnerEmailMapping();
25952 tejbeer 869
 
31677 amit.gupta 870
        Set<String> emails = storeGuyMap.get(authUser.getEmailId());
35630 aman 871
        LOGGER.info("emails: {}", emails);
872
        if (emails == null || emails.isEmpty()) {
873
            LOGGER.info("No partner emails found for user: {}", gmailId);
874
            return responseSender.ok(new ArrayList<>());
875
        }
31677 amit.gupta 876
        List<User> users = userRepository.selectAllByEmailIds(new ArrayList<>(emails));
877
        List<Partner> partners = new ArrayList<>();
878
        for (User user : users) {
35630 aman 879
            try {
880
                UserAccount uc = userAccountRepository.selectSaholicByUserId(user.getId());
881
                if (uc == null) {
882
                    LOGGER.warn("No user account found for userId: {}", user.getId());
883
                    continue;
884
                }
885
                com.spice.profitmandi.dao.entity.user.User userInfo = userUserRepository.selectById(uc.getAccountKey());
886
                if (userInfo == null) {
887
                    LOGGER.warn("No user info found for accountKey: {}", uc.getAccountKey());
888
                    continue;
889
                }
890
                CustomRetailer customRetailer = retailerService.getFofoRetailer(userInfo.getId());
891
                if (customRetailer == null) {
892
                    LOGGER.warn("No custom retailer found for userInfoId: {}", userInfo.getId());
893
                    continue;
894
                }
25952 tejbeer 895
 
35630 aman 896
                Partner partner = new Partner();
897
                partner.setBusinessName(customRetailer.getBusinessName());
898
                partner.setPartnerId(customRetailer.getPartnerId());
899
                partner.setCartId(customRetailer.getCartId());
900
                partner.setEmail(customRetailer.getEmail());
901
                partner.setGstNumber(customRetailer.getGstNumber());
902
                partner.setDisplayName(customRetailer.getDisplayName());
903
                partner.setCity(customRetailer.getAddress() != null ? customRetailer.getAddress().getCity() : null);
904
                partner.setUserId(user.getId());
905
                partners.add(partner);
906
            } catch (Exception e) {
907
                LOGGER.error("Error processing partner for userId: {}", user.getId(), e);
908
            }
31677 amit.gupta 909
        }
35630 aman 910
        LOGGER.info("partners: {}", partners);
31677 amit.gupta 911
        return responseSender.ok(partners);
912
    }
25952 tejbeer 913
 
31677 amit.gupta 914
    @RequestMapping(value = "/franchise-first-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 915
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 916
    public ResponseEntity<?> FranchiseFirstVisit(HttpServletRequest request, @RequestBody CreateFranchiseeRequest
917
            createFranchiseeRequest) throws Exception {
25952 tejbeer 918
 
31677 amit.gupta 919
        FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
920
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
921
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
25952 tejbeer 922
 
31677 amit.gupta 923
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
924
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
925
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
926
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
927
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
928
        franchiseeVisit.setScheduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
929
        // change
930
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 931
 
31677 amit.gupta 932
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
933
        franchiseeVisit.setCreatedBy(authUserName);
934
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 935
 
31677 amit.gupta 936
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 937
 
31677 amit.gupta 938
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
939
        franchiseeActivity.setAction(FranchiseeActivityStatus.FOLLOWUP);
940
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
941
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
942
        franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 943
 
31677 amit.gupta 944
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
945
        franchiseeActivityRepository.persist(franchiseeActivity);
31249 tejbeer 946
 
31677 amit.gupta 947
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
31249 tejbeer 948
 
35079 vikas 949
        visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit", authUser.getId(), createFranchiseeRequest.getFirstSchelduleTimestamp());
31249 tejbeer 950
 
31677 amit.gupta 951
        return responseSender.ok(true);
952
    }
25952 tejbeer 953
 
31677 amit.gupta 954
    @RequestMapping(value = "/franchise-visit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 955
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 956
    public ResponseEntity<?> FranchiseVisit(HttpServletRequest request,
957
                                            @RequestBody CreateFranchiseeRequest createFranchiseeRequest) throws Exception {
25952 tejbeer 958
 
34394 tejus.loha 959
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, createFranchiseeRequest.getFofoId());
34276 ranu 960
 
36677 vikas 961
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectAllByFofoId(createFranchiseeRequest.getFofoId());
36723 vikas 962
        FranchiseeVisit franchiseeVisit = franchiseeVisits.isEmpty() ? new FranchiseeVisit() : franchiseeVisits.get(0);
31677 amit.gupta 963
        franchiseeVisit.setFofoId(createFranchiseeRequest.getFofoId());
964
        CustomRetailer customRetailer = retailerService.getFofoRetailer(createFranchiseeRequest.getFofoId());
34394 tejus.loha 965
        LOGGER.info("rbmL1 {}", rbmL1);
31677 amit.gupta 966
        franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
967
        franchiseeVisit.setAgenda(createFranchiseeRequest.getAgenda());
968
        franchiseeVisit.setPartnerRemark(createFranchiseeRequest.getPartnerRemark());
969
        franchiseeVisit.setOutsideVisibity(createFranchiseeRequest.getOutsideVisibity());
970
        franchiseeVisit.setInstoreVisibility(createFranchiseeRequest.getInstoreVisibility());
971
        franchiseeVisit.setOutsideStock(createFranchiseeRequest.getOutsideStock());
972
        franchiseeVisit.setSystemKnowledge(createFranchiseeRequest.getSystemKnowledge());
973
        franchiseeVisit.setWorkingDevice(createFranchiseeRequest.getWorkingDevice());
974
        franchiseeVisit.setWorkingPrinter(createFranchiseeRequest.getWorkingPrinter());
975
        franchiseeVisit.setCarryBags(createFranchiseeRequest.getCarryBags());
976
        franchiseeVisit.setSmartdukaanTshirt(createFranchiseeRequest.getSmartdukaanTshirt());
977
        franchiseeVisit.setLatestDummies(createFranchiseeRequest.getLatestDummies());
978
        franchiseeVisit.setInvestment(createFranchiseeRequest.getInvestment());
979
        franchiseeVisit.setMtd(createFranchiseeRequest.getMtd());
980
        franchiseeVisit.setHygiene(createFranchiseeRequest.getHygiene());
981
        franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
982
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
983
        franchiseeVisit.setInformedAboutOnline(createFranchiseeRequest.getOnline());
984
        franchiseeVisit.setPendingBilling(createFranchiseeRequest.getPendingBilling());
34276 ranu 985
        franchiseeVisit.setRbmId(rbmL1);
986
        franchiseeVisit.setRbmRating(createFranchiseeRequest.getRbmRating());
31677 amit.gupta 987
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
988
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
989
        } else {
990
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
991
        }
25952 tejbeer 992
 
31677 amit.gupta 993
        // AuthUser authUser =
994
        // authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
995
        // change
996
        AuthUser authUser = authRepository.selectByGmailId(createFranchiseeRequest.getCreatedBy());
25952 tejbeer 997
 
31677 amit.gupta 998
        String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
999
        franchiseeVisit.setCreatedBy(authUserName);
1000
        franchiseeVisit.setAuthId(authUser.getId());
25952 tejbeer 1001
 
31677 amit.gupta 1002
        franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1003
 
31677 amit.gupta 1004
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
1005
        franchiseeActivity.setAction(createFranchiseeRequest.getAction());
1006
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
1007
        franchiseeActivity.setResolution(createFranchiseeRequest.getResolution());
1008
        if (createFranchiseeRequest.getAction().equals(FranchiseeActivityStatus.FOLLOWUP)) {
1009
            franchiseeActivity.setSchelduleTimestamp(createFranchiseeRequest.getSchelduleTimestamp());
31249 tejbeer 1010
 
31677 amit.gupta 1011
            visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
1012
                    franchiseeVisit.getAuthId(), createFranchiseeRequest.getSchelduleTimestamp());
1013
        } else {
1014
            franchiseeActivity.setSchelduleTimestamp(null);
1015
        }
1016
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
1017
        franchiseeActivityRepository.persist(franchiseeActivity);
25952 tejbeer 1018
 
31677 amit.gupta 1019
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
34276 ranu 1020
 
34394 tejus.loha 1021
        if (!createFranchiseeRequest.getOutsideVisibityReason().isEmpty()) {
34288 ranu 1022
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_EXTERNAL_VISIBILITY, createFranchiseeRequest.getOutsideVisibityReason(), authUser.getId());
34276 ranu 1023
        }
1024
 
34394 tejus.loha 1025
        if (!createFranchiseeRequest.getInstoreVisibilityReason().isEmpty()) {
34288 ranu 1026
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_DESIGN, ProfitMandiConstants.TICKET_CATEGORY_DESIGNING_BRANDING_INTERNAL_VISIBILITY, createFranchiseeRequest.getInstoreVisibilityReason(), authUser.getId());
34276 ranu 1027
        }
1028
 
34394 tejus.loha 1029
        if (!createFranchiseeRequest.getOutsideStockReason().isEmpty()) {
34288 ranu 1030
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_OUTSIDE_STOCK, createFranchiseeRequest.getOutsideStockReason(), authUser.getId());
34276 ranu 1031
        }
1032
 
34394 tejus.loha 1033
        if (!createFranchiseeRequest.getSystemKnowledgeReason().isEmpty()) {
34288 ranu 1034
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_TRAINING, ProfitMandiConstants.TICKET_CATEGORY_TRAINING_NEED, createFranchiseeRequest.getSystemKnowledgeReason(), authUser.getId());
34276 ranu 1035
        }
1036
 
34394 tejus.loha 1037
        if (!createFranchiseeRequest.getLatestDummiesReason().isEmpty()) {
34288 ranu 1038
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_MARKETING, ProfitMandiConstants.TICKET_CATEGORY_MARKETING_DUMMIES, createFranchiseeRequest.getLatestDummiesReason(), authUser.getId());
34276 ranu 1039
        }
1040
 
34394 tejus.loha 1041
        if (!createFranchiseeRequest.getInvestmentReason().isEmpty()) {
34288 ranu 1042
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_INVESTMENT, createFranchiseeRequest.getInvestmentReason(), authUser.getId());
34276 ranu 1043
        }
1044
 
34394 tejus.loha 1045
        if (!createFranchiseeRequest.getHygieneReason().isEmpty()) {
34288 ranu 1046
            csService.createTicket(createFranchiseeRequest.getFofoId(), ProfitMandiConstants.TICKET_CATEGORY_SALES, ProfitMandiConstants.TICKET_CATEGORY_SALES_LOW_DATA_ACCURACY, createFranchiseeRequest.getHygieneReason(), authUser.getId());
1047
        }
34276 ranu 1048
 
31677 amit.gupta 1049
        return responseSender.ok(true);
34276 ranu 1050
 
31677 amit.gupta 1051
    }
25952 tejbeer 1052
 
31677 amit.gupta 1053
    @RequestMapping(value = "/getFranchiseVisit", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1054
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1055
    public ResponseEntity<?> getFranchiseVisit(HttpServletRequest request,
35288 amit 1056
                                               @RequestParam(name = "gmailId") String gmailId, @RequestParam(name = "status") FranchiseeVisitStatus
1057
                                                       status,
31677 amit.gupta 1058
                                               @RequestParam(name = "offset", defaultValue = "0") int offset,
1059
                                               @RequestParam(name = "limit", defaultValue = "10") int limit) throws ProfitMandiBusinessException {
1060
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35079 vikas 1061
        List<VisitRequest> visitRequests = visitRequestRepository.selectByAuthIdAndDate(authUser.getId(), LocalDate.now());
31677 amit.gupta 1062
        Map<Integer, List<VisitRequest>> visitRequestMap = null;
1063
        if (!visitRequests.isEmpty()) {
1064
            visitRequestMap = visitRequests.stream().collect(Collectors.groupingBy(x -> x.getVisitId()));
1065
        }
35079 vikas 1066
        List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectByAuthIdAndStatus(authUser.getId(), status, offset, limit);
25952 tejbeer 1067
 
35415 amit 1068
        // Batch fetch all FranchiseeActivity in one query instead of N+1
1069
        List<Integer> activityIds = franchiseeVisits.stream()
1070
                .filter(fv -> fv.getFranchiseActivityId() != 0)
1071
                .map(FranchiseeVisit::getFranchiseActivityId)
1072
                .collect(Collectors.toList());
1073
        Map<Integer, FranchiseeActivity> activityMap = new HashMap<>();
1074
        if (!activityIds.isEmpty()) {
1075
            activityMap = franchiseeActivityRepository.selectByIds(activityIds).stream()
1076
                    .collect(Collectors.toMap(FranchiseeActivity::getId, x -> x));
1077
        }
1078
 
31677 amit.gupta 1079
        for (FranchiseeVisit fv : franchiseeVisits) {
1080
            if (visitRequestMap != null) {
31249 tejbeer 1081
 
31677 amit.gupta 1082
                List<VisitRequest> visitRequest = visitRequestMap.get(fv.getId());
1083
                if (visitRequest != null) {
1084
                    if (visitRequest.size() > 1) {
31249 tejbeer 1085
 
35079 vikas 1086
                        Comparator<VisitRequest> visitComparato = Comparator.comparing(VisitRequest::getCreatedTimestamp);
31249 tejbeer 1087
 
31677 amit.gupta 1088
                        VisitRequest youngestVisit = visitRequest.stream().max(visitComparato).get();
1089
                        fv.setVisitStatus(youngestVisit.getStatus());
31249 tejbeer 1090
 
31677 amit.gupta 1091
                    } else {
1092
                        fv.setVisitStatus(visitRequest.get(0).getStatus());
31249 tejbeer 1093
 
31677 amit.gupta 1094
                    }
1095
                }
1096
            }
1097
            if (fv.getFranchiseActivityId() != 0) {
35415 amit 1098
                FranchiseeActivity fA = activityMap.get(fv.getFranchiseActivityId());
31677 amit.gupta 1099
                fv.setFranchiseeActivity(fA);
1100
            }
31249 tejbeer 1101
 
31677 amit.gupta 1102
        }
25952 tejbeer 1103
 
31677 amit.gupta 1104
        return responseSender.ok(franchiseeVisits);
25952 tejbeer 1105
 
31677 amit.gupta 1106
    }
25952 tejbeer 1107
 
31677 amit.gupta 1108
    @RequestMapping(value = "/getFranchiseActivity", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1109
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1110
    public ResponseEntity<?> getFranchiseActivity(HttpServletRequest request, @RequestParam(name = "id") int id) throws
1111
            ProfitMandiBusinessException {
25952 tejbeer 1112
 
31677 amit.gupta 1113
        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityRepository.selectByFranchiseeVisitId(id);
1114
        return responseSender.ok(franchiseeActivities);
25952 tejbeer 1115
 
31677 amit.gupta 1116
    }
25952 tejbeer 1117
 
31677 amit.gupta 1118
    @RequestMapping(value = "/getFranchiseeInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1119
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1120
    public ResponseEntity<?> getFranchiseeInfo(HttpServletRequest request, @RequestParam(name = "id") int id) throws
1121
            ProfitMandiBusinessException {
36678 vikas 1122
        FranchiseeVisit franchiseeVisit;
1123
        if (String.valueOf(id).length() < 9) {
1124
            franchiseeVisit = franchiseeVisitRepository.selectById(id);
1125
        } else {
1126
            List<FranchiseeVisit> franchiseeVisits = franchiseeVisitRepository.selectAllByFofoId(id);
36722 vikas 1127
            if (franchiseeVisits.isEmpty()) {
1128
                return responseSender.ok(null);
1129
            }
36678 vikas 1130
            franchiseeVisit = franchiseeVisits.get(0);
1131
        }
25952 tejbeer 1132
 
31677 amit.gupta 1133
        List<DBObject> mobileBrands = mongoClient.getAllBrandsToDisplay(3);
30487 tejbeer 1134
 
31677 amit.gupta 1135
        List<String> brands = mobileBrands.stream().filter(x -> (boolean) x.get("active"))
1136
                .map(x -> (String) x.get("name")).collect(Collectors.toList());
30487 tejbeer 1137
 
31677 amit.gupta 1138
        franchiseeVisit.setBrands(brands);
30487 tejbeer 1139
 
31677 amit.gupta 1140
        return responseSender.ok(franchiseeVisit);
25952 tejbeer 1141
 
31677 amit.gupta 1142
    }
25952 tejbeer 1143
 
31677 amit.gupta 1144
    @RequestMapping(value = "/franchise-visit-update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1145
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1146
    public ResponseEntity<?> franchiseVisitUpdate(HttpServletRequest request, @RequestParam(name = "id") int id,
1147
                                                  @RequestParam(name = "action") FranchiseeActivityStatus action,
1148
                                                  @RequestParam(name = "resolution") String resolution,
1149
                                                  @RequestParam(name = "schelduleTimestamp") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime schelduleTimestamp)
31677 amit.gupta 1150
            throws ProfitMandiBusinessException {
1151
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
25952 tejbeer 1152
 
31677 amit.gupta 1153
        FranchiseeActivity franchiseeActivity = new FranchiseeActivity();
25952 tejbeer 1154
 
31677 amit.gupta 1155
        if (action == FranchiseeActivityStatus.FOLLOWUP) {
30487 tejbeer 1156
 
31677 amit.gupta 1157
            if (schelduleTimestamp != null) {
31249 tejbeer 1158
 
31677 amit.gupta 1159
                visitRequestRepository.createVisitRequest(franchiseeVisit.getId(), "franchiseeVisit",
1160
                        franchiseeVisit.getAuthId(), schelduleTimestamp);
1161
            }
31249 tejbeer 1162
 
31677 amit.gupta 1163
            franchiseeActivity.setSchelduleTimestamp(schelduleTimestamp);
1164
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
1165
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1166
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1167
 
31677 amit.gupta 1168
        } else {
30487 tejbeer 1169
 
31677 amit.gupta 1170
            franchiseeActivity.setSchelduleTimestamp(null);
1171
            franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
1172
            franchiseeVisit.setStatus(FranchiseeVisitStatus.CLOSE);
1173
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1174
            franchiseeVisitRepository.persist(franchiseeVisit);
25952 tejbeer 1175
 
31677 amit.gupta 1176
        }
25952 tejbeer 1177
 
31677 amit.gupta 1178
        franchiseeActivity.setResolution(resolution);
1179
        franchiseeActivity.setFranchiseeVisitd(franchiseeVisit.getId());
1180
        franchiseeActivity.setAction(action);
30487 tejbeer 1181
 
31677 amit.gupta 1182
        franchiseeActivity.setCreatedTimestamp(LocalDateTime.now());
1183
        franchiseeActivityRepository.persist(franchiseeActivity);
30487 tejbeer 1184
 
31677 amit.gupta 1185
        franchiseeVisit.setFranchiseActivityId(franchiseeActivity.getId());
1186
        franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
1187
        franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
1188
        franchiseeVisitRepository.persist(franchiseeVisit);
30487 tejbeer 1189
 
31677 amit.gupta 1190
        return responseSender.ok(true);
25952 tejbeer 1191
 
31677 amit.gupta 1192
    }
28935 tejbeer 1193
 
31677 amit.gupta 1194
    @RequestMapping(value = "/onBoardingTimelineStatus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1195
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1196
    public ResponseEntity<?> onBoardingTimelineStatus(HttpServletRequest request, Model model)
1197
            throws ProfitMandiBusinessException {
35075 aman 1198
        //This userId is of dtr.users
31677 amit.gupta 1199
        int userId = (int) request.getAttribute("userId");
35075 aman 1200
 
1201
        //UserCart contains userId/retailerId in context of user.user as
1202
        //uc contains retailerId and cartId of the retailerId that belongs to user schema
31677 amit.gupta 1203
        UserCart uc = userAccountRepository.getUserCart(userId);
1204
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
1205
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1206
        Map<StoreTimeline, OnBoardingTimelineModel> timelineStatus = null;
1207
        LOGGER.info("partnerOnBoardingPanel" + partnerOnBoardingPanel);
1208
        if (partnerOnBoardingPanel != null) {
28935 tejbeer 1209
 
31677 amit.gupta 1210
            timelineStatus = storeTimelineTatService.getTimeline(partnerOnBoardingPanel.getId());
1211
        }
1212
        List<OnBoardingTimelineModel> onBoardingModel = new ArrayList<>();
1213
        if (timelineStatus != null) {
1214
            onBoardingModel = timelineStatus.values().stream().skip(2).map(x -> x).collect(Collectors.toList());
1215
        }
1216
        return responseSender.ok(onBoardingModel);
28935 tejbeer 1217
 
31677 amit.gupta 1218
    }
35288 amit 1219
 
35075 aman 1220
    @RequestMapping(value = "/purchaseExist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1221
    @ApiImplicitParams({
1222
            @ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35415 amit 1223
    public ResponseEntity<?> purchaseExist(HttpServletRequest request) throws ProfitMandiBusinessException {
35075 aman 1224
        int userId = (int) request.getAttribute("userId");
1225
        UserCart uc = userAccountRepository.getUserCart(userId);
35415 amit 1226
        return responseSender.ok(purchaseRepository.hasPurchaseForFofoId(uc.getUserId()));
35075 aman 1227
    }
35288 amit 1228
 
31677 amit.gupta 1229
    @RequestMapping(value = "/onBoardingTimelineVisibility", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1230
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 1231
    public ResponseEntity<?> onBoardingTimelineVisibility(HttpServletRequest request, Model model)
1232
            throws ProfitMandiBusinessException {
1233
        int userId = (int) request.getAttribute("userId");
1234
        UserCart uc = userAccountRepository.getUserCart(userId);
28982 tejbeer 1235
 
31677 amit.gupta 1236
        FofoStore fs = fofoStoreRepository.selectByRetailerId(uc.getUserId());
1237
        PartnerOnBoardingPanel partnerOnBoardingPanel = partnerOnBoardingPanelRepository.selectByCode(fs.getCode());
1238
        boolean status = true;
1239
        if (partnerOnBoardingPanel != null) {
28982 tejbeer 1240
 
31677 amit.gupta 1241
            status = storeTimelineTatService.getTimelineCompleted(partnerOnBoardingPanel.getId());
1242
        }
28982 tejbeer 1243
 
31677 amit.gupta 1244
        LOGGER.info("status" + status);
28983 tejbeer 1245
 
31677 amit.gupta 1246
        return responseSender.ok(status);
28982 tejbeer 1247
 
31677 amit.gupta 1248
    }
30077 tejbeer 1249
 
31677 amit.gupta 1250
    @RequestMapping(value = "/getPartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 1251
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
35288 amit 1252
    public ResponseEntity<?> getPartnerTarget(HttpServletRequest request, @RequestParam String
1253
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
1254
            ProfitMandiBusinessException {
30077 tejbeer 1255
 
35632 ranu 1256
        long startTime = System.currentTimeMillis();
1257
        long lapTime = startTime;
1258
 
31677 amit.gupta 1259
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
35632 ranu 1260
 
35649 ranu 1261
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserPartnerIdMapping();
1262
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
31677 amit.gupta 1263
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
30078 tejbeer 1264
 
35649 ranu 1265
 
31677 amit.gupta 1266
        float totalPartnerTargetSecondary = 0;
1267
        float totalPartnerTargetCollection = 0;
1268
        float totalPartnerAchievementSecondary = 0;
1269
        float totalPartnerAchievementCollection = 0;
1270
        TargetModel tm = new TargetModel();
1271
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
35632 ranu 1272
        Map<Integer, Long> partnerTicketCount = new HashMap<>(); // Will be populated after we have fofoIdList
30416 tejbeer 1273
 
31677 amit.gupta 1274
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
30077 tejbeer 1275
 
31677 amit.gupta 1276
        if (fofoIds != null && fofoIds.size() > 0) {
32737 amit.gupta 1277
            LOGGER.info("fofoIds {}", fofoIds);
31727 amit.gupta 1278
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
31677 amit.gupta 1279
                    .filter(x -> (!x.isInternal() && (activationType == null || x.getActivationType().equals(activationType))))
1280
                    .map(x -> x.getId()).collect(Collectors.toList());
35632 ranu 1281
            LOGGER.info("PERF: selectByRetailerIds took {} ms", System.currentTimeMillis() - lapTime);
1282
            lapTime = System.currentTimeMillis();
1283
            LOGGER.info("fofoIdList size: {}", fofoIdList.size());
1284
 
1285
            // Optimized: fetch ticket counts only for specific fofoIds instead of all retailers
1286
            if (!fofoIdList.isEmpty()) {
1287
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
1288
            }
1289
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1290
            lapTime = System.currentTimeMillis();
31677 amit.gupta 1291
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
30077 tejbeer 1292
 
31677 amit.gupta 1293
            if (dayValue.equals("previous")) {
1294
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
30138 tejbeer 1295
 
31677 amit.gupta 1296
            }
30087 tejbeer 1297
 
31686 amit.gupta 1298
            if (fofoIdList.size() > 0) {
30453 tejbeer 1299
 
35632 ranu 1300
                // Fetch fofoIds with overdue loans (pending amount > 0 and created > 15 days ago)
1301
                // Optimized: returns only fofoIds, not full Loan objects
1302
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
1303
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
1304
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
1305
                lapTime = System.currentTimeMillis();
1306
 
1307
                // Fetch fofoIds with MTD billing above threshold (20000)
1308
                // Optimized: direct query on orders table instead of complex RBM query
1309
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
1310
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
35650 ranu 1311
                long billingThreshold = 1000L; // Same as RbmWeeklyBillingModel.BILLING_THRESHOLD
35632 ranu 1312
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
1313
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
1314
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
1315
                lapTime = System.currentTimeMillis();
1316
 
35079 vikas 1317
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
35632 ranu 1318
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
1319
                lapTime = System.currentTimeMillis();
30087 tejbeer 1320
 
31686 amit.gupta 1321
                if (!partnerDailyInvestments.isEmpty()) {
35079 vikas 1322
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
31686 amit.gupta 1323
                }
30077 tejbeer 1324
 
35632 ranu 1325
                // Optimized: fetch only specific fofoIds instead of all retailers
1326
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
1327
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
1328
                lapTime = System.currentTimeMillis();
30426 tejbeer 1329
 
31686 amit.gupta 1330
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
35632 ranu 1331
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
1332
                lapTime = System.currentTimeMillis();
30453 tejbeer 1333
 
31686 amit.gupta 1334
                long todayCollectionCount = 0;
1335
                if (!remarkIds.isEmpty()) {
1336
                    todayCollectionCount = partnerCollectionRemarkRepository
1337
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
1338
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
1339
                            .collect(Collectors.counting());
30453 tejbeer 1340
 
31686 amit.gupta 1341
                }
35632 ranu 1342
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
1343
                lapTime = System.currentTimeMillis();
30330 tejbeer 1344
 
35079 vikas 1345
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
35632 ranu 1346
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
1347
                lapTime = System.currentTimeMillis();
30077 tejbeer 1348
 
32978 amit.gupta 1349
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
31686 amit.gupta 1350
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
1351
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
35632 ranu 1352
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
1353
                lapTime = System.currentTimeMillis();
30077 tejbeer 1354
 
35415 amit 1355
                // Pre-fetch all AuthUsers that might be needed (instead of N+1 queries)
1356
                Set<Integer> allAuthIds = new HashSet<>();
1357
                collectionMap.values().stream()
1358
                        .map(PartnerCollectionPlanModel::getAuthId)
1359
                        .filter(id -> id != null && id != authUser.getId())
1360
                        .forEach(allAuthIds::add);
1361
                partnerSecondaryPlans.values().stream()
1362
                        .flatMap(List::stream)
1363
                        .map(PartnerSecondaryPlanModel::getAuthId)
1364
                        .filter(id -> id != null && id != authUser.getId())
1365
                        .forEach(allAuthIds::add);
1366
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
1367
                if (!allAuthIds.isEmpty()) {
1368
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
1369
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
1370
                }
1371
 
35968 ranu 1372
                // Fetch BM/ASM/RBM for all partners
1373
                Map<Integer, Map<String, Integer>> bmAsmRbmMap = csService.getBmAsmRbmAuthUserIdsByFofoIds(new HashSet<>(fofoIdList));
1374
                LOGGER.info("PERF: getBmAsmRbmAuthUserIdsByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1375
                lapTime = System.currentTimeMillis();
1376
 
1377
                // Collect all BM/ASM/RBM auth IDs to batch fetch AuthUser names
1378
                Set<Integer> bmAsmRbmAuthIds = bmAsmRbmMap.values().stream()
1379
                        .flatMap(m -> m.values().stream())
1380
                        .filter(id -> id != null && id > 0)
1381
                        .collect(Collectors.toSet());
1382
 
1383
                Map<Integer, AuthUser> bmAsmRbmAuthUserMap = new HashMap<>();
1384
                if (!bmAsmRbmAuthIds.isEmpty()) {
1385
                    bmAsmRbmAuthUserMap = authRepository.selectByIds(new ArrayList<>(bmAsmRbmAuthIds)).stream()
1386
                            .collect(Collectors.toMap(AuthUser::getId, x -> x, (a, b) -> a));
1387
                }
1388
                LOGGER.info("PERF: fetch BM/ASM/RBM AuthUsers took {} ms", System.currentTimeMillis() - lapTime);
1389
                lapTime = System.currentTimeMillis();
1390
 
32978 amit.gupta 1391
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
35968 ranu 1392
                final Map<Integer, AuthUser> finalBmAsmRbmAuthUserMap = bmAsmRbmAuthUserMap;
31686 amit.gupta 1393
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
1394
                    int fofoId = customRetailerEntry.getKey();
1395
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
1396
                    float totalSecondaryPlan = 0;
1397
                    float totalSecondaryAchivement = 0;
30077 tejbeer 1398
 
31686 amit.gupta 1399
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
1400
                    ptam.setFofoId(fofoId);
1401
                    ptam.setBusinessName(customRetailer.getBusinessName());
1402
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 1403
                    ptam.setActivationType(customRetailer.getActivationType());
30087 tejbeer 1404
 
35968 ranu 1405
                    // Set ASM/RBM/BM names
1406
                    Map<String, Integer> roleMap = bmAsmRbmMap.get(fofoId);
1407
                    if (roleMap != null) {
1408
                        Integer asmId = roleMap.get("ASM");
1409
                        if (asmId != null && asmId > 0 && finalBmAsmRbmAuthUserMap.get(asmId) != null) {
1410
                            ptam.setAsmName(finalBmAsmRbmAuthUserMap.get(asmId).getFullName());
1411
                        }
1412
                        Integer rbmId = roleMap.get("RBM");
1413
                        if (rbmId != null && rbmId > 0 && finalBmAsmRbmAuthUserMap.get(rbmId) != null) {
1414
                            ptam.setRbmName(finalBmAsmRbmAuthUserMap.get(rbmId).getFullName());
1415
                        }
1416
                        Integer bmId = roleMap.get("BM");
1417
                        if (bmId != null && bmId > 0 && finalBmAsmRbmAuthUserMap.get(bmId) != null) {
1418
                            ptam.setBmName(finalBmAsmRbmAuthUserMap.get(bmId).getFullName());
1419
                        }
1420
                    }
1421
 
31686 amit.gupta 1422
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1423
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1424
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1425
                    }
30808 tejbeer 1426
 
32978 amit.gupta 1427
                    if (collectionMap.get(fofoId) != null) {
1428
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
30330 tejbeer 1429
 
31686 amit.gupta 1430
                        ptam.setRemark(collectionPlan.getRemark());
1431
                        ptam.setMessage(collectionPlan.getMessage());
1432
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
35632 ranu 1433
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
35835 ranu 1434
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
31686 amit.gupta 1435
                        ptam.setRank(collectionPlan.getRank());
36267 ranu 1436
 
1437
                        // If remark is SALES_ESCALATION, fetch open escalation ticket activities
1438
                        if (CollectionRemark.SALES_ESCALATION.equals(collectionPlan.getRemark())
1439
                                || CollectionRemark.PARTIAL_RESOLVE.equals(collectionPlan.getRemark())
1440
                                || CollectionRemark.NOT_RESOLVED.equals(collectionPlan.getRemark())) {
1441
                            List<Ticket> openTickets = ticketRepository.selectAllOpenTicketByRetailer(fofoId);
1442
                            for (Ticket ticket : openTickets) {
1443
                                if (ticket.getSubCategoryId() == ProfitMandiConstants.SALES_ESCALATION) {
1444
                                    List<Activity> activities = activityRepository.selectAll(ticket.getId());
1445
                                    ptam.setTicketActivities(activities);
1446
                                    break;
1447
                                }
1448
                            }
1449
                        }
1450
 
31686 amit.gupta 1451
                        Integer authId = collectionPlan.getAuthId();
30330 tejbeer 1452
 
31686 amit.gupta 1453
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
30416 tejbeer 1454
 
31686 amit.gupta 1455
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
30077 tejbeer 1456
 
31686 amit.gupta 1457
                        LOGGER.info("authId" + authId);
30137 tejbeer 1458
 
31686 amit.gupta 1459
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1460
                            float targetCollection = 0;
30330 tejbeer 1461
 
31686 amit.gupta 1462
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1463
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1464
                            } else {
1465
                                targetCollection = collectionPlan.getTargetPlan();
31677 amit.gupta 1466
                            }
30451 tejbeer 1467
 
31677 amit.gupta 1468
                            if (authId != null && authId == authUser.getId()) {
31686 amit.gupta 1469
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1470
                                    totalPartnerTargetCollection += targetCollection;
1471
                                }
31677 amit.gupta 1472
                            }
31686 amit.gupta 1473
                            ptam.setCollectionTarget(targetCollection);
1474
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1475
                                    && collectionPlan.getWalletTimestamp() != null
1476
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1477
                                if (authId != null && authId == authUser.getId()) {
1478
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1479
                                }
1480
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1481
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1482
                                    && collectionPlan.getAchievementPlan() != null) {
1483
                                if (authId != null && authId == authUser.getId()) {
1484
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1485
                                }
1486
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1487
 
31677 amit.gupta 1488
                            }
31686 amit.gupta 1489
                        }
30822 tejbeer 1490
 
31686 amit.gupta 1491
                        if (authId != null && authId != authUser.getId()) {
35415 amit 1492
                            ptam.setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1493
 
31677 amit.gupta 1494
                        }
30087 tejbeer 1495
 
31686 amit.gupta 1496
                        if (collectionPlan.getCommittedDate() != null) {
30087 tejbeer 1497
 
31686 amit.gupta 1498
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1499
                        }
30087 tejbeer 1500
 
31677 amit.gupta 1501
                    }
30821 tejbeer 1502
 
31686 amit.gupta 1503
                    // Secondary
30077 tejbeer 1504
 
31686 amit.gupta 1505
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1506
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
32978 amit.gupta 1507
                    if (partnerSecondaryPlans.get(fofoId) != null) {
31686 amit.gupta 1508
                        long otherBrandSecondary = 0;
32978 amit.gupta 1509
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
31686 amit.gupta 1510
                            Integer authId = pspm.getAuthId();
1511
                            if (!brands.contains(pspm.getBrand())) {
1512
                                if (pspm.getAchievementPlan() != null) {
1513
                                    otherBrandSecondary += pspm.getAchievementPlan();
1514
                                }
1515
                            } else {
1516
                                otherPartnerSecondaryPlanModel = pspm;
1517
                            }
1518
                            if (pspm.getTargetPlan() != null) {
1519
                                totalSecondaryPlan += pspm.getTargetPlan();
1520
                            }
30330 tejbeer 1521
 
31677 amit.gupta 1522
                            if (pspm.getAchievementPlan() != null) {
31686 amit.gupta 1523
                                totalSecondaryAchivement += pspm.getAchievementPlan();
31677 amit.gupta 1524
                            }
30087 tejbeer 1525
 
31686 amit.gupta 1526
                            if (pspm.getCommittedDate() != null) {
30137 tejbeer 1527
 
31686 amit.gupta 1528
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1529
                            }
1530
                            if (authId != null && authId == authUser.getId()) {
30137 tejbeer 1531
 
31686 amit.gupta 1532
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
30087 tejbeer 1533
 
31686 amit.gupta 1534
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1535
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1536
                                    }
1537
                                }
30087 tejbeer 1538
 
31686 amit.gupta 1539
                                if (pspm.getAchievementPlan() != null) {
1540
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
31677 amit.gupta 1541
                                }
31686 amit.gupta 1542
 
31677 amit.gupta 1543
                            }
31686 amit.gupta 1544
                        }
1545
                        if (otherPartnerSecondaryPlanModel != null) {
1546
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1547
                        }
32978 amit.gupta 1548
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
31686 amit.gupta 1549
                                .filter(x -> brands.contains(x.getBrand()))
1550
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
30087 tejbeer 1551
 
31686 amit.gupta 1552
                        if (secondaryModelMap.containsKey("Others")) {
1553
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1554
                            psp.setAchievementPlan(otherBrandSecondary);
1555
                        } else {
35079 vikas 1556
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
31686 amit.gupta 1557
                        }
1558
                        for (String brand : brands) {
1559
                            if (!secondaryModelMap.containsKey(brand)) {
35079 vikas 1560
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
31677 amit.gupta 1561
                            }
31686 amit.gupta 1562
                        }
30087 tejbeer 1563
 
31686 amit.gupta 1564
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1565
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1566
                            if (authId != null && authId != authUser.getId()) {
35415 amit 1567
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
31686 amit.gupta 1568
                                ptam.setSecondaryColor("red");
1569
                            }
1570
 
31677 amit.gupta 1571
                        }
30077 tejbeer 1572
 
31686 amit.gupta 1573
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1574
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1575
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1576
                        // Secondary
1577
 
31677 amit.gupta 1578
                    } else {
31686 amit.gupta 1579
                        for (String brand : brands) {
1580
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1581
                            pspm.setAchievementPlan((long) 0);
1582
                            pspm.setTargetPlan((long) 0);
1583
                            pspm.setBrand(brand);
1584
                            pspm.setFofoId(fofoId);
1585
                            secondaryModelMap.put(brand, pspm);
31677 amit.gupta 1586
                        }
31686 amit.gupta 1587
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
31677 amit.gupta 1588
                    }
30077 tejbeer 1589
 
31686 amit.gupta 1590
                    if (!partnerTicketCount.isEmpty()) {
1591
                        if (partnerTicketCount.get(fofoId) != null) {
1592
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
1593
                        } else {
1594
                            ptam.setTicketCount(0);
1595
 
31677 amit.gupta 1596
                        }
1597
                    }
30087 tejbeer 1598
 
35632 ranu 1599
                    // Category Assignment Logic (Priority: PLAN_TODAY > CARRY_FORWARD > ZERO_BILLED > UNTOUCHED > NORMAL)
1600
                    // Check if partner has credit due (loans > 15 days with pending amount) - just a flag, doesn't affect sorting
1601
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
1602
                    ptam.setHasOverdue(hasCreditDue);
1603
 
1604
                    // Default rank to 5 (Normal) if no collection plan exists
1605
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
1606
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
1607
 
1608
                    // Assign category based on rank (overdue is just a flag, doesn't affect category)
1609
                    if (rank == 1) {
1610
                        ptam.setCategory("PLAN_TODAY");
1611
                        ptam.setCategoryPriority(1);
1612
                    } else if (rank == 2) {
1613
                        ptam.setCategory("CARRY_FORWARD");
1614
                        ptam.setCategoryPriority(2);
1615
                    } else if (hasZeroBilling && rank < 5) {
1616
                        // Zero billed only if NOT in normal category (rank 5+)
1617
                        // If rank is 1,2,3,4 and has zero billing, include in ZERO_BILLED
1618
                        ptam.setCategory("ZERO_BILLED");
1619
                        ptam.setCategoryPriority(3);
1620
                    } else if (rank == 3) {
1621
                        ptam.setCategory("UNTOUCHED");
1622
                        ptam.setCategoryPriority(4);
1623
                    } else {
1624
                        // rank 4 (future plan) and rank 5+ (normal) go to NORMAL
1625
                        // Also, zero billing with rank 5+ goes to NORMAL (not ZERO_BILLED)
1626
                        ptam.setCategory("NORMAL");
1627
                        ptam.setCategoryPriority(5);
1628
                    }
1629
 
31686 amit.gupta 1630
                    ptams.add(ptam);
30077 tejbeer 1631
 
31677 amit.gupta 1632
                }
32923 ranu 1633
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
30077 tejbeer 1634
 
32923 ranu 1635
                LOGGER.info("positions {}", positions);
1636
 
35079 vikas 1637
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 1638
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
1639
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35079 vikas 1640
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
32923 ranu 1641
 
36211 ranu 1642
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
32923 ranu 1643
 
35079 vikas 1644
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
32923 ranu 1645
 
31686 amit.gupta 1646
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
1647
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
1648
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
1649
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
1650
                tm.setTodayCollectionCount((int) todayCollectionCount);
32923 ranu 1651
                List<PartnerTargetAchievementModel> filteredPtams;
30416 tejbeer 1652
 
32923 ranu 1653
                if (isRBMAndL1) {
34428 ranu 1654
                    filteredPtams = ptams;
1655
//                    as of now all party is showing to rbm
1656
                    /*filteredPtams = ptams.stream()
32978 amit.gupta 1657
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34428 ranu 1658
                            .collect(Collectors.toList());*/
32923 ranu 1659
                } else if (isRBMAndNotL1) {
34429 ranu 1660
                    filteredPtams = ptams;
1661
                    /*filteredPtams = ptams.stream()
32923 ranu 1662
                            .filter(ptam -> !(CollectionRemark.SALES_ESCALATION.equals(ptam.getRemark())))
34429 ranu 1663
                            .collect(Collectors.toList());*/
33041 ranu 1664
                } else if (isSales) {
1665
                    filteredPtams = ptams.stream()
36211 ranu 1666
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
33041 ranu 1667
                            .collect(Collectors.toList());
32923 ranu 1668
                } else {
1669
                    filteredPtams = ptams;
1670
                }
34428 ranu 1671
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 1672
                tm.setRBMAndL2(isRBMAndL2);
1673
                tm.setRBMAndL3(isRBMAndL3);
34428 ranu 1674
                tm.setRBMAndNotL1(isRBMAndNotL1);
1675
                tm.setSales(isSales);
35632 ranu 1676
 
1677
                // Calculate category counts
1678
                Map<String, Long> categoryCounts = filteredPtams.stream()
1679
                        .collect(Collectors.groupingBy(
1680
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
1681
                                Collectors.counting()));
1682
                // Count parties with overdue flag (independent of category)
1683
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
1684
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
1685
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
1686
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
1687
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
1688
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
1689
 
1690
                // Sort by: 1) Partners with today's remark go to bottom of entire list
35835 ranu 1691
                //          EXCEPT: NO_ANSWER/SCHEDULE_CALL with scheduledCallTime reached → comes back up
35853 ranu 1692
                //          EXCEPT: NO_ANSWER without scheduledCallTime older than 4 hours → comes back up
35632 ranu 1693
                //          2) Category Priority (PLAN_TODAY=1, CARRY_FORWARD=2, ZERO_BILLED=3, UNTOUCHED=4, NORMAL=5)
1694
                //          3) Then by rank
35835 ranu 1695
                LocalDateTime now = LocalDateTime.now();
35853 ranu 1696
                LocalDateTime fourHoursAgo = now.minusHours(4);
34796 ranu 1697
                tm.setTargetAchievement(filteredPtams.stream()
1698
                        .sorted(Comparator
35632 ranu 1699
                                .comparing((PartnerTargetAchievementModel p) -> {
1700
                                    if (p.getRemarkTimestamp() == null) {
1701
                                        return false; // No remark → comes first
1702
                                    }
1703
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
1704
                                    if (!remarkDate.equals(LocalDate.now())) {
1705
                                        return false; // Not today's remark → comes first
1706
                                    }
35835 ranu 1707
                                    // Check if SCHEDULE_CALL or NO_ANSWER with scheduledCallTime
1708
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
1709
                                        if (p.getScheduledCallTime() != null) {
1710
                                            // Has scheduled time - come up only when scheduled time is reached
1711
                                            if (!p.getScheduledCallTime().isAfter(now)) {
1712
                                                return false; // Scheduled time reached → comes back up
1713
                                            }
1714
                                            return true; // Scheduled time not reached → stays at bottom
1715
                                        }
35853 ranu 1716
                                        // NO_ANSWER without scheduledCallTime - use 4 hour logic
35835 ranu 1717
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
35853 ranu 1718
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
1719
                                            return false; // NO_ANSWER older than 4 hours → comes back up
35835 ranu 1720
                                        }
35632 ranu 1721
                                    }
1722
                                    return true; // Other today's remarks → goes to bottom
1723
                                }) // false → comes first, true → goes to bottom
1724
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
34796 ranu 1725
                                .thenComparing(PartnerTargetAchievementModel::getRank)
1726
                        )
31686 amit.gupta 1727
                        .collect(Collectors.toList()));
30416 tejbeer 1728
 
34796 ranu 1729
 
31677 amit.gupta 1730
            }
30077 tejbeer 1731
 
31677 amit.gupta 1732
        }
35632 ranu 1733
        LOGGER.info("PERF: Total getPartnerTarget took {} ms", System.currentTimeMillis() - startTime);
31677 amit.gupta 1734
        return responseSender.ok(tm);
30077 tejbeer 1735
 
31677 amit.gupta 1736
    }
32737 amit.gupta 1737
 
35920 ranu 1738
    @RequestMapping(value = "/getInactivePartnerTarget", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
1739
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
1740
    public ResponseEntity<?> getInactivePartnerTarget(HttpServletRequest request, @RequestParam String
1741
            gmailId, @RequestParam String dayValue, @RequestParam ActivationType activationType) throws
1742
            ProfitMandiBusinessException {
1743
 
1744
        long startTime = System.currentTimeMillis();
1745
        long lapTime = startTime;
1746
 
1747
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
1748
 
1749
        Map<String, Set<Integer>> storeGuyMap = csService.getAuthUserInactivePartnerIdMapping();
1750
        Set<Integer> fofoIds = storeGuyMap.get(authUser.getEmailId());
1751
        List<String> brands = Arrays.asList("Vivo", "Samsung", "Oppo", "Itel", "Almost New", "Others");
1752
 
1753
        float totalPartnerTargetSecondary = 0;
1754
        float totalPartnerTargetCollection = 0;
1755
        float totalPartnerAchievementSecondary = 0;
1756
        float totalPartnerAchievementCollection = 0;
1757
        TargetModel tm = new TargetModel();
1758
        Map<Integer, PartnerDailyInvestment> partnerDailyInvestmentMap = new HashMap<>();
1759
        Map<Integer, Long> partnerTicketCount = new HashMap<>();
1760
 
1761
        List<PartnerTargetAchievementModel> ptams = new ArrayList<>();
1762
 
1763
        if (fofoIds != null && fofoIds.size() > 0) {
1764
            LOGGER.info("fofoIds {}", fofoIds);
1765
            // Get inactive stores for the given retailer IDs
1766
            List<Integer> fofoIdList = fofoStoreRepository.selectByRetailerIds(new ArrayList<>(fofoIds)).stream()
1767
                    .filter(x -> (!x.isInternal()))
1768
                    .map(x -> x.getId()).collect(Collectors.toList());
1769
            LOGGER.info("PERF: selectInActiveStore took {} ms", System.currentTimeMillis() - lapTime);
1770
            lapTime = System.currentTimeMillis();
1771
            LOGGER.info("inactive fofoIdList size: {}", fofoIdList.size());
1772
 
1773
            if (!fofoIdList.isEmpty()) {
1774
                partnerTicketCount = ticketRepository.selectOpenTicketsCountByFofoIds(fofoIdList);
1775
            }
1776
            LOGGER.info("PERF: selectOpenTicketsCountByFofoIds took {} ms", System.currentTimeMillis() - lapTime);
1777
            lapTime = System.currentTimeMillis();
1778
            LocalDateTime startDate = LocalDate.now().atStartOfDay();
1779
 
1780
            if (dayValue.equals("previous")) {
1781
                startDate = LocalDate.now().minusDays(1).atStartOfDay();
1782
            }
1783
 
1784
            if (fofoIdList.size() > 0) {
1785
 
1786
                LocalDateTime fifteenDaysAgo = LocalDate.now().minusDays(15).atStartOfDay();
1787
                Set<Integer> fofoIdsWithOverdueLoans = loanRepository.selectFofoIdsWithOverdueLoans(fofoIdList, fifteenDaysAgo);
1788
                LOGGER.info("PERF: selectFofoIdsWithOverdueLoans took {} ms", System.currentTimeMillis() - lapTime);
1789
                lapTime = System.currentTimeMillis();
1790
 
1791
                LocalDateTime mtdStartDate = LocalDate.now().withDayOfMonth(1).atStartOfDay();
1792
                LocalDateTime mtdEndDate = LocalDate.now().plusDays(1).atStartOfDay();
1793
                long billingThreshold = 1000L;
1794
                Set<Integer> allMtdBilledFofoIds = orderRepository.selectFofoIdsWithMtdBillingAboveThreshold(
1795
                        fofoIdList, mtdStartDate, mtdEndDate, billingThreshold);
1796
                LOGGER.info("PERF: selectFofoIdsWithMtdBillingAboveThreshold took {} ms", System.currentTimeMillis() - lapTime);
1797
                lapTime = System.currentTimeMillis();
1798
 
1799
                List<PartnerDailyInvestment> partnerDailyInvestments = partnerDailyInvestmentRepository.selectAll(fofoIdList, startDate.toLocalDate().minusDays(1));
1800
                LOGGER.info("PERF: partnerDailyInvestmentRepository.selectAll took {} ms", System.currentTimeMillis() - lapTime);
1801
                lapTime = System.currentTimeMillis();
1802
 
1803
                if (!partnerDailyInvestments.isEmpty()) {
1804
                    partnerDailyInvestmentMap = partnerDailyInvestments.stream().collect(Collectors.toMap(x -> x.getFofoId(), x -> x));
1805
                }
1806
 
1807
                Map<Integer, CustomRetailer> customRetailers = retailerService.getFofoRetailers(fofoIdList);
1808
                LOGGER.info("PERF: getFofoRetailers took {} ms", System.currentTimeMillis() - lapTime);
1809
                lapTime = System.currentTimeMillis();
1810
 
1811
                List<Integer> remarkIds = partnerCollectionRemarkRepository.selectMaxRemarkId(fofoIdList);
1812
                LOGGER.info("PERF: selectMaxRemarkId took {} ms", System.currentTimeMillis() - lapTime);
1813
                lapTime = System.currentTimeMillis();
1814
 
1815
                long todayCollectionCount = 0;
1816
                if (!remarkIds.isEmpty()) {
1817
                    todayCollectionCount = partnerCollectionRemarkRepository
1818
                            .selectByAuthIdAndIds(authUser.getId(), remarkIds).stream()
1819
                            .filter(x -> x.getCreateTimestamp().toLocalDate().equals(LocalDate.now()))
1820
                            .collect(Collectors.counting());
1821
                }
1822
                LOGGER.info("PERF: selectByAuthIdAndIds took {} ms", System.currentTimeMillis() - lapTime);
1823
                lapTime = System.currentTimeMillis();
1824
 
1825
                Map<Integer, PartnerCollectionPlanModel> collectionMap = partnerCollectionService.getCollectionMap(fofoIdList, startDate);
1826
                LOGGER.info("PERF: getCollectionMap took {} ms", System.currentTimeMillis() - lapTime);
1827
                lapTime = System.currentTimeMillis();
1828
 
1829
                Map<Integer, List<PartnerSecondaryPlanModel>> partnerSecondaryPlans = orderRepository
1830
                        .selectPartnerSecondaryGroupByBrand(fofoIdList, startDate.toLocalDate()).stream()
1831
                        .collect(Collectors.groupingBy(x -> x.getFofoId()));
1832
                LOGGER.info("PERF: selectPartnerSecondaryGroupByBrand took {} ms", System.currentTimeMillis() - lapTime);
1833
                lapTime = System.currentTimeMillis();
1834
 
1835
                Set<Integer> allAuthIds = new HashSet<>();
1836
                collectionMap.values().stream()
1837
                        .map(PartnerCollectionPlanModel::getAuthId)
1838
                        .filter(id -> id != null && id != authUser.getId())
1839
                        .forEach(allAuthIds::add);
1840
                partnerSecondaryPlans.values().stream()
1841
                        .flatMap(List::stream)
1842
                        .map(PartnerSecondaryPlanModel::getAuthId)
1843
                        .filter(id -> id != null && id != authUser.getId())
1844
                        .forEach(allAuthIds::add);
1845
                Map<Integer, AuthUser> authUserMap = new HashMap<>();
1846
                if (!allAuthIds.isEmpty()) {
1847
                    authUserMap = authRepository.selectByIds(new ArrayList<>(allAuthIds)).stream()
1848
                            .collect(Collectors.toMap(AuthUser::getId, x -> x));
1849
                }
1850
 
1851
                LOGGER.info("partnerSecondayPlans {}", partnerSecondaryPlans);
1852
                for (Entry<Integer, CustomRetailer> customRetailerEntry : customRetailers.entrySet()) {
1853
                    int fofoId = customRetailerEntry.getKey();
1854
                    CustomRetailer customRetailer = customRetailerEntry.getValue();
1855
                    float totalSecondaryPlan = 0;
1856
                    float totalSecondaryAchivement = 0;
1857
 
1858
                    PartnerTargetAchievementModel ptam = new PartnerTargetAchievementModel();
1859
                    ptam.setFofoId(fofoId);
1860
                    ptam.setBusinessName(customRetailer.getBusinessName());
1861
                    ptam.setMobile(customRetailer.getMobileNumber());
36211 ranu 1862
                    ptam.setActivationType(customRetailer.getActivationType());
35920 ranu 1863
 
1864
                    if (partnerDailyInvestmentMap.get(fofoId) != null) {
1865
                        ptam.setWalletAmount(partnerDailyInvestmentMap.get(fofoId).getWalletAmount());
1866
                        ptam.setShortInvestment(partnerDailyInvestmentMap.get(fofoId).getShortInvestment());
1867
                    }
1868
 
1869
                    if (collectionMap.get(fofoId) != null) {
1870
                        PartnerCollectionPlanModel collectionPlan = collectionMap.get(fofoId);
1871
 
1872
                        ptam.setRemark(collectionPlan.getRemark());
1873
                        ptam.setMessage(collectionPlan.getMessage());
1874
                        ptam.setRemarkTimestamp(collectionPlan.getRemarkTimestamp());
1875
                        ptam.setRecordingUrl(collectionPlan.getRecordingUrl());
1876
                        ptam.setScheduledCallTime(collectionPlan.getScheduledCallTime());
1877
                        ptam.setRank(collectionPlan.getRank());
1878
                        Integer authId = collectionPlan.getAuthId();
1879
 
1880
                        Map<Integer, String> rankColorMap = ProfitMandiConstants.Rank_Color_Map;
1881
                        ptam.setCollectionColor(rankColorMap.get(collectionPlan.getRank()));
1882
 
1883
                        LOGGER.info("authId" + authId);
1884
 
1885
                        if (collectionPlan.getTargetPlan() != null && collectionPlan.getCommittedDate() != null) {
1886
                            float targetCollection = 0;
1887
 
1888
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null) {
1889
                                targetCollection = collectionPlan.getTargetPlan() - collectionPlan.getAchievementPlan();
1890
                            } else {
1891
                                targetCollection = collectionPlan.getTargetPlan();
1892
                            }
1893
 
1894
                            if (authId != null && authId == authUser.getId()) {
1895
                                if (!collectionPlan.getCommittedDate().isAfter(startDate)) {
1896
                                    totalPartnerTargetCollection += targetCollection;
1897
                                }
1898
                            }
1899
                            ptam.setCollectionTarget(targetCollection);
1900
                            if (collectionPlan.getRank() == 2 && collectionPlan.getAchievementPlan() != null
1901
                                    && collectionPlan.getWalletTimestamp() != null
1902
                                    && collectionPlan.getWalletTimestamp().toLocalDate().equals(startDate.toLocalDate())) {
1903
                                if (authId != null && authId == authUser.getId()) {
1904
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1905
                                }
1906
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1907
                            } else if (collectionPlan.getCommittedDate().toLocalDate().isEqual(startDate.toLocalDate())
1908
                                    && collectionPlan.getAchievementPlan() != null) {
1909
                                if (authId != null && authId == authUser.getId()) {
1910
                                    totalPartnerAchievementCollection += collectionPlan.getAchievementPlan();
1911
                                }
1912
                                ptam.setCollectionAchievement(collectionPlan.getAchievementPlan());
1913
                            }
1914
                        }
1915
 
1916
                        if (authId != null && authId != authUser.getId()) {
1917
                            ptam.setAuthUser(authUserMap.get(authId));
1918
                        }
1919
 
1920
                        if (collectionPlan.getCommittedDate() != null) {
1921
                            ptam.setCollectionCommitmentDate(collectionPlan.getCommittedDate().toLocalDate());
1922
                        }
1923
                    }
1924
 
1925
                    PartnerSecondaryPlanModel otherPartnerSecondaryPlanModel = null;
1926
                    Map<String, PartnerSecondaryPlanModel> secondaryModelMap = new HashMap<>();
1927
                    if (partnerSecondaryPlans.get(fofoId) != null) {
1928
                        long otherBrandSecondary = 0;
1929
                        for (PartnerSecondaryPlanModel pspm : partnerSecondaryPlans.get(fofoId)) {
1930
                            Integer authId = pspm.getAuthId();
1931
                            if (!brands.contains(pspm.getBrand())) {
1932
                                if (pspm.getAchievementPlan() != null) {
1933
                                    otherBrandSecondary += pspm.getAchievementPlan();
1934
                                }
1935
                            } else {
1936
                                otherPartnerSecondaryPlanModel = pspm;
1937
                            }
1938
                            if (pspm.getTargetPlan() != null) {
1939
                                totalSecondaryPlan += pspm.getTargetPlan();
1940
                            }
1941
 
1942
                            if (pspm.getAchievementPlan() != null) {
1943
                                totalSecondaryAchivement += pspm.getAchievementPlan();
1944
                            }
1945
 
1946
                            if (pspm.getCommittedDate() != null) {
1947
                                ptam.setSecondaryCommitmentDate(pspm.getCommittedDate().toLocalDate());
1948
                            }
1949
                            if (authId != null && authId == authUser.getId()) {
1950
                                if (pspm.getTargetPlan() != null && pspm.getCommittedDate() != null) {
1951
                                    if (pspm.getCommittedDate().isEqual(startDate)) {
1952
                                        totalPartnerTargetSecondary += pspm.getTargetPlan();
1953
                                    }
1954
                                }
1955
 
1956
                                if (pspm.getAchievementPlan() != null) {
1957
                                    totalPartnerAchievementSecondary += pspm.getAchievementPlan();
1958
                                }
1959
                            }
1960
                        }
1961
                        if (otherPartnerSecondaryPlanModel != null) {
1962
                            otherPartnerSecondaryPlanModel.setAchievementPlan(otherBrandSecondary);
1963
                        }
1964
                        secondaryModelMap = partnerSecondaryPlans.get(fofoId).stream()
1965
                                .filter(x -> brands.contains(x.getBrand()))
1966
                                .collect(Collectors.toMap(x -> x.getBrand(), x -> x));
1967
 
1968
                        if (secondaryModelMap.containsKey("Others")) {
1969
                            PartnerSecondaryPlanModel psp = secondaryModelMap.get("Others");
1970
                            psp.setAchievementPlan(otherBrandSecondary);
1971
                        } else {
1972
                            secondaryModelMap.put("Others", new PartnerSecondaryPlanModel(fofoId, "Others", (long) 0, otherBrandSecondary, authUser.getId(), null));
1973
                        }
1974
                        for (String brand : brands) {
1975
                            if (!secondaryModelMap.containsKey(brand)) {
1976
                                secondaryModelMap.put(brand, new PartnerSecondaryPlanModel(fofoId, brand, (long) 0, (long) 0, authUser.getId(), null));
1977
                            }
1978
                        }
1979
 
1980
                        for (Entry<String, PartnerSecondaryPlanModel> secondaryModelEntry : secondaryModelMap.entrySet()) {
1981
                            Integer authId = secondaryModelEntry.getValue().getAuthId();
1982
                            if (authId != null && authId != authUser.getId()) {
1983
                                secondaryModelEntry.getValue().setAuthUser(authUserMap.get(authId));
1984
                                ptam.setSecondaryColor("red");
1985
                            }
1986
                        }
1987
 
1988
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
1989
                        ptam.setTotalSecondaryPlan(totalSecondaryPlan);
1990
                        ptam.setTotalSecondaryAchievement(totalSecondaryAchivement);
1991
 
1992
                    } else {
1993
                        for (String brand : brands) {
1994
                            PartnerSecondaryPlanModel pspm = new PartnerSecondaryPlanModel();
1995
                            pspm.setAchievementPlan((long) 0);
1996
                            pspm.setTargetPlan((long) 0);
1997
                            pspm.setBrand(brand);
1998
                            pspm.setFofoId(fofoId);
1999
                            secondaryModelMap.put(brand, pspm);
2000
                        }
2001
                        ptam.setPartnerSecondaryModel(secondaryModelMap);
2002
                    }
2003
 
2004
                    if (!partnerTicketCount.isEmpty()) {
2005
                        if (partnerTicketCount.get(fofoId) != null) {
2006
                            ptam.setTicketCount(partnerTicketCount.get(fofoId));
2007
                        } else {
2008
                            ptam.setTicketCount(0);
2009
                        }
2010
                    }
2011
 
2012
                    boolean hasCreditDue = fofoIdsWithOverdueLoans.contains(fofoId);
2013
                    ptam.setHasOverdue(hasCreditDue);
2014
 
2015
                    int rank = ptam.getRank() > 0 ? ptam.getRank() : 5;
2016
                    boolean hasZeroBilling = !allMtdBilledFofoIds.contains(fofoId);
2017
 
2018
                    if (rank == 1) {
2019
                        ptam.setCategory("PLAN_TODAY");
2020
                        ptam.setCategoryPriority(1);
2021
                    } else if (rank == 2) {
2022
                        ptam.setCategory("CARRY_FORWARD");
2023
                        ptam.setCategoryPriority(2);
2024
                    } else if (hasZeroBilling && rank < 5) {
2025
                        ptam.setCategory("ZERO_BILLED");
2026
                        ptam.setCategoryPriority(3);
2027
                    } else if (rank == 3) {
2028
                        ptam.setCategory("UNTOUCHED");
2029
                        ptam.setCategoryPriority(4);
2030
                    } else {
2031
                        ptam.setCategory("NORMAL");
2032
                        ptam.setCategoryPriority(5);
2033
                    }
2034
 
2035
                    ptams.add(ptam);
2036
                }
2037
 
2038
                List<Position> positions = positionRepository.selectPositionByAuthId(authUser.getId()).stream().collect(Collectors.toList());
2039
                LOGGER.info("positions {}", positions);
2040
 
2041
                boolean isRBMAndL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 2042
                boolean isRBMAndL2 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L2.equals(position.getEscalationType()));
2043
                boolean isRBMAndL3 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && EscalationType.L3.equals(position.getEscalationType()));
35920 ranu 2044
                boolean isRBMAndNotL1 = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_RBM == position.getCategoryId() && !EscalationType.L1.equals(position.getEscalationType()));
36211 ranu 2045
                LOGGER.info("isRBMAndL1{}, isRBMAndL2{}, isRBMAndL3{}", isRBMAndL1, isRBMAndL2, isRBMAndL3);
35920 ranu 2046
 
2047
                boolean isSales = positions.stream().anyMatch(position -> ProfitMandiConstants.TICKET_CATEGORY_SALES == position.getCategoryId());
2048
 
2049
                tm.setTotalPartnerTargetCollection(totalPartnerTargetCollection);
2050
                tm.setTotalPartnerTargetSecondary(totalPartnerTargetSecondary);
2051
                tm.setTotalPartnerSecondary(totalPartnerAchievementSecondary);
2052
                tm.setTotalPartnerCollection(totalPartnerAchievementCollection);
2053
                tm.setTodayCollectionCount((int) todayCollectionCount);
2054
                List<PartnerTargetAchievementModel> filteredPtams;
2055
 
2056
                if (isRBMAndL1) {
2057
                    filteredPtams = ptams;
2058
                } else if (isRBMAndNotL1) {
2059
                    filteredPtams = ptams;
2060
                } else if (isSales) {
2061
                    filteredPtams = ptams.stream()
36211 ranu 2062
                            .filter(ptam -> !(CollectionRemark.RBM_L2_ESCALATION.equals(ptam.getRemark()) || CollectionRemark.RBM_L3_ESCALATION.equals(ptam.getRemark())))
35920 ranu 2063
                            .collect(Collectors.toList());
2064
                } else {
2065
                    filteredPtams = ptams;
2066
                }
2067
                tm.setRBMAndL1(isRBMAndL1);
36211 ranu 2068
                tm.setRBMAndL2(isRBMAndL2);
2069
                tm.setRBMAndL3(isRBMAndL3);
35920 ranu 2070
                tm.setRBMAndNotL1(isRBMAndNotL1);
2071
                tm.setSales(isSales);
2072
 
2073
                Map<String, Long> categoryCounts = filteredPtams.stream()
2074
                        .collect(Collectors.groupingBy(
2075
                                p -> p.getCategory() != null ? p.getCategory() : "NORMAL",
2076
                                Collectors.counting()));
2077
                tm.setOverdueCount((int) filteredPtams.stream().filter(PartnerTargetAchievementModel::isHasOverdue).count());
2078
                tm.setPlanTodayCount(categoryCounts.getOrDefault("PLAN_TODAY", 0L).intValue());
2079
                tm.setCarryForwardCount(categoryCounts.getOrDefault("CARRY_FORWARD", 0L).intValue());
2080
                tm.setZeroBilledCount(categoryCounts.getOrDefault("ZERO_BILLED", 0L).intValue());
2081
                tm.setUntouchedCount(categoryCounts.getOrDefault("UNTOUCHED", 0L).intValue());
2082
                tm.setNormalCount(categoryCounts.getOrDefault("NORMAL", 0L).intValue());
2083
 
2084
                LocalDateTime now = LocalDateTime.now();
2085
                LocalDateTime fourHoursAgo = now.minusHours(4);
2086
                tm.setTargetAchievement(filteredPtams.stream()
2087
                        .sorted(Comparator
2088
                                .comparing((PartnerTargetAchievementModel p) -> {
2089
                                    if (p.getRemarkTimestamp() == null) {
2090
                                        return false;
2091
                                    }
2092
                                    LocalDate remarkDate = p.getRemarkTimestamp().toLocalDate();
2093
                                    if (!remarkDate.equals(LocalDate.now())) {
2094
                                        return false;
2095
                                    }
2096
                                    if (CollectionRemark.SCHEDULE_CALL.equals(p.getRemark()) || CollectionRemark.NO_ANSWER.equals(p.getRemark())) {
2097
                                        if (p.getScheduledCallTime() != null) {
2098
                                            if (!p.getScheduledCallTime().isAfter(now)) {
2099
                                                return false;
2100
                                            }
2101
                                            return true;
2102
                                        }
2103
                                        if (CollectionRemark.NO_ANSWER.equals(p.getRemark())
2104
                                                && p.getRemarkTimestamp().isBefore(fourHoursAgo)) {
2105
                                            return false;
2106
                                        }
2107
                                    }
2108
                                    return true;
2109
                                })
2110
                                .thenComparing(PartnerTargetAchievementModel::getCategoryPriority)
2111
                                .thenComparing(PartnerTargetAchievementModel::getRank)
2112
                        )
2113
                        .collect(Collectors.toList()));
2114
            }
2115
        }
2116
        LOGGER.info("PERF: Total getInactivePartnerTarget took {} ms", System.currentTimeMillis() - startTime);
2117
        return responseSender.ok(tm);
2118
 
2119
    }
2120
 
32737 amit.gupta 2121
    //TODO:Amit
31677 amit.gupta 2122
    @RequestMapping(value = "/target", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35079 vikas 2123
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
31677 amit.gupta 2124
    public ResponseEntity<?> createPartnerTarget(HttpServletRequest request,
2125
                                                 @RequestBody PartnerTargetAchievementModel ptam) throws ProfitMandiBusinessException {
30077 tejbeer 2126
 
31677 amit.gupta 2127
        LOGGER.info("ptam" + ptam);
30089 tejbeer 2128
 
31677 amit.gupta 2129
        AuthUser authUser = authRepository.selectByGmailId(ptam.getCreatedBy());
30077 tejbeer 2130
 
31677 amit.gupta 2131
        if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
2132
                || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
2133
            PartnerCollectionPlan partnerCollectionPlan = partnerCollectionPlanRepository
2134
                    .selectByLocalDate(LocalDate.now(), ptam.getFofoId(), true);
2135
            LOGGER.info("pcp" + partnerCollectionPlan);
30077 tejbeer 2136
 
31677 amit.gupta 2137
            if (partnerCollectionPlan == null) {
2138
                if (ptam.getCollectionTarget() > 0) {
30087 tejbeer 2139
 
31677 amit.gupta 2140
                    partnerCollectionPlan = new PartnerCollectionPlan();
2141
                    partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
2142
                    partnerCollectionPlan.setAuthId(authUser.getId());
2143
                    partnerCollectionPlan.setFofoId(ptam.getFofoId());
2144
                    partnerCollectionPlan.setActive(true);
2145
                    partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2146
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2147
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2148
                    partnerCollectionPlanRepository.persist(partnerCollectionPlan);
30416 tejbeer 2149
 
31677 amit.gupta 2150
                }
30087 tejbeer 2151
 
31677 amit.gupta 2152
            } else {
30087 tejbeer 2153
 
31677 amit.gupta 2154
                if (partnerCollectionPlan.getCollectionPlan() != ptam.getCollectionTarget()) {
2155
                    float totalCollectionPlan = partnerCollectionPlan.getCollectionPlan() + 10000;
2156
                    if (authUser.getId() == partnerCollectionPlan.getAuthId()) {
30087 tejbeer 2157
 
31677 amit.gupta 2158
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2159
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
2160
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
2161
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2162
                            partnerCollectionPlan.setActive(true);
2163
                            partnerCollectionPlan
2164
                                    .setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2165
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2166
                        } else {
2167
                            throw new ProfitMandiBusinessException("collection target", "",
2168
                                    "collection target should be more than " + totalCollectionPlan);
2169
                        }
30087 tejbeer 2170
 
31677 amit.gupta 2171
                    } else {
30137 tejbeer 2172
 
31677 amit.gupta 2173
                        if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2174
                                || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
2175
                                || ptam.getCollectionTarget() >= totalCollectionPlan) {
30137 tejbeer 2176
 
31677 amit.gupta 2177
                            partnerCollectionPlan.setActive(false);
2178
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2179
                            partnerCollectionPlan = new PartnerCollectionPlan();
2180
                            partnerCollectionPlan.setCreateTimestamp(LocalDateTime.now());
2181
                            partnerCollectionPlan.setAuthId(authUser.getId());
2182
                            partnerCollectionPlan.setFofoId(ptam.getFofoId());
2183
                            partnerCollectionPlan.setActive(true);
2184
                            partnerCollectionPlan
2185
                                    .setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2186
                            partnerCollectionPlan.setCollectionPlan(ptam.getCollectionTarget());
2187
                            partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2188
                            partnerCollectionPlanRepository.persist(partnerCollectionPlan);
2189
                        } else {
2190
                            throw new ProfitMandiBusinessException("collection target", "",
2191
                                    "collection target should be more than " + totalCollectionPlan);
2192
                        }
2193
                    }
2194
                }
30137 tejbeer 2195
 
31677 amit.gupta 2196
                if ((LocalDate.now().atStartOfDay().equals(ptam.getCollectionCommitmentDate().atStartOfDay())
2197
                        || ptam.getCollectionCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
2198
                        && partnerCollectionPlan.getCollectionPlan() == ptam.getCollectionTarget()) {
2199
                    partnerCollectionPlan.setCommitedTimestamp(ptam.getCollectionCommitmentDate().atStartOfDay());
2200
                    partnerCollectionPlan.setUpdatedTimestamp(LocalDateTime.now());
2201
                }
30416 tejbeer 2202
 
31677 amit.gupta 2203
            }
30433 tejbeer 2204
 
35725 ranu 2205
            long callLogId = recordingService.getLatestAgentCallLog(ptam.getFofoId(),authUser.getId());
2206
 
31677 amit.gupta 2207
            PartnerCollectionRemark pcr = new PartnerCollectionRemark();
2208
            pcr.setFofoId(ptam.getFofoId());
2209
            pcr.setAuthId(authUser.getId());
2210
            pcr.setMessage("Collection plan for" + ptam.getCollectionCommitmentDate());
2211
            pcr.setRemark(CollectionRemark.COLLECTION_PLAN);
35725 ranu 2212
            pcr.setAgentCallLogId(callLogId);
31677 amit.gupta 2213
            pcr.setCreateTimestamp(LocalDateTime.now());
2214
            partnerCollectionRemarkRepository.persist(pcr);
2215
        } else {
2216
            throw new ProfitMandiBusinessException("Date", "",
2217
                    "you can't select the back date " + ptam.getCollectionCommitmentDate());
2218
        }
30077 tejbeer 2219
 
31677 amit.gupta 2220
        for (Entry<String, PartnerSecondaryPlanModel> pspm : ptam.getPartnerSecondaryModel().entrySet()) {
30087 tejbeer 2221
 
31677 amit.gupta 2222
            if (ptam.getCollectionCommitmentDate().isAfter(LocalDate.now())
2223
                    || ptam.getCollectionCommitmentDate().isEqual(LocalDate.now())) {
2224
                PartnerSecondaryPlanModel plan = pspm.getValue();
2225
                PartnerSecondaryPlan psp = partnerSecondaryPlanRepository.selectByLocalDateBrand(plan.getBrand(),
2226
                        LocalDate.now(), ptam.getFofoId(), true);
2227
                LOGGER.info("psp" + psp);
30087 tejbeer 2228
 
31677 amit.gupta 2229
                if (psp == null) {
2230
                    if (plan.getTargetPlan() != null && plan.getTargetPlan() > 0) {
30087 tejbeer 2231
 
31677 amit.gupta 2232
                        psp = new PartnerSecondaryPlan();
2233
                        psp.setAuthId(authUser.getId());
2234
                        psp.setBrand(pspm.getKey());
2235
                        psp.setFofoId(pspm.getValue().getFofoId());
2236
                        psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2237
                        psp.setCreateTimestamp(LocalDateTime.now());
2238
                        psp.setUpdatedTimestamp(LocalDateTime.now());
2239
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2240
                        psp.setActive(true);
2241
                        partnerSecondaryPlanRepository.persist(psp);
2242
                    }
30087 tejbeer 2243
 
31677 amit.gupta 2244
                } else {
2245
                    if (plan.getTargetPlan() != psp.getSecondaryPlan()) {
2246
                        float totalSecondaryPlan = psp.getSecondaryPlan() + 10000;
2247
                        if (authUser.getId() == plan.getAuthId()) {
2248
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2249
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
2250
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
2251
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2252
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2253
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2254
                                psp.setActive(true);
2255
                            } else {
2256
                                throw new ProfitMandiBusinessException("secondary target", "",
2257
                                        "secondary target should be more than " + totalSecondaryPlan);
2258
                            }
30087 tejbeer 2259
 
31677 amit.gupta 2260
                        } else {
30087 tejbeer 2261
 
31677 amit.gupta 2262
                            if (authUser.getEmailId().equals("tarun.verma@smartdukaan.com")
2263
                                    || authUser.getEmailId().equals("rakesh.sonawane@smartdukaan.com")
2264
                                    || plan.getTargetPlan() >= totalSecondaryPlan) {
30087 tejbeer 2265
 
31677 amit.gupta 2266
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2267
                                psp.setActive(false);
2268
                                psp = new PartnerSecondaryPlan();
2269
                                psp.setAuthId(authUser.getId());
2270
                                psp.setBrand(pspm.getKey());
2271
                                psp.setFofoId(pspm.getValue().getFofoId());
2272
                                psp.setSecondaryPlan(pspm.getValue().getTargetPlan());
2273
                                psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2274
                                psp.setCreateTimestamp(LocalDateTime.now());
2275
                                psp.setUpdatedTimestamp(LocalDateTime.now());
2276
                                psp.setActive(true);
2277
                                partnerSecondaryPlanRepository.persist(psp);
2278
                            } else {
2279
                                throw new ProfitMandiBusinessException("secondary target", "",
2280
                                        "secondary target should be more than " + totalSecondaryPlan);
2281
                            }
2282
                        }
2283
                    }
30137 tejbeer 2284
 
31677 amit.gupta 2285
                    if ((LocalDate.now().atStartOfDay().equals(ptam.getSecondaryCommitmentDate().atStartOfDay())
2286
                            || ptam.getSecondaryCommitmentDate().atStartOfDay().isAfter(LocalDate.now().atStartOfDay()))
2287
                            && plan.getTargetPlan() == psp.getSecondaryPlan()) {
2288
                        psp.setCommitedTimestamp(ptam.getSecondaryCommitmentDate().atStartOfDay());
2289
                        psp.setUpdatedTimestamp(LocalDateTime.now());
2290
                    }
30137 tejbeer 2291
 
31677 amit.gupta 2292
                }
2293
            } else {
2294
                throw new ProfitMandiBusinessException("Date", "",
2295
                        "you can't select the back date " + ptam.getSecondaryCommitmentDate());
2296
            }
30137 tejbeer 2297
 
31677 amit.gupta 2298
        }
30077 tejbeer 2299
 
31677 amit.gupta 2300
        return responseSender.ok(true);
30137 tejbeer 2301
 
31677 amit.gupta 2302
    }
30077 tejbeer 2303
 
31677 amit.gupta 2304
    @RequestMapping(value = "/uploadFranchiseeVisit", method = RequestMethod.POST)
35288 amit 2305
    public ResponseEntity<?> readCsvFileAndSetLead(HttpServletRequest request, @RequestPart MultipartFile
2306
            multipartFile) throws Throwable {
30433 tejbeer 2307
 
31677 amit.gupta 2308
        int id = (int) request.getAttribute("userId");
30433 tejbeer 2309
 
31677 amit.gupta 2310
        LOGGER.info("id" + id);
30433 tejbeer 2311
 
31677 amit.gupta 2312
        User user = userRepository.selectById(id);
30433 tejbeer 2313
 
31677 amit.gupta 2314
        AuthUser authUser = authRepository.selectByEmailOrMobile(user.getEmailId());
30433 tejbeer 2315
 
31677 amit.gupta 2316
        String fileName = multipartFile.getName();
2317
        String fileNames = multipartFile.getOriginalFilename();
30433 tejbeer 2318
 
31677 amit.gupta 2319
        LOGGER.info("fileName" + fileName);
2320
        LOGGER.info("fileNames" + fileNames);
30433 tejbeer 2321
 
31677 amit.gupta 2322
        List<CSVRecord> records = FileUtil.readFile(multipartFile);
30433 tejbeer 2323
 
31677 amit.gupta 2324
        for (CSVRecord record : records) {
2325
            FranchiseeVisit franchiseeVisit = new FranchiseeVisit();
2326
            franchiseeVisit.setFofoId(Integer.parseInt(record.get(0)));
2327
            CustomRetailer customRetailer = retailerService.getFofoRetailer(Integer.parseInt(record.get(0)));
30433 tejbeer 2328
 
31677 amit.gupta 2329
            franchiseeVisit.setPartnerName(customRetailer.getBusinessName());
2330
            franchiseeVisit.setAgenda(record.get(1));
2331
            franchiseeVisit.setCreatedTimestamp(LocalDateTime.now());
2332
            franchiseeVisit.setUpdatedTimestamp(LocalDateTime.now());
2333
            franchiseeVisit.setStatus(FranchiseeVisitStatus.OPEN);
30433 tejbeer 2334
 
31677 amit.gupta 2335
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
2336
            LOGGER.info(record.get(1));
2337
            LocalDate dateTime = LocalDate.parse(record.get(2), formatter);
30433 tejbeer 2338
 
31677 amit.gupta 2339
            franchiseeVisit.setScheduleTimestamp(dateTime.atStartOfDay());
2340
            // change
30433 tejbeer 2341
 
31677 amit.gupta 2342
            String authUserName = authUser.getFirstName() + " " + authUser.getLastName();
2343
            franchiseeVisit.setCreatedBy(authUserName);
2344
            franchiseeVisit.setAuthId(authUser.getId());
30433 tejbeer 2345
 
31677 amit.gupta 2346
            franchiseeVisitRepository.persist(franchiseeVisit);
30433 tejbeer 2347
 
31677 amit.gupta 2348
            return responseSender.ok(true);
2349
        }
30433 tejbeer 2350
 
31677 amit.gupta 2351
        return responseSender.ok(true);
30433 tejbeer 2352
 
31677 amit.gupta 2353
    }
30487 tejbeer 2354
 
31677 amit.gupta 2355
    @RequestMapping(value = "/downloadFranchiseeVisitTemplate", method = RequestMethod.GET)
2356
    public ResponseEntity<?> downloadFranchiseeVisitTemplate(HttpServletRequest request) throws Exception {
30487 tejbeer 2357
 
31677 amit.gupta 2358
        // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
30487 tejbeer 2359
 
31677 amit.gupta 2360
        List<List<?>> rows = new ArrayList<>();
30487 tejbeer 2361
 
32923 ranu 2362
        ByteArrayOutputStream byteArrayOutputStream = FileUtil
31677 amit.gupta 2363
                .getCSVByteStream(Arrays.asList("Partner Id", "Agenda", "Schedule Timestamp"), rows);
30487 tejbeer 2364
 
31677 amit.gupta 2365
        try {
2366
            byteArrayOutputStream.close();
2367
        } catch (IOException e) {
2368
            // TODO Auto-generated catch block
2369
            e.printStackTrace();
2370
        }
30487 tejbeer 2371
 
31677 amit.gupta 2372
        String filename = "template.csv";
2373
        HttpHeaders headers = new HttpHeaders();
2374
        headers.add("Content-Type", "application/csv");
2375
        headers.setContentDispositionFormData(filename, filename);
30487 tejbeer 2376
 
31677 amit.gupta 2377
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
30487 tejbeer 2378
 
31677 amit.gupta 2379
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(byteArrayOutputStream.toByteArray(), headers,
2380
                HttpStatus.OK);
2381
        return response;
30544 tejbeer 2382
 
31677 amit.gupta 2383
    }
30542 tejbeer 2384
 
31677 amit.gupta 2385
    @RequestMapping(value = "/markVisitAttendance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
2386
    public ResponseEntity<?> markVisitAttendance(HttpServletRequest request, @RequestParam(name = "id") int id)
2387
            throws ProfitMandiBusinessException {
2388
        FranchiseeVisit franchiseeVisit = franchiseeVisitRepository.selectById(id);
30542 tejbeer 2389
 
31677 amit.gupta 2390
        franchiseeVisit.setVisitTimestamp(LocalDateTime.now());
30542 tejbeer 2391
 
31677 amit.gupta 2392
        return responseSender.ok(true);
30542 tejbeer 2393
 
31677 amit.gupta 2394
    }
31249 tejbeer 2395
 
31677 amit.gupta 2396
    @RequestMapping(value = "/getVisitRequests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2397
    public ResponseEntity<?> getVisitRequests(HttpServletRequest request,
2398
                                              @RequestParam(name = "gmailId") String gmailId, Model model) throws Exception {
31249 tejbeer 2399
 
31677 amit.gupta 2400
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 2401
 
31677 amit.gupta 2402
        List<Integer> authUserIds = authService.getAllReportees(authUser.getId());
2403
        List<VisitSummaryModel> visitSummary = new ArrayList<>();
31249 tejbeer 2404
 
31677 amit.gupta 2405
        if (!authUserIds.isEmpty()) {
35397 amit 2406
            List<AuthUser> authUsers = authRepository.selectByIds(authUserIds);
31249 tejbeer 2407
 
31677 amit.gupta 2408
            List<VisitRequest> allVisitRequests = visitRequestRepository.selectByAuthIdsAndDate(authUserIds,
2409
                    LocalDate.now().minusDays(7), Arrays.asList(VisitStatus.approved, VisitStatus.pending));
2410
            LOGGER.info("allVisitRequests {}", allVisitRequests);
31249 tejbeer 2411
 
31677 amit.gupta 2412
            if (!allVisitRequests.isEmpty()) {
31249 tejbeer 2413
 
31677 amit.gupta 2414
                List<Integer> leadIds = allVisitRequests.stream().filter(x -> x.getVisitType().equals("lead"))
2415
                        .map(x -> x.getVisitId()).collect(Collectors.toList());
2416
                List<Lead> leads = new ArrayList<>();
2417
                if (!leadIds.isEmpty()) {
2418
                    leads = leadRepository.selectAllByIds(leadIds);
31249 tejbeer 2419
 
35415 amit 2420
                    // Batch fetch all LeadActivities instead of N+1
2421
                    List<LeadActivity> allLeadActivities = leadActivityRepository.selectAllByleadIds(leadIds);
2422
                    Map<Integer, List<LeadActivity>> leadActivityMap = allLeadActivities.stream()
2423
                            .collect(Collectors.groupingBy(LeadActivity::getLeadId));
2424
 
31677 amit.gupta 2425
                    for (Lead lead : leads) {
35415 amit 2426
                        List<LeadActivity> leadActivities = leadActivityMap.get(lead.getId());
2427
                        if (leadActivities != null && !leadActivities.isEmpty()) {
2428
                            lead.setScheduledTimestamp(leadActivities.get(0).getSchelduleTimestamp());
2429
                            lead.setLeadActivity(leadActivities.get(0));
2430
                        }
31677 amit.gupta 2431
                    }
2432
                }
2433
                List<Integer> franchiseeIds = allVisitRequests.stream()
2434
                        .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2435
                        .collect(Collectors.toList());
2436
                List<FranchiseeVisit> franchiseeVisits = new ArrayList<>();
2437
                if (!franchiseeIds.isEmpty()) {
2438
                    franchiseeVisits = franchiseeVisitRepository.selectAllByIds(franchiseeIds);
2439
                    LOGGER.info("franchiseeVisits {}", franchiseeVisits);
31249 tejbeer 2440
 
35415 amit 2441
                    // Batch fetch all FranchiseeActivities instead of N+1
2442
                    List<FranchiseeActivity> allFranchiseeActivities = franchiseeActivityRepository
2443
                            .selectByFranchiseeVisitIds(franchiseeIds);
2444
                    Map<Integer, List<FranchiseeActivity>> franchiseeActivityMap = allFranchiseeActivities.stream()
2445
                            .collect(Collectors.groupingBy(FranchiseeActivity::getFranchiseeVisitd));
2446
 
31677 amit.gupta 2447
                    for (FranchiseeVisit franchiseeVisit : franchiseeVisits) {
35415 amit 2448
                        List<FranchiseeActivity> franchiseeActivities = franchiseeActivityMap.get(franchiseeVisit.getId());
31677 amit.gupta 2449
                        LOGGER.info("franchiseeActivities {}", franchiseeActivities);
31249 tejbeer 2450
 
35415 amit 2451
                        if (franchiseeActivities != null && !franchiseeActivities.isEmpty()) {
2452
                            franchiseeVisit.setScheduleTimestamp(franchiseeActivities.get(0).getSchelduleTimestamp());
2453
                            franchiseeVisit.setFranchiseeActivity(franchiseeActivities.get(0));
2454
                        }
31677 amit.gupta 2455
                    }
31249 tejbeer 2456
 
31677 amit.gupta 2457
                }
31249 tejbeer 2458
 
35415 amit 2459
                // Pre-fetch all retailers using cached method (instead of N+1 getFofoRetailer calls)
2460
                Map<Integer, CustomRetailer> allRetailersMap = retailerService.getAllFofoRetailers();
2461
 
31677 amit.gupta 2462
                Map<LocalDate, List<VisitRequest>> dateWiseVisitRequest = allVisitRequests.stream()
2463
                        .collect(Collectors.groupingBy(x -> x.getScheduleTimestamp().toLocalDate()));
31249 tejbeer 2464
 
31677 amit.gupta 2465
                for (Entry<LocalDate, List<VisitRequest>> visitEntry : dateWiseVisitRequest.entrySet()) {
31249 tejbeer 2466
 
31677 amit.gupta 2467
                    LocalDate date = visitEntry.getKey();
2468
                    List<VisitRequest> visitRequests = visitEntry.getValue();
31249 tejbeer 2469
 
31677 amit.gupta 2470
                    VisitSummaryModel visitSummaryModel = new VisitSummaryModel();
31249 tejbeer 2471
 
31677 amit.gupta 2472
                    visitSummaryModel.setDate(date);
2473
                    List<Integer> dateWiseLeadEntry = visitRequests.stream()
2474
                            .filter(x -> x.getVisitType().equals("lead")).map(x -> x.getVisitId())
2475
                            .collect(Collectors.toList());
31249 tejbeer 2476
 
31677 amit.gupta 2477
                    List<Integer> dateWiseFranchiseeIds = visitRequests.stream()
2478
                            .filter(x -> x.getVisitType().equals("franchiseeVisit")).map(x -> x.getVisitId())
2479
                            .collect(Collectors.toList());
31249 tejbeer 2480
 
31677 amit.gupta 2481
                    Map<Integer, List<Lead>> filteredLeadsMap = null;
2482
                    if (!leads.isEmpty()) {
2483
                        filteredLeadsMap = leads.stream().filter(x -> dateWiseLeadEntry.contains(x.getId()))
2484
                                .collect(Collectors.groupingBy(x -> x.getAssignTo()));
31249 tejbeer 2485
 
31677 amit.gupta 2486
                    }
31249 tejbeer 2487
 
31677 amit.gupta 2488
                    Map<Integer, List<FranchiseeVisit>> filteredFranchiseeVisitsMap = null;
31249 tejbeer 2489
 
31677 amit.gupta 2490
                    if (!franchiseeVisits.isEmpty()) {
2491
                        filteredFranchiseeVisitsMap = franchiseeVisits.stream()
2492
                                .filter(x -> dateWiseFranchiseeIds.contains(x.getId()))
2493
                                .collect(Collectors.groupingBy(x -> x.getAuthId()));
31249 tejbeer 2494
 
31677 amit.gupta 2495
                    }
31249 tejbeer 2496
 
31677 amit.gupta 2497
                    List<UserVisitModel> userVisits = new ArrayList<>();
31249 tejbeer 2498
 
31677 amit.gupta 2499
                    for (AuthUser auth : authUsers) {
2500
                        UserVisitModel userVisitModel = new UserVisitModel();
2501
                        List<VisitDescriptionModel> visitDescriptions = new ArrayList<>();
31249 tejbeer 2502
 
31677 amit.gupta 2503
                        List<Lead> authLeads = new ArrayList<>();
2504
                        if (filteredLeadsMap != null) {
2505
                            authLeads = filteredLeadsMap.get(auth.getId());
31249 tejbeer 2506
 
31677 amit.gupta 2507
                        }
31249 tejbeer 2508
 
31677 amit.gupta 2509
                        if (authLeads != null && !authLeads.isEmpty()) {
2510
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2511
 
31677 amit.gupta 2512
                            for (Lead lead : authLeads) {
31249 tejbeer 2513
 
31677 amit.gupta 2514
                                VisitRequest visitRequest = visitRequests.stream().filter(
2515
                                                x -> x.getVisitId() == lead.getId() && x.getCreatedBy() == lead.getAssignTo())
2516
                                        .findAny().orElse(null);
2517
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2518
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2519
                                visitDescriptionModel.setVisitName(lead.getFirstName());
2520
                                visitDescriptionModel.setCity(lead.getCity());
2521
                                visitDescriptionModel.setState(lead.getState());
2522
                                visitDescriptionModel.setScheduleTime(lead.getScheduledTimestamp());
2523
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2524
                                visitDescriptionModel.setRemarks(lead.getLeadActivity().getRemark());
2525
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
2526
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2527
 
31677 amit.gupta 2528
                            }
2529
                        }
31249 tejbeer 2530
 
31677 amit.gupta 2531
                        List<FranchiseeVisit> authfranchiseeVisit = new ArrayList<>();
2532
                        if (filteredFranchiseeVisitsMap != null) {
2533
                            authfranchiseeVisit = filteredFranchiseeVisitsMap.get(auth.getId());
31249 tejbeer 2534
 
31677 amit.gupta 2535
                        }
31249 tejbeer 2536
 
31677 amit.gupta 2537
                        if (authfranchiseeVisit != null && !authfranchiseeVisit.isEmpty()) {
2538
                            userVisitModel.setAuthUser(auth.getFullName());
31249 tejbeer 2539
 
31677 amit.gupta 2540
                            for (FranchiseeVisit franchiseeVisit : authfranchiseeVisit) {
31249 tejbeer 2541
 
31677 amit.gupta 2542
                                VisitRequest visitRequest = visitRequests.stream()
2543
                                        .filter(x -> x.getVisitId() == franchiseeVisit.getId()
2544
                                                && x.getCreatedBy() == franchiseeVisit.getAuthId())
2545
                                        .findAny().orElse(null);
31249 tejbeer 2546
 
35415 amit 2547
                                CustomRetailer customRetailer = allRetailersMap.get(franchiseeVisit.getFofoId());
31677 amit.gupta 2548
                                VisitDescriptionModel visitDescriptionModel = new VisitDescriptionModel();
2549
                                visitDescriptionModel.setVisitId(visitRequest.getId());
2550
                                visitDescriptionModel.setVisitName(franchiseeVisit.getPartnerName());
35415 amit 2551
                                if (customRetailer != null && customRetailer.getAddress() != null) {
2552
                                    visitDescriptionModel.setCity(customRetailer.getAddress().getCity());
2553
                                    visitDescriptionModel.setState(customRetailer.getAddress().getState());
2554
                                }
31677 amit.gupta 2555
                                visitDescriptionModel.setScheduleTime(
2556
                                        franchiseeVisit.getFranchiseeActivity().getSchelduleTimestamp());
2557
                                visitDescriptionModel.setStatus(visitRequest.getStatus());
2558
                                visitDescriptionModel.setRemarks(franchiseeVisit.getAgenda());
2559
                                visitDescriptionModel.setVisitType(visitRequest.getVisitType());
31249 tejbeer 2560
 
31677 amit.gupta 2561
                                visitDescriptions.add(visitDescriptionModel);
31249 tejbeer 2562
 
31677 amit.gupta 2563
                            }
2564
                        }
31249 tejbeer 2565
 
31677 amit.gupta 2566
                        userVisitModel.setVisitDescriptions(visitDescriptions);
2567
                        LOGGER.info("userVisit {}", userVisitModel);
31249 tejbeer 2568
 
31677 amit.gupta 2569
                        if (userVisitModel.getAuthUser() != null) {
2570
                            userVisits.add(userVisitModel);
2571
                        }
31249 tejbeer 2572
 
31677 amit.gupta 2573
                    }
31249 tejbeer 2574
 
31677 amit.gupta 2575
                    visitSummaryModel.setUserVisits(userVisits);
31249 tejbeer 2576
 
31677 amit.gupta 2577
                    visitSummary.add(visitSummaryModel);
31249 tejbeer 2578
 
31677 amit.gupta 2579
                }
31249 tejbeer 2580
 
31677 amit.gupta 2581
            }
31249 tejbeer 2582
 
31677 amit.gupta 2583
        }
2584
        return responseSender.ok(visitSummary);
31249 tejbeer 2585
 
31677 amit.gupta 2586
    }
31249 tejbeer 2587
 
31677 amit.gupta 2588
    @RequestMapping(value = "/visitRequest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2589
    public ResponseEntity<?> visitRequest(HttpServletRequest request, @RequestParam(name = "gmailId") String
2590
                                                  gmailId,
31677 amit.gupta 2591
                                          @RequestParam(name = "visitId") int visitId, @RequestParam(name = "status") VisitStatus status, Model model)
2592
            throws Exception {
2593
        AuthUser authUser = authRepository.selectByGmailId(gmailId);
31249 tejbeer 2594
 
31677 amit.gupta 2595
        VisitRequest visitRequest = visitRequestRepository.selectById(visitId);
2596
        visitRequest.setActionedBy(authUser.getId());
2597
        visitRequest.setStatus(status);
2598
        visitRequest.setUpdatedTimestamp(LocalDateTime.now());
2599
        if (status.equals(VisitStatus.approved)) {
2600
            visitRequest.setApprovedTimestamp(LocalDateTime.now());
2601
        }
31249 tejbeer 2602
 
31677 amit.gupta 2603
        SendNotificationModel sendNotificationModel = new SendNotificationModel();
2604
        sendNotificationModel.setCampaignName("Visit Request");
2605
        sendNotificationModel.setExpiresat(LocalDateTime.now().plusDays(1));
2606
        sendNotificationModel.setTitle("Visit Request");
2607
        String message = "Visit Request has been " + status + " for scheduled time on "
2608
                + visitRequest.getScheduleTimestamp().toLocalDate();
31249 tejbeer 2609
 
31677 amit.gupta 2610
        sendNotificationModel.setMessage(message);
2611
        sendNotificationModel.setMessageType(MessageType.notification);
2612
        User user = userRepository.selectByEmailId(gmailId);
2613
        sendNotificationModel.setUserIds(new ArrayList<>(user.getId()));
31249 tejbeer 2614
 
31677 amit.gupta 2615
        notificationService.sendNotificationToAll(sendNotificationModel);
31249 tejbeer 2616
 
31677 amit.gupta 2617
        return responseSender.ok(true);
31249 tejbeer 2618
 
31677 amit.gupta 2619
    }
31249 tejbeer 2620
 
34301 ranu 2621
    @Autowired
2622
    RbmRatingRepository rbmRatingRepository;
2623
 
34322 ranu 2624
    @Autowired
2625
    SalesRatingRepository salesRatingRepository;
2626
 
34301 ranu 2627
    @RequestMapping(value = "/rbmRating", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
35288 amit 2628
    public ResponseEntity<?> rbmRating(HttpServletRequest request, @RequestBody RbmSalesRatingRequest
2629
            rbmSalesRatingRequest, Model model) throws Exception {
34301 ranu 2630
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2631
        UserCart uc = userAccountRepository.getUserCart(userId);
2632
        int fofoId = uc.getUserId();
34322 ranu 2633
 
34301 ranu 2634
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
34322 ranu 2635
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
34301 ranu 2636
 
36114 ranu 2637
        LocalDate today = LocalDate.now();
36930 ranu 2638
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2639
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2640
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2641
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
34301 ranu 2642
 
37130 ranu 2643
        // JSON error body so Angular's HttpClient (produces = APPLICATION_JSON)
2644
        // doesn't add a "parse error" alongside the 400. Was returning a plain
2645
        // string which caused the "Http failure response … 400 Bad Request
2646
        // (2 errors)" toast for partners who tried to re-submit a rating in
2647
        // the same month.
36930 ranu 2648
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfMonthDateTime, endOfMonthDateTime);
34322 ranu 2649
        if (!existingRbmRatings.isEmpty()) {
37130 ranu 2650
            Map<String, Object> body = new HashMap<>();
2651
            body.put("code", "RATING_ALREADY_EXISTS");
2652
            body.put("message", "Rating for this month already exists.");
2653
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
34301 ranu 2654
        }
2655
 
36930 ranu 2656
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfMonthDateTime, endOfMonthDateTime);
34322 ranu 2657
        if (!existingSalesRatings.isEmpty()) {
37130 ranu 2658
            Map<String, Object> body = new HashMap<>();
2659
            body.put("code", "RATING_ALREADY_EXISTS");
2660
            body.put("message", "Rating for this month already exists.");
2661
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
34322 ranu 2662
        }
34301 ranu 2663
 
34322 ranu 2664
        // Save RBM rating
34301 ranu 2665
        RbmRating rbmRating = new RbmRating();
34322 ranu 2666
        rbmRating.setComment(rbmSalesRatingRequest.getRbmComment());
2667
        rbmRating.setRating(rbmSalesRatingRequest.getRbmRating());
34301 ranu 2668
        rbmRating.setFofoId(fofoId);
2669
        rbmRating.setRbmId(rbmL1);
2670
        rbmRating.setCreateTimeStamp(LocalDateTime.now());
2671
        rbmRatingRepository.persist(rbmRating);
2672
 
34322 ranu 2673
        // Save Sales Person rating
2674
        SalesRating salesRating = new SalesRating();
2675
        salesRating.setComment(rbmSalesRatingRequest.getSalesComment());
2676
        salesRating.setRating(rbmSalesRatingRequest.getSalesRating());
2677
        salesRating.setFofoId(fofoId);
2678
        salesRating.setSalesL1Id(salesL1Id);
2679
        salesRating.setCreateTimeStamp(LocalDateTime.now());
2680
        salesRatingRepository.persist(salesRating);
2681
 
37130 ranu 2682
        Map<String, Object> ok = new HashMap<>();
2683
        ok.put("code", "OK");
2684
        ok.put("message", "Rating submitted successfully.");
2685
        return responseSender.ok(ok);
34301 ranu 2686
    }
2687
 
37130 ranu 2688
    /**
2689
     * GET /rbmRating/exists-this-month — quick precheck so the client can
2690
     * hide/disable the rating popup when a rating for the current month
2691
     * already exists. Returns per-side booleans so the UI can distinguish
2692
     * "only RBM done" vs "only Sales done" vs "both done" if it wants.
2693
     *
2694
     * Response:
2695
     *   {
2696
     *     "rbmRated":   true|false,
2697
     *     "salesRated": true|false,
2698
     *     "canSubmit":  true|false,   // true only when NEITHER rating exists
2699
     *     "monthStart": "yyyy-MM-dd",
2700
     *     "monthEnd":   "yyyy-MM-dd"
2701
     *   }
2702
     */
2703
    @RequestMapping(value = "/rbmRating/exists-this-month", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2704
    public ResponseEntity<?> rbmRatingExistsThisMonth(HttpServletRequest request) throws Exception {
2705
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2706
        UserCart uc = userAccountRepository.getUserCart(userId);
2707
        int fofoId = uc.getUserId();
2708
 
2709
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
2710
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
2711
 
2712
        LocalDate today = LocalDate.now();
2713
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2714
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2715
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2716
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
2717
 
2718
        boolean rbmRated = !rbmRatingRepository
2719
                .findByFofoIdAndRbmIdForCurrentMonth(fofoId, rbmL1, startOfMonthDateTime, endOfMonthDateTime)
2720
                .isEmpty();
2721
        boolean salesRated = !salesRatingRepository
2722
                .findByFofoIdAndSalesL1IdForCurrentMonth(fofoId, salesL1Id, startOfMonthDateTime, endOfMonthDateTime)
2723
                .isEmpty();
2724
 
2725
        Map<String, Object> body = new HashMap<>();
2726
        body.put("rbmRated", rbmRated);
2727
        body.put("salesRated", salesRated);
2728
        // POST /rbmRating rejects when EITHER side already exists, so canSubmit
2729
        // mirrors that gate rather than a per-side flag.
2730
        body.put("canSubmit", !rbmRated && !salesRated);
2731
        body.put("monthStart", startOfMonth.toString());
2732
        body.put("monthEnd", endOfMonth.toString());
2733
        return responseSender.ok(body);
2734
    }
2735
 
36286 ranu 2736
    @RequestMapping(value = "/rbmRating/weekly-status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2737
    public ResponseEntity<?> rbmRatingWeeklyStatus(HttpServletRequest request) throws Exception {
2738
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2739
        UserCart uc = userAccountRepository.getUserCart(userId);
2740
        int fofoId = uc.getUserId();
34301 ranu 2741
 
36286 ranu 2742
        int rbmL1 = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
2743
        int salesL1Id = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
2744
 
2745
        LocalDate today = LocalDate.now();
36930 ranu 2746
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2747
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
2748
        LocalDateTime startOfMonthDateTime = startOfMonth.atStartOfDay();
2749
        LocalDateTime endOfMonthDateTime = endOfMonth.atTime(23, 59, 59);
36286 ranu 2750
 
36930 ranu 2751
        List<RbmRating> existingRbmRatings = rbmRatingRepository.findByFofoIdForCurrentWeek(fofoId, startOfMonthDateTime, endOfMonthDateTime);
2752
        List<SalesRating> existingSalesRatings = salesRatingRepository.findByFofoIdForCurrentWeek(fofoId, startOfMonthDateTime, endOfMonthDateTime);
36286 ranu 2753
 
2754
        boolean pending = existingRbmRatings.isEmpty() || existingSalesRatings.isEmpty();
2755
 
2756
        Map<String, Object> response = new HashMap<>();
2757
        response.put("pending", pending);
36930 ranu 2758
        response.put("weekStart", startOfMonth.toString());
2759
        response.put("weekEnd", endOfMonth.toString());
36286 ranu 2760
 
2761
        if (rbmL1 > 0) {
2762
            AuthUser rbmUser = authRepository.selectById(rbmL1);
2763
            if (rbmUser != null) {
2764
                response.put("rbmName", rbmUser.getFullName());
2765
            }
2766
        }
2767
        if (salesL1Id > 0) {
2768
            AuthUser salesUser = authRepository.selectById(salesL1Id);
2769
            if (salesUser != null) {
2770
                response.put("salesPersonName", salesUser.getFullName());
2771
            }
2772
        }
2773
 
2774
        return responseSender.ok(response);
2775
    }
2776
 
2777
    @Autowired
2778
    private RatingReminderRepository ratingReminderRepository;
2779
 
2780
    @RequestMapping(value = "/rbmRating/reminder", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
2781
    public ResponseEntity<?> rbmRatingReminder(HttpServletRequest request) throws Exception {
2782
        int userId = (int) request.getAttribute(ProfitMandiConstants.USER_ID);
2783
        UserCart uc = userAccountRepository.getUserCart(userId);
2784
        int fofoId = uc.getUserId();
2785
 
2786
        LocalDate today = LocalDate.now();
36930 ranu 2787
        LocalDate startOfMonth = today.with(TemporalAdjusters.firstDayOfMonth());
2788
        LocalDate endOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
36286 ranu 2789
 
36930 ranu 2790
        RatingReminder reminder = ratingReminderRepository.findByFofoIdAndWeek(fofoId, startOfMonth);
36286 ranu 2791
 
2792
        int attemptsRemaining;
2793
        if (reminder == null) {
2794
            reminder = new RatingReminder();
2795
            reminder.setFofoId(fofoId);
36930 ranu 2796
            reminder.setWeekStart(startOfMonth);
2797
            reminder.setWeekEnd(endOfMonth);
36286 ranu 2798
            reminder.setAttemptsRemaining(RatingReminder.MAX_ATTEMPTS_PER_WEEK);
2799
            reminder.setCreateTimestamp(LocalDateTime.now());
2800
            ratingReminderRepository.persist(reminder);
2801
            attemptsRemaining = RatingReminder.MAX_ATTEMPTS_PER_WEEK;
2802
        } else {
2803
            ratingReminderRepository.decrementRemaining(reminder.getId());
36930 ranu 2804
            reminder = ratingReminderRepository.findByFofoIdAndWeek(fofoId, startOfMonth);
36286 ranu 2805
            attemptsRemaining = reminder.getAttemptsRemaining();
2806
        }
2807
 
2808
        Map<String, Object> response = new HashMap<>();
2809
        response.put("partnerId", fofoId);
2810
        response.put("attemptsRemaining", attemptsRemaining);
2811
 
2812
        return responseSender.ok(response);
2813
    }
2814
 
2815
 
30077 tejbeer 2816
}