argos/notification-service/notification/src/main/java/gr/cite/notification/service/user/UserServiceImpl.java

202 lines
8.8 KiB
Java

package gr.cite.notification.service.user;
import com.fasterxml.jackson.core.JsonProcessingException;
import gr.cite.commons.web.authz.service.AuthorizationService;
import gr.cite.notification.authorization.AuthorizationFlags;
import gr.cite.notification.authorization.OwnedResource;
import gr.cite.notification.authorization.Permission;
import gr.cite.notification.common.JsonHandlingService;
import gr.cite.notification.common.enums.IsActive;
import gr.cite.notification.convention.ConventionService;
import gr.cite.notification.data.UserContactInfoEntity;
import gr.cite.notification.data.UserCredentialEntity;
import gr.cite.notification.data.UserEntity;
import gr.cite.notification.integrationevent.inbox.usertouched.UserTouchedIntegrationEvent;
import gr.cite.notification.model.User;
import gr.cite.notification.model.builder.UserBuilder;
import gr.cite.notification.model.deleter.UserDeleter;
import gr.cite.notification.query.UserContactInfoQuery;
import gr.cite.tools.data.builder.BuilderFactory;
import gr.cite.tools.data.deleter.DeleterFactory;
import gr.cite.tools.data.query.QueryFactory;
import gr.cite.tools.exception.MyApplicationException;
import gr.cite.tools.exception.MyForbiddenException;
import gr.cite.tools.exception.MyNotFoundException;
import gr.cite.tools.exception.MyValidationException;
import gr.cite.tools.fieldset.BaseFieldSet;
import gr.cite.tools.fieldset.FieldSet;
import gr.cite.tools.logging.LoggerService;
import gr.cite.tools.logging.MapLogEntry;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.management.InvalidApplicationException;
import java.time.Instant;
import java.util.*;
@Service
public class UserServiceImpl implements UserService {
private static final LoggerService logger = new LoggerService(LoggerFactory.getLogger(UserServiceImpl.class));
private final AuthorizationService authorizationService;
private final DeleterFactory deleterFactory;
private final ConventionService conventionService;
private final EntityManager entityManager;
private final BuilderFactory builderFactory;
private final QueryFactory queryFactory;
private final JsonHandlingService jsonHandlingService;
public UserServiceImpl(AuthorizationService authorizationService,
DeleterFactory deleterFactory,
ConventionService conventionService,
EntityManager entityManager,
BuilderFactory builderFactory,
QueryFactory queryFactory,
JsonHandlingService jsonHandlingService) {
this.authorizationService = authorizationService;
this.deleterFactory = deleterFactory;
this.conventionService = conventionService;
this.entityManager = entityManager;
this.builderFactory = builderFactory;
this.queryFactory = queryFactory;
this.jsonHandlingService = jsonHandlingService;
}
@Override
@Transactional
public User persist(UserTouchedIntegrationEvent model, FieldSet fields) throws MyForbiddenException, MyValidationException, MyApplicationException, MyNotFoundException, InvalidApplicationException, JsonProcessingException {
logger.debug(new MapLogEntry("persisting user").And("model", model).And("fields", fields));
// this.authorizationService.authorizeAtLeastOneForce(model.getId() != null ? List.of(new OwnedResource(model.getId())) : null, Permission.EditUser);
Boolean isValid = this.conventionService.isValidGuid(model.getId());
UserEntity data;
if (isValid) {
data = this.entityManager.find(UserEntity.class, model.getId());
if (data == null) {
data = new UserEntity();
data.setId(model.getId());
data.setName(model.getName());
data.setAdditionalInfo(this.jsonHandlingService.toJson(model.getProfile()));
data.setCreatedAt(Instant.now());
data.setUpdatedAt(Instant.now());
data.setIsActive(IsActive.Active);
this.entityManager.persist(data);
for (UserTouchedIntegrationEvent.UserContactInfo eventC : model.getUserContactInfo()) {
this.entityManager.persist(this.buildContactInfoEntityFromEventData(eventC, model.getId()));
}
this.entityManager.persist(this.buildUserCredentialEntityFromEventData(model));
} else {
data.setName(model.getName());
data.setAdditionalInfo(this.jsonHandlingService.toJson(model.getProfile()));
data.setUpdatedAt(Instant.now());
data.setIsActive(IsActive.Active);
this.entityManager.merge(data);
List<UserContactInfoEntity> contactInfoList = this.queryFactory.query(UserContactInfoQuery.class).userIds(model.getId()).collect();
List<UserContactInfoEntity> updatedContacts = new ArrayList<>();
for (UserContactInfoEntity c : contactInfoList) {
boolean updated = false;
//Contact found on the existing, update it
for (UserTouchedIntegrationEvent.UserContactInfo eventC : model.getUserContactInfo()) {
if (c.getType() == eventC.getType() && Objects.equals(c.getValue(), eventC.getValue())) {
c.setUserId(model.getId());
c.setType(c.getType());
c.setValue(c.getValue());
c.setOrdinal(c.getOrdinal());
c.setUpdatedAt(Instant.now());
c.setIsActive(IsActive.Active);
this.entityManager.merge(c);
updatedContacts.add(c);
updated = true;
break;
}
}
//Contact was not found on the event data, remove it
if (!updated) {
c.setIsActive(IsActive.Inactive);
this.entityManager.merge(c);
}
}
for (UserTouchedIntegrationEvent.UserContactInfo eventC : model.getUserContactInfo()) {
boolean updated = false;
for (UserContactInfoEntity c : updatedContacts) {
if (c.getType() == eventC.getType() && Objects.equals(c.getValue(), eventC.getValue())) {
updated = true;
break;
}
}
//New contact detected since it came with the event data and was not existing in the database, add it
if (!updated) {
this.entityManager.persist(this.buildContactInfoEntityFromEventData(eventC, model.getId()));
}
}
}
} else {
throw new MyApplicationException("Not valid user id");
}
this.entityManager.flush();
return this.builderFactory.builder(UserBuilder.class).authorize(EnumSet.of(AuthorizationFlags.None)).build(BaseFieldSet.build(fields, User._id), data);
}
@Override
public void deleteAndSave(UUID id) throws MyForbiddenException, InvalidApplicationException {
logger.debug("deleting User: {}", id);
this.authorizationService.authorizeForce(Permission.DeleteUser);
this.deleterFactory.deleter(UserDeleter.class).deleteAndSaveByIds(List.of(id));
}
private UserContactInfoEntity buildContactInfoEntityFromEventData(UserTouchedIntegrationEvent.UserContactInfo eventC, UUID userId) {
UserContactInfoEntity contactInfo = new UserContactInfoEntity();
contactInfo.setId(UUID.randomUUID());
contactInfo.setUserId(userId);
contactInfo.setType(eventC.getType());
contactInfo.setValue(eventC.getValue());
contactInfo.setOrdinal(eventC.getOrdinal());
contactInfo.setCreatedAt(Instant.now());
contactInfo.setUpdatedAt(Instant.now());
contactInfo.setIsActive(IsActive.Active);
return contactInfo;
}
private UserCredentialEntity buildUserCredentialEntityFromEventData(UserTouchedIntegrationEvent event) {
UserCredentialEntity credentialEntity = new UserCredentialEntity();
credentialEntity.setId(UUID.randomUUID());
credentialEntity.setUserId(event.getId());
credentialEntity.setExternalId(event.getSubjectId());
credentialEntity.setCreatedAt(Instant.now());
credentialEntity.setUpdatedAt(Instant.now());
credentialEntity.setIsActive(IsActive.Active);
return credentialEntity;
}
}