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-324] feat: origin check when setting payer fiscal code on receipt #54

Merged
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
1 change: 1 addition & 0 deletions helm/values-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ microservice-chart:
PDV_TOKENIZER_MULTIPLIER: "2.0"
PDV_TOKENIZER_RANDOMIZATION_FACTOR: "0.6"
PDV_TOKENIZER_MAX_RETRIES: "3"
LIST_VALID_ORIGINS: "IO"
ENABLE_ECS_CONSOLE: "true"
CONSOLE_LOG_THRESHOLD: "DEBUG"
CONSOLE_LOG_PATTERN: "%d{HH:mm:ss.SSS}[%thread]%-5level%logger{36}-%msg%n"
Expand Down
5 changes: 3 additions & 2 deletions helm/values-prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ microservice-chart:
PDV_TOKENIZER_MULTIPLIER: "2.0"
PDV_TOKENIZER_RANDOMIZATION_FACTOR: "0.6"
PDV_TOKENIZER_MAX_RETRIES: "3"
LIST_VALID_ORIGINS: "IO"
ENABLE_ECS_CONSOLE: "true"
CONSOLE_LOG_THRESHOLD: "DEBUG"
CONSOLE_LOG_PATTERN: "%d{HH:mm:ss.SSS}[%thread]%-5level%logger{36}-%msg%n"
Expand All @@ -112,8 +113,8 @@ microservice-chart:
MAX_DATE_DIFF_MILLIS: "1800000" # 30min
MAX_DATE_DIFF_NOTIFY_MILLIS: "1800000" # 30nin
MAX_DATE_DIFF_CART_MILLIS: "1800000" # 30nin
TRIGGER_NOTIFY_REC_SCHEDULE: "0 */15 * * * *"
RECOVER_FAILED_CRON: "0 */15 * * * *"
TRIGGER_NOTIFY_REC_SCHEDULE: "0 */25 * * * *"
RECOVER_FAILED_CRON: "0 */30 * * * *"
RECOVER_FAILED_CART_CRON: "0 0 */1 * * *"
AZURE_FUNCTIONS_MESH_JAVA_OPTS: "-javaagent:/home/site/wwwroot/jmx_prometheus_javaagent-0.19.0.jar=12345:/home/site/wwwroot/config.yaml -javaagent:/home/site/wwwroot/opentelemetry-javaagent.jar -Xmx768m -XX:+UseG1GC"
FAILED_AUTORECOVER_ENABLED: "true"
Expand Down
1 change: 1 addition & 0 deletions helm/values-uat.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ microservice-chart:
PDV_TOKENIZER_RANDOMIZATION_FACTOR: "0.6"
PDV_TOKENIZER_MAX_RETRIES: "3"
ENABLE_ECS_CONSOLE: "true"
LIST_VALID_ORIGINS;: "IO"
CONSOLE_LOG_THRESHOLD: "DEBUG"
CONSOLE_LOG_PATTERN: "%d{HH:mm:ss.SSS}[%thread]%-5level%logger{36}-%msg%n"
CONSOLE_LOG_CHARSET: "UTF-8"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,11 @@ public RecoverFailedCart(){
/**
* This function will be invoked when a Http Trigger occurs.
* <p>
* It recovers the receipt with the specified biz event id that has the following status:
* - ({@link ReceiptStatusType#INSERTED})
* - ({@link ReceiptStatusType#FAILED})
* - ({@link ReceiptStatusType#NOT_QUEUE_SENT})
* It recovers the cart receipt with the specified cart id that has the following status:
* - ({@link CartStatusType#INSERTED})
* - ({@link CartStatusType#FAILED})
* <p>
* It creates the receipts if not exist and send on queue the event in order to proceed with the receipt generation.
* It creates the cart rekated receipt if not exist and send on queue the event in order to proceed with the receipt generation.
*
* @return response with {@link HttpStatus#OK} if the operation succeeded
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.List;
import java.util.Optional;

import static it.gov.pagopa.receipt.pdf.helpdesk.utils.BizEventToReceiptUtils.isFromAuthenticatedOrigin;
import static it.gov.pagopa.receipt.pdf.helpdesk.utils.GenerateReceiptUtils.*;


Expand Down Expand Up @@ -119,7 +120,8 @@ && isHasAllAttachments(receipt)
try {

if (receipt.getEventData().getDebtorFiscalCode() == null ||
receipt.getEventData().getPayerFiscalCode() == null) {
(receipt.getEventData().getPayerFiscalCode() == null
&& isFromAuthenticatedOrigin(bizEvent))) {
BizEventToReceiptUtils.tokenizeReceipt(bizEventToReceiptService, isCart ?
listBizEvent : Collections.singletonList(bizEvent), receipt);
documentdb.setValue(receipt);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.enumeration.ReasonErrorCode;
import it.gov.pagopa.receipt.pdf.helpdesk.entity.receipt.enumeration.ReceiptStatusType;
import it.gov.pagopa.receipt.pdf.helpdesk.exception.PDVTokenizerException;
import it.gov.pagopa.receipt.pdf.helpdesk.exception.PdfJsonMappingException;
import it.gov.pagopa.receipt.pdf.helpdesk.service.BizEventToReceiptService;
import it.gov.pagopa.receipt.pdf.helpdesk.service.PDVTokenizerServiceRetryWrapper;
import it.gov.pagopa.receipt.pdf.helpdesk.utils.ObjectMapperUtils;
Expand All @@ -31,8 +32,7 @@
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static it.gov.pagopa.receipt.pdf.helpdesk.utils.BizEventToReceiptUtils.getAmount;
import static it.gov.pagopa.receipt.pdf.helpdesk.utils.BizEventToReceiptUtils.getItemSubject;
import static it.gov.pagopa.receipt.pdf.helpdesk.utils.BizEventToReceiptUtils.*;

public class BizEventToReceiptServiceImpl implements BizEventToReceiptService {

Expand Down Expand Up @@ -130,17 +130,22 @@ public void tokenizeFiscalCodes(BizEvent bizEvent, Receipt receipt, EventData ev
if (bizEvent.getDebtor() != null && bizEvent.getDebtor().getEntityUniqueIdentifierValue() != null) {
eventData.setDebtorFiscalCode("ANONIMO".equals(bizEvent.getDebtor().getEntityUniqueIdentifierValue()) ?
bizEvent.getDebtor().getEntityUniqueIdentifierValue() :
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(bizEvent.getDebtor().getEntityUniqueIdentifierValue())
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(
bizEvent.getDebtor().getEntityUniqueIdentifierValue())
);
}
if (bizEvent.getPayer() != null && bizEvent.getPayer().getEntityUniqueIdentifierValue() != null) {
if (bizEvent.getPayer() != null && bizEvent.getPayer().getEntityUniqueIdentifierValue() != null
&& isFromAuthenticatedOrigin(bizEvent)) {
eventData.setPayerFiscalCode(
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(bizEvent.getPayer().getEntityUniqueIdentifierValue())
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(
bizEvent.getPayer().getEntityUniqueIdentifierValue())
);
} else if (bizEvent.getTransactionDetails() != null && bizEvent.getTransactionDetails().getUser() != null &&
bizEvent.getTransactionDetails().getUser().getFiscalCode() != null) {
} else if (bizEvent.getTransactionDetails() != null && bizEvent.getTransactionDetails().getUser() != null
&& bizEvent.getTransactionDetails().getUser().getFiscalCode() != null
&& isFromAuthenticatedOrigin(bizEvent)) {
eventData.setPayerFiscalCode(
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(bizEvent.getTransactionDetails().getUser().getFiscalCode())
pdvTokenizerService.generateTokenForFiscalCodeWithRetry(
bizEvent.getTransactionDetails().getUser().getFiscalCode())
);
}
} catch (PDVTokenizerException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand All @@ -37,6 +34,12 @@ public class BizEventToReceiptUtils {

private static final String REMITTANCE_INFORMATION_REGEX = "/TXT/(.*)";

private static final List<String> listOrigin;

static {
listOrigin = Arrays.asList(System.getenv().getOrDefault("LIST_VALID_ORIGINS", "IO").split(","));
}

public static Receipt getEvent(
String eventId,
ExecutionContext context,
Expand Down Expand Up @@ -420,5 +423,16 @@ public static BigDecimal formatAmount(long grandTotal) {
return amount.divide(divider, 2, RoundingMode.UNNECESSARY);
}

public static boolean isFromAuthenticatedOrigin(BizEvent bizEvent) {
return bizEvent.getTransactionDetails() != null &&
((bizEvent.getTransactionDetails().getTransaction() != null &&
bizEvent.getTransactionDetails().getTransaction().getOrigin() != null &&
listOrigin.contains(bizEvent.getTransactionDetails().getTransaction().getOrigin())) ||
(bizEvent.getTransactionDetails().getInfo() != null &&
bizEvent.getTransactionDetails().getInfo().getClientId() != null &&
listOrigin.contains(bizEvent.getTransactionDetails().getInfo().getClientId())
));
}

private BizEventToReceiptUtils() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,7 @@ private BizEvent generateValidBizEvent(String totalNotice){
Transaction transaction = new Transaction();
transaction.setCreationDate(String.valueOf(LocalDateTime.now()));
transactionDetails.setTransaction(transaction);
transaction.setOrigin("IO");

PaymentInfo paymentInfo = new PaymentInfo();
paymentInfo.setTotalNotice(totalNotice);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,6 @@ public void releaseMocks() throws Exception {
void requestOnValidBizEventShouldCreateRequest() {
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE))
.thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE);
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE))
.thenReturn(TOKENIZED_PAYER_FISCAL_CODE);

Response<SendMessageResult> queueResponse = mock(Response.class);
when(queueResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value());
Expand Down Expand Up @@ -130,7 +128,6 @@ void requestOnValidBizEventShouldCreateRequest() {
Receipt captured = receiptCaptor.getValue();
assertEquals(ReceiptStatusType.INSERTED, captured.getStatus());
assertEquals(EVENT_ID, captured.getEventId());
assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode());
assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode());
assertNotNull(captured.getEventData().getCart());
assertEquals(1, captured.getEventData().getCart().size());
Expand All @@ -141,8 +138,6 @@ void requestOnValidBizEventShouldCreateRequest() {
void requestOnValidCartShouldCreateRequest() {
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE))
.thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE);
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE))
.thenReturn(TOKENIZED_PAYER_FISCAL_CODE);

Response<SendMessageResult> queueResponse = mock(Response.class);
when(queueResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value());
Expand Down Expand Up @@ -175,7 +170,6 @@ void requestOnValidCartShouldCreateRequest() {
Receipt captured = receiptCaptor.getValue();
assertEquals(ReceiptStatusType.INSERTED, captured.getStatus());
assertEquals(EVENT_ID, captured.getEventId());
assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode());
assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode());
assertNotNull(captured.getEventData().getCart());
assertEquals(1, captured.getEventData().getCart().size());
Expand Down Expand Up @@ -300,8 +294,6 @@ void requestOnValidCartAndFailedReceiptShouldResend() throws BizEventNotFoundExc
void requestOnValidBizEventAndFailedReceiptWithoutEventDataShouldUpdateWithToken() {
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE))
.thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE);
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE))
.thenReturn(TOKENIZED_PAYER_FISCAL_CODE);

Response<SendMessageResult> queueResponse = mock(Response.class);
when(queueResponse.getStatusCode()).thenReturn(HttpStatus.CREATED.value());
Expand Down Expand Up @@ -331,7 +323,6 @@ void requestOnValidBizEventAndFailedReceiptWithoutEventDataShouldUpdateWithToken
Receipt captured = receiptCaptor.getValue();
assertEquals(ReceiptStatusType.INSERTED, captured.getStatus());
assertEquals(EVENT_ID, captured.getEventId());
assertEquals(TOKENIZED_PAYER_FISCAL_CODE, captured.getEventData().getPayerFiscalCode());
assertEquals(TOKENIZED_DEBTOR_FISCAL_CODE, captured.getEventData().getDebtorFiscalCode());
assertNotNull(captured.getEventData().getCart());
assertEquals(1, captured.getEventData().getCart().size());
Expand Down Expand Up @@ -517,8 +508,6 @@ void errorTokenizingFiscalCodes() {
void errorAddingMessageToQueue() {
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(DEBTOR_FISCAL_CODE))
.thenReturn(TOKENIZED_DEBTOR_FISCAL_CODE);
when(pdvTokenizerServiceMock.generateTokenForFiscalCodeWithRetry(PAYER_FISCAL_CODE))
.thenReturn(TOKENIZED_PAYER_FISCAL_CODE);

Response<SendMessageResult> queueResponse = mock(Response.class);
when(queueResponse.getStatusCode()).thenReturn(HttpStatus.FORBIDDEN.value());
Expand Down Expand Up @@ -551,6 +540,7 @@ private BizEvent generateValidBizEvent(String totalNotice){
Transaction transaction = new Transaction();
transaction.setCreationDate(String.valueOf(LocalDateTime.now()));
transactionDetails.setTransaction(transaction);
transactionDetails.setOrigin("INFO");

PaymentInfo paymentInfo = new PaymentInfo();
paymentInfo.setTotalNotice(totalNotice);
Expand All @@ -572,6 +562,7 @@ private BizEvent generateValidBizEventWithTDetails(String totalNotice){
debtor.setEntityUniqueIdentifierValue(DEBTOR_FISCAL_CODE);

TransactionDetails transactionDetails = new TransactionDetails();
transactionDetails.setInfo(InfoTransaction.builder().clientId("IO").build());
Transaction transaction = new Transaction();
transaction.setCreationDate(String.valueOf(LocalDateTime.now()));
transactionDetails.setTransaction(transaction);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class RegenerateReceiptPdfTest {

static {
try {
bizEvent = ObjectMapperUtils.mapString("{\"id\":\"variant062-a330-4210-9c67-465b7d641aVS\",\"version\":\"2\",\"idPaymentManager\":null,\"complete\":\"false\",\"receiptId\":\"9a9bad2caf604b86a339476373c659b0\",\"missingInfo\":[\"idPaymentManager\",\"psp.pspPartitaIVA\",\"paymentInfo.primaryCiIncurredFee\",\"paymentInfo.idBundle\",\"paymentInfo.idCiBundle\",\"paymentInfo.metadata\"],\"debtorPosition\":{\"modelType\":\"2\",\"noticeNumber\":\"302119891614290410\",\"iuv\":\"02119891614290410\"},\"creditor\":{\"idPA\":\"66666666666\",\"idBrokerPA\":\"66666666666\",\"idStation\":\"66666666666_01\",\"companyName\":\"PA paolo\",\"officeName\":\"office PA\"},\"psp\":{\"idPsp\":\"60000000001\",\"idBrokerPsp\":\"60000000001\",\"idChannel\":\"60000000001_01\",\"psp\":\"PSP Paolo\",\"pspPartitaIVA\":null,\"pspFiscalCode\":\"CF60000000006\",\"channelDescription\":\"app\"},\"debtor\":{\"fullName\":\"John Doe\",\"entityUniqueIdentifierType\":\"F\",\"entityUniqueIdentifierValue\":\"JHNDOE00A01F205N\",\"streetName\":\"street\",\"civicNumber\":\"12\",\"postalCode\":\"89020\",\"city\":\"city\",\"stateProvinceRegion\":\"MI\",\"country\":\"IT\",\"eMail\":\"[email protected]\"},\"payer\":{\"fullName\":\"John Doe\",\"entityUniqueIdentifierType\":\"F\",\"entityUniqueIdentifierValue\":\"JHNDOE00A01F205N\",\"streetName\":\"street\",\"civicNumber\":\"12\",\"postalCode\":\"89020\",\"city\":\"city\",\"stateProvinceRegion\":\"MI\",\"country\":\"IT\",\"eMail\":\"[email protected]\"},\"paymentInfo\":{\"paymentDateTime\":\"2023-04-12T16:21:39.022486\",\"applicationDate\":\"2021-10-01\",\"transferDate\":\"2021-10-02\",\"dueDate\":\"2021-07-31\",\"paymentToken\":\"9a9bad2caf604b86a339476373c659b0\",\"amount\":\"7000\",\"fee\":\"200\",\"primaryCiIncurredFee\":null,\"idBundle\":null,\"idCiBundle\":null,\"totalNotice\":\"1\",\"paymentMethod\":\"creditCard\",\"touchpoint\":\"app\",\"remittanceInformation\":\"TARI 2021\",\"description\":\"TARI 2021\",\"metadata\":null},\"transferList\":[{\"idTransfer\":\"1\",\"fiscalCodePA\":\"77777777777\",\"companyName\":\"Pa Salvo\",\"amount\":\"7000\",\"transferCategory\":\"0101101IM\",\"remittanceInformation\":\"TARI Comune EC_TE\",\"metadata\":null,\"mbdattachment\":null,\"iban\":\"IT96R0123454321000000012345\"}],\"transactionDetails\":{\"transaction\":{\"psp\":{\"businessName\":\"Nexi\"}},\"wallet\":{\"info\":{\"brand\":\"MASTER\"}}},\"timestamp\":1686919660002,\"properties\":{},\"eventStatus\":\"DONE\",\"eventRetryEnrichmentCount\":0,\"eventTriggeredBySchedule\":false,\"eventErrorMessage\":null}",BizEvent.class);
bizEvent = ObjectMapperUtils.mapString("{\"id\":\"variant062-a330-4210-9c67-465b7d641aVS\",\"version\":\"2\",\"idPaymentManager\":null,\"complete\":\"false\",\"receiptId\":\"9a9bad2caf604b86a339476373c659b0\",\"missingInfo\":[\"idPaymentManager\",\"psp.pspPartitaIVA\",\"paymentInfo.primaryCiIncurredFee\",\"paymentInfo.idBundle\",\"paymentInfo.idCiBundle\",\"paymentInfo.metadata\"],\"debtorPosition\":{\"modelType\":\"2\",\"noticeNumber\":\"302119891614290410\",\"iuv\":\"02119891614290410\"},\"creditor\":{\"idPA\":\"66666666666\",\"idBrokerPA\":\"66666666666\",\"idStation\":\"66666666666_01\",\"companyName\":\"PA paolo\",\"officeName\":\"office PA\"},\"psp\":{\"idPsp\":\"60000000001\",\"idBrokerPsp\":\"60000000001\",\"idChannel\":\"60000000001_01\",\"psp\":\"PSP Paolo\",\"pspPartitaIVA\":null,\"pspFiscalCode\":\"CF60000000006\",\"channelDescription\":\"app\"},\"debtor\":{\"fullName\":\"John Doe\",\"entityUniqueIdentifierType\":\"F\",\"entityUniqueIdentifierValue\":\"JHNDOE00A01F205N\",\"streetName\":\"street\",\"civicNumber\":\"12\",\"postalCode\":\"89020\",\"city\":\"city\",\"stateProvinceRegion\":\"MI\",\"country\":\"IT\",\"eMail\":\"[email protected]\"},\"payer\":{\"fullName\":\"John Doe\",\"entityUniqueIdentifierType\":\"F\",\"entityUniqueIdentifierValue\":\"JHNDOE00A01F205N\",\"streetName\":\"street\",\"civicNumber\":\"12\",\"postalCode\":\"89020\",\"city\":\"city\",\"stateProvinceRegion\":\"MI\",\"country\":\"IT\",\"eMail\":\"[email protected]\"},\"paymentInfo\":{\"paymentDateTime\":\"2023-04-12T16:21:39.022486\",\"applicationDate\":\"2021-10-01\",\"transferDate\":\"2021-10-02\",\"dueDate\":\"2021-07-31\",\"paymentToken\":\"9a9bad2caf604b86a339476373c659b0\",\"amount\":\"7000\",\"fee\":\"200\",\"primaryCiIncurredFee\":null,\"idBundle\":null,\"idCiBundle\":null,\"totalNotice\":\"1\",\"paymentMethod\":\"creditCard\",\"touchpoint\":\"app\",\"remittanceInformation\":\"TARI 2021\",\"description\":\"TARI 2021\",\"metadata\":null},\"transferList\":[{\"idTransfer\":\"1\",\"fiscalCodePA\":\"77777777777\",\"companyName\":\"Pa Salvo\",\"amount\":\"7000\",\"transferCategory\":\"0101101IM\",\"remittanceInformation\":\"TARI Comune EC_TE\",\"metadata\":null,\"mbdattachment\":null,\"iban\":\"IT96R0123454321000000012345\"}],\"transactionDetails\":{\"transaction\":{\"origin\":\"IO\",\"psp\":{\"businessName\":\"Nexi\"}},\"wallet\":{\"info\":{\"brand\":\"MASTER\"}}},\"timestamp\":1686919660002,\"properties\":{},\"eventStatus\":\"DONE\",\"eventRetryEnrichmentCount\":0,\"eventTriggeredBySchedule\":false,\"eventErrorMessage\":null}",BizEvent.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
Expand Down
Loading
Loading