Skip to content

Commit

Permalink
feat: refactor logic
Browse files Browse the repository at this point in the history
  • Loading branch information
gianmarcoplutino committed Nov 26, 2024
1 parent 22697ed commit 61754ba
Show file tree
Hide file tree
Showing 6 changed files with 224 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ public class OnboardingAttachment {
private Onboarding onboarding;
private AttachmentTemplate attachment;

public OnboardingAttachment() {}

private OnboardingAttachment(OnboardingAttachment.Builder builder) {
this.onboarding = builder.onboarding;
this.attachment = builder.attachment;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package it.pagopa.selfcare.onboarding.service;

import it.pagopa.selfcare.onboarding.entity.Onboarding;
import it.pagopa.selfcare.onboarding.entity.OnboardingAttachment;
import it.pagopa.selfcare.onboarding.entity.OnboardingWorkflow;
import org.openapi.quarkus.user_registry_json.model.UserResource;

Expand All @@ -24,6 +25,8 @@ File createAttachmentPDF(

File retrieveContractNotSigned(OnboardingWorkflow onboardingWorkflow, String productName);

File retrieveAttachment(OnboardingAttachment onboardingAttachment, String productName);

Optional<File> getLogoFile();

void uploadAggregatesCsv(OnboardingWorkflow onboardingWorkflow);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
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.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;
Expand Down Expand Up @@ -387,6 +384,16 @@ public File retrieveContractNotSigned(OnboardingWorkflow onboardingWorkflow, Str
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(onboardingAttachment.getAttachment().getName(), productName);
final String path =
String.format("%s%s/%s", azureStorageConfig.contractPath(), onboardingId, filename);
return azureBlobClient.getFileAsPdf(path);
}

@Override
public Optional<File> getLogoFile() {
if (Objects.nonNull(isLogoEnable) && isLogoEnable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,11 @@ public void saveTokenWithAttachment(OnboardingAttachment onboardingAttachment) {

Product product = productService.getProductIsValid(onboarding.getProductId());

saveTokenAttachment(onboardingAttachment, product);
File contract = contractService.retrieveAttachment(onboardingAttachment, product.getTitle());
DSSDocument document = new FileDocument(contract);
String digest = document.getDigest(DigestAlgorithm.SHA256);

saveTokenAttachment(onboardingAttachment, product, digest);
}

private boolean checkTokenExist(Onboarding onboarding) {
Expand All @@ -168,25 +172,25 @@ private void saveToken(OnboardingWorkflow onboardingWorkflow, Product product, S
Onboarding onboarding = onboardingWorkflow.getOnboarding();

// Persist token entity
Token token = buildBaseToken(onboarding);
Token token = buildBaseToken(onboarding, digest);
token.setContractTemplate(onboardingWorkflow.getContractTemplatePath(product));
token.setContractVersion(onboardingWorkflow.getContractTemplateVersion(product));
token.setContractFilename(
CONTRACT_FILENAME_FUNC.apply(
onboardingWorkflow.getPdfFormatFilename(), product.getTitle()));
token.setChecksum(digest);
token.setType(onboardingWorkflow.getTokenType());

tokenRepository.persist(token);
}

private void saveTokenAttachment(OnboardingAttachment onboardingAttachment, Product product) {
private void saveTokenAttachment(
OnboardingAttachment onboardingAttachment, Product product, String digest) {

Onboarding onboarding = onboardingAttachment.getOnboarding();
AttachmentTemplate attachmentTemplate = onboardingAttachment.getAttachment();

// Persist token entity
Token token = buildBaseToken(onboarding);
Token token = buildBaseToken(onboarding, digest);
token.setContractTemplate(attachmentTemplate.getTemplatePath());
token.setContractVersion(attachmentTemplate.getTemplateVersion());
token.setContractFilename(
Expand All @@ -196,13 +200,14 @@ private void saveTokenAttachment(OnboardingAttachment onboardingAttachment, Prod
tokenRepository.persist(token);
}

private Token buildBaseToken(Onboarding onboarding) {
private Token buildBaseToken(Onboarding onboarding, String digest) {
log.debug("creating Token for onboarding {} ...", onboarding.getId());
Token token = new Token();
token.setId(UUID.randomUUID().toString());
token.setOnboardingId(onboarding.getId());
token.setCreatedAt(LocalDateTime.now());
token.setUpdatedAt(LocalDateTime.now());
token.setChecksum(digest);
token.setProductId(onboarding.getProductId());
return token;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,6 @@
package it.pagopa.selfcare.onboarding.functions;

import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.BUILD_CONTRACT_ACTIVITY_NAME;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_AGGREGATES_CSV_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_AGGREGATE_ONBOARDING_REQUEST_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_DELEGATION_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_INSTITUTION_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_ONBOARDING_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.CREATE_USERS_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.DELETE_MANAGERS_BY_IC_AND_ADE;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.EXISTS_DELEGATION_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.ONBOARDINGS_AGGREGATE_ORCHESTRATOR;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.RETRIEVE_AGGREGATES_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SAVE_TOKEN_WITH_CONTRACT_ACTIVITY_NAME;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_COMPLETION_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_ONBOARDING_APPROVE_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_REGISTRATION_APPROVE_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_REGISTRATION_FOR_CONTRACT;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_REGISTRATION_FOR_CONTRACT_WHEN_APPROVE_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_REGISTRATION_REQUEST_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.SEND_MAIL_REJECTION_ACTIVITY;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.STORE_ONBOARDING_ACTIVATEDAT;
import static it.pagopa.selfcare.onboarding.functions.utils.ActivityName.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
Expand Down Expand Up @@ -86,8 +67,7 @@ class OnboardingFunctionsTest {

@InjectMock CompletionService completionService;

@InjectMock
ProductService productService;
@InjectMock ProductService productService;

@Inject ObjectMapper objectMapper;

Expand All @@ -96,6 +76,13 @@ class OnboardingFunctionsTest {
final String onboardingWorkflowString =
"{\"type\":\"INSTITUTION\",\"onboarding\":{\"id\":\"id\",\"productId\":\"prod-test\",\"testEnvProductIds\":null,\"workflowType\":\"FOR_APPROVE\",\"institution\":null,\"users\":null,\"aggregates\":null,\"pricingPlan\":null,\"billing\":null,\"signContract\":null,\"expiringDate\":null,\"status\":\"REQUEST\",\"userRequestUid\":null,\"workflowInstanceId\":null,\"createdAt\":null,\"updatedAt\":null,\"activatedAt\":null,\"deletedAt\":null,\"reasonForReject\":null,\"isAggregator\":null}}";

final String onboardingWorkflowString2 =
"{\"type\":\"INSTITUTION\",\"onboarding\":{\"id\":\"id\",\"productId\":\"prod-test\",\"testEnvProductIds\":null,\"workflowType\":\"CONTRACT_REGISTRATION\",\"institution\":null,\"users\":null,\"aggregates\":null,\"pricingPlan\":null,\"billing\":null,\"signContract\":null,\"expiringDate\":null,\"status\":\"REQUEST\",\"userRequestUid\":null,\"workflowInstanceId\":null,\"createdAt\":null,\"updatedAt\":null,\"activatedAt\":null,\"deletedAt\":null,\"reasonForReject\":null,\"isAggregator\":null}}";

final String onboardingAttachmentString =
"{\"onboarding\":{\"id\":\"id\",\"productId\":\"prod-test\",\"testEnvProductIds\":null,\"workflowType\":\"FOR_APPROVE\",\"institution\":null,\"users\":null,\"aggregates\":null,\"pricingPlan\":null,\"billing\":null,\"signContract\":null,\"expiringDate\":null,\"status\":\"REQUEST\",\"userRequestUid\":null,\"workflowInstanceId\":null,\"createdAt\":null,\"updatedAt\":null,\"activatedAt\":null,\"deletedAt\":null,\"reasonForReject\":null,\"isAggregator\":null},\"attachmentTemplate\":{"
+ "\"templatePath\": null, \"templateVersion\": null, \"name\": null, \"mandatory\": null, \"generated\": null, \"workflowType\": null, \"workflowState\": null, \"order\": null}}";

static ExecutionContext executionContext;

static {
Expand Down Expand Up @@ -671,7 +658,78 @@ void buildContract() {
}

@Test
void buildAttachmentsAndSaveTokensOrchestrator_invokeActivity() throws JsonProcessingException {
void buildAttachmentsAndSaveTokens_validBody_returnsAccepted() {
// Mock HttpRequestMessage with valid body
final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class);
doReturn(Optional.of(onboardingWorkflowString)).when(req).getBody();

doAnswer(
(Answer<HttpResponseMessage.Builder>)
invocation -> {
HttpStatus status = (HttpStatus) invocation.getArguments()[0];
return new HttpResponseMessageMock.HttpResponseMessageBuilderMock()
.status(status);
})
.when(req)
.createResponseBuilder(any(HttpStatus.class));

final ExecutionContext context = mock(ExecutionContext.class);
doReturn(Logger.getGlobal()).when(context).getLogger();

final DurableClientContext durableContext = mock(DurableClientContext.class);
final DurableTaskClient client = mock(DurableTaskClient.class);
final String instanceId = "instanceId123";

doReturn(client).when(durableContext).getClient();
doReturn(instanceId)
.when(client)
.scheduleNewOrchestrationInstance("BuildAttachmentAndSaveToken", onboardingWorkflowString);
when(durableContext.createCheckStatusResponse(req, instanceId))
.thenReturn(
new HttpResponseMessageMock.HttpResponseMessageBuilderMock()
.status(HttpStatus.ACCEPTED)
.build());

// Invoke
HttpResponseMessage responseMessage =
function.buildAttachmentsAndSaveTokens(req, durableContext, context);

// Verify
assertEquals(HttpStatus.ACCEPTED.value(), responseMessage.getStatusCode());
}

@Test
void buildAttachmentsAndSaveTokens_emptyBody_returnsBadRequest() {
// Mock HttpRequestMessage with empty body
final HttpRequestMessage<Optional<String>> req = mock(HttpRequestMessage.class);
doReturn(Optional.empty()).when(req).getBody();

doAnswer(
(Answer<HttpResponseMessage.Builder>)
invocation -> {
HttpStatus status = (HttpStatus) invocation.getArguments()[0];
return new HttpResponseMessageMock.HttpResponseMessageBuilderMock()
.status(status);
})
.when(req)
.createResponseBuilder(any(HttpStatus.class));

final ExecutionContext context = mock(ExecutionContext.class);
doReturn(Logger.getGlobal()).when(context).getLogger();

final DurableClientContext durableContext = mock(DurableClientContext.class);

// Invoke
HttpResponseMessage responseMessage =
function.buildAttachmentsAndSaveTokens(req, durableContext, context);

// Verify
assertEquals(HttpStatus.BAD_REQUEST.value(), responseMessage.getStatusCode());
assertEquals("Body can not be empty", responseMessage.getBody());
}

@Test
void buildAttachmentAndSaveToken_invokeActivity() throws JsonProcessingException {
// given
Product product = createDummyProduct();
when(productService.getProductIsValid(anyString())).thenReturn(product);
Expand All @@ -689,20 +747,51 @@ void buildAttachmentsAndSaveTokensOrchestrator_invokeActivity() throws JsonProce

// then
verify(productService, times(1)).getProductIsValid(anyString());
Mockito.verify(orchestrationContext, times(2))
.callActivity(any(), any(), any(), any());
Mockito.verify(orchestrationContext, times(2)).callActivity(any(), any(), any(), any());
}

// @Test
@Test
void buildAttachmentAndSaveToken_noAttachments_invokeActivity() throws JsonProcessingException {
// given
Product product = createDummyProduct();

when(productService.getProductIsValid(anyString())).thenReturn(product);

TaskOrchestrationContext orchestrationContext = mock(TaskOrchestrationContext.class);
when(orchestrationContext.getInput(String.class)).thenReturn(onboardingWorkflowString2);

Task task = mock(Task.class);
when(orchestrationContext.callActivity(any(), any(), any(), any())).thenReturn(task);
when(task.await()).thenReturn("false");
when(orchestrationContext.allOf(anyList())).thenReturn(task);

// when
function.buildAttachmentAndSaveToken(orchestrationContext, executionContext);

// then
verify(productService, times(1)).getProductIsValid(anyString());
}

@Test
void buildAttachment() {

doNothing().when(service).createAttachment(any());

function.buildAttachment(onboardingWorkflowString, executionContext);
function.buildAttachment(onboardingAttachmentString, executionContext);

verify(service, times(1)).createAttachment(any());
}

@Test
void saveTokenAttachment() {

doNothing().when(service).saveTokenWithAttachment(any());

function.saveTokenAttachment(onboardingAttachmentString, executionContext);

verify(service, times(1)).saveTokenWithAttachment(any());
}

@Test
void saveToken() {

Expand Down
Loading

0 comments on commit 61754ba

Please sign in to comment.