diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/OnboardingFunctions.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/OnboardingFunctions.java index 6135d5fe4..aabe12af4 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/OnboardingFunctions.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/OnboardingFunctions.java @@ -36,11 +36,18 @@ public class OnboardingFunctions { public static final String BUILD_CONTRACT_ACTIVITY_NAME = "BuildContract"; public static final String FORMAT_LOGGER_ONBOARDING_STRING = "%s: %s"; public static final String SEND_MAIL_REGISTRATION_WITH_CONTRACT_ACTIVITY_NAME = "SendMailRegistrationWithContract"; - @Inject - OnboardingService service; + public static final String SEND_MAIL_REGISTRATION_REQUEST_ACTIVITY_NAME = "SendMailRegistrationRequest"; + public static final String SEND_MAIL_REGISTRATION_APPROVE_ACTIVITY_NAME = "SendMailRegistrationApprove"; + public static final String SEND_MAIL_ONBOARDING_APPROVE_ACTIVITY_NAME = "SendMailOnboardingApprove"; - @Inject - ObjectMapper objectMapper; + private final OnboardingService service; + + private final ObjectMapper objectMapper; + + public OnboardingFunctions(OnboardingService service, ObjectMapper objectMapper) { + this.service = service; + this.objectMapper = objectMapper; + } private static final TaskOptions optionsRetry; @@ -81,7 +88,7 @@ public String onboardingsOrchestrator( String onboardingId = ctx.getInput(String.class); String onboardingString = getOnboardingString(onboardingId); - return onboardingsOrchestratorPAorSAorGSPIPA(ctx, onboardingString); + return onboardingsOrchestratorDefault(ctx, onboardingString); } private String getOnboardingString(String onboardingId) { @@ -101,7 +108,8 @@ private String onboardingsOrchestratorDefault(TaskOrchestrationContext ctx, Stri String result = ""; result += ctx.callActivity(BUILD_CONTRACT_ACTIVITY_NAME, onboardingString, optionsRetry, String.class).await() + ", "; result += ctx.callActivity(SAVE_TOKEN_WITH_CONTRACT_ACTIVITY_NAME, onboardingString, optionsRetry, String.class).await() + ", "; - result += ctx.callActivity("SendMailRegistration", onboardingString, optionsRetry, String.class).await() + ", "; + result += ctx.callActivity(SEND_MAIL_REGISTRATION_APPROVE_ACTIVITY_NAME, onboardingString, optionsRetry, String.class).await() + ", "; + result += ctx.callActivity(SEND_MAIL_ONBOARDING_APPROVE_ACTIVITY_NAME, onboardingString, optionsRetry, String.class).await() + ", "; return result; } @@ -126,11 +134,7 @@ private String onboardingsOrchestratorPG(TaskOrchestrationContext ctx, String on @FunctionName(BUILD_CONTRACT_ACTIVITY_NAME) public String buildContract(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, BUILD_CONTRACT_ACTIVITY_NAME, onboardingString)); - try { - service.createContract(objectMapper.readValue(onboardingString, Onboarding.class)); - } catch (JsonProcessingException e) { - throw new FunctionOrchestratedException(e); - } + service.createContract(readOnboardingValue(onboardingString)); return onboardingString; } @@ -140,11 +144,7 @@ public String buildContract(@DurableActivityTrigger(name = "onboardingString") S @FunctionName(SAVE_TOKEN_WITH_CONTRACT_ACTIVITY_NAME) public String saveToken(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, SAVE_TOKEN_WITH_CONTRACT_ACTIVITY_NAME, onboardingString)); - try { - service.saveTokenWithContract(objectMapper.readValue(onboardingString, Onboarding.class)); - } catch (JsonProcessingException e) { - throw new FunctionOrchestratedException(e); - } + service.saveTokenWithContract(readOnboardingValue(onboardingString)); return onboardingString; } @@ -154,20 +154,28 @@ public String saveToken(@DurableActivityTrigger(name = "onboardingString") Strin @FunctionName(SEND_MAIL_REGISTRATION_WITH_CONTRACT_ACTIVITY_NAME) public String sendMailRegistrationWithContract(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, SEND_MAIL_REGISTRATION_WITH_CONTRACT_ACTIVITY_NAME, onboardingString)); - try { - service.sendMailRegistrationWithContract(objectMapper.readValue(onboardingString, Onboarding.class)); - } catch (JsonProcessingException e) { - throw new FunctionOrchestratedException(e); - } + service.sendMailRegistrationWithContract(readOnboardingValue(onboardingString)); return onboardingString; } - /** - * This is the activity function that gets invoked by the orchestrator function. - */ - @FunctionName("SendMailRegistration") + @FunctionName(SEND_MAIL_REGISTRATION_REQUEST_ACTIVITY_NAME) public String sendMailRegistration(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { - context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, "SendMailRegistration", onboardingString)); + context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, SEND_MAIL_REGISTRATION_REQUEST_ACTIVITY_NAME, onboardingString)); + service.sendMailRegistration(readOnboardingValue(onboardingString)); + return onboardingString; + } + + @FunctionName(SEND_MAIL_REGISTRATION_APPROVE_ACTIVITY_NAME) + public String sendMailRegistrationApprove(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { + context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, SEND_MAIL_REGISTRATION_APPROVE_ACTIVITY_NAME, onboardingString)); + service.sendMailRegistrationApprove(readOnboardingValue(onboardingString)); + return onboardingString; + } + + @FunctionName(SEND_MAIL_ONBOARDING_APPROVE_ACTIVITY_NAME) + public String sendMailOnboardingApprove(@DurableActivityTrigger(name = "onboardingString") String onboardingString, final ExecutionContext context) { + context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING, SEND_MAIL_ONBOARDING_APPROVE_ACTIVITY_NAME, onboardingString)); + service.sendMailOnboardingApprove(readOnboardingValue(onboardingString)); return onboardingString; } @@ -179,4 +187,12 @@ public String sendMailConfirmation(@DurableActivityTrigger(name = "onboardingStr context.getLogger().info(String.format(FORMAT_LOGGER_ONBOARDING_STRING,"SendMailConfirmation", onboardingString)); return onboardingString; } + + private Onboarding readOnboardingValue(String onboardingString) { + try { + return objectMapper.readValue(onboardingString, Onboarding.class); + } catch (JsonProcessingException e) { + throw new FunctionOrchestratedException(e); + } + } } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePathConfig.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePathConfig.java index 4cb884123..de71c16db 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePathConfig.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePathConfig.java @@ -14,9 +14,9 @@ public interface MailTemplatePathConfig { String registrationPath(); - String notificationPath(); + String onboardingApprovePath(); String rejectPath(); String registrationRequestPath(); - String registrationNotificationAdminPath(); + String registrationApprovePath(); } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePlaceholdersConfig.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePlaceholdersConfig.java index 396d0f8e9..cc8aace79 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePlaceholdersConfig.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/config/MailTemplatePlaceholdersConfig.java @@ -27,7 +27,5 @@ public interface MailTemplatePlaceholdersConfig { String rejectOnboardingUrlValue(); String rejectProductName(); - String notificationAdminEmail(); - } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefault.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefault.java index 172628fe0..682b4e391 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefault.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefault.java @@ -42,11 +42,14 @@ public class ContractServiceDefault implements ContractService { private static final Logger log = LoggerFactory.getLogger(ContractServiceDefault.class); public static final String PDF_FORMAT_FILENAME = "%s.pdf"; - @Inject - AzureStorageConfig azureStorageConfig; + private final AzureStorageConfig azureStorageConfig; - @Inject - AzureBlobClient azureBlobClient; + private final AzureBlobClient azureBlobClient; + + public ContractServiceDefault(AzureStorageConfig azureStorageConfig, AzureBlobClient azureBlobClient) { + this.azureStorageConfig = azureStorageConfig; + this.azureBlobClient = azureBlobClient; + } /** * Creates a PDF contract document from a given contract template file and institution data. diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationService.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationService.java index 3d5d994b2..9fb9be0f3 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationService.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationService.java @@ -3,5 +3,11 @@ public interface NotificationService { + void sendMailRegistration(String institutionName, String destination, String name, String username, String productName); + + void sendMailRegistrationApprove(String institutionName, String name, String username, String productName, String token); + + void sendMailOnboardingApprove(String institutionName, String name, String username, String productName, String token); + void sendMailRegistrationWithContract(String onboardingId, String destination, String name, String username, String productName, String token); } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefault.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefault.java index 181809e65..8f493eacb 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefault.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefault.java @@ -9,7 +9,6 @@ import it.pagopa.selfcare.onboarding.entity.MailTemplate; import it.pagopa.selfcare.onboarding.exception.GenericOnboardingException; import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; import org.apache.commons.text.StringSubstitutor; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.slf4j.Logger; @@ -19,10 +18,7 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -35,18 +31,21 @@ public class NotificationServiceDefault implements NotificationService { private static final Logger log = LoggerFactory.getLogger(NotificationServiceDefault.class); - final private MailTemplatePlaceholdersConfig templatePlaceholdersConfig; - final private MailTemplatePathConfig templatePathConfig; - final private AzureBlobClient azureBlobClient; - final private ObjectMapper objectMapper; - final private ContractService contractService; - final private String senderMail; - final private Boolean destinationMailTest; - final private String destinationMailTestAddress; - final private Mailer mailer; + private final MailTemplatePlaceholdersConfig templatePlaceholdersConfig; + private final MailTemplatePathConfig templatePathConfig; + private final AzureBlobClient azureBlobClient; + private final ObjectMapper objectMapper; + private final ContractService contractService; + private final String senderMail; + private final Boolean destinationMailTest; + private final String destinationMailTestAddress; + + private final String notificationAdminMail; + private final Mailer mailer; public NotificationServiceDefault(MailTemplatePlaceholdersConfig templatePlaceholdersConfig, MailTemplatePathConfig templatePathConfig, AzureBlobClient azureBlobClient, ObjectMapper objectMapper, Mailer mailer, ContractService contractService, + @ConfigProperty(name = "onboarding-functions.notification-admin-email") String notificationAdminMail, @ConfigProperty(name = "onboarding-functions.sender-mail") String senderMail, @ConfigProperty(name = "onboarding-functions.destination-mail-test") Boolean destinationMailTest, @ConfigProperty(name = "onboarding-functions.destination-mail-test-address") String destinationMailTestAddress) { @@ -58,9 +57,47 @@ public NotificationServiceDefault(MailTemplatePlaceholdersConfig templatePlaceho this.senderMail = senderMail; this.destinationMailTest = destinationMailTest; this.destinationMailTestAddress = destinationMailTestAddress; + this.notificationAdminMail = notificationAdminMail; this.mailer = mailer; } + @Override + public void sendMailRegistration(String institutionName, String destination, String name, String username, String productName) { + + // Prepare data for email + Map mailParameters = new HashMap<>(); + mailParameters.put(templatePlaceholdersConfig.productName(), productName); + Optional.ofNullable(name).ifPresent(value -> mailParameters.put(templatePlaceholdersConfig.notificationRequesterName(), value)); + Optional.ofNullable(username).ifPresent(value -> mailParameters.put(templatePlaceholdersConfig.notificationRequesterSurname(), value)); + mailParameters.put(templatePlaceholdersConfig.institutionDescription(), institutionName); + + sendMailWithFile(List.of(destination), templatePathConfig.registrationRequestPath(), mailParameters, productName, null); + } + + @Override + public void sendMailRegistrationApprove(String institutionName, String name, String username, String productName, String token) { + sendMailOnboardingOrRegistrationApprove(institutionName, name, username, productName, token, templatePathConfig.registrationApprovePath()); + } + + @Override + public void sendMailOnboardingApprove(String institutionName, String name, String username, String productName, String token) { + sendMailOnboardingOrRegistrationApprove(institutionName, name, username, productName, token, templatePathConfig.onboardingApprovePath()); + } + + + private void sendMailOnboardingOrRegistrationApprove(String institutionName, String name, String username, String productName, String token, String templatePath) { + // Prepare data for email + Map mailParameters = new HashMap<>(); + mailParameters.put(templatePlaceholdersConfig.productName(), productName); + Optional.ofNullable(name).ifPresent(value -> mailParameters.put(templatePlaceholdersConfig.notificationRequesterName(), value)); + Optional.ofNullable(username).ifPresent(value -> mailParameters.put(templatePlaceholdersConfig.notificationRequesterSurname(), value)); + mailParameters.put(templatePlaceholdersConfig.institutionDescription(), institutionName); + StringBuilder adminApproveLink = new StringBuilder(templatePlaceholdersConfig.adminLink()); + mailParameters.put(templatePlaceholdersConfig.confirmTokenName(), adminApproveLink.append(token).toString()); + + sendMailWithFile(List.of(notificationAdminMail), templatePath, mailParameters, productName, null); + } + @Override public void sendMailRegistrationWithContract(String onboardingId, String destination, String name, String username, String productName, String token) { @@ -78,11 +115,6 @@ public void sendMailRegistrationWithContract(String onboardingId, String destina throw new RuntimeException(e); } - // Dev mode send mail to test digital address - List destinationMail = destinationMailTest ? - List.of(destinationMailTestAddress): - List.of(destination); - // Prepare data for email Map mailParameters = new HashMap<>(); mailParameters.put(templatePlaceholdersConfig.productName(), productName); @@ -91,33 +123,44 @@ public void sendMailRegistrationWithContract(String onboardingId, String destina mailParameters.put(templatePlaceholdersConfig.rejectTokenName(), templatePlaceholdersConfig.rejectTokenPlaceholder() + token); mailParameters.put(templatePlaceholdersConfig.confirmTokenName(), templatePlaceholdersConfig.confirmTokenPlaceholder() + token); - sendMailWithFile(destinationMail, templatePathConfig.registrationPath(), mailParameters, contractZipData, fileNameZip, productName); - log.debug("Mail registration with contract successful sent !!"); + FileMailData fileMailData = new FileMailData(); + fileMailData.contentType = "application/zip"; + fileMailData.data = contractZipData; + fileMailData.name = fileNameZip; + + sendMailWithFile(List.of(destination), templatePathConfig.registrationPath(), mailParameters, productName, fileMailData); } - public void sendMailWithFile(List destinationMail, String templateName, Map mailParameters, byte[] fileData, String fileName, String prefixSubject) { + private void sendMailWithFile(List destinationMail, String templateName, Map mailParameters, String prefixSubject, FileMailData fileMailData) { try { - log.info("START - sendMailWithFile to {}, with prefixSubject {}", destinationMail, prefixSubject); + + // Dev mode send mail to test digital address + List destinations = destinationMailTest ? + List.of(destinationMailTestAddress): + destinationMail; + + log.info("Sending mail to {}, with prefixSubject {}", destinationMail, prefixSubject); String template = azureBlobClient.getFileAsText(templateName); MailTemplate mailTemplate = objectMapper.readValue(template, MailTemplate.class); String html = StringSubstitutor.replace(mailTemplate.getBody(), mailParameters); - log.trace("sendMessage start"); final String subject = String.format("%s: %s", prefixSubject, mailTemplate.getSubject()); Mail mail = Mail - .withHtml(destinationMail.get(0), subject, html) - .addAttachment(fileName, fileData, "application/zip") + .withHtml(destinations.get(0), subject, html) .setFrom(senderMail); + if(Objects.nonNull(fileMailData)) { + mail.addAttachment(fileMailData.name, fileMailData.data, fileMailData.contentType); + } + mailer.send(mail); - log.info("END - sendMail to {}, with subject {}", destinationMail, subject); + log.info("End of sending mail to {}, with subject {}", destinationMail, subject); } catch (Exception e) { - log.error(ERROR_DURING_SEND_MAIL + ":" + e.getMessage()); + log.error(String.format("%s: %s", ERROR_DURING_SEND_MAIL, e.getMessage())); throw new GenericOnboardingException(ERROR_DURING_SEND_MAIL.getMessage()); } - log.trace("sendMessage end"); } public byte[] zipBytes(String filename, byte[] data) { @@ -136,4 +179,10 @@ public byte[] zipBytes(String filename, byte[] data) { } } + static class FileMailData { + byte[] data; + String name; + String contentType; + } + } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/OnboardingService.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/OnboardingService.java index 4d585992b..ecdc8f93b 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/OnboardingService.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/service/OnboardingService.java @@ -35,6 +35,9 @@ public class OnboardingService { private static final Logger log = LoggerFactory.getLogger(OnboardingService.class); public static final String USERS_FIELD_LIST = "fiscalCode,familyName,name"; + public static final String TOKEN_DOES_NOT_EXISTS_FOR_ONBOARDING_S = "Token does not exists for onboarding %s"; + public static final String loggedUserName = "example"; + public static final String loggedUserSurname = "example"; @RestClient @Inject @@ -79,6 +82,13 @@ public void loadContract(Onboarding onboarding) { } public void saveTokenWithContract(Onboarding onboarding) { + // Skip if token already exists + Optional optToken = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()); + if(optToken.isPresent()) { + log.debug("Token has already exists for onboarding {}", onboarding.getId()); + return; + } + // Load PDF contract and create digest File contract = contractService.retrieveContractNotSigned(onboarding.getOnboardingId()); DSSDocument document = new FileDocument(contract); @@ -88,12 +98,6 @@ public void saveTokenWithContract(Onboarding onboarding) { } private void saveToken(Onboarding onboarding, String digest) { - // Skip if token already exists - Optional optToken = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()); - if(optToken.isPresent()) { - log.debug("Token has already exists for onboarding {}", onboarding.getId()); - return; - } log.debug("creating Token for onboarding {} ...", onboarding.getId()); @@ -112,18 +116,25 @@ private void saveToken(Onboarding onboarding, String digest) { tokenRepository.persist(token); } - public void sendMailRegistrationWithContract(Onboarding onboarding) { + public void sendMailRegistration(Onboarding onboarding) { - Optional optToken = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()); - if(optToken.isEmpty()) { - throw new GenericOnboardingException(String.format("Token has already exists for onboarding %s", onboarding.getId())); - } + Product product = productService.getProduct(onboarding.getProductId()); + + notificationService.sendMailRegistration(onboarding.getInstitution().getDescription(), + onboarding.getInstitution().getDigitalAddress(), loggedUserName, loggedUserSurname, + product.getTitle()); + } + + public void sendMailRegistrationWithContract(Onboarding onboarding) { + + Token token = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()) + .orElseThrow(() -> new GenericOnboardingException(String.format(TOKEN_DOES_NOT_EXISTS_FOR_ONBOARDING_S, onboarding.getId()))); Product product = productService.getProduct(onboarding.getProductId()); notificationService.sendMailRegistrationWithContract(onboarding.getOnboardingId(), - onboarding.getInstitution().getDigitalAddress(), "example", "example", - product.getTitle(), optToken.get().getId().toHexString()); + onboarding.getInstitution().getDigitalAddress(), loggedUserName, loggedUserSurname, + product.getTitle(), token.getId().toHexString()); } @@ -137,4 +148,27 @@ public String getValidManagerId(List users) { .orElseThrow(() -> new GenericOnboardingException(GenericError.MANAGER_NOT_FOUND_GENERIC_ERROR.getMessage(), GenericError.MANAGER_NOT_FOUND_GENERIC_ERROR.getCode())); } + + public void sendMailRegistrationApprove(Onboarding onboarding) { + + + Token token = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()) + .orElseThrow(() -> new GenericOnboardingException(String.format(TOKEN_DOES_NOT_EXISTS_FOR_ONBOARDING_S, onboarding.getId()))); + Product product = productService.getProduct(onboarding.getProductId()); + + notificationService.sendMailRegistrationApprove(onboarding.getInstitution().getDescription(), + loggedUserName, loggedUserSurname, product.getTitle(), token.getId().toHexString()); + + } + + public void sendMailOnboardingApprove(Onboarding onboarding) { + + Token token = tokenRepository.findByOnboardingId(onboarding.getOnboardingId()) + .orElseThrow(() -> new GenericOnboardingException(String.format(TOKEN_DOES_NOT_EXISTS_FOR_ONBOARDING_S, onboarding.getId()))); + Product product = productService.getProduct(onboarding.getProductId()); + + notificationService.sendMailOnboardingApprove(onboarding.getInstitution().getDescription(), + loggedUserName, loggedUserSurname, product.getTitle(), token.getId().toHexString()); + + } } diff --git a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/utils/PdfMapper.java b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/utils/PdfMapper.java index c79b5be7b..d76566d58 100644 --- a/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/utils/PdfMapper.java +++ b/apps/onboarding-functions/src/main/java/it/pagopa/selfcare/onboarding/utils/PdfMapper.java @@ -16,6 +16,16 @@ public class PdfMapper { private static final String[] PLAN_LIST = {"C1", "C2", "C3", "C4", "C5", "C6", "C7"}; + public static final String INSTITUTION_REA = "institutionREA"; + public static final String INSTITUTION_NAME = "institutionName"; + public static final String INSTITUTION_SHARE_CAPITAL = "institutionShareCapital"; + public static final String INSTITUTION_BUSINESS_REGISTER_PLACE = "institutionBusinessRegisterPlace"; + public static final String PRICING_PLAN_PREMIUM = "pricingPlanPremium"; + public static final String PRICING_PLAN_PREMIUM_CHECKBOX = "pricingPlanPremiumCheckbox"; + public static final String PRICING_PLAN_FAST_CHECKBOX = "pricingPlanFastCheckbox"; + public static final String PRICING_PLAN_BASE_CHECKBOX = "pricingPlanBaseCheckbox"; + public static final String PRICING_PLAN = "pricingPlan"; + public static final String INSTITUTION_REGISTER_LABEL_VALUE = "institutionRegisterLabelValue"; public static Map setUpCommonData(UserResource validManager, List users, Institution institution, Billing billing, List geographicTaxonomies) { @@ -24,7 +34,7 @@ public static Map setUpCommonData(UserResource validManager, Lis //} Map map = new HashMap<>(); - map.put("institutionName", institution.getDescription()); + map.put(INSTITUTION_NAME, institution.getDescription()); map.put("address", institution.getAddress()); map.put("institutionTaxCode", institution.getTaxCode()); map.put("zipCode", institution.getZipCode()); @@ -90,9 +100,9 @@ public static void setupProdIOData(Onboarding onboarding, Map ma map.put("GPSmanagerSurname", InstitutionType.GSP == institutionType ? validManager.getFamilyName() : underscore); map.put("GPSmanagerTaxCode", InstitutionType.GSP == institutionType ? validManager.getFiscalCode() : underscore); - map.put("institutionREA", Optional.ofNullable(institution.getRea()).orElse(underscore)); - map.put("institutionShareCapital", Optional.ofNullable(institution.getShareCapital()).orElse(underscore)); - map.put("institutionBusinessRegisterPlace", Optional.ofNullable(institution.getBusinessRegisterPlace()).orElse(underscore)); + map.put(INSTITUTION_REA, Optional.ofNullable(institution.getRea()).orElse(underscore)); + map.put(INSTITUTION_SHARE_CAPITAL, Optional.ofNullable(institution.getShareCapital()).orElse(underscore)); + map.put(INSTITUTION_BUSINESS_REGISTER_PLACE, Optional.ofNullable(institution.getBusinessRegisterPlace()).orElse(underscore)); addPricingPlan(onboarding.getPricingPlan(), map); } @@ -100,9 +110,9 @@ public static void setupProdIOData(Onboarding onboarding, Map ma public static void setupSAProdInteropData(Map map, Institution institution) { String underscore = "_______________"; - map.put("institutionREA", Optional.ofNullable(institution.getRea()).orElse(underscore)); - map.put("institutionShareCapital", Optional.ofNullable(institution.getShareCapital()).orElse(underscore)); - map.put("institutionBusinessRegisterPlace", Optional.ofNullable(institution.getBusinessRegisterPlace()).orElse(underscore)); + map.put(INSTITUTION_REA, Optional.ofNullable(institution.getRea()).orElse(underscore)); + map.put(INSTITUTION_SHARE_CAPITAL, Optional.ofNullable(institution.getShareCapital()).orElse(underscore)); + map.put(INSTITUTION_BUSINESS_REGISTER_PLACE, Optional.ofNullable(institution.getBusinessRegisterPlace()).orElse(underscore)); //override originId to not fill ipa code in case of SA if(InstitutionType.SA.equals(institution.getInstitutionType())) map.put("originId", underscore); @@ -119,19 +129,19 @@ public static void setupProdPNData(Map map, Institution institut private static void addPricingPlan(String pricingPlan, Map map) { if (Objects.nonNull(pricingPlan) && Arrays.stream(PLAN_LIST).anyMatch(s -> s.equalsIgnoreCase(pricingPlan))) { - map.put("pricingPlanPremium", pricingPlan.replace("C", "")); - map.put("pricingPlanPremiumCheckbox", "X"); + map.put(PRICING_PLAN_PREMIUM, pricingPlan.replace("C", "")); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, "X"); } else { - map.put("pricingPlanPremium", ""); - map.put("pricingPlanPremiumCheckbox", ""); + map.put(PRICING_PLAN_PREMIUM, ""); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, ""); } map.put("pricingPlanPremiumBase", Optional.ofNullable(pricingPlan).orElse("")); if (Objects.nonNull(pricingPlan) && "C0".equalsIgnoreCase(pricingPlan)) { - map.put("pricingPlanPremiumBaseCheckbox", "X"); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, "X"); } else { - map.put("pricingPlanPremiumBaseCheckbox", ""); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, ""); } } @@ -139,30 +149,30 @@ private static void addInstitutionRegisterLabelValue(Institution institution, Ma if (institution.getPaymentServiceProvider() != null && Objects.nonNull(institution.getPaymentServiceProvider().getBusinessRegisterNumber())) { map.put("number", institution.getPaymentServiceProvider().getBusinessRegisterNumber()); - map.put("institutionRegisterLabelValue", "
  • codice di iscrizione all’Indice delle Pubbliche Amministrazioni e dei gestori di pubblici servizi (I.P.A.) ${number}
  • \n"); + map.put(INSTITUTION_REGISTER_LABEL_VALUE, "
  • codice di iscrizione all’Indice delle Pubbliche Amministrazioni e dei gestori di pubblici servizi (I.P.A.) ${number}
  • \n"); } else { - map.put("institutionRegisterLabelValue", ""); + map.put(INSTITUTION_REGISTER_LABEL_VALUE, ""); } } private static void decodePricingPlan(String pricingPlan, String productId, Map map) { if (PricingPlan.FA.name().equals(pricingPlan)) { - map.put("pricingPlanFastCheckbox", "X"); - map.put("pricingPlanBaseCheckbox", ""); - map.put("pricingPlanPremiumCheckbox", ""); - map.put("pricingPlan", PricingPlan.FA.getValue()); + map.put(PRICING_PLAN_FAST_CHECKBOX, "X"); + map.put(PRICING_PLAN_BASE_CHECKBOX, ""); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, ""); + map.put(PRICING_PLAN, PricingPlan.FA.getValue()); return; } if (PROD_IO.getValue().equalsIgnoreCase(productId)) { - map.put("pricingPlanFastCheckbox", ""); - map.put("pricingPlanBaseCheckbox", "X"); - map.put("pricingPlanPremiumCheckbox", ""); - map.put("pricingPlan", PricingPlan.BASE.getValue()); + map.put(PRICING_PLAN_FAST_CHECKBOX, ""); + map.put(PRICING_PLAN_BASE_CHECKBOX, "X"); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, ""); + map.put(PRICING_PLAN, PricingPlan.BASE.getValue()); } else { - map.put("pricingPlanFastCheckbox", ""); - map.put("pricingPlanBaseCheckbox", ""); - map.put("pricingPlanPremiumCheckbox", "X"); - map.put("pricingPlan", PricingPlan.PREMIUM.getValue()); + map.put(PRICING_PLAN_FAST_CHECKBOX, ""); + map.put(PRICING_PLAN_BASE_CHECKBOX, ""); + map.put(PRICING_PLAN_PREMIUM_CHECKBOX, "X"); + map.put(PRICING_PLAN, PricingPlan.PREMIUM.getValue()); } } diff --git a/apps/onboarding-functions/src/main/resources/application.properties b/apps/onboarding-functions/src/main/resources/application.properties index e9632492c..4528fa3ae 100644 --- a/apps/onboarding-functions/src/main/resources/application.properties +++ b/apps/onboarding-functions/src/main/resources/application.properties @@ -40,7 +40,7 @@ onboarding-functions.blob-storage.connection-string-product = ${BLOB_STORAGE_CON onboarding-functions.sender-mail = ${MAIL_SENDER_ADDRESS:test@test.it} onboarding-functions.destination-mail-test = ${MAIL_DESTINATION_TEST:true} onboarding-functions.destination-mail-test-address = ${MAIL_DESTINATION_TEST_ADDRESS:test@test.it} -onboarding-functions.mail-template.placeholders.onboarding.notification-admin-email = ${ADDRESS_EMAIL_NOTIFICATION_ADMIN:default} +onboarding-functions.notification-admin-email = ${ADDRESS_EMAIL_NOTIFICATION_ADMIN:default} ## MAIL TEMPLATE onboarding-functions.mail-template.path.onboarding.complete-path = ${MAIL_TEMPLATE_COMPLETE_PATH:default} @@ -50,9 +50,9 @@ onboarding-functions.mail-template.path.onboarding.autocomplete-path = ${MAIL_TE onboarding-functions.mail-template.path.onboarding.delegation-notification-path = ${MAIL_TEMPLATE_DELEGATION_NOTIFICATION_PATH:default} onboarding-functions.mail-template.path.onboarding.registration-path = ${MAIL_TEMPLATE_REGISTRATION_PATH:default} -onboarding-functions.mail-template.path.onboarding.notification-path = ${MAIL_TEMPLATE_NOTIFICATION_PATH:default} +onboarding-functions.mail-template.path.onboarding.onboarding-approve-path = ${MAIL_TEMPLATE_NOTIFICATION_PATH:default} onboarding-functions.mail-template.path.onboarding.registration-request-path = ${MAIL_TEMPLATE_REGISTRATION_REQUEST_PT_PATH:default} -onboarding-functions.mail-template.path.onboarding.registration-notification-admin-path = ${MAIL_TEMPLATE_REGISTRATION_NOTIFICATION_ADMIN_PATH:default} +onboarding-functions.mail-template.path.onboarding.registration-approve-path = ${MAIL_TEMPLATE_REGISTRATION_NOTIFICATION_ADMIN_PATH:default} onboarding-functions.mail-template.path.onboarding.reject-path = ${MAIL_TEMPLATE_REJECT_PATH:default} @@ -95,4 +95,4 @@ quarkus.mailer.start-tls=${MAIL_SERVER_SMTP_TLS_ENABLE:REQUIRED} ## Jacoco -quarkus.jacoco.includes=it/pagopa/selfcare/onboarding/controller/*,it/pagopa/selfcare/onboarding/service/**,it/pagopa/selfcare/onboarding/repository/** +quarkus.jacoco.includes=it/pagopa/selfcare/onboarding/*,it/pagopa/selfcare/onboarding/service/**,it/pagopa/selfcare/onboarding/repository/** diff --git a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/OnboardingFunctionsTest.java b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/OnboardingFunctionsTest.java index 37145dfe6..dd44a496b 100644 --- a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/OnboardingFunctionsTest.java +++ b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/OnboardingFunctionsTest.java @@ -5,9 +5,19 @@ import com.microsoft.azure.functions.HttpResponseMessage; import com.microsoft.azure.functions.HttpStatus; import com.microsoft.durabletask.DurableTaskClient; +import com.microsoft.durabletask.Task; +import com.microsoft.durabletask.TaskOrchestrationContext; import com.microsoft.durabletask.azurefunctions.DurableClientContext; +import io.quarkus.test.InjectMock; +import io.quarkus.test.Mock; import io.quarkus.test.junit.QuarkusTest; import it.pagopa.selfcare.onboarding.OnboardingFunctions; +import it.pagopa.selfcare.onboarding.entity.Onboarding; +import it.pagopa.selfcare.onboarding.exception.ResourceNotFoundException; +import it.pagopa.selfcare.onboarding.service.OnboardingService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -18,11 +28,9 @@ import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - +import static org.mockito.Mockito.*; /** @@ -34,10 +42,15 @@ public class OnboardingFunctionsTest { @Inject OnboardingFunctions function; + @InjectMock + OnboardingService service; + + final String onboardinString = "{\"onboardingId\":\"onboardingId\"}"; + /** * Unit test for HttpTriggerJava method. */ - //@Test + @Test public void testHttpTriggerJava() throws Exception { // Setup @SuppressWarnings("unchecked") @@ -45,7 +58,8 @@ public void testHttpTriggerJava() throws Exception { final HttpResponseMessage res = mock(HttpResponseMessage.class); final Map queryParams = new HashMap<>(); - queryParams.put("onboardingId", "Azure"); + final String onboardingId = "onboardingId"; + queryParams.put("onboardingId", onboardingId); doReturn(queryParams).when(req).getQueryParameters(); final Optional queryBody = Optional.empty(); @@ -65,14 +79,106 @@ public HttpResponseMessage.Builder answer(InvocationOnMock invocation) { final DurableClientContext durableContext = mock(DurableClientContext.class); final DurableTaskClient client = mock(DurableTaskClient.class); final String scheduleNewOrchestrationInstance = "scheduleNewOrchestrationInstance"; - doReturn(scheduleNewOrchestrationInstance).when(client).scheduleNewOrchestrationInstance(any()); doReturn(client).when(durableContext).getClient(); - doReturn(res).when(durableContext).createCheckStatusResponse(req, scheduleNewOrchestrationInstance); + doReturn(scheduleNewOrchestrationInstance).when(client).scheduleNewOrchestrationInstance("Onboardings",onboardingId); + doReturn(res).when(durableContext).createCheckStatusResponse(any(), any()); // Invoke - final HttpResponseMessage ret = function.startOrchestration(req, durableContext, context); + function.startOrchestration(req, durableContext, context); // Verify - assertEquals(ret.getStatus(), ret.getStatus()); + ArgumentCaptor captorInstanceId = ArgumentCaptor.forClass(String.class); + Mockito.verify(durableContext, times(1)) + .createCheckStatusResponse(any(), captorInstanceId.capture()); + assertEquals(scheduleNewOrchestrationInstance, captorInstanceId.getValue()); + } + + @Test + void onboardingsOrchestrator_thorwExceptionIfOnboardingNotPresent() { + final String onboardingId = "onboardingId"; + TaskOrchestrationContext orchestrationContext = mock(TaskOrchestrationContext.class); + when(orchestrationContext.getInput(String.class)).thenReturn(onboardingId); + when(service.getOnboarding(onboardingId)).thenReturn(Optional.empty()); + assertThrows(ResourceNotFoundException.class, () -> function.onboardingsOrchestrator(orchestrationContext)); + } + + @Test + void onboardingsOrchestratorDefault() { + Onboarding onboarding = new Onboarding(); + onboarding.setOnboardingId("onboardingId"); + + TaskOrchestrationContext orchestrationContext = mock(TaskOrchestrationContext.class); + when(orchestrationContext.getInput(String.class)).thenReturn(onboarding.getOnboardingId()); + when(service.getOnboarding(onboarding.getOnboardingId())).thenReturn(Optional.of(onboarding)); + + Task task = mock(Task.class); + when(orchestrationContext.callActivity(any(),any(),any(),any())).thenReturn(task); + when(task.await()).thenReturn("example"); + + function.onboardingsOrchestrator(orchestrationContext); + + Mockito.verify(orchestrationContext, times(4)) + .callActivity(any(), any(), any(),any()); + + } + + @Test + void buildContract() { + ExecutionContext executionContext = mock(ExecutionContext.class); + when(executionContext.getLogger()).thenReturn(Logger.getGlobal()); + doNothing().when(service).createContract(any()); + + function.buildContract(onboardinString, executionContext); + + Mockito.verify(service, times(1)) + .createContract(any()); + } + + @Test + void saveToken() { + ExecutionContext executionContext = mock(ExecutionContext.class); + when(executionContext.getLogger()).thenReturn(Logger.getGlobal()); + doNothing().when(service).saveTokenWithContract(any()); + + function.saveToken(onboardinString, executionContext); + + Mockito.verify(service, times(1)) + .saveTokenWithContract(any()); + } + + @Test + void sendMailRegistrationWithContract() { + ExecutionContext executionContext = mock(ExecutionContext.class); + when(executionContext.getLogger()).thenReturn(Logger.getGlobal()); + doNothing().when(service).sendMailRegistrationWithContract(any()); + + function.sendMailRegistrationWithContract(onboardinString, executionContext); + + Mockito.verify(service, times(1)) + .sendMailRegistrationWithContract(any()); + } + + @Test + void sendMailRegistration() { + ExecutionContext executionContext = mock(ExecutionContext.class); + when(executionContext.getLogger()).thenReturn(Logger.getGlobal()); + doNothing().when(service).sendMailRegistration(any()); + + function.sendMailRegistration(onboardinString, executionContext); + + Mockito.verify(service, times(1)) + .sendMailRegistration(any()); + } + + @Test + void sendMailRegistrationApprove() { + ExecutionContext executionContext = mock(ExecutionContext.class); + when(executionContext.getLogger()).thenReturn(Logger.getGlobal()); + doNothing().when(service).sendMailRegistrationApprove(any()); + + function.sendMailRegistrationApprove(onboardinString, executionContext); + + Mockito.verify(service, times(1)) + .sendMailRegistrationApprove(any()); } } diff --git a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefaultTest.java b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefaultTest.java index 25988a8e6..4a3ca0279 100644 --- a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefaultTest.java +++ b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/NotificationServiceDefaultTest.java @@ -11,6 +11,7 @@ import it.pagopa.selfcare.onboarding.config.MailTemplatePathConfig; import it.pagopa.selfcare.onboarding.config.MailTemplatePlaceholdersConfig; import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -44,11 +45,13 @@ class NotificationServiceDefaultTest { Mailer mailer; NotificationServiceDefault notificationService; + final String notificationAdminMail = "adminAddress"; + @BeforeEach void startup() { mailer = mock(Mailer.class); this.notificationService = new NotificationServiceDefault(templatePlaceholdersConfig, templatePathConfig, - azureBlobClient, objectMapper, mailer, contractService, "senderMail", false, "destinationMailTestAddress"); + azureBlobClient, objectMapper, mailer, contractService, notificationAdminMail, "senderMail", false, "destinationMailTestAddress"); } @Test @@ -86,4 +89,51 @@ void sendMailRegistrationWithContract_shouldThrowException() { Mockito.when(contractService.retrieveContractNotSigned(onboardingId)).thenReturn(file); assertThrows(RuntimeException.class, () -> notificationService.sendMailRegistrationWithContract(onboardingId, "example@pagopa.it","mario","rossi","prod-example","token")); } + + @Test + void sendMailRegistration() { + + final String mailTemplate = "{\"subject\":\"example\",\"body\":\"example\"}"; + + final String onboardingId = "onboardingId"; + final String destination = "test@test.it"; + + Mockito.when(azureBlobClient.getFileAsText(templatePathConfig.registrationRequestPath())) + .thenReturn(mailTemplate); + + Mockito.doNothing().when(mailer).send(any()); + + notificationService.sendMailRegistration(onboardingId, destination,"","",""); + + Mockito.verify(azureBlobClient, Mockito.times(1)) + .getFileAsText(any()); + + ArgumentCaptor mailArgumentCaptor = ArgumentCaptor.forClass(Mail.class); + Mockito.verify(mailer, Mockito.times(1)) + .send(mailArgumentCaptor.capture()); + assertEquals(destination, mailArgumentCaptor.getValue().getTo().get(0)); + } + + + @Test + void sendMailRegistrationApprove() { + + final String mailTemplate = "{\"subject\":\"example\",\"body\":\"example\"}"; + final String institutionName = "institutionName"; + + Mockito.when(azureBlobClient.getFileAsText(templatePathConfig.registrationApprovePath())) + .thenReturn(mailTemplate); + Mockito.doNothing().when(mailer).send(any()); + + notificationService.sendMailRegistrationApprove(institutionName, "name","username","product","token"); + + Mockito.verify(azureBlobClient, Mockito.times(1)) + .getFileAsText(any()); + + ArgumentCaptor mailArgumentCaptor = ArgumentCaptor.forClass(Mail.class); + Mockito.verify(mailer, Mockito.times(1)) + .send(mailArgumentCaptor.capture()); + assertEquals(notificationAdminMail, mailArgumentCaptor.getValue().getTo().get(0)); + } + } diff --git a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/OnboardingServiceTest.java b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/OnboardingServiceTest.java index c63856dbc..583867024 100644 --- a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/OnboardingServiceTest.java +++ b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/OnboardingServiceTest.java @@ -55,6 +55,8 @@ class OnboardingServiceTest { @Inject OnboardingService onboardingService; + final Product dummyProduct = new Product(); + private Onboarding createOnboarding() { Onboarding onboarding = new Onboarding(); onboarding.setId(ObjectId.get()); @@ -126,6 +128,21 @@ private Product createDummyProduct() { product.setContractTemplateVersion("version"); return product; } + @Test + void saveToken_shouldSkipIfTokenExists() { + Onboarding onboarding = createOnboarding(); + Token token = new Token(); + token.setId(ObjectId.get()); + + when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) + .thenReturn(Optional.of(token)); + + onboardingService.saveTokenWithContract(onboarding); + + Mockito.verify(tokenRepository, Mockito.times(1)) + .findByOnboardingId(onboarding.getOnboardingId()); + Mockito.verifyNoMoreInteractions(tokenRepository); + } @Test @@ -161,7 +178,7 @@ void loadContract() { Onboarding onboarding = createOnboarding(); when(productService.getProductIsValid(onboarding.getProductId())) - .thenReturn(new Product()); + .thenReturn(dummyProduct); onboardingService.loadContract(onboarding); @@ -171,7 +188,7 @@ void loadContract() { @Test - void sendMailRegistrationWithContract_throwExceptionWhenTokenIsPresent() { + void sendMailRegistrationWithContract() { Onboarding onboarding = createOnboarding(); Token token = new Token(); @@ -180,7 +197,7 @@ void sendMailRegistrationWithContract_throwExceptionWhenTokenIsPresent() { when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) .thenReturn(Optional.of(token)); when(productService.getProduct(onboarding.getProductId())) - .thenReturn(new Product()); + .thenReturn(dummyProduct); doNothing().when(notificationService).sendMailRegistrationWithContract(any(), any(), any(),any(),any(),any()); onboardingService.sendMailRegistrationWithContract(onboarding); @@ -191,13 +208,82 @@ void sendMailRegistrationWithContract_throwExceptionWhenTokenIsPresent() { @Test - void sendMailRegistrationWithContract() { + void sendMailRegistrationWithContract_throwExceptionWhenTokenIsNotPresent() { + Onboarding onboarding = createOnboarding(); + when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) + .thenReturn(Optional.empty()); + assertThrows(GenericOnboardingException.class, () -> onboardingService.sendMailRegistrationWithContract(onboarding)); + } + + + @Test + void sendMailRegistration() { Onboarding onboarding = createOnboarding(); + when(productService.getProduct(onboarding.getProductId())) + .thenReturn(dummyProduct); + doNothing().when(notificationService).sendMailRegistration(any(), any(), any(),any(),any()); + + onboardingService.sendMailRegistration(onboarding); + + Mockito.verify(notificationService, times(1)) + .sendMailRegistration(any(), any(), any(),any(),any()); + } + + @Test + void sendMailRegistrationApprove() { + + Onboarding onboarding = createOnboarding(); + Token token = new Token(); + token.setId(ObjectId.get()); + when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) + .thenReturn(Optional.of(token)); + when(productService.getProduct(onboarding.getProductId())) + .thenReturn(dummyProduct); + doNothing().when(notificationService).sendMailRegistrationApprove(any(), any(), any(),any(),any()); + + onboardingService.sendMailRegistrationApprove(onboarding); + + Mockito.verify(notificationService, times(1)) + .sendMailRegistrationApprove(any(), any(), any(),any(),any()); + } + + + @Test + void sendMailRegistrationApprove_throwExceptionWhenTokenIsNotPresent() { + Onboarding onboarding = createOnboarding(); when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) .thenReturn(Optional.empty()); + assertThrows(GenericOnboardingException.class, () -> onboardingService.sendMailRegistrationApprove(onboarding)); + } - assertThrows(GenericOnboardingException.class, () -> onboardingService.sendMailRegistrationWithContract(onboarding)); + + @Test + void sendMailOnboardingApprove() { + + Onboarding onboarding = createOnboarding(); + Token token = new Token(); + token.setId(ObjectId.get()); + + when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) + .thenReturn(Optional.of(token)); + when(productService.getProduct(onboarding.getProductId())) + .thenReturn(dummyProduct); + doNothing().when(notificationService).sendMailOnboardingApprove(any(), any(), any(),any(),any()); + + onboardingService.sendMailOnboardingApprove(onboarding); + + Mockito.verify(notificationService, times(1)) + .sendMailOnboardingApprove(any(), any(), any(),any(),any()); + } + + + @Test + void sendMailOnboardingApprove_throwExceptionWhenTokenIsNotPresent() { + Onboarding onboarding = createOnboarding(); + when(tokenRepository.findByOnboardingId(onboarding.getOnboardingId())) + .thenReturn(Optional.empty()); + assertThrows(GenericOnboardingException.class, () -> onboardingService.sendMailOnboardingApprove(onboarding)); } } diff --git a/apps/onboarding-functions/src/test/resources/application.properties b/apps/onboarding-functions/src/test/resources/application.properties index 52fc4c963..3d05d6e62 100644 --- a/apps/onboarding-functions/src/test/resources/application.properties +++ b/apps/onboarding-functions/src/test/resources/application.properties @@ -7,7 +7,7 @@ quarkus.azure-functions.app-service-plan-name=example ## MAIL AND MAIL TEMPLATE ## onboarding-functions.sender-mail = ${MAIL_SENDER_ADDRESS:test@test.it} -onboarding-functions.mail-template.placeholders.onboarding.notification-admin-email = default +onboarding-functions.notification-admin-email = default ## MAIL TEMPLATE onboarding-functions.mail-template.path.onboarding.complete-path = default @@ -17,9 +17,9 @@ onboarding-functions.mail-template.path.onboarding.autocomplete-path = default onboarding-functions.mail-template.path.onboarding.delegation-notification-path = default onboarding-functions.mail-template.path.onboarding.registration-path = default -onboarding-functions.mail-template.path.onboarding.notification-path = default +onboarding-functions.mail-template.path.onboarding.onboarding-approve-path = default onboarding-functions.mail-template.path.onboarding.registration-request-path = default -onboarding-functions.mail-template.path.onboarding.registration-notification-admin-path = default +onboarding-functions.mail-template.path.onboarding.registration-approve-path = default onboarding-functions.mail-template.path.onboarding.reject-path = default