Search in sources :

Example 1 with User

use of com.redhat.cloud.notifications.recipients.User in project notifications-backend by RedHatInsights.

the class EmailAggregator method getAggregated.

public Map<User, Map<String, Object>> getAggregated(EmailAggregationKey aggregationKey, EmailSubscriptionType emailSubscriptionType, LocalDateTime start, LocalDateTime end) {
    Map<User, AbstractEmailPayloadAggregator> aggregated = new HashMap<>();
    Set<String> subscribers = getEmailSubscribers(aggregationKey, emailSubscriptionType);
    // First, we retrieve all aggregations that match the given key.
    List<EmailAggregation> aggregations = emailAggregationRepository.getEmailAggregation(aggregationKey, start, end);
    // For each aggregation...
    for (EmailAggregation aggregation : aggregations) {
        // We need its event type to determine the target endpoints.
        String eventType = getEventType(aggregation);
        // Let's retrieve these targets.
        Set<Endpoint> endpoints = Set.copyOf(endpointRepository.getTargetEmailSubscriptionEndpoints(aggregationKey.getAccountId(), aggregationKey.getBundle(), aggregationKey.getApplication(), eventType));
        // Now we want to determine who will actually receive the aggregation email.
        // All users who subscribed to the current application and subscription type combination are recipients candidates.
        /*
             * The actual recipients list may differ from the candidates depending on the endpoint properties and the action settings.
             * The target endpoints properties will determine whether or not each candidate will actually receive an email.
             */
        Set<User> users = recipientResolver.recipientUsers(aggregationKey.getAccountId(), aggregationKey.getOrgId(), Stream.concat(endpoints.stream().map(EndpointRecipientSettings::new), getActionRecipient(aggregation).stream()).collect(Collectors.toSet()), subscribers);
        /*
             * We now have the final recipients list.
             * Let's populate the Map that will be returned by the method.
             */
        users.forEach(user -> {
            // It's aggregation time!
            fillUsers(aggregationKey, user, aggregated, aggregation);
        });
    }
    return aggregated.entrySet().stream().peek(entry -> {
        // TODO These fields could be passed to EmailPayloadAggregatorFactory.by since we know them from the beginning.
        entry.getValue().setStartTime(start);
        entry.getValue().setEndTimeKey(end);
    }).collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getContext()));
}
Also used : AbstractEmailPayloadAggregator(com.redhat.cloud.notifications.processors.email.aggregators.AbstractEmailPayloadAggregator) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailPayloadAggregatorFactory(com.redhat.cloud.notifications.processors.email.aggregators.EmailPayloadAggregatorFactory) LocalDateTime(java.time.LocalDateTime) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) HashMap(java.util.HashMap) Inject(javax.inject.Inject) EmailAggregationRepository(com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) Recipient(com.redhat.cloud.notifications.ingress.Recipient) User(com.redhat.cloud.notifications.recipients.User) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) Set(java.util.Set) EmailAggregationKey(com.redhat.cloud.notifications.models.EmailAggregationKey) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Collectors(java.util.stream.Collectors) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Stream(java.util.stream.Stream) RecipientResolver(com.redhat.cloud.notifications.recipients.RecipientResolver) ApplicationScoped(javax.enterprise.context.ApplicationScoped) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) User(com.redhat.cloud.notifications.recipients.User) AbstractEmailPayloadAggregator(com.redhat.cloud.notifications.processors.email.aggregators.AbstractEmailPayloadAggregator) HashMap(java.util.HashMap) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Endpoint(com.redhat.cloud.notifications.models.Endpoint) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with User

use of com.redhat.cloud.notifications.recipients.User in project notifications-backend by RedHatInsights.

the class EmailSubscriptionTypeProcessor method sendEmail.

private List<NotificationHistory> sendEmail(Event event, Set<Endpoint> endpoints, EmailTemplate emailTemplate) {
    EmailSubscriptionType emailSubscriptionType = EmailSubscriptionType.INSTANT;
    processedEmailCount.increment();
    Action action = event.getAction();
    TemplateInstance subject;
    TemplateInstance body;
    if (useTemplatesFromDb) {
        Optional<InstantEmailTemplate> instantEmailTemplate = templateRepository.findInstantEmailTemplate(event.getEventType().getId());
        if (instantEmailTemplate.isEmpty()) {
            return Collections.emptyList();
        } else {
            String subjectData = instantEmailTemplate.get().getSubjectTemplate().getData();
            subject = templateService.compileTemplate(subjectData, "subject");
            String bodyData = instantEmailTemplate.get().getBodyTemplate().getData();
            body = templateService.compileTemplate(bodyData, "body");
        }
    } else {
        if (!emailTemplate.isSupported(action.getEventType(), emailSubscriptionType)) {
            return Collections.emptyList();
        }
        subject = emailTemplate.getTitle(action.getEventType(), emailSubscriptionType);
        body = emailTemplate.getBody(action.getEventType(), emailSubscriptionType);
    }
    if (subject == null || body == null) {
        return Collections.emptyList();
    }
    Set<RecipientSettings> requests = Stream.concat(endpoints.stream().map(EndpointRecipientSettings::new), ActionRecipientSettings.fromAction(action).stream()).collect(Collectors.toSet());
    Set<String> subscribers = Set.copyOf(emailSubscriptionRepository.getEmailSubscribersUserId(action.getAccountId(), action.getBundle(), action.getApplication(), emailSubscriptionType));
    LOG.info("sending email for event: " + event);
    return recipientResolver.recipientUsers(action.getAccountId(), action.getOrgId(), requests, subscribers).stream().map(user -> emailSender.sendEmail(user, event, subject, body)).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());
}
Also used : Arrays(java.util.Arrays) Endpoint(com.redhat.cloud.notifications.models.Endpoint) BaseTransformer(com.redhat.cloud.notifications.transformers.BaseTransformer) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) EmailTemplateFactory(com.redhat.cloud.notifications.templates.EmailTemplateFactory) EmailTemplate(com.redhat.cloud.notifications.templates.EmailTemplate) Map(java.util.Map) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) User(com.redhat.cloud.notifications.recipients.User) ZoneOffset(java.time.ZoneOffset) Context(com.redhat.cloud.notifications.ingress.Context) Counter(io.micrometer.core.instrument.Counter) TemplateInstance(io.quarkus.qute.TemplateInstance) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) Set(java.util.Set) UUID(java.util.UUID) EmailAggregation(com.redhat.cloud.notifications.models.EmailAggregation) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) AggregationCommand(com.redhat.cloud.notifications.models.AggregationCommand) Incoming(org.eclipse.microprofile.reactive.messaging.Incoming) AggregationEmailTemplate(com.redhat.cloud.notifications.models.AggregationEmailTemplate) Logger(org.jboss.logging.Logger) LocalDateTime(java.time.LocalDateTime) USE_TEMPLATES_FROM_DB_KEY(com.redhat.cloud.notifications.templates.TemplateService.USE_TEMPLATES_FROM_DB_KEY) TemplateService(com.redhat.cloud.notifications.templates.TemplateService) Inject(javax.inject.Inject) EmailAggregationRepository(com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository) EmailSubscriptionRepository(com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Blocking(io.smallrye.reactive.messaging.annotations.Blocking) Acknowledgment(org.eclipse.microprofile.reactive.messaging.Acknowledgment) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) EmailAggregationKey(com.redhat.cloud.notifications.models.EmailAggregationKey) EndpointTypeProcessor(com.redhat.cloud.notifications.processors.EndpointTypeProcessor) MeterRegistry(io.micrometer.core.instrument.MeterRegistry) TemplateRepository(com.redhat.cloud.notifications.db.repositories.TemplateRepository) RecipientResolver(com.redhat.cloud.notifications.recipients.RecipientResolver) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) Action(com.redhat.cloud.notifications.ingress.Action) Collections(java.util.Collections) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) Action(com.redhat.cloud.notifications.ingress.Action) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) RecipientSettings(com.redhat.cloud.notifications.recipients.RecipientSettings) ActionRecipientSettings(com.redhat.cloud.notifications.recipients.request.ActionRecipientSettings) EndpointRecipientSettings(com.redhat.cloud.notifications.recipients.request.EndpointRecipientSettings) EmailSubscriptionType(com.redhat.cloud.notifications.models.EmailSubscriptionType) Optional(java.util.Optional) InstantEmailTemplate(com.redhat.cloud.notifications.models.InstantEmailTemplate) TemplateInstance(io.quarkus.qute.TemplateInstance)

Example 3 with User

use of com.redhat.cloud.notifications.recipients.User in project notifications-backend by RedHatInsights.

the class ITUserServiceTest method shouldPickPrimaryEMailAsUsersEmail.

@Test
void shouldPickPrimaryEMailAsUsersEmail() {
    ITUserResponse itUserResponse = new ITUserResponse();
    final PersonalInformation personalInformation = new PersonalInformation();
    personalInformation.firstName = "myFirstname";
    personalInformation.lastNames = "myLastname";
    itUserResponse.personalInformation = personalInformation;
    Authentication authentication = new Authentication();
    authentication.principal = "myPrincipal";
    authentication.providerName = "myProviderName";
    itUserResponse.authentications = new ArrayList<>();
    itUserResponse.authentications.add(authentication);
    final AccountRelationship accountRelationship = new AccountRelationship();
    Email primaryEmail = new Email();
    primaryEmail.isPrimary = true;
    primaryEmail.address = "first_adress@trashmail.org";
    Email nonPrimaryEmail = new Email();
    nonPrimaryEmail.isPrimary = false;
    nonPrimaryEmail.address = "second_adress@trashmail.org";
    accountRelationship.emails = new ArrayList<>();
    accountRelationship.emails.add(nonPrimaryEmail);
    accountRelationship.emails.add(primaryEmail);
    itUserResponse.accountRelationships = new ArrayList<>();
    itUserResponse.accountRelationships.add(accountRelationship);
    itUserResponse.accountRelationships.get(0).permissions = List.of();
    List<ITUserResponse> itUserResponses = List.of(itUserResponse);
    when(itUserService.getUsers(any(ITUserRequest.class))).thenReturn(itUserResponses);
    final List<User> someAccountId = rbacRecipientUsersProvider.getUsers("someAccountId", "someOrgId", true);
    assertTrue(someAccountId.get(0).isActive());
    assertEquals(someAccountId.get(0).getEmail(), "first_adress@trashmail.org");
}
Also used : PersonalInformation(com.redhat.cloud.notifications.recipients.itservice.pojo.response.PersonalInformation) Email(com.redhat.cloud.notifications.recipients.itservice.pojo.response.Email) User(com.redhat.cloud.notifications.recipients.User) AccountRelationship(com.redhat.cloud.notifications.recipients.itservice.pojo.response.AccountRelationship) Authentication(com.redhat.cloud.notifications.recipients.itservice.pojo.response.Authentication) ITUserRequest(com.redhat.cloud.notifications.recipients.itservice.pojo.request.ITUserRequest) ITUserResponse(com.redhat.cloud.notifications.recipients.itservice.pojo.response.ITUserResponse) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Test(org.junit.jupiter.api.Test)

Example 4 with User

use of com.redhat.cloud.notifications.recipients.User in project notifications-backend by RedHatInsights.

the class ITUserServiceTest method shouldMapUsersCorrectly.

@Test
void shouldMapUsersCorrectly() {
    final RbacRecipientUsersProvider mock = Mockito.mock(RbacRecipientUsersProvider.class);
    User mockedUser = createNonAdminMockedUser();
    List<User> mockedUsers = List.of(mockedUser);
    when(mock.getUsers(anyString(), anyString(), anyBoolean())).thenReturn(mockedUsers);
    final List<User> users = mock.getUsers("someAccountId", "someOrgId", false);
    final User user = users.get(0);
    assertEquals("firstName", user.getFirstName());
    assertEquals("lastName", user.getLastName());
    assertEquals("userName", user.getUsername());
    assertEquals("email@trashmail.xyz", user.getEmail());
    assertTrue(user.isActive());
    assertFalse(user.isAdmin());
}
Also used : RbacRecipientUsersProvider(com.redhat.cloud.notifications.recipients.rbac.RbacRecipientUsersProvider) User(com.redhat.cloud.notifications.recipients.User) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Test(org.junit.jupiter.api.Test)

Example 5 with User

use of com.redhat.cloud.notifications.recipients.User in project notifications-backend by RedHatInsights.

the class ITUserServiceTest method createNonAdminMockedUser.

private User createNonAdminMockedUser() {
    User mockedUser = new User();
    mockedUser.setActive(true);
    mockedUser.setLastName("lastName");
    mockedUser.setFirstName("firstName");
    mockedUser.setUsername("userName");
    mockedUser.setEmail("email@trashmail.xyz");
    mockedUser.setAdmin(false);
    mockedUser.setActive(true);
    return mockedUser;
}
Also used : User(com.redhat.cloud.notifications.recipients.User)

Aggregations

User (com.redhat.cloud.notifications.recipients.User)13 Action (com.redhat.cloud.notifications.ingress.Action)3 ITUserResponse (com.redhat.cloud.notifications.recipients.itservice.pojo.response.ITUserResponse)3 TemplateInstance (io.quarkus.qute.TemplateInstance)3 QuarkusTest (io.quarkus.test.junit.QuarkusTest)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 Test (org.junit.jupiter.api.Test)3 EmailAggregationRepository (com.redhat.cloud.notifications.db.repositories.EmailAggregationRepository)2 EmailSubscriptionRepository (com.redhat.cloud.notifications.db.repositories.EmailSubscriptionRepository)2 Context (com.redhat.cloud.notifications.ingress.Context)2 AggregationEmailTemplate (com.redhat.cloud.notifications.models.AggregationEmailTemplate)2 EmailAggregation (com.redhat.cloud.notifications.models.EmailAggregation)2 EmailAggregationKey (com.redhat.cloud.notifications.models.EmailAggregationKey)2 EmailSubscriptionType (com.redhat.cloud.notifications.models.EmailSubscriptionType)2 Endpoint (com.redhat.cloud.notifications.models.Endpoint)2 Event (com.redhat.cloud.notifications.models.Event)2 InstantEmailTemplate (com.redhat.cloud.notifications.models.InstantEmailTemplate)2 RecipientResolver (com.redhat.cloud.notifications.recipients.RecipientResolver)2 ITUserRequest (com.redhat.cloud.notifications.recipients.itservice.pojo.request.ITUserRequest)2