From e23288f2015e6bfc6276bfbc674c07bc076dad45 Mon Sep 17 00:00:00 2001 From: Giulia Tremolada <124147597+giulia-tremolada@users.noreply.github.com> Date: Thu, 9 Jan 2025 09:55:03 +0100 Subject: [PATCH] [SELC-6140] feat: manage aggregates csv for SEND (#662) --- .../service/ContractServiceDefault.java | 987 ++++++++-------- .../service/ContractServiceDefaultTest.java | 1019 +++++++++-------- 2 files changed, 1045 insertions(+), 961 deletions(-) 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 8043fe75d..94affe6d2 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 @@ -1,26 +1,5 @@ package it.pagopa.selfcare.onboarding.service; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_INTEROP; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_IO; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_IO_PREMIUM; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_IO_SIGN; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_PAGOPA; -import static it.pagopa.selfcare.onboarding.common.ProductId.PROD_PN; -import static it.pagopa.selfcare.onboarding.utils.GenericError.CREATE_AGGREGATES_CSV_ERROR; -import static it.pagopa.selfcare.onboarding.utils.GenericError.GENERIC_ERROR; -import static it.pagopa.selfcare.onboarding.utils.GenericError.LOAD_AGGREGATES_CSV_ERROR; -import static it.pagopa.selfcare.onboarding.utils.GenericError.UNABLE_TO_DOWNLOAD_FILE; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setECData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setUpAttachmentData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setUpCommonData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupPRVData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupPSPData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupProdIOData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupProdIODataAggregates; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupProdPNData; -import static it.pagopa.selfcare.onboarding.utils.PdfMapper.setupSAProdInteropData; -import static it.pagopa.selfcare.onboarding.utils.Utils.CONTRACT_FILENAME_FUNC; - import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; import com.openhtmltopdf.svgsupport.BatikSVGDrawer; import it.pagopa.selfcare.azurestorage.AzureBlobClient; @@ -30,14 +9,23 @@ import it.pagopa.selfcare.onboarding.config.PagoPaSignatureConfig; import it.pagopa.selfcare.onboarding.crypto.PadesSignService; import it.pagopa.selfcare.onboarding.crypto.entity.SignatureInformation; -import it.pagopa.selfcare.onboarding.entity.AggregateInstitution; -import it.pagopa.selfcare.onboarding.entity.Institution; -import it.pagopa.selfcare.onboarding.entity.Onboarding; -import it.pagopa.selfcare.onboarding.entity.OnboardingAttachment; -import it.pagopa.selfcare.onboarding.entity.OnboardingWorkflow; +import it.pagopa.selfcare.onboarding.entity.*; import it.pagopa.selfcare.onboarding.exception.GenericOnboardingException; import it.pagopa.selfcare.onboarding.utils.ClassPathStream; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.text.StringSubstitutor; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.eclipse.microprofile.rest.client.inject.RestClient; +import org.jsoup.Jsoup; +import org.jsoup.helper.W3CDom; +import org.openapi.quarkus.user_registry_json.api.UserApi; +import org.openapi.quarkus.user_registry_json.model.UserResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; @@ -48,477 +36,518 @@ import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; +import java.util.*; import java.util.function.Function; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVPrinter; -import org.apache.commons.text.StringSubstitutor; -import org.eclipse.microprofile.config.inject.ConfigProperty; -import org.jsoup.Jsoup; -import org.jsoup.helper.W3CDom; -import org.openapi.quarkus.user_registry_json.model.UserResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static it.pagopa.selfcare.onboarding.common.ProductId.*; +import static it.pagopa.selfcare.onboarding.service.OnboardingService.USERS_WORKS_FIELD_LIST; +import static it.pagopa.selfcare.onboarding.utils.GenericError.*; +import static it.pagopa.selfcare.onboarding.utils.PdfMapper.*; +import static it.pagopa.selfcare.onboarding.utils.Utils.CONTRACT_FILENAME_FUNC; @ApplicationScoped public class ContractServiceDefault implements ContractService { - private static final Logger log = LoggerFactory.getLogger(ContractServiceDefault.class); - public static final String PAGOPA_SIGNATURE_DISABLED = "disabled"; - - private final AzureStorageConfig azureStorageConfig; - private final AzureBlobClient azureBlobClient; - private final PadesSignService padesSignService; - private final PagoPaSignatureConfig pagoPaSignatureConfig; - private final MailTemplatePlaceholdersConfig templatePlaceholdersConfig; - - Boolean isLogoEnable; - - private final String logoPath; - - private static final String[] CSV_HEADERS_IO = { - "Ragione Sociale", - "PEC", - "Codice Fiscale", - "P.IVA", - "Sede legale - Indirizzo", - "Sede legale - Citta'", - "Sede legale - Provincia (Sigla)", - "Codice IPA", - "AOO/UO", - "Codice Univoco" - }; - - private static final String[] CSV_HEADERS_PAGOPA = { - "Ragione Sociale", - "PEC", - "Codice Fiscale", - "P.IVA", - "Sede legale - Indirizzo", - "Sede legale - Citta'", - "Sede legale - Provincia (Sigla)", - "Ragione Sociale Partener Tecnologico", - "Codice Fiscale Partner Tecnologico", - "IBAN", - "Servizio", - "Modalità Sincrona/Asincrona" - }; - - private static final String LEGAL_SENTENCE_IO = - "*** Il presente file non puo' essere modificato se non unitamente al " - + "documento \"Allegato 3\" in cui e' incoporato. Ogni modifica, alterazione e variazione dei dati e delle " - + "informazioni del presente file non accompagnata dall'invio e dalla firma digitale dell'intero documento " - + "\"Allegato 3\" e' da considerarsi priva di ogni efficacia ai sensi di legge e ai fini del presente Accordo. " - + "In caso di discrepanza tra i dati contenuti nel presente file e i dati contenuti nell'Allegato 3, " - + "sara' data prevalenza a questi ultimi."; - - private static final Function> IO_MAPPER = - institution -> - Arrays.asList( - institution.getDescription(), - institution.getDigitalAddress(), - institution.getTaxCode(), - institution.getVatNumber(), - institution.getAddress(), - institution.getCity(), - institution.getCounty(), - Optional.ofNullable(institution.getSubunitType()) - .map(originId -> "") - .orElse(institution.getOriginId()), - institution.getSubunitType(), - institution.getSubunitCode()); - - private static final Function> PAGOPA_MAPPER = - institution -> - Arrays.asList( - institution.getDescription(), - institution.getDigitalAddress(), - institution.getTaxCode(), - institution.getVatNumber(), - institution.getAddress(), - institution.getCity(), - institution.getCounty(), - institution.getDescriptionPT(), - institution.getTaxCodePT(), - institution.getIban(), - institution.getService(), - institution.getSyncAsyncMode()); - - public ContractServiceDefault( - AzureStorageConfig azureStorageConfig, - AzureBlobClient azureBlobClient, - PadesSignService padesSignService, - PagoPaSignatureConfig pagoPaSignatureConfig, - MailTemplatePlaceholdersConfig templatePlaceholdersConfig, - @ConfigProperty(name = "onboarding-functions.logo-path") String logoPath, - @ConfigProperty(name = "onboarding-functions.logo-enable") Boolean isLogoEnable) { - this.azureStorageConfig = azureStorageConfig; - this.azureBlobClient = azureBlobClient; - this.padesSignService = padesSignService; - this.pagoPaSignatureConfig = pagoPaSignatureConfig; - this.templatePlaceholdersConfig = templatePlaceholdersConfig; - this.logoPath = logoPath; - this.isLogoEnable = isLogoEnable; - } - - /** - * Creates a PDF contract document from a given contract template file and institution data. Based - * on @contractTemplatePath it loads contract template as test and replace placeholder using a map - * with institution information. Contract will be stored at - * parties/docs/{onboardingId}/{productName}_accordo_di_adesione.pdf - * - * @param contractTemplatePath The file path to the contract template. - * @param onboarding Information related to the onboarding process. - * @param manager A user resource representing a valid manager. - * @param users A list of user resources. - * @param productName Product's name of onboarding. - * @return A File object representing the created PDF contract document. - * @throws GenericOnboardingException If an error occurs during PDF generation. - */ - @Override - public File createContractPDF( - String contractTemplatePath, - Onboarding onboarding, - UserResource manager, - List users, - String productName, - String pdfFormatFilename) { - - log.info("START - createContractPdf for template: {}", contractTemplatePath); - // Generate a unique filename for the PDF. - final String productId = onboarding.getProductId(); - final Institution institution = onboarding.getInstitution(); - - try { - final String[] split = contractTemplatePath.split("\\."); - final String fileType = split[split.length - 1]; - - // If contract template is a PDF, I get without parsing - File temporaryPdfFile = - "pdf".equals(fileType) - ? azureBlobClient.getFileAsPdf(contractTemplatePath) - : createPdfFileContract(contractTemplatePath, onboarding, manager, users); - - // Define the filename and path for storage. - final String filename = CONTRACT_FILENAME_FUNC.apply(pdfFormatFilename, productName); - final String path = - String.format("%s%s", azureStorageConfig.contractPath(), onboarding.getId()); - - File signedPath = signPdf(temporaryPdfFile, institution.getDescription(), productId); - azureBlobClient.uploadFile(path, filename, Files.readAllBytes(signedPath.toPath())); - - return signedPath; - } catch (IOException e) { - throw new GenericOnboardingException( - String.format("Can not create contract PDF, message: %s", e.getMessage())); + @Inject + @RestClient + UserApi userRegistryApi; + + private static final Logger log = LoggerFactory.getLogger(ContractServiceDefault.class); + public static final String PAGOPA_SIGNATURE_DISABLED = "disabled"; + private final AzureStorageConfig azureStorageConfig; + private final AzureBlobClient azureBlobClient; + private final PadesSignService padesSignService; + private final PagoPaSignatureConfig pagoPaSignatureConfig; + private final MailTemplatePlaceholdersConfig templatePlaceholdersConfig; + + Boolean isLogoEnable; + + private final String logoPath; + + private static final String[] CSV_HEADERS_IO = { + "Ragione Sociale", + "PEC", + "Codice Fiscale", + "P.IVA", + "Sede legale - Indirizzo", + "Sede legale - Citta'", + "Sede legale - Provincia (Sigla)", + "Codice IPA", + "AOO/UO", + "Codice Univoco" + }; + + private static final String[] CSV_HEADERS_PAGOPA = { + "Ragione Sociale", + "PEC", + "Codice Fiscale", + "P.IVA", + "Sede legale - Indirizzo", + "Sede legale - Citta'", + "Sede legale - Provincia (Sigla)", + "Ragione Sociale Partener Tecnologico", + "Codice Fiscale Partner Tecnologico", + "IBAN", + "Servizio", + "Modalità Sincrona/Asincrona" + }; + + private static final String[] CSV_HEADERS_SEND = { + "Ragione Sociale", + "PEC", + "Codice Fiscale", + "P.IVA", + "Codice SDI", + "Sede legale - Indirizzo", + "Sede legale - Citta'", + "Sede legale - Provincia (Sigla)", + "Codice IPA", + "AOO/UO", + "Codice Univoco", + "Nome Amministratore Ente Aggregato", + "Cognome Amministratore Ente Aggregato", + "Codice Fiscale Amministratore Ente Aggregato", + "email Amministratore Ente Aggregato" + }; + + private static final String LEGAL_SENTENCE_IO = + "*** Il presente file non puo' essere modificato se non unitamente al " + + "documento \"Allegato 3\" in cui e' incoporato. Ogni modifica, alterazione e variazione dei dati e delle " + + "informazioni del presente file non accompagnata dall'invio e dalla firma digitale dell'intero documento " + + "\"Allegato 3\" e' da considerarsi priva di ogni efficacia ai sensi di legge e ai fini del presente Accordo. " + + "In caso di discrepanza tra i dati contenuti nel presente file e i dati contenuti nell'Allegato 3, " + + "sara' data prevalenza a questi ultimi."; + + private static final Function> IO_MAPPER = + institution -> + Arrays.asList( + institution.getDescription(), + institution.getDigitalAddress(), + institution.getTaxCode(), + institution.getVatNumber(), + institution.getAddress(), + institution.getCity(), + institution.getCounty(), + Optional.ofNullable(institution.getSubunitType()) + .map(originId -> "") + .orElse(institution.getOriginId()), + institution.getSubunitType(), + institution.getSubunitCode()); + + private static final Function> PAGOPA_MAPPER = + institution -> + Arrays.asList( + institution.getDescription(), + institution.getDigitalAddress(), + institution.getTaxCode(), + institution.getVatNumber(), + institution.getAddress(), + institution.getCity(), + institution.getCounty(), + institution.getDescriptionPT(), + institution.getTaxCodePT(), + institution.getIban(), + institution.getService(), + institution.getSyncAsyncMode()); + + public static Function> sendMapper(UserResource userInfo, User user) { + return institution -> Arrays.asList( + institution.getDescription(), + institution.getDigitalAddress(), + institution.getTaxCode(), + institution.getVatNumber(), + institution.getRecipientCode(), + institution.getAddress(), + institution.getCity(), + institution.getCounty(), + Optional.ofNullable(institution.getSubunitType()) + .map(originId -> "") + .orElse(institution.getOriginId()), + institution.getSubunitType(), + institution.getSubunitCode(), + userInfo.getName().getValue(), + userInfo.getFamilyName().getValue(), + userInfo.getFiscalCode(), + userInfo.getWorkContacts().get(user.getUserMailUuid()).getEmail().getValue() + ); + } + + public ContractServiceDefault( + AzureStorageConfig azureStorageConfig, + AzureBlobClient azureBlobClient, + PadesSignService padesSignService, + PagoPaSignatureConfig pagoPaSignatureConfig, + MailTemplatePlaceholdersConfig templatePlaceholdersConfig, + @ConfigProperty(name = "onboarding-functions.logo-path") String logoPath, + @ConfigProperty(name = "onboarding-functions.logo-enable") Boolean isLogoEnable, + @RestClient UserApi userRegistryApi) { + this.azureStorageConfig = azureStorageConfig; + this.azureBlobClient = azureBlobClient; + this.padesSignService = padesSignService; + this.pagoPaSignatureConfig = pagoPaSignatureConfig; + this.templatePlaceholdersConfig = templatePlaceholdersConfig; + this.logoPath = logoPath; + this.isLogoEnable = isLogoEnable; + this.userRegistryApi = userRegistryApi; + } + + /** + * Creates a PDF contract document from a given contract template file and institution data. Based + * on @contractTemplatePath it loads contract template as test and replace placeholder using a map + * with institution information. Contract will be stored at + * parties/docs/{onboardingId}/{productName}_accordo_di_adesione.pdf + * + * @param contractTemplatePath The file path to the contract template. + * @param onboarding Information related to the onboarding process. + * @param manager A user resource representing a valid manager. + * @param users A list of user resources. + * @param productName Product's name of onboarding. + * @return A File object representing the created PDF contract document. + * @throws GenericOnboardingException If an error occurs during PDF generation. + */ + @Override + public File createContractPDF( + String contractTemplatePath, + Onboarding onboarding, + UserResource manager, + List users, + String productName, + String pdfFormatFilename) { + + log.info("START - createContractPdf for template: {}", contractTemplatePath); + // Generate a unique filename for the PDF. + final String productId = onboarding.getProductId(); + final Institution institution = onboarding.getInstitution(); + + try { + final String[] split = contractTemplatePath.split("\\."); + final String fileType = split[split.length - 1]; + + // If contract template is a PDF, I get without parsing + File temporaryPdfFile = + "pdf".equals(fileType) + ? azureBlobClient.getFileAsPdf(contractTemplatePath) + : createPdfFileContract(contractTemplatePath, onboarding, manager, users); + + // Define the filename and path for storage. + final String filename = CONTRACT_FILENAME_FUNC.apply(pdfFormatFilename, productName); + final String path = + String.format("%s%s", azureStorageConfig.contractPath(), onboarding.getId()); + + File signedPath = signPdf(temporaryPdfFile, institution.getDescription(), productId); + azureBlobClient.uploadFile(path, filename, Files.readAllBytes(signedPath.toPath())); + + return signedPath; + } catch (IOException e) { + throw new GenericOnboardingException( + String.format("Can not create contract PDF, message: %s", e.getMessage())); + } + } + + public File createAttachmentPDF( + String attachmentTemplatePath, + Onboarding onboarding, + String productName, + String attachmentName, UserResource userResource) { + + log.info("START - createAttachmentPDF for template: {}", attachmentTemplatePath); + + try { + final String[] split = attachmentTemplatePath.split("\\."); + final String fileType = split[split.length - 1]; + + // If contract template is a PDF, I get without parsing + File attachmentPdfFile = + "pdf".equals(fileType) + ? azureBlobClient.getFileAsPdf(attachmentTemplatePath) + : createPdfFileAttachment(attachmentTemplatePath, onboarding, userResource); + + // Define the filename and path for storage. + final String filename = + CONTRACT_FILENAME_FUNC.apply("%s_" + attachmentName + ".pdf", productName); + final String path = + String.format( + "%s%s%s", azureStorageConfig.contractPath(), onboarding.getId(), "/attachments"); + + azureBlobClient.uploadFile(path, filename, Files.readAllBytes(attachmentPdfFile.toPath())); + + return attachmentPdfFile; + } catch (IOException e) { + throw new GenericOnboardingException( + String.format("Can not create attachment PDF, message: %s", e.getMessage())); + } } - } - - public File createAttachmentPDF( - String attachmentTemplatePath, - Onboarding onboarding, - String productName, - String attachmentName, UserResource userResource) { - - log.info("START - createAttachmentPDF for template: {}", attachmentTemplatePath); - - try { - final String[] split = attachmentTemplatePath.split("\\."); - final String fileType = split[split.length - 1]; - - // If contract template is a PDF, I get without parsing - File attachmentPdfFile = - "pdf".equals(fileType) - ? azureBlobClient.getFileAsPdf(attachmentTemplatePath) - : createPdfFileAttachment(attachmentTemplatePath, onboarding, userResource); - - // Define the filename and path for storage. - final String filename = - CONTRACT_FILENAME_FUNC.apply("%s_" + attachmentName + ".pdf", productName); - final String path = - String.format( - "%s%s%s", azureStorageConfig.contractPath(), onboarding.getId(), "/attachments"); - - azureBlobClient.uploadFile(path, filename, Files.readAllBytes(attachmentPdfFile.toPath())); - - return attachmentPdfFile; - } catch (IOException e) { - throw new GenericOnboardingException( - String.format("Can not create attachment PDF, message: %s", e.getMessage())); + + private File createPdfFileContract( + String contractTemplatePath, + Onboarding onboarding, + UserResource manager, + List users) + throws IOException { + final String builder = + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + + "_" + + UUID.randomUUID() + + "_contratto_interoperabilita."; + + final String productId = onboarding.getProductId(); + final Institution institution = onboarding.getInstitution(); + + // Read the content of the contract template file. + String contractTemplateText = azureBlobClient.getFileAsText(contractTemplatePath); + // Create a temporary PDF file to store the contract. + Path temporaryPdfFile = Files.createTempFile(builder, ".pdf"); + // Prepare common data for the contract document. + Map data = setUpCommonData(manager, users, onboarding); + + StringBuilder baseUrl = + new StringBuilder(templatePlaceholdersConfig.rejectOnboardingUrlValue()); + + // Customize data based on the product and institution type. + if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) + && InstitutionType.PSP == institution.getInstitutionType()) { + setupPSPData(data, manager, onboarding); + } else if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) + && InstitutionType.PRV == institution.getInstitutionType() || InstitutionType.GPU == institution.getInstitutionType()) { + setupPRVData(data, onboarding, baseUrl.toString(), users); + } else if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) + && InstitutionType.PSP != institution.getInstitutionType() + && InstitutionType.PT != institution.getInstitutionType()) { + setECData(data, onboarding); + } else if (PROD_IO.getValue().equalsIgnoreCase(productId)) { + setupProdIODataAggregates(onboarding, data, manager, baseUrl.toString()); + } else if (PROD_IO_PREMIUM.getValue().equalsIgnoreCase(productId) + || PROD_IO_SIGN.getValue().equalsIgnoreCase(productId)) { + setupProdIOData(onboarding, data, manager); + } else if (PROD_PN.getValue().equalsIgnoreCase(productId)) { + setupProdPNData(data, institution, onboarding.getBilling()); + } else if (PROD_INTEROP.getValue().equalsIgnoreCase(productId)) { + setupSAProdInteropData(data, institution); + } + log.debug("data Map for PDF: {}", data); + fillPDFAsFile(temporaryPdfFile, contractTemplateText, data); + return temporaryPdfFile.toFile(); } - } - - private File createPdfFileContract( - String contractTemplatePath, - Onboarding onboarding, - UserResource manager, - List users) - throws IOException { - final String builder = - LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) - + "_" - + UUID.randomUUID() - + "_contratto_interoperabilita."; - - final String productId = onboarding.getProductId(); - final Institution institution = onboarding.getInstitution(); - - // Read the content of the contract template file. - String contractTemplateText = azureBlobClient.getFileAsText(contractTemplatePath); - // Create a temporary PDF file to store the contract. - Path temporaryPdfFile = Files.createTempFile(builder, ".pdf"); - // Prepare common data for the contract document. - Map data = setUpCommonData(manager, users, onboarding); - - StringBuilder baseUrl = - new StringBuilder(templatePlaceholdersConfig.rejectOnboardingUrlValue()); - - // Customize data based on the product and institution type. - if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) - && InstitutionType.PSP == institution.getInstitutionType()) { - setupPSPData(data, manager, onboarding); - } else if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) - && InstitutionType.PRV == institution.getInstitutionType() || InstitutionType.GPU == institution.getInstitutionType()) { - setupPRVData(data, onboarding, baseUrl.toString(), users); - } else if (PROD_PAGOPA.getValue().equalsIgnoreCase(productId) - && InstitutionType.PSP != institution.getInstitutionType() - && InstitutionType.PT != institution.getInstitutionType()) { - setECData(data, onboarding); - } else if (PROD_IO.getValue().equalsIgnoreCase(productId)) { - setupProdIODataAggregates(onboarding, data, manager, baseUrl.toString()); - } else if (PROD_IO_PREMIUM.getValue().equalsIgnoreCase(productId) - || PROD_IO_SIGN.getValue().equalsIgnoreCase(productId)) { - setupProdIOData(onboarding, data, manager); - } else if (PROD_PN.getValue().equalsIgnoreCase(productId)) { - setupProdPNData(data, institution, onboarding.getBilling()); - } else if (PROD_INTEROP.getValue().equalsIgnoreCase(productId)) { - setupSAProdInteropData(data, institution); + + private File createPdfFileAttachment(String attachmentTemplatePath, Onboarding onboarding, UserResource userResource) + throws IOException { + final String builder = + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + + "_" + + UUID.randomUUID() + + "_allegato_interoperabilita."; + + // Read the content of the contract template file. + String attachmentTemplateText = azureBlobClient.getFileAsText(attachmentTemplatePath); + // Create a temporary PDF file to store the contract. + Path attachmentPdfFile = Files.createTempFile(builder, ".pdf"); + // Prepare common data for the contract document. + Map data = setUpAttachmentData(onboarding, userResource); + + log.debug("data Map for PDF: {}", data); + fillPDFAsFile(attachmentPdfFile, attachmentTemplateText, data); + return attachmentPdfFile.toFile(); } - log.debug("data Map for PDF: {}", data); - fillPDFAsFile(temporaryPdfFile, contractTemplateText, data); - return temporaryPdfFile.toFile(); - } - - private File createPdfFileAttachment(String attachmentTemplatePath, Onboarding onboarding, UserResource userResource) - throws IOException { - final String builder = - LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) - + "_" - + UUID.randomUUID() - + "_allegato_interoperabilita."; - - // Read the content of the contract template file. - String attachmentTemplateText = azureBlobClient.getFileAsText(attachmentTemplatePath); - // Create a temporary PDF file to store the contract. - Path attachmentPdfFile = Files.createTempFile(builder, ".pdf"); - // Prepare common data for the contract document. - Map data = setUpAttachmentData(onboarding, userResource); - - log.debug("data Map for PDF: {}", data); - fillPDFAsFile(attachmentPdfFile, attachmentTemplateText, data); - return attachmentPdfFile.toFile(); - } - - private File signPdf(File pdf, String institutionDescription, String productId) - throws IOException { - if (PAGOPA_SIGNATURE_DISABLED.equals(pagoPaSignatureConfig.source())) { - log.info("Skipping PagoPA contract pdf sign due to global disabling"); - return pdf; + + private File signPdf(File pdf, String institutionDescription, String productId) + throws IOException { + if (PAGOPA_SIGNATURE_DISABLED.equals(pagoPaSignatureConfig.source())) { + log.info("Skipping PagoPA contract pdf sign due to global disabling"); + return pdf; + } + + String signReason = + pagoPaSignatureConfig + .applyOnboardingTemplateReason() + .replace("${institutionName}", institutionDescription) + .replace("${productName}", productId); + + log.info("Signing input file {} using reason {}", pdf.getName(), signReason); + Path signedPdf = Files.createTempFile("signed", ".pdf"); + padesSignService.padesSign(pdf, signedPdf.toFile(), buildSignatureInfo(signReason)); + return signedPdf.toFile(); } - String signReason = - pagoPaSignatureConfig - .applyOnboardingTemplateReason() - .replace("${institutionName}", institutionDescription) - .replace("${productName}", productId); - - log.info("Signing input file {} using reason {}", pdf.getName(), signReason); - Path signedPdf = Files.createTempFile("signed", ".pdf"); - padesSignService.padesSign(pdf, signedPdf.toFile(), buildSignatureInfo(signReason)); - return signedPdf.toFile(); - } - - private SignatureInformation buildSignatureInfo(String signReason) { - return new SignatureInformation( - pagoPaSignatureConfig.signer(), pagoPaSignatureConfig.location(), signReason); - } - - /** Only for test */ - @Override - public File loadContractPDF( - String contractTemplatePath, String onboardingId, String productName) { - try { - File pdf = azureBlobClient.getFileAsPdf(contractTemplatePath); - - final String filename = CONTRACT_FILENAME_FUNC.apply("%s.pdf", productName); - final String path = String.format("%s/%s", azureStorageConfig.contractPath(), onboardingId); - azureBlobClient.uploadFile(path, filename, Files.readAllBytes(pdf.toPath())); - - return pdf; - } catch (IOException e) { - throw new GenericOnboardingException( - String.format("Can not load contract PDF, message: %s", e.getMessage())); + private SignatureInformation buildSignatureInfo(String signReason) { + return new SignatureInformation( + pagoPaSignatureConfig.signer(), pagoPaSignatureConfig.location(), signReason); } - } - - private void fillPDFAsFile(Path file, String contractTemplate, Map data) { - log.debug("Getting PDF for HTML template..."); - String html = StringSubstitutor.replace(contractTemplate, data); - PdfRendererBuilder builder = new PdfRendererBuilder(); - builder.useFastMode(); - builder.useProtocolsStreamImplementation( - url -> { - URI fullUri; - try { - fullUri = new URI(url); - return new ClassPathStream(fullUri.getPath()); - } catch (URISyntaxException e) { - log.error("URISintaxException in ClassPathStreamFactory: ", e); + + /** + * Only for test + */ + @Override + public File loadContractPDF( + String contractTemplatePath, String onboardingId, String productName) { + try { + File pdf = azureBlobClient.getFileAsPdf(contractTemplatePath); + + final String filename = CONTRACT_FILENAME_FUNC.apply("%s.pdf", productName); + final String path = String.format("%s/%s", azureStorageConfig.contractPath(), onboardingId); + azureBlobClient.uploadFile(path, filename, Files.readAllBytes(pdf.toPath())); + + return pdf; + } catch (IOException e) { throw new GenericOnboardingException( - GENERIC_ERROR.getMessage(), GENERIC_ERROR.getCode()); - } - }, - "classpath"); - var doc = Jsoup.parse(html, "UTF-8"); - var dom = W3CDom.convert(doc); - builder.withW3cDocument(dom, null); - builder.useSVGDrawer(new BatikSVGDrawer()); - - try (FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) { - builder.toStream(fileOutputStream); - builder.run(); - } catch (IOException e) { - throw new GenericOnboardingException(e.getMessage()); + String.format("Can not load contract PDF, message: %s", e.getMessage())); + } + } + + private void fillPDFAsFile(Path file, String contractTemplate, Map data) { + log.debug("Getting PDF for HTML template..."); + String html = StringSubstitutor.replace(contractTemplate, data); + PdfRendererBuilder builder = new PdfRendererBuilder(); + builder.useFastMode(); + builder.useProtocolsStreamImplementation( + url -> { + URI fullUri; + try { + fullUri = new URI(url); + return new ClassPathStream(fullUri.getPath()); + } catch (URISyntaxException e) { + log.error("URISintaxException in ClassPathStreamFactory: ", e); + throw new GenericOnboardingException( + GENERIC_ERROR.getMessage(), GENERIC_ERROR.getCode()); + } + }, + "classpath"); + var doc = Jsoup.parse(html, "UTF-8"); + var dom = W3CDom.convert(doc); + builder.withW3cDocument(dom, null); + builder.useSVGDrawer(new BatikSVGDrawer()); + + try (FileOutputStream fileOutputStream = new FileOutputStream(file.toFile())) { + builder.toStream(fileOutputStream); + builder.run(); + } catch (IOException e) { + throw new GenericOnboardingException(e.getMessage()); + } + + log.debug("PDF stream properly retrieved"); + } + + @Override + public File retrieveContractNotSigned(OnboardingWorkflow onboardingWorkflow, String productName) { + final String onboardingId = onboardingWorkflow.getOnboarding().getId(); + final String filename = + CONTRACT_FILENAME_FUNC.apply(onboardingWorkflow.getPdfFormatFilename(), productName); + final String path = + String.format("%s%s/%s", azureStorageConfig.contractPath(), onboardingId, filename); + return azureBlobClient.getFileAsPdf(path); } - log.debug("PDF stream properly retrieved"); - } - - @Override - public File retrieveContractNotSigned(OnboardingWorkflow onboardingWorkflow, String productName) { - final String onboardingId = onboardingWorkflow.getOnboarding().getId(); - final String filename = - CONTRACT_FILENAME_FUNC.apply(onboardingWorkflow.getPdfFormatFilename(), productName); - final String path = - String.format("%s%s/%s", azureStorageConfig.contractPath(), onboardingId, filename); - return azureBlobClient.getFileAsPdf(path); - } - - @Override - public File retrieveAttachment(OnboardingAttachment onboardingAttachment, String productName) { - final String onboardingId = onboardingAttachment.getOnboarding().getId(); - final String filename = - CONTRACT_FILENAME_FUNC.apply( - "%s_" + onboardingAttachment.getAttachment().getName() + ".pdf", productName); - final String path = - String.format( - "%s%s/%s/%s", azureStorageConfig.contractPath(), onboardingId, "attachments", filename); - return azureBlobClient.getFileAsPdf(path); - } - - @Override - public Optional getLogoFile() { - if (Boolean.TRUE.equals(isLogoEnable)) { - - StringBuilder stringBuilder = - new StringBuilder( - LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))); - stringBuilder.append("_").append(UUID.randomUUID()).append("_logo"); - try { - Path path = Files.createTempFile(stringBuilder.toString(), ".png"); - Files.writeString(path, azureBlobClient.getFileAsText(logoPath)); - return Optional.of(path.toFile()); - } catch (IOException e) { - throw new IllegalArgumentException( - String.format(UNABLE_TO_DOWNLOAD_FILE.getMessage(), logoPath)); - } + @Override + public File retrieveAttachment(OnboardingAttachment onboardingAttachment, String productName) { + final String onboardingId = onboardingAttachment.getOnboarding().getId(); + final String filename = + CONTRACT_FILENAME_FUNC.apply( + "%s_" + onboardingAttachment.getAttachment().getName() + ".pdf", productName); + final String path = + String.format( + "%s%s/%s/%s", azureStorageConfig.contractPath(), onboardingId, "attachments", filename); + return azureBlobClient.getFileAsPdf(path); } - return Optional.empty(); - } - - @Override - public void uploadAggregatesCsv(OnboardingWorkflow onboardingWorkflow) { - - try { - Onboarding onboarding = onboardingWorkflow.getOnboarding(); - Path filePath = Files.createTempFile("tempfile", ".csv"); - File csv = - generateAggregatesCsv(onboarding.getProductId(), onboarding.getAggregates(), filePath); - final String path = - String.format( - "%s%s/%s", - azureStorageConfig.aggregatesPath(), onboarding.getId(), onboarding.getProductId()); - final String filename = "aggregates.csv"; - azureBlobClient.uploadFile(path, filename, Files.readAllBytes(csv.toPath())); - } catch (IOException e) { - throw new GenericOnboardingException( - String.format(LOAD_AGGREGATES_CSV_ERROR.getMessage(), e.getMessage())); + @Override + public Optional getLogoFile() { + if (Boolean.TRUE.equals(isLogoEnable)) { + + StringBuilder stringBuilder = + new StringBuilder( + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))); + stringBuilder.append("_").append(UUID.randomUUID()).append("_logo"); + try { + Path path = Files.createTempFile(stringBuilder.toString(), ".png"); + Files.writeString(path, azureBlobClient.getFileAsText(logoPath)); + return Optional.of(path.toFile()); + } catch (IOException e) { + throw new IllegalArgumentException( + String.format(UNABLE_TO_DOWNLOAD_FILE.getMessage(), logoPath)); + } + } + + return Optional.empty(); } - } - - private File generateAggregatesCsv( - String productId, List institutions, Path filePath) { - String[] headers; - Function> mapper; - - // Determine headers and mapping logic based on productId - switch (productId) { - case "prod-io": - headers = CSV_HEADERS_IO; - mapper = IO_MAPPER; - break; - case "prod-pagopa": - headers = CSV_HEADERS_PAGOPA; - mapper = PAGOPA_MAPPER; - break; - case "prod-pn": - return new File( - String.valueOf( - filePath)); // prod-pn is available for aggregator's workflow but csv structure is - // still not defined. - default: - throw new IllegalArgumentException( - String.format("Product %s is not available for aggregators", productId)); + + @Override + public void uploadAggregatesCsv(OnboardingWorkflow onboardingWorkflow) { + + try { + Onboarding onboarding = onboardingWorkflow.getOnboarding(); + Path filePath = Files.createTempFile("tempfile", ".csv"); + File csv = + generateAggregatesCsv(onboarding.getProductId(), onboarding.getAggregates(), filePath); + final String path = + String.format( + "%s%s/%s", + azureStorageConfig.aggregatesPath(), onboarding.getId(), onboarding.getProductId()); + final String filename = "aggregates.csv"; + azureBlobClient.uploadFile(path, filename, Files.readAllBytes(csv.toPath())); + } catch (IOException e) { + throw new GenericOnboardingException( + String.format(LOAD_AGGREGATES_CSV_ERROR.getMessage(), e.getMessage())); + } + } + + private File generateAggregatesCsv( + String productId, List institutions, Path filePath) { + String[] headers; + Function> mapper; + String legalSentence = null; + + // Determine headers and mapping logic based on productId + switch (productId) { + case "prod-io": + headers = CSV_HEADERS_IO; + mapper = IO_MAPPER; + legalSentence = LEGAL_SENTENCE_IO; + break; + case "prod-pagopa": + headers = CSV_HEADERS_PAGOPA; + mapper = PAGOPA_MAPPER; + break; + case "prod-pn": + headers = CSV_HEADERS_SEND; + User user = institutions.get(0).getUsers().get(0); + UserResource userInfo = userRegistryApi.findByIdUsingGET(USERS_WORKS_FIELD_LIST, user.getId()); + mapper = sendMapper(userInfo, user); + break; + default: + throw new IllegalArgumentException( + String.format("Product %s is not available for aggregators", productId)); + } + return createAggregatesCsv(institutions, filePath, headers, mapper, legalSentence); } - return createAggregatesCsv(institutions, filePath, headers, mapper, productId); - } - - private File createAggregatesCsv( - List institutions, - Path filePath, - String[] headers, - Function> mapper, - String productId) { - File csvFile = filePath.toFile(); - - // Using the builder pattern to create the CSV format with headers - CSVFormat csvFormat = - CSVFormat.Builder.create(CSVFormat.DEFAULT).setHeader(headers).setDelimiter(';').build(); - - try (FileWriter writer = new FileWriter(csvFile); - CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { - - // Iterate over each AggregateInstitution object and write a row for each one - for (AggregateInstitution institution : institutions) { - csvPrinter.printRecord(mapper.apply(institution)); - } - - // If productType is PROD_IO, add the final legal sentence at the last row - if (PROD_IO.getValue().equals(productId)) { - csvPrinter.println(); - csvPrinter.printRecord(LEGAL_SENTENCE_IO); - } - - } catch (IOException e) { - throw new GenericOnboardingException( - String.format(CREATE_AGGREGATES_CSV_ERROR.getMessage(), e.getMessage())); + private File createAggregatesCsv( + List institutions, + Path filePath, + String[] headers, + Function> mapper, + String legalSentence) { + + File csvFile = filePath.toFile(); + + // Using the builder pattern to create the CSV format with headers + CSVFormat csvFormat = + CSVFormat.Builder.create(CSVFormat.DEFAULT).setHeader(headers).setDelimiter(';').build(); + + try (FileWriter writer = new FileWriter(csvFile); + CSVPrinter csvPrinter = new CSVPrinter(writer, csvFormat)) { + + // Iterate over each AggregateInstitution object and write a row for each one + for (AggregateInstitution institution : institutions) { + csvPrinter.printRecord(mapper.apply(institution)); + } + + // Add the final legal sentence at the last row in case of prod-io + csvPrinter.println(); + csvPrinter.printRecord(legalSentence); + + } catch (IOException e) { + throw new GenericOnboardingException( + String.format(CREATE_AGGREGATES_CSV_ERROR.getMessage(), e.getMessage())); + } + return csvFile; } - return csvFile; - } } diff --git a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefaultTest.java b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefaultTest.java index 88cf9b2d4..317771c09 100644 --- a/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefaultTest.java +++ b/apps/onboarding-functions/src/test/java/it/pagopa/selfcare/onboarding/service/ContractServiceDefaultTest.java @@ -1,14 +1,5 @@ package it.pagopa.selfcare.onboarding.service; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; import it.pagopa.selfcare.azurestorage.AzureBlobClient; @@ -17,23 +8,9 @@ import it.pagopa.selfcare.onboarding.config.MailTemplatePlaceholdersConfig; import it.pagopa.selfcare.onboarding.config.PagoPaSignatureConfig; import it.pagopa.selfcare.onboarding.crypto.PadesSignService; -import it.pagopa.selfcare.onboarding.entity.AggregateInstitution; -import it.pagopa.selfcare.onboarding.entity.GPUData; -import it.pagopa.selfcare.onboarding.entity.Institution; -import it.pagopa.selfcare.onboarding.entity.Onboarding; -import it.pagopa.selfcare.onboarding.entity.OnboardingWorkflow; -import it.pagopa.selfcare.onboarding.entity.OnboardingWorkflowAggregator; -import it.pagopa.selfcare.onboarding.entity.OnboardingWorkflowInstitution; -import it.pagopa.selfcare.onboarding.entity.PaymentServiceProvider; -import it.pagopa.selfcare.onboarding.entity.User; +import it.pagopa.selfcare.onboarding.entity.*; import jakarta.inject.Inject; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; +import org.eclipse.microprofile.rest.client.inject.RestClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,497 +18,575 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.openapi.quarkus.user_registry_json.api.UserApi; import org.openapi.quarkus.user_registry_json.model.CertifiableFieldResourceOfstring; import org.openapi.quarkus.user_registry_json.model.UserResource; import org.openapi.quarkus.user_registry_json.model.WorkContactResource; +import java.io.File; +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + @QuarkusTest class ContractServiceDefaultTest { - @Inject AzureStorageConfig azureStorageConfig; - - @InjectMock AzureBlobClient azureBlobClient; - PadesSignService padesSignService; - - @Inject ContractService contractService; - - @Inject PagoPaSignatureConfig pagoPaSignatureConfig; - - @Inject MailTemplatePlaceholdersConfig mailTemplatePlaceholdersConfig; - - static final String PRODUCT_NAME_EXAMPLE = "product-name"; - static final String LOGO_PATH = "logo-path"; - static final String PDF_FORMAT_FILENAME = "%s_accordo_adesione.pdf"; - - @BeforeEach - void setup() { - padesSignService = mock(PadesSignService.class); - contractService = - new ContractServiceDefault( - azureStorageConfig, - azureBlobClient, - padesSignService, - pagoPaSignatureConfig, - mailTemplatePlaceholdersConfig, - LOGO_PATH, - true); - } - - private Onboarding createOnboarding() { - Onboarding onboarding = new Onboarding(); - onboarding.setId("example"); - onboarding.setProductId("productId"); - onboarding.setUsers(List.of()); - - createInstitution(onboarding); - - User user = new User(); - user.setId(UUID.randomUUID().toString()); - user.setUserMailUuid("setUserMailUuid"); - onboarding.setUsers(List.of(user)); - return onboarding; - } - - private static void createInstitution(Onboarding onboarding) { - Institution institution = new Institution(); - institution.setInstitutionType(InstitutionType.PSP); - institution.setDescription("42"); - - PaymentServiceProvider paymentServiceProvider = createPaymentServiceProvider(); - institution.setPaymentServiceProvider(paymentServiceProvider); - - GPUData gpuData = createGpuData(); - institution.setGpuData(gpuData); - - institution.setRea("rea"); - institution.setBusinessRegisterPlace("place"); - institution.setShareCapital("10000"); - onboarding.setInstitution(institution); - } - - private static GPUData createGpuData() { - GPUData gpuData = new GPUData(); - gpuData.setManager(true); - gpuData.setManagerAuthorized(true); - gpuData.setManagerEligible(true); - gpuData.setManagerProsecution(true); - gpuData.setInstitutionCourtMeasures(true); - return gpuData; - } - - private static PaymentServiceProvider createPaymentServiceProvider() { - PaymentServiceProvider paymentServiceProvider = new PaymentServiceProvider(); - paymentServiceProvider.setBusinessRegisterNumber("businessRegisterNumber"); - paymentServiceProvider.setLegalRegisterName("legalRegisterName"); - paymentServiceProvider.setLegalRegisterNumber("legalRegisterNumber"); - return paymentServiceProvider; - } - - AggregateInstitution createAggregateInstitutionIO(int number) { - AggregateInstitution aggregateInstitution = new AggregateInstitution(); - aggregateInstitution.setTaxCode(String.format("taxCode%s", number)); - aggregateInstitution.setOriginId(String.format("originId%s", number)); - aggregateInstitution.setDescription(String.format("description%s", number)); - aggregateInstitution.setVatNumber(String.format("vatNumber%s", number)); - aggregateInstitution.setAddress(String.format("address%s", number)); - aggregateInstitution.setCity(String.format("city%s", number)); - aggregateInstitution.setCounty(String.format("county%s", number)); - aggregateInstitution.setDigitalAddress(String.format("pec%s", number)); - return aggregateInstitution; - } - - AggregateInstitution createAggregateInstitutionAOO_IO(int number) { - AggregateInstitution aggregateInstitution = createAggregateInstitutionIO(number); - aggregateInstitution.setSubunitType("AOO"); - aggregateInstitution.setSubunitCode(String.format("code%s", number)); - return aggregateInstitution; - } - - AggregateInstitution createAggregateInstitutionPagoPa(int number) { - AggregateInstitution aggregateInstitution = new AggregateInstitution(); - aggregateInstitution.setTaxCode(String.format("taxCode%s", number)); - aggregateInstitution.setDescription(String.format("description%s", number)); - aggregateInstitution.setVatNumber(String.format("vatNumber%s", number)); - aggregateInstitution.setAddress(String.format("address%s", number)); - aggregateInstitution.setCity(String.format("city%s", number)); - aggregateInstitution.setCounty(String.format("county%s", number)); - aggregateInstitution.setDigitalAddress(String.format("pec%s", number)); - aggregateInstitution.setTaxCodePT(String.format("taxCodePT%s", number)); - aggregateInstitution.setDescriptionPT(String.format("descriptionPT%s", number)); - aggregateInstitution.setIban(String.format("iban%s", number)); - aggregateInstitution.setService(String.format("service%s", number)); - aggregateInstitution.setSyncAsyncMode(String.format("mode%s", number)); - return aggregateInstitution; - } - - OnboardingWorkflow createOnboardingWorkflowIO() { - Onboarding onboarding = createOnboarding(); - onboarding.setProductId("prod-io"); - List aggregateInstitutionList = new ArrayList<>(); - - for (int i = 1; i <= 5; i++) { - AggregateInstitution aggregateInstitution = createAggregateInstitutionIO(i); - aggregateInstitutionList.add(aggregateInstitution); + @Inject AzureStorageConfig azureStorageConfig; + + @InjectMock AzureBlobClient azureBlobClient; + + @InjectMock @RestClient UserApi userRegistryApi; + PadesSignService padesSignService; + + @Inject ContractService contractService; + + @Inject PagoPaSignatureConfig pagoPaSignatureConfig; + + @Inject + MailTemplatePlaceholdersConfig mailTemplatePlaceholdersConfig; + + + static final String PRODUCT_NAME_EXAMPLE = "product-name"; + static final String LOGO_PATH = "logo-path"; + static final String PDF_FORMAT_FILENAME = "%s_accordo_adesione.pdf"; + + @BeforeEach + void setup() { + padesSignService = mock(PadesSignService.class); + contractService = + new ContractServiceDefault( + azureStorageConfig, + azureBlobClient, + padesSignService, + pagoPaSignatureConfig, + mailTemplatePlaceholdersConfig, + LOGO_PATH, + true, + userRegistryApi); + } + + private Onboarding createOnboarding() { + Onboarding onboarding = new Onboarding(); + onboarding.setId("example"); + onboarding.setProductId("productId"); + onboarding.setUsers(List.of()); + + createInstitution(onboarding); + + User user = new User(); + user.setId(UUID.randomUUID().toString()); + user.setUserMailUuid("setUserMailUuid"); + onboarding.setUsers(List.of(user)); + return onboarding; + } + + private static void createInstitution(Onboarding onboarding) { + Institution institution = new Institution(); + institution.setInstitutionType(InstitutionType.PSP); + institution.setDescription("42"); + + PaymentServiceProvider paymentServiceProvider = createPaymentServiceProvider(); + institution.setPaymentServiceProvider(paymentServiceProvider); + + GPUData gpuData = createGpuData(); + institution.setGpuData(gpuData); + + institution.setRea("rea"); + institution.setBusinessRegisterPlace("place"); + institution.setShareCapital("10000"); + onboarding.setInstitution(institution); + } + + private static GPUData createGpuData() { + GPUData gpuData = new GPUData(); + gpuData.setManager(true); + gpuData.setManagerAuthorized(true); + gpuData.setManagerEligible(true); + gpuData.setManagerProsecution(true); + gpuData.setInstitutionCourtMeasures(true); + return gpuData; + } + + private static PaymentServiceProvider createPaymentServiceProvider() { + PaymentServiceProvider paymentServiceProvider = new PaymentServiceProvider(); + paymentServiceProvider.setBusinessRegisterNumber("businessRegisterNumber"); + paymentServiceProvider.setLegalRegisterName("legalRegisterName"); + paymentServiceProvider.setLegalRegisterNumber("legalRegisterNumber"); + return paymentServiceProvider; + } + + AggregateInstitution createAggregateInstitutionIO(int number) { + AggregateInstitution aggregateInstitution = new AggregateInstitution(); + aggregateInstitution.setTaxCode(String.format("taxCode%s", number)); + aggregateInstitution.setOriginId(String.format("originId%s", number)); + aggregateInstitution.setDescription(String.format("description%s", number)); + aggregateInstitution.setVatNumber(String.format("vatNumber%s", number)); + aggregateInstitution.setAddress(String.format("address%s", number)); + aggregateInstitution.setCity(String.format("city%s", number)); + aggregateInstitution.setCounty(String.format("county%s", number)); + aggregateInstitution.setDigitalAddress(String.format("pec%s", number)); + return aggregateInstitution; + } + + AggregateInstitution createAggregateInstitutionAOO_IO(int number) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionIO(number); + aggregateInstitution.setSubunitType("AOO"); + aggregateInstitution.setSubunitCode(String.format("code%s", number)); + return aggregateInstitution; + } + + AggregateInstitution createAggregateInstitutionPagoPa(int number) { + AggregateInstitution aggregateInstitution = new AggregateInstitution(); + aggregateInstitution.setTaxCode(String.format("taxCode%s", number)); + aggregateInstitution.setDescription(String.format("description%s", number)); + aggregateInstitution.setVatNumber(String.format("vatNumber%s", number)); + aggregateInstitution.setAddress(String.format("address%s", number)); + aggregateInstitution.setCity(String.format("city%s", number)); + aggregateInstitution.setCounty(String.format("county%s", number)); + aggregateInstitution.setDigitalAddress(String.format("pec%s", number)); + aggregateInstitution.setTaxCodePT(String.format("taxCodePT%s", number)); + aggregateInstitution.setDescriptionPT(String.format("descriptionPT%s", number)); + aggregateInstitution.setIban(String.format("iban%s", number)); + aggregateInstitution.setService(String.format("service%s", number)); + aggregateInstitution.setSyncAsyncMode(String.format("mode%s", number)); + return aggregateInstitution; + } + + AggregateInstitution createAggregateInstitutionSend(int number) { + AggregateInstitution aggregateInstitution = new AggregateInstitution(); + aggregateInstitution.setTaxCode(String.format("taxCode%s", number)); + aggregateInstitution.setOriginId(String.format("originId%s", number)); + aggregateInstitution.setDescription(String.format("description%s", number)); + aggregateInstitution.setVatNumber(String.format("vatNumber%s", number)); + aggregateInstitution.setRecipientCode(String.format("recipientCode%s", number)); + aggregateInstitution.setAddress(String.format("address%s", number)); + aggregateInstitution.setCity(String.format("city%s", number)); + aggregateInstitution.setCounty(String.format("county%s", number)); + aggregateInstitution.setDigitalAddress(String.format("pec%s", number)); + User user = new User(); + user.setId("userId"); + user.setUserMailUuid("mailUuid"); + aggregateInstitution.setUsers(List.of(user)); + return aggregateInstitution; + } + + AggregateInstitution createAggregateInstitutionAOO_Send(int number) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionSend(number); + aggregateInstitution.setSubunitType("AOO"); + aggregateInstitution.setSubunitCode(String.format("code%s", number)); + return aggregateInstitution; + } + + OnboardingWorkflow createOnboardingWorkflowIO() { + Onboarding onboarding = createOnboarding(); + onboarding.setProductId("prod-io"); + List aggregateInstitutionList = new ArrayList<>(); + + for (int i = 1; i <= 5; i++) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionIO(i); + aggregateInstitutionList.add(aggregateInstitution); + } + + for (int i = 6; i <= 10; i++) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionAOO_IO(i); + aggregateInstitutionList.add(aggregateInstitution); + } + + onboarding.setAggregates(aggregateInstitutionList); + + return new OnboardingWorkflowAggregator(onboarding, "string"); + } + + OnboardingWorkflow createOnboardingWorkflowPagoPa() { + Onboarding onboarding = createOnboarding(); + onboarding.setProductId("prod-pagopa"); + List aggregateInstitutionList = new ArrayList<>(); + + for (int i = 1; i <= 7; i++) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionPagoPa(i); + aggregateInstitutionList.add(aggregateInstitution); + } + + onboarding.setAggregates(aggregateInstitutionList); + + return new OnboardingWorkflowAggregator(onboarding, "string"); + } + + + OnboardingWorkflow createOnboardingWorkflowSend() { + Onboarding onboarding = createOnboarding(); + onboarding.setProductId("prod-pn"); + List aggregateInstitutionList = new ArrayList<>(); + + for (int i = 1; i <= 4; i++) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionSend(i); + aggregateInstitutionList.add(aggregateInstitution); + } + + for (int i = 5; i <= 7; i++) { + AggregateInstitution aggregateInstitution = createAggregateInstitutionAOO_Send(i); + aggregateInstitutionList.add(aggregateInstitution); + } + + onboarding.setAggregates(aggregateInstitutionList); + + return new OnboardingWorkflowAggregator(onboarding, "string"); } - for (int i = 6; i <= 10; i++) { - AggregateInstitution aggregateInstitution = createAggregateInstitutionAOO_IO(i); - aggregateInstitutionList.add(aggregateInstitution); + UserResource createDummyUserResource(String id, String userMailUuid) { + UserResource validManager = new UserResource(); + validManager.setId(UUID.fromString(id)); + CertifiableFieldResourceOfstring emailCert = new CertifiableFieldResourceOfstring(); + emailCert.setValue("email"); + WorkContactResource workContact = new WorkContactResource(); + workContact.setEmail(emailCert); + Map map = new HashMap<>(); + map.put(userMailUuid, workContact); + + validManager.setWorkContacts(map); + return validManager; } - onboarding.setAggregates(aggregateInstitutionList); + @Test + void createContractPDF() { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; + final String productNameAccent = "Interoperabilità"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - return new OnboardingWorkflowAggregator(onboarding, "string"); - } + File contract = + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + productNameAccent, + PDF_FORMAT_FILENAME); - OnboardingWorkflow createOnboardingWorkflowPagoPa() { - Onboarding onboarding = createOnboarding(); - onboarding.setProductId("prod-pagopa"); - List aggregateInstitutionList = new ArrayList<>(); + assertNotNull(contract); - for (int i = 1; i <= 7; i++) { - AggregateInstitution aggregateInstitution = createAggregateInstitutionPagoPa(i); - aggregateInstitutionList.add(aggregateInstitution); + ArgumentCaptor captorFilename = ArgumentCaptor.forClass(String.class); + verify(azureBlobClient, times(1)).uploadFile(any(), captorFilename.capture(), any()); + assertEquals("Interoperabilita_accordo_adesione.pdf", captorFilename.getValue()); } - onboarding.setAggregates(aggregateInstitutionList); - - return new OnboardingWorkflowAggregator(onboarding, "string"); - } - - UserResource createDummyUserResource(String id, String userMailUuid) { - UserResource validManager = new UserResource(); - validManager.setId(UUID.fromString(id)); - CertifiableFieldResourceOfstring emailCert = new CertifiableFieldResourceOfstring(); - emailCert.setValue("email"); - WorkContactResource workContact = new WorkContactResource(); - workContact.setEmail(emailCert); - Map map = new HashMap<>(); - map.put(userMailUuid, workContact); - - validManager.setWorkContacts(map); - return validManager; - } - - @Test - void createContractPDF() { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - final String productNameAccent = "Interoperabilità"; - - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - File contract = - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - productNameAccent, - PDF_FORMAT_FILENAME); - - assertNotNull(contract); - - ArgumentCaptor captorFilename = ArgumentCaptor.forClass(String.class); - verify(azureBlobClient, times(1)).uploadFile(any(), captorFilename.capture(), any()); - assertEquals("Interoperabilita_accordo_adesione.pdf", captorFilename.getValue()); - } - - @Test - void createAttachmentPDF() { - final String contractFilepath = "attachment"; - final String contractHtml = "attachment"; - final String productNameAccent = "Interoperabilità"; - final String pdfFormatFile = "checklist"; - - Onboarding onboarding = createOnboarding(); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - UserResource userResource = createUserResource(); - - File attachmentPDF = - contractService.createAttachmentPDF( - contractFilepath, onboarding, productNameAccent, pdfFormatFile, userResource); - - assertNotNull(attachmentPDF); - - ArgumentCaptor captorFilename = ArgumentCaptor.forClass(String.class); - verify(azureBlobClient, times(1)).uploadFile(any(), captorFilename.capture(), any()); - assertEquals("Interoperabilita_checklist.pdf", captorFilename.getValue()); - } - - @Test - void createContractPDFSA() { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - onboarding.getInstitution().setInstitutionType(InstitutionType.SA); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - assertNotNull( - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - PRODUCT_NAME_EXAMPLE, - PDF_FORMAT_FILENAME)); - } - - @Test - void createContractPDFForECAndProdPagoPA() { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - onboarding.getInstitution().setInstitutionType(InstitutionType.PA); - onboarding.setProductId("prod-pagopa"); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - assertNotNull( - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - PRODUCT_NAME_EXAMPLE, - PDF_FORMAT_FILENAME)); - } - - @ParameterizedTest - @ValueSource(strings = {"prod-io", "prod-io-sign"}) - void createContractPDFForProdIo(String productId) { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - onboarding.getInstitution().setInstitutionType(InstitutionType.PA); - onboarding.setProductId(productId); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - assertNotNull( - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - PRODUCT_NAME_EXAMPLE, - PDF_FORMAT_FILENAME)); - } - - @Test - void createContractPDFAndSigned() { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - - pagoPaSignatureConfig = Mockito.spy(this.pagoPaSignatureConfig); - when(pagoPaSignatureConfig.source()).thenReturn("local"); - contractService = - new ContractServiceDefault( - azureStorageConfig, - azureBlobClient, - padesSignService, - pagoPaSignatureConfig, - mailTemplatePlaceholdersConfig, - "logo-path", - true); - - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - - Mockito.doNothing().when(padesSignService).padesSign(any(), any(), any()); + @Test + void createAttachmentPDF() { + final String contractFilepath = "attachment"; + final String contractHtml = "attachment"; + final String productNameAccent = "Interoperabilità"; + final String pdfFormatFile = "checklist"; - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + Onboarding onboarding = createOnboarding(); - assertNotNull( - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - PRODUCT_NAME_EXAMPLE, - PDF_FORMAT_FILENAME)); - } - - @Test - void loadContractPDF() { - final String contractFilepath = "contract"; - final String contractHtml = "contract"; - - Onboarding onboarding = createOnboarding(); + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - File pdf = - new File( - Objects.requireNonNull( - getClass().getClassLoader().getResource("application.properties")) - .getFile()); - - Mockito.when(azureBlobClient.getFileAsPdf(contractFilepath)).thenReturn(pdf); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + UserResource userResource = createUserResource(); - assertNotNull( - contractService.loadContractPDF( - contractFilepath, onboarding.getId(), PRODUCT_NAME_EXAMPLE)); - } - - @Test - void retrieveContractNotSigned() { - - Onboarding onboarding = createOnboarding(); - OnboardingWorkflow onboardingWorkflow = new OnboardingWorkflowInstitution(); - onboardingWorkflow.setOnboarding(onboarding); - - File pdf = mock(File.class); - Mockito.when(azureBlobClient.getFileAsPdf(any())).thenReturn(pdf); - - contractService.retrieveContractNotSigned(onboardingWorkflow, PRODUCT_NAME_EXAMPLE); - - ArgumentCaptor filepathActual = ArgumentCaptor.forClass(String.class); - Mockito.verify(azureBlobClient, times(1)).getFileAsPdf(filepathActual.capture()); - assertTrue(filepathActual.getValue().contains(onboarding.getId())); - assertTrue(filepathActual.getValue().contains(PRODUCT_NAME_EXAMPLE)); - } - - @Test - void getLogoFile() { - Mockito.when(azureBlobClient.getFileAsText(any())).thenReturn("example"); - - contractService.getLogoFile(); - - Mockito.verify(azureBlobClient, times(1)).getFileAsText(any()); - } - - @Test - void uploadCsvAggregatesIO() { - final String contractHtml = "contract"; - - OnboardingWorkflow onboardingWorkflow = createOnboardingWorkflowIO(); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - contractService.uploadAggregatesCsv(onboardingWorkflow); - - Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); - } - - @Test - void uploadCsvAggregatesPagoPa() { - final String contractHtml = "contract"; - - OnboardingWorkflow onboardingWorkflow = createOnboardingWorkflowPagoPa(); - - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - - contractService.uploadAggregatesCsv(onboardingWorkflow); + File attachmentPDF = + contractService.createAttachmentPDF( + contractFilepath, onboarding, productNameAccent, pdfFormatFile, userResource); - Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); - } + assertNotNull(attachmentPDF); - @Test - void uploadCsvAggregatesProdPn() { - final String contractHtml = "contract"; + ArgumentCaptor captorFilename = ArgumentCaptor.forClass(String.class); + verify(azureBlobClient, times(1)).uploadFile(any(), captorFilename.capture(), any()); + assertEquals("Interoperabilita_checklist.pdf", captorFilename.getValue()); + } + + @Test + void createContractPDFSA() { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + onboarding.getInstitution().setInstitutionType(InstitutionType.SA); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + assertNotNull( + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + PRODUCT_NAME_EXAMPLE, + PDF_FORMAT_FILENAME)); + } + + @Test + void createContractPDFForECAndProdPagoPA() { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + onboarding.getInstitution().setInstitutionType(InstitutionType.PA); + onboarding.setProductId("prod-pagopa"); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + assertNotNull( + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + PRODUCT_NAME_EXAMPLE, + PDF_FORMAT_FILENAME)); + } + + @ParameterizedTest + @ValueSource(strings = {"prod-io", "prod-io-sign"}) + void createContractPDFForProdIo(String productId) { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + onboarding.getInstitution().setInstitutionType(InstitutionType.PA); + onboarding.setProductId(productId); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + assertNotNull( + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + PRODUCT_NAME_EXAMPLE, + PDF_FORMAT_FILENAME)); + } + + @Test + void createContractPDFAndSigned() { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + + pagoPaSignatureConfig = Mockito.spy(this.pagoPaSignatureConfig); + when(pagoPaSignatureConfig.source()).thenReturn("local"); + contractService = + new ContractServiceDefault( + azureStorageConfig, + azureBlobClient, + padesSignService, + pagoPaSignatureConfig, + mailTemplatePlaceholdersConfig, + "logo-path", + true, + userRegistryApi); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + + Mockito.doNothing().when(padesSignService).padesSign(any(), any(), any()); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + assertNotNull( + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + PRODUCT_NAME_EXAMPLE, + PDF_FORMAT_FILENAME)); + } - Onboarding onboarding = createOnboarding(); - onboarding.setProductId("prod-pn"); - OnboardingWorkflow onboardingWorkflow = new OnboardingWorkflowAggregator(onboarding, "string"); + @Test + void loadContractPDF() { + final String contractFilepath = "contract"; + final String contractHtml = "contract"; - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + Onboarding onboarding = createOnboarding(); - contractService.uploadAggregatesCsv(onboardingWorkflow); + File pdf = + new File( + Objects.requireNonNull( + getClass().getClassLoader().getResource("application.properties")) + .getFile()); - Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); - } + Mockito.when(azureBlobClient.getFileAsPdf(contractFilepath)).thenReturn(pdf); - @Test - void uploadCsvAggregatesProductNotValid() { - Onboarding onboarding = createOnboarding(); - onboarding.setProductId("prod-interop"); - OnboardingWorkflow onboardingWorkflow = new OnboardingWorkflowAggregator(onboarding, "string"); + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); - Assertions.assertThrows( - IllegalArgumentException.class, - () -> contractService.uploadAggregatesCsv(onboardingWorkflow)); - } + assertNotNull( + contractService.loadContractPDF( + contractFilepath, onboarding.getId(), PRODUCT_NAME_EXAMPLE)); + } - @Test - void createContractPRV() { - // given - String contractFilepath = "contract"; - String contractHtml = "contract"; + @Test + void retrieveContractNotSigned() { - Onboarding onboarding = createOnboarding(); - User userManager = onboarding.getUsers().get(0); - UserResource manager = - createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); - onboarding.getInstitution().setInstitutionType(InstitutionType.PRV); - onboarding.setProductId("prod-pagopa"); + Onboarding onboarding = createOnboarding(); + OnboardingWorkflow onboardingWorkflow = new OnboardingWorkflowInstitution(); + onboardingWorkflow.setOnboarding(onboarding); - Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); - Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + File pdf = mock(File.class); + Mockito.when(azureBlobClient.getFileAsPdf(any())).thenReturn(pdf); - // when - File result = - contractService.createContractPDF( - contractFilepath, - onboarding, - manager, - List.of(), - PRODUCT_NAME_EXAMPLE, - PDF_FORMAT_FILENAME); + contractService.retrieveContractNotSigned(onboardingWorkflow, PRODUCT_NAME_EXAMPLE); - // then - assertNotNull(result); - Mockito.verify(azureBlobClient, Mockito.times(1)).getFileAsText(contractFilepath); - Mockito.verify(azureBlobClient, Mockito.times(1)).uploadFile(any(), any(), any()); - Mockito.verifyNoMoreInteractions(azureBlobClient); - } + ArgumentCaptor filepathActual = ArgumentCaptor.forClass(String.class); + Mockito.verify(azureBlobClient, times(1)).getFileAsPdf(filepathActual.capture()); + assertTrue(filepathActual.getValue().contains(onboarding.getId())); + assertTrue(filepathActual.getValue().contains(PRODUCT_NAME_EXAMPLE)); + } - private UserResource createUserResource() { - UserResource userResource = new UserResource(); - userResource.setId(UUID.randomUUID()); + @Test + void getLogoFile() { + Mockito.when(azureBlobClient.getFileAsText(any())).thenReturn("example"); - CertifiableFieldResourceOfstring resourceOfName = new CertifiableFieldResourceOfstring(); - resourceOfName.setCertification(CertifiableFieldResourceOfstring.CertificationEnum.NONE); - resourceOfName.setValue("name"); - userResource.setName(resourceOfName); + contractService.getLogoFile(); - CertifiableFieldResourceOfstring resourceOfSurname = new CertifiableFieldResourceOfstring(); - resourceOfSurname.setCertification(CertifiableFieldResourceOfstring.CertificationEnum.NONE); - resourceOfSurname.setValue("surname"); - userResource.setFamilyName(resourceOfSurname); - return userResource; - } + Mockito.verify(azureBlobClient, times(1)).getFileAsText(any()); + } + + @Test + void uploadCsvAggregatesIO() { + final String contractHtml = "contract"; + + OnboardingWorkflow onboardingWorkflow = createOnboardingWorkflowIO(); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + contractService.uploadAggregatesCsv(onboardingWorkflow); + + Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); + } + + @Test + void uploadCsvAggregatesPagoPa() { + final String contractHtml = "contract"; + + OnboardingWorkflow onboardingWorkflow = createOnboardingWorkflowPagoPa(); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + contractService.uploadAggregatesCsv(onboardingWorkflow); + + Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); + } + + @Test + void uploadCsvAggregatesProdPn() { + final String contractHtml = "contract"; + + OnboardingWorkflow onboardingWorkflow = createOnboardingWorkflowSend(); + + UserResource userResource = new UserResource(); + CertifiableFieldResourceOfstring name = new CertifiableFieldResourceOfstring(); + name.setValue("name"); + CertifiableFieldResourceOfstring familyName = new CertifiableFieldResourceOfstring(); + familyName.setValue("familyName"); + String fiscalCode = "fiscalCode"; + CertifiableFieldResourceOfstring email = new CertifiableFieldResourceOfstring(); + email.setValue("email"); + WorkContactResource workContactResource = new WorkContactResource(); + workContactResource.setEmail(email); + Map workContacts = new HashMap<>(); + workContacts.put("mailUuid", workContactResource); + userResource.setName(name); + userResource.setFamilyName(familyName); + userResource.setFiscalCode(fiscalCode); + userResource.setWorkContacts(workContacts); + + when(userRegistryApi.findByIdUsingGET(anyString(), any())) + .thenReturn(userResource); + + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + contractService.uploadAggregatesCsv(onboardingWorkflow); + + Mockito.verify(azureBlobClient, times(1)).uploadFile(any(), any(), any()); + } + + @Test + void uploadCsvAggregatesProductNotValid() { + Onboarding onboarding = createOnboarding(); + onboarding.setProductId("prod-interop"); + OnboardingWorkflow onboardingWorkflow = new OnboardingWorkflowAggregator(onboarding, "string"); + + Assertions.assertThrows( + IllegalArgumentException.class, + () -> contractService.uploadAggregatesCsv(onboardingWorkflow)); + } + + @Test + void createContractPRV() { + // given + String contractFilepath = "contract"; + String contractHtml = "contract"; + + Onboarding onboarding = createOnboarding(); + User userManager = onboarding.getUsers().get(0); + UserResource manager = + createDummyUserResource(userManager.getId(), userManager.getUserMailUuid()); + onboarding.getInstitution().setInstitutionType(InstitutionType.PRV); + onboarding.setProductId("prod-pagopa"); + + Mockito.when(azureBlobClient.getFileAsText(contractFilepath)).thenReturn(contractHtml); + Mockito.when(azureBlobClient.uploadFile(any(), any(), any())).thenReturn(contractHtml); + + // when + File result = + contractService.createContractPDF( + contractFilepath, + onboarding, + manager, + List.of(), + PRODUCT_NAME_EXAMPLE, + PDF_FORMAT_FILENAME); + + // then + assertNotNull(result); + Mockito.verify(azureBlobClient, Mockito.times(1)).getFileAsText(contractFilepath); + Mockito.verify(azureBlobClient, Mockito.times(1)).uploadFile(any(), any(), any()); + Mockito.verifyNoMoreInteractions(azureBlobClient); + } + + private UserResource createUserResource() { + UserResource userResource = new UserResource(); + userResource.setId(UUID.randomUUID()); + + CertifiableFieldResourceOfstring resourceOfName = new CertifiableFieldResourceOfstring(); + resourceOfName.setCertification(CertifiableFieldResourceOfstring.CertificationEnum.NONE); + resourceOfName.setValue("name"); + userResource.setName(resourceOfName); + + CertifiableFieldResourceOfstring resourceOfSurname = new CertifiableFieldResourceOfstring(); + resourceOfSurname.setCertification(CertifiableFieldResourceOfstring.CertificationEnum.NONE); + resourceOfSurname.setValue("surname"); + userResource.setFamilyName(resourceOfSurname); + return userResource; + } }