-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProfileServiceImpl.java
More file actions
1780 lines (1501 loc) · 80 KB
/
ProfileServiceImpl.java
File metadata and controls
1780 lines (1501 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.igot.cb.profile.service;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import com.igot.cb.common.OutboundRequestHandlerServiceImpl;
import com.igot.cb.extendedprofile.service.ExtendedProfileService;
import com.igot.cb.masterdata.service.ValidationService;
import com.igot.cb.util.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.igot.cb.authentication.util.AccessTokenValidator;
import com.igot.cb.profile.entity.CustomFieldEntity;
import com.igot.cb.profile.repository.CustomFieldRepository;
import com.igot.cb.transactional.cassandrautils.CassandraOperation;
import com.igot.cb.transactional.elasticsearch.service.EsUtilServiceImpl;
import com.igot.cb.transactional.redis.cache.CacheService;
import com.igot.cb.transactional.service.RequestHandlerServiceImpl;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class ProfileServiceImpl implements ProfileService {
@Autowired
private AccessTokenValidator accessTokenValidator;
@Autowired
private CbServerProperties serverConfig;
@Autowired
private CassandraOperation cassandraOperation;
@Autowired
private CacheService cacheService;
@Autowired
private ObjectMapper mapper;
@Autowired
private ProjectUtil projectUtil;
@Autowired
private RequestHandlerServiceImpl requestHandlerService;
@Autowired
private CustomFieldRepository customFieldRepository;
@Autowired
private EsUtilServiceImpl esUtilService;
@Value("${profile.visible.allowed.fields}")
private String profileVisibleAllowedFields;
@Value("${user.basic.details.filtered}")
private String basicDetailsFilteredKeys;
@Autowired
OutboundRequestHandlerServiceImpl outboundRequestHandlerService;
@Autowired
ValidationService validationService;
@Autowired
ExtendedProfileService extendedProfileService;
// -------------------- Service METHODS --------------------
@Override
public ApiResponse saveExtendedProfile(Map<String, Object> request, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.create");
Map<String, Object> requestData = (Map<String, Object>) request.get(Constants.REQUEST);
String userId = (String) requestData.get(Constants.USER_ID_RQST);
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) {
ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST);
return response;
}
String validationError = validateRequestContextTypes(requestData, serverConfig.getContextType());
if (StringUtils.isNotBlank(validationError)) {
ProjectUtil.errorResponse(response, validationError, HttpStatus.BAD_REQUEST);
return response;
}
String payloadError = performInputSanitizationCheck(requestData);
if (StringUtils.isNotBlank(payloadError)) {
ProjectUtil.errorResponse(response, payloadError, HttpStatus.BAD_REQUEST);
return response;
}
String errMsg = validateUserExtendedProfileRequest(requestData, userToken);
if (StringUtils.isNotBlank(errMsg)) {
ProjectUtil.errorResponse(response, errMsg, HttpStatus.BAD_REQUEST);
return response;
}
List<Map<String, Object>> savedDataWithUUIDs = new ArrayList<>();
for (String contextType : serverConfig.getContextType()) {
List<Map<String, Object>> incomingList = (List<Map<String, Object>>) requestData.get(contextType);
if (incomingList == null || incomingList.isEmpty())
continue;
List<Map<String, Object>> dataWithUUIDs = addUUIDs(incomingList);
List<Map<String, Object>> existingList = getExistingContextData(userId, contextType);
if(Constants.ACHIEVEMENTS.equalsIgnoreCase(contextType)) {
mergeAndSortByIssuedDateOrTitle(existingList, dataWithUUIDs);
}else{
existingList.addAll(dataWithUUIDs);
}
//sortContextData(existingList, contextType);
if (!saveContextData(userId, contextType, existingList)) {
ProjectUtil.errorResponse(response, "Failed to save data for contextType: " + contextType,
HttpStatus.INTERNAL_SERVER_ERROR);
return response;
}
cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), existingList);
updateExtendedProfileAllCache(userId, contextType, existingList);
savedDataWithUUIDs.addAll(dataWithUUIDs);
}
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESULT, savedDataWithUUIDs);
return response;
}
@Override
public ApiResponse updateExtendedProfile(Map<String, Object> request, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.update");
Map<String, Object> requestData = (Map<String, Object>) request.get(Constants.REQUEST);
String userId = (String) requestData.get(Constants.USER_ID_RQST);
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) {
ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST);
return response;
}
for (String contextType : serverConfig.getContextType()) {
List<Map<String, Object>> incomingList = (List<Map<String, Object>>) requestData.get(contextType);
if (incomingList == null || incomingList.isEmpty())
continue;
List<Map<String, Object>> existingData = getExistingContextData(userId, contextType);
Map<String, Map<String, Object>> dataMap = existingData.stream()
.filter(e -> e.get(Constants.UUID) != null)
.collect(Collectors.toMap(e -> (String) e.get(Constants.UUID), e -> e));
for (Map<String, Object> item : incomingList) {
String uuid = (String) item.get(Constants.UUID);
if (uuid != null && dataMap.containsKey(uuid)) {
dataMap.get(uuid).putAll(item);
} else {
ProjectUtil.errorResponse(response, "Invalid or missing UUID in incoming data.",
HttpStatus.BAD_REQUEST);
return response;
}
}
List<Map<String, Object>> mergedList = new ArrayList<>(dataMap.values());
//sortContextData(mergedList, contextType);
if (Constants.ACHIEVEMENTS.equalsIgnoreCase(contextType)) {
mergeAndSortByIssuedDateOrTitle(mergedList, new ArrayList<>());
}
if (!saveContextData(userId, contextType, mergedList)) {
ProjectUtil.errorResponse(response, "Failed to update data for contextType: " + contextType,
HttpStatus.INTERNAL_SERVER_ERROR);
return response;
}
cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), mergedList);
updateExtendedProfileAllCache(userId, contextType, mergedList);
}
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE, Constants.SUCCESS);
return response;
}
@Override
public ApiResponse deleteExtendedProfile(Map<String, Object> request, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.delete");
Map<String, Object> requestData = (Map<String, Object>) request.get(Constants.REQUEST);
String userId = (String) requestData.get(Constants.USER_ID_RQST);
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) {
ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST);
return response;
}
for (String contextType : serverConfig.getContextType()) {
List<Map<String, Object>> toDeleteList = (List<Map<String, Object>>) requestData.get(contextType);
if (toDeleteList == null || toDeleteList.isEmpty())
continue;
Set<String> uuids = toDeleteList.stream()
.map(e -> (String) e.get(Constants.UUID))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
List<Map<String, Object>> existingData = getExistingContextData(userId, contextType);
existingData.removeIf(e -> uuids.contains(e.get(Constants.UUID)));
//sortContextData(existingData, contextType);
if (!saveContextData(userId, contextType, existingData)) {
ProjectUtil.errorResponse(response, "Failed to delete data for contextType: " + contextType,
HttpStatus.INTERNAL_SERVER_ERROR);
return response;
}
cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), existingData);
updateExtendedProfileAllCache(userId, contextType, existingData);
}
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE, Constants.SUCCESS);
return response;
}
@Override
public ApiResponse getExtendedProfileSummary(String userId, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.read");
if (accessTokenValidator.fetchUserIdFromAccessToken(userToken) == null) {
ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST);
return response;
}
String redisKey = buildCacheKey("user:extendedProfile", "all", userId);
try {
String cachedJson = cacheService.getCache(redisKey);
if (cachedJson != null) {
Map<String, Object> cachedResult = mapper.readValue(cachedJson, Map.class);
Map<String, Object> limitedResult = buildLimitedSummary(cachedResult);
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE, limitedResult);
return response;
}
} catch (Exception e) {
log.error("Failed to fetch summary from cache for userId {}: {}", userId, e);
}
Map<String, Object> result = new HashMap<>();
for (String contextType : serverConfig.getContextType()) {
List<Map<String, Object>> data = getExistingContextData(userId, contextType);
if (!data.isEmpty()) {
Map<String, Object> contextSummary = new HashMap<>();
contextSummary.put(Constants.COUNT, data.size());
contextSummary.put(Constants.DATA, data.stream().limit(2).collect(Collectors.toList()));
result.put(contextType, contextSummary);
}
}
if (result.isEmpty()) {
ProjectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT);
return response;
}
result.put(Constants.USERID_KEY, userId);
try {
cacheService.putCache(redisKey, result);
} catch (Exception e) {
log.warn("Failed to cache extended profile summary for userId {}: {}", userId, e.getMessage());
}
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE, result);
return response;
}
@Override
public ApiResponse readFullExtendedProfile(String userId, String contextType, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.read");
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (userIdFromToken == null) {
ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST);
return response;
}
String redisKey = buildCacheKey("user:extendedProfile", contextType, userId);
List<Map<String, Object>> contextData = null;
try {
String cachedJson = cacheService.getCache(redisKey);
if (cachedJson != null) {
contextData = projectUtil.parseListOfMap(cachedJson);
}
} catch (Exception e) {
log.warn("Error reading from cache for key {}: {}", redisKey, e.getMessage());
}
if (contextData == null) {
contextData = getExistingContextData(userId, contextType);
if (contextData == null || contextData.isEmpty()) {
ProjectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT);
return response;
}
try {
cacheService.putCache(redisKey, contextData);
} catch (Exception e) {
log.warn("Failed to cache data for key {}: {}", redisKey, e.getMessage());
}
}
Map<String, Object> result = new HashMap<>();
result.put(contextType, contextData);
result.put(Constants.USER_ID_RQST, userId);
result.put(Constants.COUNT, contextData.size());
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE,
contextType.equalsIgnoreCase(Constants.LOCATION_DETAILS) ? contextData.get(0) : result);
return response;
}
@Override
public ApiResponse getBasicProfile(String userId, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.getBasicProfile.read");
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (userIdFromToken == null) {
ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED);
return response;
}
boolean isSelfUser = userIdFromToken.equalsIgnoreCase(userId);
String cacheKey = Constants.USER + ":basicProfile:" + userId;
try {
String cachedJson = cacheService.getCache(cacheKey);
Map<String, Object> userProfile;
if (StringUtils.isNotEmpty(cachedJson)) {
userProfile = mapper.readValue(cachedJson, new TypeReference<>() {});
Set<String> cachedKeysLower = userProfile.keySet().stream()
.map(String::toLowerCase)
.collect(Collectors.toSet());
List<String> differenceList = serverConfig.getBasicProfileFields().stream()
.filter(key -> !cachedKeysLower.contains(key.toLowerCase()))
.toList();
if (!differenceList.isEmpty()) {
Set<String> allRequiredKeys = new LinkedHashSet<>();
allRequiredKeys.addAll(userProfile.keySet());
allRequiredKeys.addAll(differenceList);
Map<String, Object> userDetails =
readUserDataFromDB(userId, new ArrayList<>(allRequiredKeys));
if (MapUtils.isNotEmpty(userDetails)) {
userProfile.putAll(userDetails);
}
}
} else {
userProfile = readUserDataFromDB(userId, null);
}
UserUtility.decryptSpecificUserData(userProfile, Arrays.asList(Constants.USERNAME_LOWERCASE));
if (MapUtils.isEmpty(userProfile)) {
response.setResponseCode(HttpStatus.NOT_FOUND);
response.put(Constants.RESPONSE, Collections.emptyMap());
return response;
}
userProfile.put(Constants.PROFILE_COMPLETION_PERCENTAGE, calculateProfileCompletionPercentage(userProfile,
userId, userToken));
userProfile.put(Constants.KARMA_POINTS, getUserKarmaPoints(userId));
userProfile.put(Constants.CERTIFICATE_COUNT, getIssuedCertificateCount(userId));
userProfile.put(Constants.POSTCOUNT, getUserPostCount(userId));
userProfile.put(Constants.ROLES, getUserRoles(userId,(String)userProfile.get(Constants.ROOT_ORG_ID)));
if (!isSelfUser) {
sanitizeProfile(userProfile, userToken);
}
Map<String,Object> responseMap = new HashMap<>();
responseMap.put(Constants.RESPONSE, userProfile);
response.setResponse(responseMap);
} catch (Exception e) {
log.error("Error fetching basic profile for userId: {}", userId, e);
ProjectUtil.errorResponse(response, "Internal server error while fetching profile",
HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
@Override
public ApiResponse listCompetencies(String userId, String userToken) {
ApiResponse response = ProjectUtil.createDefaultResponse("api.listCompetencies.read");
String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken);
if (userIdFromToken == null) {
ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED);
return response;
}
String cacheKey = Constants.USER + ":competencies:" + userId;
try {
String cachedJson = cacheService.getCache(cacheKey);
Map<String, Object> competencies = (cachedJson != null) ? projectUtil.parseMap(cachedJson) : Map.of();
if (competencies.isEmpty()) {
Map<String, Object> queryParams = Map.of(Constants.USERID_KEY, userId);
List<String> fields = Arrays.asList(Constants.USERID_KEY, Constants.COURSE_ID, Constants.BATCH_ID,
Constants.ACTIVE, Constants.STATUS);
List<Map<String, Object>> allEnrolmentRecords = cassandraOperation.getAllRecordsByPrimaryKey(
Constants.KEYSPACE_SUNBIRD_COURSES,
Constants.TABLE_USER_ENROLMENTS, queryParams, fields, 100);
List<String> completedCourseIdList = allEnrolmentRecords.stream()
.filter(map -> Boolean.TRUE.equals(map.get(Constants.ACTIVE_LOWERCASE)) && Integer.valueOf(2).equals(map.get(Constants.STATUS)))
.map(map -> map.get(Constants.COURSE_ID))
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toList());
if (completedCourseIdList.isEmpty()) {
ProjectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT);
return response;
}
Map<String, Map<String, Object>> courseMetadata = getCourseMetadataBatched(completedCourseIdList, 100,
Arrays.asList(Constants.COURSE_ID, Constants.COURSE_CATEGORY, Constants.COMPETENCIES_V6,
Constants.NAME));
competencies = analyzeCompetencies(courseMetadata);
if (competencies.isEmpty()) {
ProjectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT);
return response;
}
cacheService.putCache(cacheKey, competencies);
}
response.setResponseCode(HttpStatus.OK);
response.put(Constants.RESPONSE, competencies);
} catch (Exception e) {
log.error("Error fetching competencies for userId: {}", userId, e);
ProjectUtil.errorResponse(response, "Internal server error while fetching competencies",
HttpStatus.INTERNAL_SERVER_ERROR);
}
return response;
}
// -------------------- HELPER METHODS --------------------
private List<Map<String, Object>> addUUIDs(List<Map<String, Object>> list) {
return list.stream().peek(item -> item.put(Constants.UUID, UUID.randomUUID().toString()))
.collect(Collectors.toList());
}
private List<Map<String, Object>> getExistingContextData(String userId, String contextType) {
Map<String, Object> query = Map.of(Constants.USERID_KEY, userId, Constants.CONTEXT_TYPE, contextType);
List<Map<String, Object>> rows = cassandraOperation.getRecordsByPropertiesByKey(Constants.KEYSPACE_SUNBIRD,
Constants.TABLE_USER_EXTENDED_PROFILE, query, null, null);
if (rows != null && !rows.isEmpty()) {
String json = (String) rows.get(0).get(Constants.CONTEXT_DATA);
try {
return projectUtil.parseListOfMap(json);
} catch (IOException e) {
log.error("Error parsing existing data for userId: {}, contextType: {}", userId, contextType);
}
}
return new ArrayList<>();
}
private boolean saveContextData(String userId, String contextType, List<Map<String, Object>> dataList) {
try {
String finalJson = mapper.writeValueAsString(dataList);
Map<String, Object> query = new HashMap<>();
query.put(Constants.USERID_KEY, userId);
query.put(Constants.CONTEXT_TYPE, contextType);
query.put(Constants.CONTEXT_DATA, finalJson);
ApiResponse insertResponse = (ApiResponse) cassandraOperation.insertRecord(Constants.KEYSPACE_SUNBIRD,
Constants.TABLE_USER_EXTENDED_PROFILE, query);
return Constants.SUCCESS.equalsIgnoreCase((String) insertResponse.get(Constants.RESPONSE));
} catch (JsonProcessingException e) {
log.error("Failed to serialize context data for userId: {}, contextType: {}", userId, contextType);
}
return false;
}
private void sortContextData(List<Map<String, Object>> dataList, String contextType) {
Comparator<Map<String, Object>> comparator = getSortingComparator(contextType);
if (comparator != null) {
dataList.sort(comparator.reversed());
}
}
private Comparator<Map<String, Object>> getSortingComparator(String contextType) {
return switch (contextType) {
case Constants.SERVICE_HISTORY ->
Comparator.comparing(map -> OffsetDateTime.parse((String) map.get(Constants.START_DATE)));
case Constants.EDUCATIONAL_QUALIFICATIONS ->
Comparator.comparing(map -> Integer.parseInt((String) map.get(Constants.START_YEAR)));
case Constants.ACHIVEMENTS ->
Comparator.comparing(map -> OffsetDateTime.parse((String) map.get(Constants.ISSUED_DATE)));
default -> null;
};
}
private String buildCacheKey(String prefix, String contextType, String userId) {
return String.join(":", prefix, contextType, userId);
}
private void updateExtendedProfileAllCache(String userId, String contextType,
List<Map<String, Object>> updatedContextData) {
String allKey = "user:extendedProfile:all:" + userId;
try {
String allJson = cacheService.getCache(allKey);
Map<String, Object> allProfileData = (allJson != null && !allJson.isEmpty())
? mapper.readValue(allJson, new TypeReference<>() {
})
: new HashMap<>();
Map<String, Object> updatedContext = new HashMap<>();
updatedContext.put(Constants.DATA, updatedContextData);
updatedContext.put(Constants.COUNT, updatedContextData != null ? updatedContextData.size() : 0);
allProfileData.put(contextType, updatedContext);
cacheService.putCache(allKey, allProfileData);
} catch (Exception e) {
log.error("Error updating extendedProfile all cache for userId {}: {}", userId, e.getMessage());
}
}
private String validateUserExtendedProfileRequest(Map<String, Object> requestData, String userToken) {
if (requestData == null)
return "Request data is missing.";
List<String> errList = new ArrayList<>();
validateFieldsForList(requestData, Constants.EDUCATIONAL_QUALIFICATIONS,
serverConfig.getEducationalQualificationMandatoryFields(), errList, false);
validateFieldsForList(requestData, Constants.ACHIVEMENTS, serverConfig.getAchievementsMandatoryFields(),
errList, false);
validateFieldsForList(requestData, Constants.SERVICE_HISTORY, serverConfig.getServiceHistoryMandatoryFields(),
errList, true);
validateMasterDataFields(requestData, userToken, errList);
validateServiceHistoryMasterData(requestData, userToken, errList);
if (!errList.isEmpty()) {
return "Failed Due To Missing or Invalid Params - " + String.join(", ", errList) + ".";
}
return "";
}
private void validateFieldsForList(Map<String, Object> requestData, String listKey, String mandatoryFields,
List<String> errList, boolean allowSkipEndDate) {
List<Map<String, Object>> dataList = (List<Map<String, Object>>) requestData.get(listKey);
if (dataList != null) {
for (Map<String, Object> data : dataList) {
String error = validateFields(data, mandatoryFields, allowSkipEndDate);
if (!error.isEmpty()) {
errList.add(error);
}
}
}
}
private String validateFields(Map<String, Object> data, String mandatoryFields, boolean allowSkipEndDate) {
StringBuilder errorMessages = new StringBuilder();
for (String field : mandatoryFields.split(",")) {
if (allowSkipEndDate && Constants.END_DATE.equals(field)) {
Object currentlyWorking = data.get(Constants.CURRENTLY_WORKING);
if (Constants.TRUE.equalsIgnoreCase(String.valueOf(currentlyWorking))) {
continue;
}
}
if (StringUtils.isBlank((String) data.get(field))) {
errorMessages.append(field).append(" is mandatory. ");
}
}
return errorMessages.toString();
}
private String validateRequestContextTypes(Map<String, Object> requestData, String[] contextTypes) {
Set<String> allowedKeys = new HashSet<>(Arrays.asList(contextTypes));
allowedKeys.add(Constants.USER_ID_RQST);
return requestData.keySet().stream()
.filter(key -> !allowedKeys.contains(key))
.findFirst()
.map(key -> "Invalid context type in request: " + key)
.orElse(null);
}
public Map<String, Object> readUserDataFromDB(String userId, List<String> keyList) {
if (CollectionUtils.isEmpty(keyList)) {
keyList = serverConfig.getBasicProfileFields();
}
String cacheKey = Constants.USER + ":basicProfile:" + userId;
Map<String, Object> queryParams = Map.of(Constants.ID, userId);
List<Map<String, Object>> userList = cassandraOperation.getRecordsByPropertiesByKey(
Constants.KEYSPACE_SUNBIRD, Constants.USER, queryParams, keyList, null);
if (CollectionUtils.isEmpty(userList)) {
return Map.of();
}
Map<String, Object> userObj = userList.get(0);
String profileDetailsJson = (String) userObj.get(Constants.PROFILE_DETAILS);
try {
if (StringUtils.isNotBlank(profileDetailsJson)) {
Map<String, Object> profileDetailsMap = mapper.readValue(profileDetailsJson, new TypeReference<Map<String, Object>>() {
});
userObj.put(Constants.PROFILE_DETAILS, profileDetailsMap);
} else {
userObj.put(Constants.PROFILE_DETAILS, Map.of());
}
cacheService.putCache(cacheKey, userObj);
} catch (IOException e) {
log.error("Invalid profileDetails JSON for userId: {}", userId, e);
userObj.put(Constants.PROFILE_DETAILS, Map.of());
}
return userObj;
}
private void sanitizeProfile(Map<String, Object> profile, String userToken) {
Object detailsObj = profile.get(Constants.PROFILE_DETAILS);
if (detailsObj instanceof Map<?, ?> detailsMap) {
if (detailsMap.containsKey(Constants.PERSONAL_DETAILS)) {
detailsMap.remove(Constants.PERSONAL_DETAILS);
log.info("Removed personalDetails due to unrecognized profilePreference.");
}
ProfilePreference profilePref = ProfilePreference.PUBLIC; // default to PUBLIC
Object preferenceObj = detailsMap.get(Constants.PROFILE_PREFERENCE);
if (preferenceObj instanceof Integer) {
ProfilePreference resolvedPref = ProfilePreference.fromValue((Integer) preferenceObj);
if (resolvedPref != null) {
profilePref = resolvedPref;
}
}
// If PUBLIC, return everything
if (ProfilePreference.PUBLIC.equals(profilePref)) {
return;
}
// Load keys from property
List<String> filteredKeys = Arrays.asList(basicDetailsFilteredKeys.split(","));
// Shared allowed keys from config
List<String> allowedKeys = Arrays.asList(profileVisibleAllowedFields.split(","));
Map<String, Object> filteredDetails = new HashMap<>();
// If PRIVATE_NO_ONE
if (ProfilePreference.PRIVATE_NO_ONE.equals(profilePref)) {
for (String key : allowedKeys) {
if (detailsMap.containsKey(key)) {
filteredDetails.put(key, detailsMap.get(key));
}
}
filteredKeys.forEach(profile::remove);
profile.put(Constants.PROFILE_DETAILS, filteredDetails);
log.info("Sanitized profileDetails for PRIVATE_NO_ONE ({}). Allowed fields: {}", profilePref.getValue(), allowedKeys);
} else if (ProfilePreference.PRIVATE_CONNECTIONS.equals(profilePref)) {
Map<String, Object> connectionResponse = checkConnected(
(String) profile.get(Constants.ID),
(String) profile.get(Constants.AUTH_TOKEN),
userToken);
if (connectionResponse != null) {
Object statusObj = connectionResponse.get(Constants.STATUS);
if (statusObj != null && Constants.APPROVED.equalsIgnoreCase(statusObj.toString())) {
return; // If connection approved, allow full profile
}
}
filteredKeys.forEach(profile::remove);
for (String key : allowedKeys) {
if (detailsMap.containsKey(key)) {
filteredDetails.put(key, detailsMap.get(key));
}
}
profile.put(Constants.PROFILE_DETAILS, filteredDetails);
log.info("Sanitized profileDetails for PRIVATE_CONNECTIONS ({}). Allowed fields: {}", profilePref.getValue(), allowedKeys);
} else {
// Fallback case – remove personalDetails
if (detailsMap.containsKey(Constants.PERSONAL_DETAILS)) {
detailsMap.remove(Constants.PERSONAL_DETAILS);
log.info("Removed personalDetails due to unrecognized profilePreference.");
}
}
}
}
public Map<String, Object> checkConnected(String userId, String authToken, String userAuthToken) {
Map<String, String> header = new HashMap<>();
if (StringUtils.isNotEmpty(authToken)) {
header.put(Constants.AUTH_TOKEN, authToken);
}
if (StringUtils.isNotEmpty(userAuthToken)) {
header.put(Constants.X_AUTH_TOKEN, userAuthToken);
}
Map<String, Object> responseMap = new HashMap<>();
Map<String, Object> readData = (Map<String, Object>) outboundRequestHandlerService
.fetchUsingGetWithHeadersProfile(serverConfig.hubGraphService + serverConfig.connectionApi + userId,
header);
if (readData != null) {
Object resultObj = readData.get(Constants.RESULT);
if (resultObj instanceof Map<?, ?> resultMap) {
Object responseObj = resultMap.get(Constants.RESPONSE);
if (responseObj instanceof Map<?, ?> responseData) {
for (Map.Entry<?, ?> entry : responseData.entrySet()) {
if (entry.getKey() instanceof String) {
responseMap.put((String) entry.getKey(), entry.getValue());
}
}
}
}
}
return responseMap;
}
protected double calculateProfileCompletionPercentage(Map<String, Object> profileData,
String userId, String userToken) {
List<String> requiredFields = serverConfig.getProfileCompletionRequiredFields();
if (profileData == null || requiredFields == null || requiredFields.isEmpty())
return 0.0;
double totalCompletion = 0.0;
Map<String, Object> nestedData = Optional.ofNullable(profileData.get(Constants.PROFILE_DETAILS))
.filter(Map.class::isInstance)
.map(Map.class::cast)
.orElse(Collections.emptyMap());
for (String field : requiredFields) {
boolean isFilled;
try {
if (isExtendedProfileField(field)) {
isFilled = hasExtendedProfileData(userId, field, userToken)
|| (Constants.SERVICE_HISTORY.equalsIgnoreCase(field) &&
Optional.ofNullable(profileData.get(Constants.PROFILE_DETAILS))
.filter(Map.class::isInstance)
.map(Map.class::cast)
.map(details -> details.get(Constants.PROFESSIONAL_DETAILS))
.filter(List.class::isInstance)
.map(List.class::cast)
.map(CollectionUtils::isNotEmpty)
.orElse(false));
} else {
if (Constants.EMPLOYMENT_DETAILS.equalsIgnoreCase(field)) {
isFilled = Optional.ofNullable(profileData.get(Constants.PROFILE_DETAILS))
.filter(Map.class::isInstance)
.map(Map.class::cast)
.map(details -> details.get(Constants.EMPLOYMENT_DETAILS))
.filter(Map.class::isInstance)
.map(Map.class::cast)
.map(empDetails -> empDetails.get(Constants.ABOUT_ME))
.map(Object::toString)
.filter(aboutMe -> !aboutMe.trim().isEmpty())
.isPresent();
}else {
Object value = profileData.getOrDefault(field, nestedData.get(field));
isFilled = value != null && !value.toString().trim().isEmpty();
}
}
} catch (Exception e) {
log.warn("Exception checking field '{}' for user '{}': {}", field, userId, e.getMessage());
isFilled = false;
}
if (isFilled)
totalCompletion += serverConfig.getFieldWeight();
}
return Math.min(100.0, Math.round(totalCompletion * 10.0) / 10.0);
}
private boolean isExtendedProfileField(String field) {
return serverConfig.getExtendedFieldsConfig().stream()
.anyMatch(f -> f.equalsIgnoreCase(field));
}
protected boolean hasExtendedProfileData(String userId, String contextType, String userToken) {
try {
ApiResponse response = readFullExtendedProfile(userId, contextType, userToken);
if (response != null && response.getResponseCode() == HttpStatus.OK) {
Map<String, Object> result = (Map<String, Object>) response.get(Constants.RESPONSE);
if (Constants.LOCATION_DETAILS.equalsIgnoreCase(contextType))
return Stream.of(Constants.STATE, Constants.DISTRICT).allMatch(result::containsKey);
Object contextData = result.get(contextType);
return contextData instanceof Collection && !((Collection<?>) contextData).isEmpty();
}
} catch (Exception e) {
log.error("Error checking extended profile data for userId {} and contextType {}: {}", userId,
contextType, e.getMessage());
}
return false;
}
public Map<String, Map<String, Object>> getCourseMetadataBatched(List<String> courseIds, int batchSize,
List<String> fields) {
Map<String, Map<String, Object>> allResults = new LinkedHashMap<>();
if (courseIds == null || courseIds.isEmpty())
return allResults;
for (int i = 0; i < courseIds.size(); i += batchSize) {
int end = Math.min(i + batchSize, courseIds.size());
List<String> batch = courseIds.subList(i, end);
Map<String, String> courseDetailsStrMap = cacheService.getCourseMetadataAsJsonString(batch);
for (int j = 0; j < batch.size(); j++) {
String courseId = batch.get(j);
String json = courseDetailsStrMap.get(courseId);
if (json != null) {
try {
Map<String, Object> parsed = projectUtil.parseMap(json);
if (parsed == null || parsed.isEmpty()) {
log.warn("Parsed JSON for key {} is empty or null", courseId);
continue;
}
if (fields == null || fields.isEmpty()) {
allResults.put(courseId, parsed);
} else {
// Filter only requested fields
Map<String, Object> filtered = parsed.entrySet().stream()
.filter(e -> fields.contains(e.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (!filtered.isEmpty()) {
allResults.put(courseId, filtered);
}
}
} catch (Exception e) {
log.error("Failed to parse JSON for key {}: {}", courseId, e.getMessage(), e);
}
} else {
log.warn("No cached data found for courseId: {}", courseId);
}
}
}
return allResults;
}
public Map<String, Object> analyzeCompetencies(Map<String, Map<String, Object>> courseMetadata) {
// Result containers
Map<String, Long> areaCountMap = new HashMap<>();
Map<String, Map<String, Object>> themeGroupMap = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> entry : courseMetadata.entrySet()) {
String courseId = entry.getKey();
Map<String, Object> course = entry.getValue();
Object compObj = course.get(Constants.COMPETENCIES_V6);
if (!(compObj instanceof List<?> competencies))
continue;
for (Object comp : competencies) {
if (!(comp instanceof Map<?, ?> compMap))
continue;
String areaName = String.valueOf(compMap.get(Constants.COMPETENCY_AREA_NAME));
String themeName = String.valueOf(compMap.get(Constants.COMPETENCY_THEME_NAME));
String subThemeName = String.valueOf(compMap.get(Constants.COMPETENCY_SUB_THEME_NAME));
// 1. Count by competencyAreaName
areaCountMap.merge(areaName, 1L, Long::sum);
// 2. Group by competencyThemeName
themeGroupMap.computeIfAbsent(themeName, k -> {
Map<String, Object> m = new HashMap<>();
m.put(Constants.COMPETENCY_SUB_THEME_NAMES, new HashSet<String>());
m.put(Constants.COURSE_IDS, new HashSet<String>());
return m;
});
Set<String> subThemes = (Set<String>) themeGroupMap.get(themeName).get(Constants.COMPETENCY_SUB_THEME_NAMES);
Set<String> courseIds = (Set<String>) themeGroupMap.get(themeName).get(Constants.COURSE_IDS);
if (subThemeName != null && !subThemeName.isBlank())
subThemes.add(subThemeName);
courseIds.add(courseId);
}
}
// Prepare final output
Map<String, Object> result = new HashMap<>();
result.put(Constants.COMPETENCY_AREA_COUNTS, areaCountMap);
// Convert sets to lists for serialization/final response
Map<String, Map<String, Object>> groupedThemes = new LinkedHashMap<>();
for (Map.Entry<String, Map<String, Object>> entry : themeGroupMap.entrySet()) {
groupedThemes.put(entry.getKey(), Map.of(
Constants.COMPETENCY_SUB_THEME_NAMES,
new ArrayList<>((Set<?>) entry.getValue().get(Constants.COMPETENCY_SUB_THEME_NAMES)),
Constants.COURSE_IDS, new ArrayList<>((Set<?>) entry.getValue().get(Constants.COURSE_IDS))));
}
result.put(Constants.COMPETENCY_THEME_GROUPS, groupedThemes);
return result;
}
private Map<String, Object> buildLimitedSummary(Map<String, Object> fullData) {
Map<String, Object> limitedData = new HashMap<>();
for (Map.Entry<String, Object> entry : fullData.entrySet()) {
String key = entry.getKey();
if (!(entry.getValue() instanceof Map)) {
limitedData.put(key, entry.getValue());
continue;
}
Map<String, Object> contextBlock = (Map<String, Object>) entry.getValue();
Object dataObj = contextBlock.get(Constants.DATA);
if (dataObj instanceof List) {
List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataObj;
Map<String, Object> limitedBlock = new HashMap<>();
limitedBlock.put(Constants.COUNT, contextBlock.get(Constants.COUNT));
limitedBlock.put(Constants.DATA, dataList.size() > 2 ? dataList.subList(0, 2) : dataList);
limitedData.put(key, limitedBlock);
} else {
limitedData.put(key, contextBlock);
}
}
return limitedData;
}
private int getUserKarmaPoints(String userId) {
String redisKey = "user:karmaPoints:" + userId;
try {
String redisValue = cacheService.getCache(redisKey);
if (redisValue != null) {
return Integer.parseInt(redisValue);
}
List<Map<String, Object>> records = cassandraOperation.getRecordsByPropertiesByKey(Constants.KEYSPACE_SUNBIRD,Constants.USER_KARMA_POINTS_SUMMARY_TABLE,
Map.of(Constants.USERID_KEY, userId), List.of(Constants.TOTAL_POINTS), userId);
int totalPoints = 0;
if(!CollectionUtils.isEmpty(records)){
totalPoints=(int) records.get(0).get(Constants.TOTAL_POINTS);
}
cacheService.putCache(redisKey, totalPoints);
return totalPoints;
} catch (Exception e) {
log.warn("Failed to fetch karma points for userId {}: {}", userId, e.getMessage());
return 0;
}
}
private int getIssuedCertificateCount(String userId) {
String redisKey = serverConfig.getCertificateCountRedisKey();
try {
String cachedValue = cacheService.hget(redisKey,serverConfig.getDataIndex(),userId,serverConfig.getCertificateCountRedisTtl());
if (cachedValue != null) {
return Integer.parseInt(cachedValue);
}
List<Map<String, Object>> courseRecords = cassandraOperation.getRecordsByPropertiesByKey(
Constants.KEYSPACE_SUNBIRD_COURSES,
serverConfig.getUserEnrolmentsTable(),
Map.of(Constants.USERID_KEY, userId),
List.of(Constants.ISSUED_CERTIFICATES),
userId
);
int totalIssuedCertificates = 0;
totalIssuedCertificates += (int) courseRecords.stream()
.filter(MapUtils::isNotEmpty)
.map(record -> record.get(Constants.ISSUED_CERTIFICATES_KEY))
.filter(certObj -> certObj instanceof List<?>)
.map(certObj -> (List<?>) certObj)
.filter(CollectionUtils::isNotEmpty)
.count();
List<Map<String, Object>> eventRecords = cassandraOperation.getRecordsByPropertiesByKey(
Constants.KEYSPACE_SUNBIRD_COURSES,
Constants.USER_ENTITY_ENROLMENTS,
Map.of(Constants.USERID_KEY, userId),
List.of(Constants.ISSUED_CERTIFICATES,Constants.PROGRESS_KEY,Constants.STATUS),
userId
);
int certificatesFromEvents = (int) eventRecords.stream()
.filter(MapUtils::isNotEmpty)
.filter(r -> r.get(Constants.STATUS) instanceof Number && ((Number)r.get(Constants.STATUS)).intValue() == 2)
.filter(r -> r.get(Constants.PROGRESS_KEY) instanceof Number && ((Number)r.get(Constants.PROGRESS_KEY)).intValue() == 100)
.map(r -> r.get(Constants.ISSUED_CERTIFICATES_KEY))
.filter(obj -> obj instanceof List<?>)