Untitled

 avatar
unknown
plain_text
5 months ago
13 kB
2
Indexable
@Component
@Slf4j
public class LexisNexisValidationCommandHandler extends BaseCommandHandler<LexisNexisValidationCommand> {

    private static final String FOUR_0_0 = "4-0-0";
    private static final Integer FOUR_0_0_PRODUCT_CODE = 3;

    private MotorOffersMapper motorOfferMapper;
    private UpdateOffersQueryHandler updateOffersQueryHandler;
    private MotorOffersRepository motorOffersRepository;
    private GetOriginationDetailsQueryHandler getOriginationDetailsQueryHandler;
    private PolicyAcceptFailEventCommandHandler policyAcceptFailEventCommandHandler;
    private PolicyAcceptedEventCommandHandler policyAcceptedEventCommandHandler;
    private PolicyAcceptedInternalEventCommandHandler policyAcceptedInternalEventCommandHandler;
    @Value("${retry-Lexis-Nexis}")
    private int retryLexisNexis;
    @Value("${lexis_Nexis_enable}")
    private boolean lexisNexisEnable;

    public LexisNexisValidationCommandHandler(MotorOffersMapper motorOfferMapper,
                                              UpdateOffersQueryHandler updateOffersQueryHandler,
                                              MotorOffersRepository motorOffersRepository,
                                              GetOriginationDetailsQueryHandler getOriginationDetailsQueryHandler,
                                              PolicyAcceptFailEventCommandHandler policyAcceptFailEventCommandHandler,
                                              PolicyAcceptedEventCommandHandler policyAcceptedEventCommandHandler,
                                              PolicyAcceptedInternalEventCommandHandler policyAcceptedInternalEventCommandHandler){
        super();
        this.motorOfferMapper = motorOfferMapper;
        this.updateOffersQueryHandler = updateOffersQueryHandler;
        this.motorOffersRepository = motorOffersRepository;
        this.getOriginationDetailsQueryHandler = getOriginationDetailsQueryHandler;
        this.policyAcceptFailEventCommandHandler = policyAcceptFailEventCommandHandler;
        this.policyAcceptedEventCommandHandler = policyAcceptedEventCommandHandler;
        this.policyAcceptedInternalEventCommandHandler = policyAcceptedInternalEventCommandHandler;

    }
    @Override
    protected CommandResult handle(LexisNexisValidationCommand command, RequestContext requestContext) {
        Optional<MotorOffersEntity> optionalMotorOffersEntity = motorOffersRepository.findById(command.getOfferId());
        QueryResult<MotorInsuranceOriginationResponse> originationQueryResult = getOriginationDetailsQueryHandler
                .handleDecorators(new GetOriginationDetailsQuery(optionalMotorOffersEntity.get().getOriginationId()),requestContext);
        if(null!=originationQueryResult && originationQueryResult.hasError()){
            log.error("GET origination details API failed");
            return new CommandResult.Builder().withFailures(originationQueryResult.getFailures())
                    .withStatusCode(originationQueryResult.getStatusCode()).build();
        }

        try {
            retryLexisNexisFlagProcess( optionalMotorOffersEntity.get(), originationQueryResult.getResult(), requestContext);
        }catch (Exception e){
            PolicyAcceptFailEventCommand policyFailedCommand =  getPolicyAcceptFailEventCommand(optionalMotorOffersEntity.get());
            List<Failure> failureList = new ArrayList<>();
            Failure failure  = new Failure();
            failure.setMessage(e.getMessage());
            failureList.add(failure);
            policyFailedCommand.setErrors(failureList);
            policyAcceptFailEventCommandHandler.handleDecorators(policyFailedCommand,requestContext);
            log.error("Unable to validate LexisNexis Validation to RSA {} ", e.getMessage());
        }
        return null;
    }

    private PolicyAcceptFailEventCommand getPolicyAcceptFailEventCommand(MotorOffersEntity motorOffersEntity) {
        PolicyAcceptFailEventCommand policyAcceptFailEventCommand = PolicyAcceptFailEventCommand.builder()
                .applicationId(motorOffersEntity.getApplicationId())
                .originationId(motorOffersEntity.getOriginationId())
                .customerId(motorOffersEntity.getCustomerId())
                .offerId(motorOffersEntity.get_id())
                .productCode("motor")
                .productType("insurance")
                .build();
        return policyAcceptFailEventCommand;
    }

    private void executeSleep(int i)  {
        try {
            switch (i) {
                case 1:
                    Thread.sleep(60000);
                    break;
                case 2:
                    Thread.sleep(120000);
                    break;
                case 3:
                    Thread.sleep(180000);
                    break;
                default:
                    log.info("exetuted Retry of LexisNexis");
            }
        }catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new FrameworkException(RSA_UPDATE_QUOTE,400);

        }
    }

    private void retryLexisNexisFlagProcess(MotorOffersEntity motorOffersEntity, MotorInsuranceOriginationResponse result, RequestContext requestContext) {
        log.info("execute retryLexisNexisFlagProcess {} ",motorOffersEntity.getApplicationId());
        for(int i = 1; i<=retryLexisNexis ; i++){
            boolean flag1 = prepareReBuildRSAOfferUpdate(i,motorOffersEntity, result, requestContext);
            executeSleep(i);
            if(flag1) {
               // publishPolicyAccepteEvent(motorOffersEntity,requestContext);
                publishPolicyAccepteInternalEvent(motorOffersEntity,requestContext);
                break;
            }
        }
        log.info("execute successfully retryLexisNexisFlagProcess {} ",motorOffersEntity.getApplicationId());
    }

    private void publicPoliyAcceptFailEvent(MotorOffersEntity motorOffersEntity, RequestContext requestContext) {
        PolicyAcceptFailEventCommand policyAcceptedEventCommand = PolicyAcceptFailEventCommand.builder()
                .applicationId(motorOffersEntity.getApplicationId())
                .originationId(motorOffersEntity.getOriginationId())
                .customerId(motorOffersEntity.getCustomerId())
                .offerId(motorOffersEntity.get_id())
                .productCode("motor")
                .productType("insurance")
                .build();
        policyAcceptFailEventCommandHandler.handleDecorators(policyAcceptedEventCommand,requestContext);

    }

    private void publishPolicyAccepteInternalEvent(MotorOffersEntity motorOffersEntity, RequestContext requestContext) {
        PolicyAcceptedInternalEventCommand policyAcceptedEventCommand = PolicyAcceptedInternalEventCommand.builder()
                .applicationId(motorOffersEntity.getApplicationId())
                .originationId(motorOffersEntity.getOriginationId())
                .customerId(motorOffersEntity.getCustomerId())
                .offerId(motorOffersEntity.get_id())
                .productCode("motor")
                .productType("insurance")
                .build();
        policyAcceptedInternalEventCommandHandler.handleDecorators(policyAcceptedEventCommand,requestContext);

    }

    private void publishPolicyAccepteEvent(MotorOffersEntity motorOffersEntity,RequestContext requestContext) {
        PolicyAcceptedEventCommand policyAcceptedEventCommand = PolicyAcceptedEventCommand.builder()
                .applicationId(motorOffersEntity.getApplicationId())
                .originationId(motorOffersEntity.getOriginationId())
                .customerId(motorOffersEntity.getCustomerId())
                .offerId(motorOffersEntity.get_id())
                .productCode("motor")
                .productType("insurance")
                .build();
        policyAcceptedEventCommandHandler.handleDecorators(policyAcceptedEventCommand,requestContext);

    }

    private boolean prepareReBuildRSAOfferUpdate(int count, MotorOffersEntity motorOffersEntity, MotorInsuranceOriginationResponse originationQueryResult, RequestContext requestContext) {
        boolean flag = false;
        log.info("execute prepareReBuildRSAOfferUpdate {}, times {}",motorOffersEntity.getApplicationId(),count);
        QuotationRequest quotationRequest = null;
        quotationRequest = motorOfferMapper.rebuildRSAOfferUpdateRequest(motorOffersEntity, originationQueryResult, requestContext);
        RSAUpdateOfferQuery rsaUpdateOfferQuery = RSAUpdateOfferQuery.builder().quotationRequest(quotationRequest).build();
        QueryResult<QuotationResponse> updateRSAOfferApiResult = updateOffersQueryHandler.handleDecorators(rsaUpdateOfferQuery, requestContext);
        if (updateRSAOfferApiResult.hasError()) {
            throw new FrameworkException(RSA_UPDATE_QUOTE,400);
        }
        List<MotorOffersEntity> motorOfferEntityList = motorOfferMapper.buildMotorOffersEntitiesFromRsaResponse(motorOffersEntity, updateRSAOfferApiResult.getResult());
        MotorOffersEntity m = motorOfferEntityList.get(0);
        flag =  validateLexisNexisFlag(m);
        correctDefaultSelectedProductsBasedOnProductCode(motorOfferEntityList, motorOffersEntity);

        motorOffersRepository.deleteAll(motorOffersRepository.findByOriginationId(motorOffersEntity.getOriginationId()));
        motorOffersRepository.saveAll(motorOfferEntityList);

        if(count == 3 && !flag) {
            publicPoliyAcceptFailEvent(motorOffersEntity, requestContext);
            throw new FrameworkException(LEXISNEXIS_VALIDATION_FAILURE, 400);
        }
        log.info("execute successfully prepareReBuildRSAOfferUpdate {} ",motorOffersEntity.getApplicationId());
        return flag;
    }

    private void setOldOfferIdToNewSelectedOffer(MotorOffersEntity selectedOffer, MotorOffersEntity existingOffer) {
        selectedOffer.setIsSelected(true);
        selectedOffer.set_id(existingOffer.get_id());
        log.warn("Old Offer id is set:: {}",existingOffer.get_id());
    }

    private boolean validateLexisNexisFlag(MotorOffersEntity offerEntity) {
        boolean flag = false;
        try {
            LexisNexisInfoMotorOffers l = offerEntity.getLexisNexisInfo();
            if (l.getFlag() != null && l.getFlag().equalsIgnoreCase("S") || l.getFlag().equalsIgnoreCase("F")) {
                flag = true;
            }
        }catch (Exception e){
            log.error("unable to process validateLexisNexisFlag");
        }
        return flag;
    }
    private void correctDefaultSelectedProductsBasedOnProductCode(List<MotorOffersEntity> motorOfferEntityList, MotorOffersEntity existingOffer) {
        motorOfferEntityList.stream().filter(offer -> offer.getIsSelected()).forEach(selectedOffer -> {
            if (isItAProductThreeOffer(selectedOffer)) {
                selectedOffer.setIsSelected(false);
                log.warn("Setting setIsSelected False");
                if (isAgencyRepairedValueSameForOldDbOfferAndNewRSAOffer(selectedOffer, existingOffer)) {
                    log.warn("Setting Old Offer id to new Selected");
                    setOldOfferIdToNewSelectedOffer(selectedOffer, existingOffer);
                }
            } else {
                log.warn("Handle non product code");
                handleNonProductCodeThreeOffer(selectedOffer,existingOffer);
            }
        });

    }
    private boolean isItAProductThreeOffer(MotorOffersEntity selectedOffer) {
        return selectedOffer.getOfferDetail().getProductCode() == FOUR_0_0_PRODUCT_CODE;
    }

    /*private void setOldOfferIdToNewSelectedOffer(MotorOffersEntity selectedOffer, MotorOffersEntity existingOffer) {
        selectedOffer.setIsSelected(true);
        selectedOffer.set_id(existingOffer.get_id());
        log.warn("Old Offer id is set:: {}",existingOffer.get_id());
    }*/
    private boolean isAgencyRepairedValueSameForOldDbOfferAndNewRSAOffer(MotorOffersEntity offersEntity, MotorOffersEntity existingOffer) {
        if(offersEntity.getOfferDetail().getIsAgencyRepairIncluded() == null) return true;
        return offersEntity.getOfferDetail().getIsAgencyRepairIncluded() != null && offersEntity.getOfferDetail().getIsAgencyRepairIncluded() == existingOffer.getOfferDetail().getIsAgencyRepairIncluded() && offersEntity.getOfferDetail().getProductCode() == FOUR_0_0_PRODUCT_CODE;
    }
    private void handleNonProductCodeThreeOffer(MotorOffersEntity selectedOffer, MotorOffersEntity existingOffer) {
        setOldOfferIdToNewSelectedOffer(selectedOffer, existingOffer);
    }

}
Editor is loading...
Leave a Comment