· 7 years ago · Jan 15, 2019, 08:10 AM
1package com.piq.strata.service.impl;
2
3import java.util.ArrayList;
4import java.util.HashMap;
5import java.util.List;
6import java.util.Optional;
7import java.util.stream.Collectors;
8
9import org.apache.commons.lang.StringUtils;
10import org.json.JSONObject;
11import org.json.simple.parser.ParseException;
12import org.springframework.beans.factory.annotation.Autowired;
13import org.springframework.beans.factory.annotation.Value;
14import org.springframework.context.annotation.Description;
15import org.springframework.data.domain.Page;
16import org.springframework.data.domain.PageRequest;
17import org.springframework.data.domain.Pageable;
18import org.springframework.stereotype.Service;
19import org.springframework.transaction.annotation.Transactional;
20
21import com.piq.strata.dao.BuildingDao;
22import com.piq.strata.dao.CommitteeMemberDao;
23import com.piq.strata.enumerated.CommitteeMemberStatus;
24import com.piq.strata.enumerated.EmailTemplateType;
25import com.piq.strata.enumerated.ErrorCodes;
26import com.piq.strata.enumerated.Roles;
27import com.piq.strata.enumerated.UserStatuses;
28import com.piq.strata.exception.BuildingNotFoundServiceException;
29import com.piq.strata.exception.StrataNotFoundServiceException;
30import com.piq.strata.factory.BuildingFactory;
31import com.piq.strata.factory.CommitteeMemberFactory;
32import com.piq.strata.factory.ContactFactory;
33import com.piq.strata.model.Building;
34import com.piq.strata.model.CommitteeMember;
35import com.piq.strata.model.Lot;
36import com.piq.strata.model.Strata;
37import com.piq.strata.model.User;
38import com.piq.strata.model.UserLot;
39import com.piq.strata.model.UserRole;
40import com.piq.strata.repository.BuildingRepository;
41import com.piq.strata.repository.CommitteeMemberRepository;
42import com.piq.strata.repository.RoleRepository;
43import com.piq.strata.repository.StrataRepository;
44import com.piq.strata.repository.UserLotRepository;
45import com.piq.strata.repository.UserRepository;
46import com.piq.strata.repository.criteria_query.CommitteeMemberCriteria;
47import com.piq.strata.repository.criteria_query.LotCriteria;
48import com.piq.strata.repository.criteria_query.UserLotCriteria;
49import com.piq.strata.request.dto.UserInitiateRequestDTO;
50import com.piq.strata.response.dto.BuildingDTO;
51import com.piq.strata.response.dto.CommitteeMemberDTO;
52import com.piq.strata.response.dto.CommitteeMembersDTO;
53import com.piq.strata.response.dto.Pagination;
54import com.piq.strata.service.CommitteeMemberService;
55import com.piq.strata.service.NotificationServiceBK;
56import com.piq.strata.util.AwsCognitoUtil;
57import com.piq.strata.util.HashUtil;
58import com.piq.strata.util.ValidationUtil;
59
60@Service
61public class CommitteeMemberServiceImpl implements CommitteeMemberService {
62
63 @Value("${default.page.limit}")
64 private int defaultPageLimit;
65 @Value("${aws.ses.portalLink}")
66 private String portalLink;
67
68 private StrataRepository strataRepo;
69 private BuildingRepository buildingRepo;
70 private BuildingDao buildingDao;
71 private BuildingFactory buildingFactory;
72 private CommitteeMemberRepository committeeMemberRepo;
73 private CommitteeMemberFactory committeeMemberFactory;
74 private CommitteeMemberDao committeeMemberDao;
75 private CommitteeMemberCriteria committeeMemberCriteria;
76 private LotCriteria lotCriteria;
77 private AwsCognitoUtil awsCognitoUtil;
78 private UserRepository userRepo;
79 private RoleRepository roleRepo;
80 private NotificationServiceBK notificationService;
81 private ContactFactory contactFactory;
82 private UserLotCriteria userLotCriteria;
83 private UserLotRepository userLotRepo;
84
85 @Autowired
86 public CommitteeMemberServiceImpl(StrataRepository strataRepo, BuildingRepository buildingRepo,
87 BuildingDao buildingDao, BuildingFactory buildingFactory, CommitteeMemberRepository committeeMemberRepo,
88 CommitteeMemberFactory committeeMemberFactory, CommitteeMemberDao committeeMemberDao,
89 CommitteeMemberCriteria committeeMemberCriteria, LotCriteria lotCriteria, AwsCognitoUtil awsCognitoUtil,
90 UserRepository userRepo, RoleRepository roleRepo, NotificationServiceBK notificationService,
91 ContactFactory contactFactory, UserLotCriteria userLotCriteria, UserLotRepository userLotRepo) {
92 this.strataRepo = strataRepo;
93 this.buildingRepo = buildingRepo;
94 this.buildingDao = buildingDao;
95 this.buildingFactory = buildingFactory;
96 this.committeeMemberRepo = committeeMemberRepo;
97 this.committeeMemberFactory = committeeMemberFactory;
98 this.committeeMemberDao = committeeMemberDao;
99 this.committeeMemberCriteria = committeeMemberCriteria;
100 this.lotCriteria = lotCriteria;
101 this.awsCognitoUtil = awsCognitoUtil;
102 this.userRepo = userRepo;
103 this.roleRepo = roleRepo;
104 this.notificationService = notificationService;
105 this.contactFactory = contactFactory;
106 this.userLotCriteria = userLotCriteria;
107 this.userLotRepo = userLotRepo;
108 }
109
110 @Override
111 @Transactional
112 public CommitteeMembersDTO findAllCommitteeMembersByBuildingIdAndStrataId(long strataId, long buildingId,
113 boolean fetch, Integer page, Integer limit) throws ParseException, java.text.ParseException {
114
115 // get strata from db
116 Strata strata = strataRepo.findById(strataId).orElseThrow(() -> new StrataNotFoundServiceException());
117
118 Pagination pagination = ValidationUtil.validatePagination(page, limit);
119 Pageable pageable = PageRequest.of(Long.valueOf(pagination.getPage()).intValue(), pagination.getLimit());
120
121 // get building from db
122 Optional<Building> buildingFromDb = Optional
123 .ofNullable(buildingRepo.findByStrataIdAndExternalId(strataId, buildingId))
124 .orElseThrow(() -> new BuildingNotFoundServiceException(ErrorCodes.BUILDING_NOT_FOUND_ON_DB_CODE));
125
126 if (fetch) {
127
128 if (!buildingFromDb.isPresent()) { // populate buildings
129 // get building from piq, if building doesn't exists in piq then throw an
130 // exception
131
132 Building buildingAfterSave = populateBuilding(buildingId, strata);
133
134 // Get committee member from PIQ
135 CommitteeMembersDTO committeeMembersFromPIQDTO = committeeMemberDao
136 .findAllCommitteeMembersByStrataIdAndBuildingId(strataId, buildingId);
137
138 if (committeeMembersFromPIQDTO.getCommitteeMembers().size() == 0) {
139 return committeeMembersFromPIQDTO;
140 }
141
142 // Add or Update
143 addNewOrUpdateCommitteeMembers(strata, buildingAfterSave, committeeMembersFromPIQDTO);
144
145 } else {
146
147 // Get committee member from PIQ
148 CommitteeMembersDTO committeeMembersFromPIQDTO = committeeMemberDao
149 .findAllCommitteeMembersByStrataIdAndBuildingId(strataId, buildingId);
150
151 if (committeeMembersFromPIQDTO.getCommitteeMembers().size() == 0) {
152 return committeeMembersFromPIQDTO;
153 }
154
155 // Add or Update
156 addNewOrUpdateCommitteeMembers(strata, buildingFromDb.get(), committeeMembersFromPIQDTO);
157
158 // populateCommmitteeMembers(buildingId, strata, buildingFromDb.get(),
159 // committeeMembersFromPIQDTO);
160 }
161
162 }
163
164 return getCommitteeMembersFromDB(strataId, buildingId, pageable);
165
166 }
167
168 private Building populateBuilding(long buildingId, Strata strata) throws ParseException, java.text.ParseException {
169
170 BuildingDTO buildingFromPiq = Optional.ofNullable(buildingDao.findBuildingById(strata.getId(), buildingId))
171 .orElseThrow(() -> new BuildingNotFoundServiceException(ErrorCodes.BUILDING_NOT_FOUND_ON_PIQ_CODE));
172
173 // save building to DB
174 Building buildingToSave = buildingFactory.dtoToEntity(buildingFromPiq, strata);
175 Building buildingAfterSave = buildingRepo.save(buildingToSave);
176
177 return buildingAfterSave;
178 }
179
180 private void addNewOrUpdateCommitteeMembers(Strata strata, Building building,
181 CommitteeMembersDTO committeeMembersFromPIQDTO) {
182
183 String committeeMemberHash = HashUtil.md5Hash(committeeMembersFromPIQDTO);
184
185 committeeMembersFromPIQDTO.getCommitteeMembers().forEach(currentComMember -> {
186
187 boolean isComMemberActive = Optional.ofNullable(currentComMember.getStatus()).orElse("")
188 .equalsIgnoreCase("active");
189
190 boolean isComMemberResigned = Optional.ofNullable(currentComMember.getStatus()).orElse("")
191 .equalsIgnoreCase("resigned");
192
193 boolean isIntegratedWithPortalV2 = Optional.ofNullable(currentComMember.getIsIntegratedWithPortalV2())
194 .orElse(false);
195
196 String emailFromPiq = Optional.ofNullable(currentComMember.getContact().getEmail()).orElse("");
197
198 Optional<CommitteeMember> comMemFromDb = committeeMemberCriteria.findOne(strata.getId(),
199 building.getExternalId(), currentComMember.getId());
200
201 if (comMemFromDb.isPresent()) {
202
203 updateComMem(strata, building, committeeMemberHash, currentComMember, isComMemberActive,
204 isComMemberResigned, isIntegratedWithPortalV2, emailFromPiq, comMemFromDb);
205
206 } else {
207
208 addComMem(strata, building, committeeMemberHash, currentComMember, isComMemberActive,
209 isComMemberResigned, isIntegratedWithPortalV2, emailFromPiq);
210 }
211
212 });
213
214 }
215
216 private void addComMem(Strata strata, Building building, String committeeMemberHash,
217 CommitteeMemberDTO currentComMember, boolean isComMemberActive, boolean isComMemberResigned,
218 boolean isIntegratedWithPortalV2, String emailFromPiq) {
219 // add -> create user
220
221 // convert committeeMember dto to entity for saving
222 Long lotId = Optional.ofNullable(currentComMember.getLot()).isPresent() ? currentComMember.getLot().getId()
223 : 0L;
224
225 Optional<Lot> lotEntity = lotCriteria.findOne(strata.getId(), building.getExternalId(), lotId);
226 CommitteeMember comMemToSave = null;
227 if (lotEntity.isPresent()) {
228 comMemToSave = committeeMemberFactory.dtoToEntity(currentComMember, building, strata, lotEntity.get());
229
230 comMemToSave.setLot(lotEntity.get());
231 } else {
232 comMemToSave = committeeMemberFactory.dtoToEntity(currentComMember, building, strata, null);
233 }
234
235 // Save committee member details
236 comMemToSave.setHash(committeeMemberHash);
237 comMemToSave.setDeactivated(isComMemberActive ? false : true);
238 comMemToSave = committeeMemberRepo.save(comMemToSave);
239
240 // Optional<User> user = userRepo.findByEmail(emailFromPiq);
241
242 authorizedCommitteeMemberAsUser(isComMemberActive, isComMemberResigned, isIntegratedWithPortalV2, comMemToSave,
243 currentComMember, StringUtils.EMPTY, StringUtils.EMPTY);
244 }
245
246 private void updateComMem(Strata strata, Building building, String committeeMemberHash,
247 CommitteeMemberDTO currentComMember, boolean isComMemberActive, boolean isComMemberResigned,
248 boolean isIntegratedWithPortalV2, String emailFromPiq, Optional<CommitteeMember> comMemFromDb) {
249
250 String oldEmail = comMemFromDb.get().getCommitteeMemberContact().getEmail();
251
252 CommitteeMember comMemToUpdate = null;
253 Long lotId = Optional.ofNullable(currentComMember.getLot()).isPresent() ? currentComMember.getLot().getId()
254 : 0L;
255 Optional<Lot> lotFromDb = lotCriteria.findOne(strata.getId(), building.getExternalId(), lotId);
256 // Optional<User> user =
257 // userRepo.findByEmail(comMemFromDb.get().getUser().getEmail());
258
259 comMemToUpdate = committeeMemberFactory.entityToEntity(currentComMember, comMemFromDb.get(), strata, building,
260 lotFromDb.isPresent() ? lotFromDb.get() : null);
261 comMemToUpdate.setDeactivated(isComMemberActive ? false : true);
262 comMemToUpdate.setHash(committeeMemberHash);
263 CommitteeMember comMemberEntity = committeeMemberRepo.save(comMemToUpdate);
264
265 authorizedCommitteeMemberAsUser(isComMemberActive, isComMemberResigned, isIntegratedWithPortalV2,
266 comMemberEntity, currentComMember, oldEmail, emailFromPiq);
267
268 }
269
270 @Description("handles registration, deregistration, changeDefault email of committee member as User")
271 private void authorizedCommitteeMemberAsUser(boolean isComMemberActive, boolean isComMemberResigned,
272 boolean isIntegratedWithPortalV2, CommitteeMember comMember, CommitteeMemberDTO currentComMember,
273 String oldEmail, String newEmailFromPiq) {
274
275 // comMemFromDb.get().getUser()
276
277 if (comMember != null) {
278 if (comMember.getUser() != null) {
279
280 Optional<User> user = userRepo.findByEmail(comMember.getUser().getEmail());
281
282 if (isComMemberActive && isIntegratedWithPortalV2 == true) {
283
284 reactivateUserAsCommitteeMember(comMember, user);
285
286 changeComMemEmail(comMember, user, oldEmail, newEmailFromPiq);
287
288 } else if (isComMemberResigned || isIntegratedWithPortalV2 == false) {
289 // No notification email for deregistering committee member
290 deregisterResignedCommitteeMember(comMember, user);
291 }
292 } else {
293 registerUserAsCommitteeMember(isComMemberActive, isIntegratedWithPortalV2, comMember);
294 }
295 } else {
296 registerUserAsCommitteeMember(isComMemberActive, isIntegratedWithPortalV2, comMember);
297 }
298
299 }
300
301 private void changeComMemEmail(CommitteeMember comMember, Optional<User> user, String oldEmail,
302 String newEmailFromPiq) {
303
304 boolean isComMemEmailChanged = !oldEmail.equals(newEmailFromPiq);
305
306 if (isComMemEmailChanged) {
307
308 boolean isComMemLinkedToUser = Optional.ofNullable(comMember.getUser()).isPresent();
309
310 if (isComMemLinkedToUser) {
311
312 List<UserLot> userLotList = userLotCriteria.findAll(comMember.getStrata().getId(),
313 comMember.getUser().getId(), null, null, null);
314 List<UserLot> activeUserLotList = userLotList.stream().filter(x -> x.getDeactivated().equals(false))
315 .collect(Collectors.toList());
316
317 List<CommitteeMember> userComMemberList = committeeMemberCriteria.findAll(comMember.getStrata().getId(),
318 comMember.getBuilding().getId(), comMember.getUser().getId());
319 List<CommitteeMember> activeComMemList = userComMemberList.stream()
320 .filter(x -> x.getDeactivated().equals(false)).collect(Collectors.toList());
321
322 boolean isUserEmailSameOnAllLots = activeUserLotList.stream()
323 .allMatch(x -> x.getEmail().equals(newEmailFromPiq));
324
325 boolean isUserEmailSameOnComMemAcc = activeComMemList.stream()
326 .allMatch(x -> x.getCommitteeMemberContact().getEmail().equals(newEmailFromPiq));
327
328 boolean isUserComMemOnly = userLotList.isEmpty() && activeComMemList.size() == 1;
329 boolean isUserComMemAndLotOwner = isUserEmailSameOnAllLots && isUserEmailSameOnComMemAcc;
330 boolean isUserRegisteredOnAwsCognito = !awsCognitoUtil.getUserInCognito(newEmailFromPiq).isEmpty();
331
332 if (isUserComMemOnly) {
333 if (!isUserRegisteredOnAwsCognito) {
334 /*
335 * the email your trying to update isn't being used by cognito so we just update
336 * the email on cognito and all details of that user
337 */
338 awsCognitoUtil.updateUserEmail(oldEmail, newEmailFromPiq);
339 user.get().setEmail(newEmailFromPiq);
340 // user.get().setContact(contactFactory.entityToEntity(currentComMember.getContact(),
341 // user.get().getContact()));
342 userRepo.save(user.get());
343
344 // send email here
345
346 sendCommitteeMemberEmailTemplate(changeDefaultEmailProp(comMember, oldEmail, newEmailFromPiq),
347 EmailTemplateType.EMAIL_UPDATED);
348
349 } else {
350 /*
351 * the email your trying to update is being used by another cognito account so
352 * we transfer all the lots & building from old user to the new user then we
353 * deactivate the old user on cognito and on db
354 */
355
356 // this should always have value, this should not throw no value present
357 // exception
358 User newUserToLink = userRepo.findByEmail(newEmailFromPiq).get();
359
360 // deactivate user on cognito
361 awsCognitoUtil.deactivateUser(comMember.getUser().getId());
362
363 // deactivate/update user on db
364 user.get().setStatus(UserStatuses.DLT);
365 userRepo.save(user.get());
366
367 comMember.setUser(newUserToLink);
368 committeeMemberRepo.save(comMember);
369
370 // send email here
371 sendCommitteeMemberEmailTemplate(changeDefaultEmailProp(comMember, oldEmail, newEmailFromPiq),
372 EmailTemplateType.EMAIL_UPDATED);
373
374 }
375
376 // update email on user table
377 } else if (isUserComMemAndLotOwner) {
378 // send email
379 // update email on user table
380
381 if (!isUserRegisteredOnAwsCognito) {
382 /*
383 * the email your trying to update isn't being used by cognito so we just update
384 * the email on cognito and all details of that user
385 */
386 awsCognitoUtil.updateUserEmail(oldEmail, newEmailFromPiq);
387 user.get().setEmail(newEmailFromPiq);
388 // user.get().setContact(contactFactory.entityToEntity(currentComMember.getContact(),
389 // user.get().getContact()));
390 userRepo.save(user.get());
391
392 // send email here
393 sendCommitteeMemberEmailTemplate(changeDefaultEmailProp(comMember, oldEmail, newEmailFromPiq),
394 EmailTemplateType.EMAIL_UPDATED);
395 } else {
396 /*
397 * the email your trying to update is being used by another cognito account so
398 * we transfer all the lots & building from old user to the new user then we
399 * deactivate the old user on cognito and on db
400 */
401
402 // this should always have value, this should not throw no value present
403 // exception
404 User newUserToLink = userRepo.findByEmail(newEmailFromPiq).get();
405
406 // deactivate user on cognito
407 awsCognitoUtil.deactivateUser(comMember.getUser().getId());
408
409 // deactivate/update user on db
410 user.get().setStatus(UserStatuses.DLT);
411 userRepo.save(user.get());
412
413 comMember.setUser(newUserToLink);
414 committeeMemberRepo.save(comMember);
415
416 // update the userLot
417 activeUserLotList.forEach(currentUserLot -> {
418 currentUserLot.setUser(newUserToLink);
419 userLotRepo.save(currentUserLot);
420 });
421
422 // update the committee member
423 activeComMemList.forEach(currentComMem -> {
424 currentComMem.setUser(newUserToLink);
425 committeeMemberRepo.save(currentComMem);
426 });
427
428 // send email here
429 sendCommitteeMemberEmailTemplate(changeDefaultEmailProp(comMember, oldEmail, newEmailFromPiq),
430 EmailTemplateType.EMAIL_UPDATED);
431
432 }
433
434 }
435
436 } // end of islinkedtouser
437
438 }
439 }
440
441 private HashMap<String, String> changeDefaultEmailProp(CommitteeMember comMember, String oldEmail,
442 String newEmailFromPiq) {
443 HashMap<String, String> changeDefaultEmailProp = new HashMap<>();
444 changeDefaultEmailProp.put("strataName", comMember.getStrata().getName());
445 changeDefaultEmailProp.put("strataId", comMember.getStrata().getId().toString());
446 changeDefaultEmailProp.put("emailAddress", oldEmail);
447 changeDefaultEmailProp.put("displayEmail", newEmailFromPiq);
448 changeDefaultEmailProp.put("portalLink", portalLink);
449 return changeDefaultEmailProp;
450 }
451
452 @Description("reactivates user as committee member")
453 private User reactivateUserAsCommitteeMember(CommitteeMember comMember, Optional<User> user) {
454
455 User newUserData = null;
456 boolean isUserDeleted = user.get().getStatus().equals(UserStatuses.DLT);
457
458 if (isUserDeleted) {
459 user.get().setStatus(UserStatuses.ACT);
460 }
461
462 boolean hasCommitteeMemRole = user.get().getUserRoleList().stream()
463 .filter(x -> x.getRole().getId().equals(Roles.COMMITTEE_MEMBER.getId())).findFirst().isPresent();
464
465 boolean isUserRegisteredToAwsCognito = !awsCognitoUtil
466 .getUserInCognito(comMember.getCommitteeMemberContact().getEmail()).isEmpty();
467
468 if (isUserRegisteredToAwsCognito && hasCommitteeMemRole) {
469 boolean isReactivationSuccess = awsCognitoUtil.reActivateUser(user.get().getId());
470
471 if (isReactivationSuccess == false) {
472 throw new NullPointerException("reactivation failed!!!!");
473 }
474
475 // not yet cater scenario wherein change use
476 // user.get().setStatus(UserStatuses.ACT);
477
478 user.get().getUserRoleList().forEach(currentUserRole -> {
479 boolean isCommitteeMemberRoleExistInUser = currentUserRole.getRole().getId()
480 .equals(Roles.COMMITTEE_MEMBER.getId());
481 if (isCommitteeMemberRoleExistInUser) {
482 // update user role status
483 // currentUserRole.setStatus(UserStatuses.ACT);
484 comMember.setUser(user.get());
485 comMember.setStatus(CommitteeMemberStatus.ACTIVE);
486 comMember.setDeactivated(false);
487 committeeMemberRepo.save(comMember);
488 }
489 });
490 newUserData = userRepo.save(user.get());
491
492 HashMap<String, String> portalAccessEmailProp = new HashMap<>();
493 portalAccessEmailProp.put("strataName", comMember.getStrata().getName());
494 portalAccessEmailProp.put("strataId", comMember.getStrata().getId().toString());
495 portalAccessEmailProp.put("emailAddress", comMember.getCommitteeMemberContact().getEmail());
496 portalAccessEmailProp.put("displayEmail", comMember.getCommitteeMemberContact().getEmail());
497 portalAccessEmailProp.put("strataName", comMember.getStrata().getName());
498 portalAccessEmailProp.put("portalLink", portalLink);
499
500 sendCommitteeMemberEmailTemplate(portalAccessEmailProp, EmailTemplateType.COMMITTEE_ACCESS);
501
502 } else {
503
504 // add role to user role as committee member
505 UserRole userRole = new UserRole();
506
507 // this should never throw no value present exception because the value must be
508 // on database
509 userRole.setRole(roleRepo.findById(Roles.COMMITTEE_MEMBER.getId()).get());
510 userRole.setUser(user.get());
511 user.get().getUserRoleList().add(userRole);
512
513 newUserData = userRepo.save(user.get());
514
515 // update committee member
516 comMember.setUser(user.get());
517 comMember.setStatus(CommitteeMemberStatus.ACTIVE);
518 comMember.setDeactivated(false);
519 committeeMemberRepo.save(comMember);
520
521 HashMap<String, String> portalAccessEmailProp = new HashMap<>();
522 portalAccessEmailProp.put("strataName", comMember.getStrata().getName());
523 portalAccessEmailProp.put("strataId", comMember.getStrata().getId().toString());
524 portalAccessEmailProp.put("emailAddress", comMember.getCommitteeMemberContact().getEmail());
525 portalAccessEmailProp.put("displayEmail", comMember.getCommitteeMemberContact().getEmail());
526 portalAccessEmailProp.put("strataName", comMember.getStrata().getName());
527 portalAccessEmailProp.put("portalLink", portalLink);
528
529 sendCommitteeMemberEmailTemplate(portalAccessEmailProp, EmailTemplateType.COMMITTEE_ACCESS);
530
531 }
532 return newUserData;
533
534 }
535
536 @Description("deactivate committee member as User")
537 private void deregisterResignedCommitteeMember(CommitteeMember comMember, Optional<User> user) {
538
539 /*
540 * added addtional checking if the user is registered on our db but has no
541 * record on aws cognito
542 */
543
544 boolean hasCommitteeMemRole = user.get().getUserRoleList().stream()
545 .filter(x -> x.getRole().getId().equals(Roles.COMMITTEE_MEMBER.getId())).findFirst().isPresent();
546
547 boolean isUserRegisteredToAwsCognito = !awsCognitoUtil
548 .getUserInCognito(comMember.getCommitteeMemberContact().getEmail()).isEmpty();
549
550 if (isUserRegisteredToAwsCognito && hasCommitteeMemRole) {
551
552 // additional checking when diregistering user.status
553 List<UserLot> userLotList = userLotCriteria.findAll(comMember.getStrata().getId(), user.get().getId(), null,
554 null, null);
555 List<CommitteeMember> userComMemberList = committeeMemberCriteria.findAll(comMember.getStrata().getId(),
556 comMember.getBuilding().getId(), user.get().getId());
557 List<CommitteeMember> activeComMemberList = userComMemberList.stream()
558 .filter(x -> x.getDeactivated().equals(false) && !x.getId().equals(comMember.getId()))
559 .collect(Collectors.toList());
560
561 boolean isUserDeactivatedAllLots = userLotList.stream().allMatch(x -> x.getDeactivated().equals(true));
562 boolean isUserDeactivatedAllComMember = userComMemberList.stream()
563 .allMatch(x -> x.getDeactivated().equals(true));
564
565 boolean isUserComMemOnly = userLotList.isEmpty() && activeComMemberList.isEmpty();
566 boolean isUserComMemAndLotOwner = isUserDeactivatedAllLots && isUserDeactivatedAllComMember;
567
568 if (isUserComMemAndLotOwner) {
569 user.get().setStatus(UserStatuses.DLT);
570 // deactivate user
571 boolean isDeactivationSuccess = awsCognitoUtil.deactivateUser(user.get().getId());
572 if (isDeactivationSuccess == false) {
573 throw new NullPointerException("deactivation failed!!!!");
574 }
575
576 user.get().getUserRoleList().forEach(currentUserRole -> {
577 boolean isCommitteeMemberRoleExistInUser = currentUserRole.getRole().getId()
578 .equals(Roles.COMMITTEE_MEMBER.getId());
579 if (isCommitteeMemberRoleExistInUser) {
580 comMember.setUser(user.get());
581 comMember.setDeactivated(true);
582 committeeMemberRepo.save(comMember);
583 }
584 });
585
586 user.get().getUserRoleList().removeIf(x -> x.getRole().getId().equals(Roles.COMMITTEE_MEMBER.getId()));
587 } else if (isUserComMemOnly) {
588
589 user.get().setStatus(UserStatuses.DLT);
590 // deactivate user
591 boolean isDeactivationSuccess = awsCognitoUtil.deactivateUser(user.get().getId());
592 if (isDeactivationSuccess == false) {
593 throw new NullPointerException("deactivation failed!!!!");
594 }
595
596 user.get().getUserRoleList().forEach(currentUserRole -> {
597 boolean isCommitteeMemberRoleExistInUser = currentUserRole.getRole().getId()
598 .equals(Roles.COMMITTEE_MEMBER.getId());
599 if (isCommitteeMemberRoleExistInUser) {
600 comMember.setUser(user.get());
601 comMember.setDeactivated(true);
602 committeeMemberRepo.save(comMember);
603 }
604 });
605 user.get().getUserRoleList().removeIf(x -> x.getRole().getId().equals(Roles.COMMITTEE_MEMBER.getId()));
606 }
607
608 userRepo.save(user.get());
609 }
610
611 }
612
613 @Description("creates a new user data with committee member as its role")
614 private User registerUserAsCommitteeMember(boolean isComMemberActive, boolean isIntegratedWithPortalV2,
615 CommitteeMember comMem) {
616
617 User user = null;
618
619 if (isComMemberActive && isIntegratedWithPortalV2) {
620
621 HashMap<String, String> userAwsCognitoCredentials = awsCognitoUtil
622 .getUserInCognito(comMem.getCommitteeMemberContact().getEmail());
623
624 if (!userAwsCognitoCredentials.isEmpty()) {
625 /*
626 * we should never go to this scenario wherein user is registered in cognito but
627 * not in our db, just to play safe I added this code below, don't send portal
628 * invitation email here !
629 */
630
631 String newUserUUID = userAwsCognitoCredentials.get("cognitoId");
632
633 if (StringUtils.isEmpty(newUserUUID)) {
634 throw new NullPointerException("new user registration on cognito failed!");
635 }
636 User userToSave = buildUserInfoUpdate(comMem, newUserUUID);
637 // save user on db
638 user = userToSave = userRepo.save(userToSave);
639
640 awsCognitoUtil.reActivateUser(userToSave.getId());
641
642 comMem.setUser(user);
643 comMem.setDeactivated(false);
644 committeeMemberRepo.save(comMem);
645
646 } else {
647 UserInitiateRequestDTO userToSaveOnAwsCognito = buildUserInfoToAwsCognito(comMem);
648 // save user on aws cognito
649 HashMap<String, String> newAwsCogUserCredentials = awsCognitoUtil
650 .cognitoAdminSignUpUser(userToSaveOnAwsCognito);
651
652 if (newAwsCogUserCredentials.isEmpty()) {
653 throw new NullPointerException("new user registration on cognito failed!");
654 }
655
656 newAwsCogUserCredentials.put("strataName", comMem.getStrata().getName());
657 newAwsCogUserCredentials.put("strataId", comMem.getStrata().getId().toString());
658 newAwsCogUserCredentials.put("emailAddress", comMem.getCommitteeMemberContact().getEmail());
659 newAwsCogUserCredentials.put("displayEmail", comMem.getCommitteeMemberContact().getEmail());
660 newAwsCogUserCredentials.put("strataName", comMem.getStrata().getName());
661 newAwsCogUserCredentials.put("portalLink", portalLink);
662
663 User userToSave = buildUserInfo(comMem, newAwsCogUserCredentials.get("cognitoId"));
664 // save user on db
665 user = userToSave = userRepo.save(userToSave);
666
667 // update comMember table
668 comMem.setUser(user);
669 comMem.setDeactivated(false);
670 committeeMemberRepo.save(comMem);
671
672 // send email
673 sendCommitteeMemberEmailTemplate(newAwsCogUserCredentials, EmailTemplateType.COMMITTEE_INVITATION);
674
675 }
676
677 }
678
679 return user;
680 }
681
682 @Description("generate user info to save on aws cognito")
683 private UserInitiateRequestDTO buildUserInfoToAwsCognito(CommitteeMember comMemToUpdate) {
684 UserInitiateRequestDTO userInitiateRequestDTO = new UserInitiateRequestDTO();
685 userInitiateRequestDTO.setEmail(comMemToUpdate.getCommitteeMemberContact().getEmail());
686 userInitiateRequestDTO.setFirstname(comMemToUpdate.getCommitteeMemberContact().getFirstName());
687 userInitiateRequestDTO.setMiddlename(comMemToUpdate.getCommitteeMemberContact().getMiddleName());
688 userInitiateRequestDTO.setLastname(comMemToUpdate.getCommitteeMemberContact().getLastName());
689 return userInitiateRequestDTO;
690 }
691
692 @Description("generate user info to save on db")
693 private User buildUserInfo(CommitteeMember comMem, String UUID) {
694 User userToSave = new User();
695 UserRole userRole = new UserRole();
696
697 userToSave.setId(UUID);
698 userToSave.setEmail(comMem.getCommitteeMemberContact().getEmail());
699 userToSave.setContact(comMem.getCommitteeMemberContact());
700 userToSave.setStatus(UserStatuses.ACT);
701 userToSave = userRepo.save(userToSave);
702
703 // add committee member role
704 userRole.setRole(roleRepo.findById(Roles.COMMITTEE_MEMBER.getId()).get());
705 userRole.setUser(userToSave);
706 userToSave.getUserRoleList().add(userRole);
707
708 return userToSave;
709 }
710
711 private User buildUserInfoUpdate(CommitteeMember comMem, String UUID) {
712
713 Optional<User> userToSave = userRepo.findById(UUID);
714
715 // UserRole userRole = new UserRole();
716
717 userToSave.get().setId(UUID);
718 userToSave.get().setEmail(comMem.getCommitteeMemberContact().getEmail());
719 userToSave.get().setContact(comMem.getCommitteeMemberContact());
720 userToSave.get().setStatus(UserStatuses.ACT);
721 userRepo.save(userToSave.get());
722
723 // // add committee member role
724 // userRole.setRole(roleRepo.findById(Roles.COMMITTEE_MEMBER.getId()).get());
725 // userRole.setUser(userToSave.get());
726 // userToSave.get().getUserRoleList().add(userRole);
727
728 return userToSave.get();
729 }
730
731 private void sendCommitteeMemberEmailTemplate(HashMap<String, String> userCredentials,
732 EmailTemplateType emailTemplate) {
733
734 // set portal invitation email message properties
735 JSONObject msgProperties = new JSONObject();
736 msgProperties.put("strataName", userCredentials.get("strataName"));
737 msgProperties.put("emailAddress", userCredentials.get("displayEmail"));
738 msgProperties.put("tempPassword", userCredentials.get("tempPassword"));
739 msgProperties.put("portalLink", userCredentials.get("portalLink"));
740
741 notificationService.sendSQSMessage(Long.valueOf(userCredentials.get("strataId")), msgProperties,
742 userCredentials.get("emailAddress"),
743 userCredentials.get("strataName") + " - " + emailTemplate.getSubject(),
744 emailTemplate.getTemplateType());
745
746 }
747
748 @Description("get data from db")
749 private CommitteeMembersDTO getCommitteeMembersFromDB(long strataId, long buildingId, Pageable pageable) {
750
751 CommitteeMembersDTO committeeMembersDTO = new CommitteeMembersDTO();
752
753 Page<CommitteeMember> paginatedComMem = committeeMemberCriteria.findAll(strataId, buildingId, pageable);
754
755 List<CommitteeMemberDTO> committeeMemberDtoList = new ArrayList<>();
756
757 paginatedComMem.getContent().forEach(x -> {
758 committeeMemberDtoList.add(committeeMemberFactory.entityToDTO(x));
759 });
760
761 Pagination pagination = new Pagination();
762 pagination.setTotalCount(paginatedComMem.getTotalElements());
763 pagination.setLimit(pageable.getPageSize());
764 pagination.setPage(pageable.getPageNumber());
765
766 committeeMembersDTO.setCommitteeMembers(committeeMemberDtoList);
767 committeeMembersDTO.setPagination(pagination);
768 committeeMembersDTO
769 .setMessage(ValidationUtil.validateMessage(pagination.getTotalCount(), pagination.getLimit()));
770
771 return committeeMembersDTO;
772
773 }
774
775}