Skip to content

Commit

Permalink
Ppantt 151 rework taxonomy query (#510)
Browse files Browse the repository at this point in the history
Co-authored-by: Pasquale Spica <[email protected]>
Co-authored-by: pagopa-github-bot <[email protected]>
Co-authored-by: gioelemella <[email protected]>
  • Loading branch information
4 people authored Oct 10, 2024
1 parent 63bf630 commit 9c143a2
Show file tree
Hide file tree
Showing 13 changed files with 170 additions and 53 deletions.
4 changes: 2 additions & 2 deletions helm/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ apiVersion: v2
name: pagopa-selfcare-ms-backoffice
description: Microservice that manage api keys for pagopa product from selfcare
type: application
version: 0.405.0
appVersion: "2.25.0-5-next"
version: 0.409.0
appVersion: "2.26.3"
dependencies:
- name: microservice-chart
version: 2.4.0
Expand Down
2 changes: 1 addition & 1 deletion helm/values-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-selfcare-ms-backoffice-backend
tag: "2.25.0-5-next"
tag: "2.26.3"
pullPolicy: Always
livenessProbe:
httpGet:
Expand Down
2 changes: 1 addition & 1 deletion helm/values-prod.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-selfcare-ms-backoffice-backend
tag: "2.25.0-5-next" #improve
tag: "2.26.3" #improve
pullPolicy: Always
livenessProbe:
httpGet:
Expand Down
2 changes: 1 addition & 1 deletion helm/values-uat.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ microservice-chart:
fullnameOverride: ""
image:
repository: ghcr.io/pagopa/pagopa-selfcare-ms-backoffice-backend
tag: "2.25.0-5-next" #improve
tag: "2.26.3" #improve
pullPolicy: Always
livenessProbe:
httpGet:
Expand Down
2 changes: 1 addition & 1 deletion openapi/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "Microservice to manage PagoPA Backoffice",
"termsOfService": "https://www.pagopa.gov.it/",
"title": "SelfCare Backoffice",
"version": "2.25.0-5-next"
"version": "2.26.3"
},
"servers": [
{
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<version>2.5.14</version>
</parent>
<artifactId>pagopa-selfcare-ms-backoffice</artifactId>
<version>2.25.0-5-next</version>
<version>2.26.3</version>
<name>SelfCare Backoffice</name>
<description>Microservice to manage PagoPA Backoffice</description>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ public interface AuthorizerConfigClient {

@DeleteMapping(value = "/authorizations/{authorization-id}")
void deleteAuthorization(@PathVariable("authorization-id") String authorizationId);

@PutMapping(value = "/authorizations/{authorization-id}", produces = MediaType.APPLICATION_JSON_VALUE)
@Valid
Authorization updateAuthorization(
@PathVariable("authorization-id") String authorizationId,
@RequestBody Authorization authorization
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import java.time.Instant;
import java.util.List;
import java.util.regex.Pattern;

public interface TaxonomyRepository extends MongoRepository<TaxonomyEntity, String> {

Expand All @@ -17,7 +18,7 @@ public interface TaxonomyRepository extends MongoRepository<TaxonomyEntity, Stri
" ]}")
List<TaxonomyEntity> searchTaxonomies(String ec, String macroArea, String code, Boolean valid, Instant now);

List<TaxonomyEntity> findBySpecificBuiltInDataIn(List<String> codes);
List<TaxonomyEntity> findBySpecificBuiltInDataIn(List<Pattern> codes);


}
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,8 @@ public void updateBrokerAuthorizerSegregationCodesMetadata(
apiKeys.parallelStream().forEach(
apiKey -> {
String prefixId = apiKey.getId().split("-")[0] + "-";
updateAuthorizerConfigMetadata(institutionId, prefixId, ciSegregationCodes, true);
updateAuthorizerConfigMetadata(institutionId, prefixId, ciSegregationCodes, false);
updateAuthorizerConfigMetadata(institutionId, prefixId, ciSegregationCodes, true, apiKey.getPrimaryKey());
updateAuthorizerConfigMetadata(institutionId, prefixId, ciSegregationCodes, false, apiKey.getSecondaryKey());
}
);
}
Expand All @@ -311,25 +311,28 @@ private void updateAuthorization(
.orElseThrow(() -> new AppException(AppError.APIM_KEY_NOT_FOUND, institutionId));

Subscription subscription = Subscription.fromPrefix(subscriptionPrefixId);
InstitutionResponse institution = getInstitutionResponse(institutionId);
DelegationInfo delegationInfoResponse = getDelegationInfo(institutionId, subscription.getAuthDelegations(), institution.getTaxCode());
String subKey = isPrimaryKey ? apiKeys.getPrimaryKey() : apiKeys.getSecondaryKey();
Authorization authorization;
try {
String authorizationId = createAuthorizationId(subscriptionPrefixId, institutionId, isPrimaryKey);
authorization = this.authorizerConfigClient.getAuthorization(authorizationId);

authorization.setSubscriptionKey(isPrimaryKey ? apiKeys.getPrimaryKey() : apiKeys.getSecondaryKey());

InstitutionResponse institution = getInstitutionResponse(institutionId);
DelegationInfo delegationInfoResponse = getDelegationInfo(institutionId, subscription.getAuthDelegations(), institution.getTaxCode());

authorization.setSubscriptionKey(subKey);
authorization.setAuthorizedEntities(getAuthorizationEntities(institution, delegationInfoResponse.delegationResponse));
authorization.setOtherMetadata(getAuthorizationMetadataList(delegationInfoResponse.ciSegregationCodes, authorization.getOtherMetadata()));

this.authorizerConfigClient.deleteAuthorization(authorization.getId());
this.authorizerConfigClient.createAuthorization(authorization);
} catch (FeignException.NotFound e) {
log.error("An error occurred while updating API key authorizer configuration for institution {} and subscription {}, proceed to recreate the API key",
sanitizeLogParam(institutionId), sanitizeLogParam(subscription.getDisplayName()), e);
createSubscriptionKeys(institutionId, subscription);
log.error("{} key authorizer configuration for institution {} and subscription {} not found, proceed to recreate the configuration",
isPrimaryKey ? PRIMARY : SECONDARY,
sanitizeLogParam(institutionId),
sanitizeLogParam(subscription.getDisplayName()),
e);
authorization = buildAuthorization(subscription, subKey, institution, isPrimaryKey, delegationInfoResponse);
this.authorizerConfigClient.createAuthorization(authorization);
}

}
Expand Down Expand Up @@ -433,21 +436,26 @@ private void updateAuthorizerConfigMetadata(
String institutionId,
String prefixId,
CreditorInstitutionStationSegregationCodesList ciSegregationCodes,
boolean isPrimaryKey
boolean isPrimaryKey,
String subKey
) {
Subscription subscription = Subscription.fromPrefix(prefixId);
Authorization authorization;
String authorizationId = createAuthorizationId(prefixId, institutionId, isPrimaryKey);
try {
String authorizationId = createAuthorizationId(prefixId, institutionId, isPrimaryKey);
Authorization authorization = this.authorizerConfigClient.getAuthorization(authorizationId);

authorization = this.authorizerConfigClient.getAuthorization(authorizationId);
authorization.setOtherMetadata(getAuthorizationMetadataList(ciSegregationCodes, authorization.getOtherMetadata()));

this.authorizerConfigClient.deleteAuthorization(authorization.getId());
this.authorizerConfigClient.createAuthorization(authorization);
this.authorizerConfigClient.updateAuthorization(authorizationId, authorization);
} catch (FeignException.NotFound e) {
log.error("An error occurred while updating API key authorizer configuration for institution {} and subscription {}, proceed to recreate the API key",
sanitizeLogParam(institutionId), sanitizeLogParam(subscription.getDisplayName()), e);
createSubscriptionKeys(institutionId, subscription);
log.error("{} key authorizer configuration for institution {} and subscription {} not found, proceed to recreate the configuration",
isPrimaryKey ? PRIMARY : SECONDARY,
sanitizeLogParam(institutionId),
sanitizeLogParam(subscription.getDisplayName()),
e);
InstitutionResponse institution = getInstitutionResponse(institutionId);
DelegationInfo delegationInfoResponse = getDelegationInfo(institutionId, subscription.getAuthDelegations(), institution.getTaxCode());
authorization = buildAuthorization(subscription, subKey, institution, isPrimaryKey, delegationInfoResponse);
this.authorizerConfigClient.createAuthorization(authorization);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
import java.util.Objects;
import java.util.Optional;

import static it.pagopa.selfcare.pagopa.backoffice.util.Utility.sanitizeLogParam;

@Slf4j
@Service
public class CreditorInstitutionService {
Expand Down Expand Up @@ -130,10 +132,10 @@ public AvailableCodes getCreditorInstitutionSegregationCodes(String ciTaxCode, S
* Check if the provided tax code is a creditor institution tax code and if so, associates it to the given station and
* updates the authorizer config for each broker's api keys by adding the specified segregation code
*
* @param ciTaxCode creditor institution's tax code
* @param ciTaxCode creditor institution's tax code
* @param institutionId broker's institution id
* @param brokerTaxCode broker's tax code
* @param dto creditor institution - station association info
* @param dto creditor institution - station association info
* @return the creditor institution - station association info
*/
public CreditorInstitutionStationEditResource associateStationToCreditorInstitution(
Expand All @@ -148,7 +150,8 @@ public CreditorInstitutionStationEditResource associateStationToCreditorInstitut
try {
this.apiManagementService.updateBrokerAuthorizerSegregationCodesMetadata(institutionId, brokerTaxCode);
} catch (Exception e) {
log.error("Failed to update broker API key authorizations, revert associate station to CI operation");
log.error("Failed to update broker {} API key authorizations, revert associate station to CI operation",
sanitizeLogParam(brokerTaxCode), e);
this.apiConfigClient.deleteCreditorInstitutionStationRelationship(ciTaxCode, ecStation.getStationCode());
throw e;
}
Expand All @@ -162,7 +165,7 @@ public CreditorInstitutionStationEditResource associateStationToCreditorInstitut
* station with the provided info
*
* @param ciTaxCode creditor institution's tax code
* @param dto creditor institution - station association info
* @param dto creditor institution - station association info
* @return the updated creditor institution - station association info
*/
public CreditorInstitutionStationEditResource updateStationAssociationToCreditorInstitution(
Expand All @@ -181,7 +184,7 @@ public CreditorInstitutionStationEditResource updateStationAssociationToCreditor
* Removes the association and updates the authorizer config for each broker's api keys by removing
* the segregation code of the association
*
* @param ciTaxCode creditor institution's tax code
* @param ciTaxCode creditor institution's tax code
* @param institutionId broker's institution id
* @param brokerTaxCode broker's tax code
*/
Expand All @@ -191,17 +194,24 @@ public void deleteCreditorInstitutionStationRelationship(
String institutionId,
String brokerTaxCode
) {
CreditorInstitutions ciForRollback =
this.apiConfigClient.getCreditorInstitutionsByStation(stationCode, 1, 0, ciTaxCode);
this.apiConfigClient.deleteCreditorInstitutionStationRelationship(ciTaxCode, stationCode);
try {
this.apiManagementService.updateBrokerAuthorizerSegregationCodesMetadata(institutionId, brokerTaxCode);
} catch (Exception e) {
log.error("Failed to update broker API key authorizations, revert dissociate station to CI operation");
CreditorInstitutions creditorInstitutions =
this.apiConfigClient.getCreditorInstitutionsByStation(stationCode, 1, 0, ciTaxCode);
CreditorInstitutionStationEdit dto =
this.modelMapper.map(creditorInstitutions.getCreditorInstitutionList().get(0), CreditorInstitutionStationEdit.class);
dto.setStationCode(stationCode);
this.apiConfigClient.createCreditorInstitutionStationRelationship(ciTaxCode, dto);
log.error("Failed to update broker {} API key authorizations, revert dissociate station to CI operation",
sanitizeLogParam(brokerTaxCode), e);
if (ciForRollback != null && ciForRollback.getCreditorInstitutionList() != null && ciForRollback.getCreditorInstitutionList().size() == 1) {
CreditorInstitutionStationEdit dto =
this.modelMapper.map(ciForRollback.getCreditorInstitutionList().get(0), CreditorInstitutionStationEdit.class);
dto.setStationCode(stationCode);
dto.setAuxDigit(dto.getAuxDigit() == null ? 3L : dto.getAuxDigit());
this.apiConfigClient.createCreditorInstitutionStationRelationship(ciTaxCode, dto);
} else {
log.error("Unable to rollback dissociate station ({}) to CI ({}) operation",
sanitizeLogParam(stationCode), sanitizeLogParam(ciTaxCode));
}
throw e;
}
}
Expand Down Expand Up @@ -313,8 +323,7 @@ public CreditorInstitutionInfoResource getAvailableCreditorInstitutionsForStatio
) {
List<CreditorInstitutionInfo> infoList = new ArrayList<>();
List<String> delegations = getDelegationExternals(brokerId, ciName).parallelStream()
.filter(Objects::nonNull)
.filter(delegation -> RoleType.CI.equals(RoleType.fromSelfcareRole(delegation.getTaxCode(), delegation.getInstitutionType())))
.filter(delegation -> isCIDelegation(brokerId, delegation))
.map(DelegationExternal::getTaxCode)
.toList();

Expand Down Expand Up @@ -365,6 +374,7 @@ private List<DelegationExternal> getDelegationExternals(String brokerId, String
.taxCode(broker.getTaxCode())
.institutionName(broker.getDescription())
.institutionType(broker.getInstitutionType().toString())
.brokerId(brokerId)
.build()
);
}
Expand All @@ -376,9 +386,12 @@ private boolean brokerCanBeAddedToDelegation(
InstitutionResponse broker,
String ciNameFilter
) {
return RoleType.CI.equals(RoleType.fromSelfcareRole(broker.getTaxCode(), broker.getInstitutionType().name()))
return (
RoleType.CI.equals(RoleType.fromSelfcareRole(broker.getTaxCode(), broker.getInstitutionType().name()))
|| RoleType.PT.equals(RoleType.fromSelfcareRole(broker.getTaxCode(), broker.getInstitutionType().name()))
)
&& (StringUtils.isBlank(ciNameFilter) || broker.getDescription().toLowerCase().contains(ciNameFilter.toLowerCase()))
&& delegationExternals.stream().noneMatch(delegationExternal -> delegationExternal.getTaxCode().equals(broker.getTaxCode()));
&& delegationExternals.parallelStream().noneMatch(delegationExternal -> delegationExternal.getTaxCode().equals(broker.getTaxCode()));
}

private void checkIfIsCITaxCodeFailOtherwise(String ciTaxCode) {
Expand All @@ -388,4 +401,15 @@ private void checkIfIsCITaxCodeFailOtherwise(String ciTaxCode) {
throw new AppException(AppError.CREDITOR_INSTITUTION_NOT_FOUND, ciTaxCode);
}
}

private boolean isCIDelegation(String brokerId, DelegationExternal delegation) {
return delegation != null
&& (
RoleType.CI.equals(RoleType.fromSelfcareRole(delegation.getTaxCode(), delegation.getInstitutionType()))
|| (
delegation.getBrokerId().equals(brokerId)
&& RoleType.PT.equals(RoleType.fromSelfcareRole(delegation.getTaxCode(), delegation.getInstitutionType()))
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import java.time.Instant;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
Expand All @@ -30,7 +31,7 @@ public class TaxonomyService {

public Taxonomies getTaxonomies(String code, String ec, String macroArea, Boolean onlyValid) {
List<Taxonomy> taxonomies = taxonomyRepository.searchTaxonomies(
ec, macroArea, code != null ? ".*".concat(code).concat(".*") : null, onlyValid, Instant.now())
ec, macroArea, code != null ? "^[0-9]/.*".concat(code).concat(".*/$") : null, onlyValid, Instant.now())
.stream()
.map(elem -> modelMapper.map(elem, Taxonomy.class))
.toList();
Expand All @@ -40,7 +41,9 @@ public Taxonomies getTaxonomies(String code, String ec, String macroArea, Boolea
}

public List<Taxonomy> getTaxonomiesByCodes(List<String> codes) {
return taxonomyRepository.findBySpecificBuiltInDataIn(codes).stream()
return taxonomyRepository.findBySpecificBuiltInDataIn(
codes.stream().map(code -> Pattern.compile(code.contains("/") ? "^"+code+"$" : "^[0-9]/"+code+"/$"))
.toList()).stream()
.map(elem -> modelMapper.map(elem, Taxonomy.class)).collect(Collectors.toList());
}

Expand Down
Loading

0 comments on commit 9c143a2

Please sign in to comment.