Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PRDP-255] feat: Refactored RegenerateReceiptPdf class #13

Merged
merged 5 commits into from
Dec 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion helm/values-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ microservice-chart:
envSecret:
APPLICATIONINSIGHTS_CONNECTION_STRING: "ai-d-connection-string"
COSMOS_RECEIPTS_CONN_STRING: "cosmos-receipt-connection-string"
RECEIPT_QUEUE_CONN_STRING: "receipts-storage-account-connection-string"
RECEIPT_QUEUE_CONN_STRING: "receipts-storage-account-connection-string",
RECEIPTS_STORAGE_CONN_STRING: "receipts-storage-account-connection-string",
COSMOS_BIZ_EVENT_CONN_STRING: "cosmos-biz-event-d-connection-string"
COSMOS_RECEIPT_KEY: "cosmos-receipt-pkey"
COSMOS_BIZ_EVENT_KEY: "cosmos-bizevent-pkey"
Expand Down
1 change: 1 addition & 0 deletions helm/values-prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ microservice-chart:
envSecret:
APPLICATIONINSIGHTS_CONNECTION_STRING: "ai-p-connection-string"
COSMOS_RECEIPTS_CONN_STRING: "cosmos-receipt-connection-string"
RECEIPTS_STORAGE_CONN_STRING: "receipts-storage-account-connection-string",
RECEIPT_QUEUE_CONN_STRING: "receipts-storage-account-connection-string"
COSMOS_BIZ_EVENT_CONN_STRING: "cosmos-biz-event-p-connection-string"
COSMOS_RECEIPT_KEY: "cosmos-receipt-pkey"
Expand Down
1 change: 1 addition & 0 deletions helm/values-uat.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ microservice-chart:
envSecret:
APPLICATIONINSIGHTS_CONNECTION_STRING: "ai-u-connection-string"
COSMOS_RECEIPTS_CONN_STRING: "cosmos-receipt-connection-string"
RECEIPTS_STORAGE_CONN_STRING: "receipts-storage-account-connection-string",
RECEIPT_QUEUE_CONN_STRING: "receipts-storage-account-connection-string"
COSMOS_BIZ_EVENT_CONN_STRING: "cosmos-biz-event-u-connection-string"
COSMOS_RECEIPT_KEY: "cosmos-receipt-pkey"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.microsoft.azure.functions.*;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.BindingName;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import it.gov.pagopa.receipt.pdf.helpdesk.client.BizEventCosmosClient;
Expand All @@ -13,15 +14,14 @@
import it.gov.pagopa.receipt.pdf.helpdesk.exception.BizEventNotFoundException;
import it.gov.pagopa.receipt.pdf.helpdesk.exception.ReceiptNotFoundException;
import it.gov.pagopa.receipt.pdf.helpdesk.model.PdfGeneration;
import it.gov.pagopa.receipt.pdf.helpdesk.model.request.RegenerateReceiptRequest;
import it.gov.pagopa.receipt.pdf.helpdesk.model.ProblemJson;
import it.gov.pagopa.receipt.pdf.helpdesk.service.GenerateReceiptPdfService;
import it.gov.pagopa.receipt.pdf.helpdesk.service.impl.GenerateReceiptPdfServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.util.NoSuchElementException;
import java.util.Optional;

import static it.gov.pagopa.receipt.pdf.helpdesk.utils.GenerateReceiptUtils.*;
Expand Down Expand Up @@ -63,26 +63,25 @@ public RegenerateReceiptPdf(){
@FunctionName("RegenerateReceiptPdf")
public HttpResponseMessage run (
@HttpTrigger(name = "RegenerateReceiptPdfTrigger",
methods = {HttpMethod.PUT},
route = "regenerateReceiptPdf",
methods = {HttpMethod.POST},
route = "/receipts/{bizevent-id}/regenerate-receipt-pdf",
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<RegenerateReceiptRequest>> request,
HttpRequestMessage<Optional<String>> request,
@BindingName("bizevent-id") String eventId,
final ExecutionContext context) {

try {

RegenerateReceiptRequest regenerateReceiptRequest = request.getBody().get();
if (eventId != null) {

if (regenerateReceiptRequest.getEventId() != null) {

BizEvent bizEvent = bizEventCosmosClient.getBizEventDocument(
regenerateReceiptRequest.getEventId());
BizEvent bizEvent = bizEventCosmosClient.getBizEventDocument(eventId);

//Retrieve receipt's data from CosmosDB
Receipt receipt = getReceipt(context, bizEvent, receiptCosmosClient, logger);


//Verify receipt status
if (receipt.getEventData() != null) {
if (receipt.getEventData() != null && isHasAllAttachments(receipt)) {

logger.info("[{}] Generating pdf for Receipt with id {} and bizEvent with id {}",
context.getFunctionName(),
Expand All @@ -102,11 +101,22 @@ public HttpResponseMessage run (
request.createResponseBuilder(HttpStatus.OK)
.body("OK")
.build() :
request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR).build();
request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ProblemJson.builder()
.title(HttpStatus.INTERNAL_SERVER_ERROR.name())
.detail("Receipt could not be updated with the new attachments")
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.build())
.build();

} catch (Exception e) {
logger.error(e.getMessage(), e);
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ProblemJson.builder()
.title(HttpStatus.INTERNAL_SERVER_ERROR.name())
.detail("Error during receipt generation: " + e.getMessage())
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.build())
.build();
} finally {
deleteTempFolder(workingDirPath, logger);
Expand All @@ -116,18 +126,55 @@ public HttpResponseMessage run (

}

return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ProblemJson.builder()
.title(HttpStatus.BAD_REQUEST.name())
.detail("Missing valid eventId paramater")
.status(HttpStatus.BAD_REQUEST.value())
.build())
.build();

} catch (NoSuchElementException | ReceiptNotFoundException | BizEventNotFoundException exception) {
} catch (ReceiptNotFoundException | BizEventNotFoundException exception) {
logger.error(exception.getMessage(), exception);
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
String message = "Missing required informations";
if (exception.getClass().equals(ReceiptNotFoundException.class)) {
message = "Receipt not found with event-id " + eventId;
} else if (exception.getClass().equals(BizEventNotFoundException.class)) {
message = "BizEvent not found with event-id " + eventId;
}
return request
.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ProblemJson.builder()
.title(HttpStatus.BAD_REQUEST.name())
.detail(message)
.status(HttpStatus.BAD_REQUEST.value())
.build())
.build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ProblemJson.builder()
.title(HttpStatus.INTERNAL_SERVER_ERROR.name())
.detail("Unexpected error while managing the receipt file")
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.build())
.build();
}
}

private static boolean isHasAllAttachments(Receipt receipt) {
String debtorCF = receipt.getEventData().getDebtorFiscalCode();
String payerCF = receipt.getEventData().getPayerFiscalCode();
boolean hasAllAttachments;
if (payerCF == null) {
hasAllAttachments = receipt.getMdAttach() != null && receipt.getMdAttach().getUrl() != null;
} else if (debtorCF.equals(payerCF)) {
hasAllAttachments = receipt.getMdAttach() != null && receipt.getMdAttach().getUrl() != null;
} else {
hasAllAttachments = receipt.getMdAttach() != null && receipt.getMdAttach().getUrl() != null &&
receipt.getMdAttachPayer() != null && receipt.getMdAttachPayer().getUrl() != null;
}
return hasAllAttachments;
}

}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package it.gov.pagopa.receipt.pdf.helpdesk.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import it.gov.pagopa.receipt.pdf.helpdesk.client.PdfEngineClient;
import it.gov.pagopa.receipt.pdf.helpdesk.client.ReceiptBlobClient;
import it.gov.pagopa.receipt.pdf.helpdesk.client.impl.PdfEngineClientImpl;
import it.gov.pagopa.receipt.pdf.helpdesk.client.impl.ReceiptBlobClientImpl;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.event.BizEvent;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.ReasonError;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.Receipt;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.ReceiptMetadata;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.enumeration.ReasonErrorCode;
Expand All @@ -31,10 +29,10 @@
import java.io.FileInputStream;
import java.net.URL;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

import static org.apache.http.HttpStatus.SC_OK;

public class GenerateReceiptPdfServiceImpl implements GenerateReceiptPdfService {

private final Logger logger = LoggerFactory.getLogger(GenerateReceiptPdfServiceImpl.class);
Expand Down Expand Up @@ -76,34 +74,23 @@ public PdfGeneration generateReceipts(Receipt receipt, BizEvent bizEvent, Path w
if (payerCF.equals(debtorCF)) {
pdfGeneration.setGenerateOnlyDebtor(true);
//Generate debtor's complete PDF
if (receiptAlreadyCreated(receipt.getMdAttach())) {
pdfGeneration.setDebtorMetadata(PdfMetadata.builder().statusCode(ALREADY_CREATED).build());
return pdfGeneration;
}
PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, PAYER_TEMPLATE_SUFFIX, false, workingDirPath);
PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, receipt.getMdAttach().getName(), false, workingDirPath);
pdfGeneration.setDebtorMetadata(generationResult);
return pdfGeneration;
}

//Generate payer's complete PDF
if (receiptAlreadyCreated(receipt.getMdAttachPayer())) {
pdfGeneration.setPayerMetadata(PdfMetadata.builder().statusCode(ALREADY_CREATED).build());
} else {
PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, receipt.getMdAttachPayer().getName(), false, workingDirPath);
pdfGeneration.setPayerMetadata(generationResult);

PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, PAYER_TEMPLATE_SUFFIX, false, workingDirPath);
pdfGeneration.setPayerMetadata(generationResult);
}
} else {
pdfGeneration.setGenerateOnlyDebtor(true);
}

//Generate debtor's partial PDF
if (receiptAlreadyCreated(receipt.getMdAttach())) {
pdfGeneration.setDebtorMetadata(PdfMetadata.builder().statusCode(ALREADY_CREATED).build());
} else {
PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, DEBTOR_TEMPLATE_SUFFIX, true, workingDirPath);
pdfGeneration.setDebtorMetadata(generationResult);
}
PdfMetadata generationResult = generateAndSavePDFReceipt(bizEvent, receipt.getMdAttach().getName(), true, workingDirPath);
pdfGeneration.setDebtorMetadata(generationResult);


return pdfGeneration;
}
Expand All @@ -120,20 +107,8 @@ public boolean verifyAndUpdateReceipt(Receipt receipt, PdfGeneration pdfGenerati
return false;
}

if (debtorMetadata.getStatusCode() == HttpStatus.SC_OK) {
ReceiptMetadata receiptMetadata = new ReceiptMetadata();
receiptMetadata.setName(debtorMetadata.getDocumentName());
receiptMetadata.setUrl(debtorMetadata.getDocumentUrl());

receipt.setMdAttach(receiptMetadata);
} else if (debtorMetadata.getStatusCode() != ALREADY_CREATED) {
ReasonError reasonError = new ReasonError(debtorMetadata.getStatusCode(), debtorMetadata.getErrorMessage());
receipt.setReasonErr(reasonError);
result = false;
}

if (pdfGeneration.isGenerateOnlyDebtor()) {
if (debtorMetadata.getStatusCode() == ReasonErrorCode.ERROR_TEMPLATE_PDF.getCode()) {
if (debtorMetadata.getStatusCode() != SC_OK) {
String errMsg = String.format("Debtor receipt generation fail with status %s", debtorMetadata.getStatusCode());
throw new ReceiptGenerationNotToRetryException(errMsg);
}
Expand All @@ -146,32 +121,18 @@ public boolean verifyAndUpdateReceipt(Receipt receipt, PdfGeneration pdfGenerati
return false;
}

if (payerMetadata.getStatusCode() == HttpStatus.SC_OK) {
ReceiptMetadata receiptMetadata = new ReceiptMetadata();
receiptMetadata.setName(payerMetadata.getDocumentName());
receiptMetadata.setUrl(payerMetadata.getDocumentUrl());

receipt.setMdAttachPayer(receiptMetadata);
} else if (payerMetadata.getStatusCode() != ALREADY_CREATED) {
ReasonError reasonErrorPayer = new ReasonError(payerMetadata.getStatusCode(), payerMetadata.getErrorMessage());
receipt.setReasonErrPayer(reasonErrorPayer);
result = false;
}

if (debtorMetadata.getStatusCode() == ReasonErrorCode.ERROR_TEMPLATE_PDF.getCode()
|| payerMetadata.getStatusCode() == ReasonErrorCode.ERROR_TEMPLATE_PDF.getCode()) {
if (debtorMetadata.getStatusCode() != SC_OK
|| payerMetadata.getStatusCode() != SC_OK) {
String errMsg = String.format("Receipt generation fail for debtor (status: %s) and/or payer (status: %s)",
debtorMetadata.getStatusCode(), payerMetadata.getStatusCode());
throw new ReceiptGenerationNotToRetryException(errMsg);
}
return result;
}

private PdfMetadata generateAndSavePDFReceipt(BizEvent bizEvent, String templateSuffix, boolean partialTemplate, Path workingDirPath) {
private PdfMetadata generateAndSavePDFReceipt(BizEvent bizEvent, String blobName, boolean partialTemplate, Path workingDirPath) {
try {
ReceiptPDFTemplate template = buildTemplateService.buildTemplate(bizEvent, partialTemplate);
String dateFormatted = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
String blobName = String.format("%s-%s-%s-%s", TEMPLATE_PREFIX, dateFormatted, bizEvent.getId(), templateSuffix);
PdfEngineResponse pdfEngineResponse = generatePDFReceipt(template, workingDirPath);
return saveToBlobStorage(pdfEngineResponse, blobName);
} catch (PDFReceiptGenerationException e) {
Expand Down Expand Up @@ -201,7 +162,7 @@ private PdfMetadata saveToBlobStorage(PdfEngineResponse pdfEngineResponse, Strin
return PdfMetadata.builder()
.documentName(blobStorageResponse.getDocumentName())
.documentUrl(blobStorageResponse.getDocumentUrl())
.statusCode(HttpStatus.SC_OK)
.statusCode(SC_OK)
.build();
}

Expand All @@ -216,7 +177,7 @@ private PdfEngineResponse generatePDFReceipt(ReceiptPDFTemplate template, Path w

PdfEngineResponse pdfEngineResponse = pdfEngineClient.generatePDF(request, workingDirPath);

if (pdfEngineResponse.getStatusCode() != HttpStatus.SC_OK) {
if (pdfEngineResponse.getStatusCode() != SC_OK) {
String errMsg = String.format("PDF-Engine response KO (%s): %s", pdfEngineResponse.getStatusCode(), pdfEngineResponse.getErrorMessage());
throw new GeneratePDFException(errMsg, pdfEngineResponse.getStatusCode());
}
Expand Down
Loading
Loading