Untitled

 avatar
unknown
plain_text
2 years ago
20 kB
4
Indexable
/**
 * @description       :
 * @author            : Hersilio Belini de Oliveira
 * @group             :
 * @last modified on  : 2023-10-24
 * @last modified by  : Hersilio Belini de Oliveira
**/
public with sharing class RequestOrchestratorTransformer {
    Decimal valorLimiteClean;
    RequestOrchestrator requestOrchestrator;
    OrchestratorIntegration__c orchestratorIntegrationConfig = OrchestratorIntegration__c.getInstance();

    public static final Map<String, Integer> parsePaymentFrequencyId = new Map<String, Integer>{
        'Mensal' => 1,
        'Quinzenal' => 8,
        'Anual' => 6,
        'Final' => 2,
        'Irregular' => 1
    };

    public static final Map<String, Integer> parsePaymentChargesId = new Map<String, Integer>{ '30' => 1 };

    public RequestOrchestrator to(
        Proposals__c proposal,
        List<Guarantee__c> guarantees,
        CalculateIOF calculateIOF
    ) {
        this.requestOrchestrator = new RequestOrchestrator();

        RequestOrchestrator.Header = toHeader(proposal);
        RequestOrchestrator.Operacao = toOperation(proposal);
        System.debug('Passou Operação');
        if(calculateIOF != null){
            requestOrchestrator.Boleta = toBoleta(proposal, calculateIOF);
        }
        requestOrchestrator.NSL = toNsl(toGuarantees(guarantees), proposal);
        requestOrchestrator.Boleta.DcEntradaJson = JSON.serialize(
            new List<RequestOrchestrator.DcEntradaJson>{
                toDcEntradaJson(toIOF(calculateIof, proposal), proposal)
                    }
        );
        system.debug('orquestrator '+ requestOrchestrator);

        return requestOrchestrator;
    }

    public RequestOrchestrator.Header toHeader(Proposals__c proposal) {
        RequestOrchestrator.Header header = new RequestOrchestrator.Header();

        header.id = proposal.Id;
        header.origem = 'SALESFORCE';
        header.usuario = proposal.FederationIdentifier__c;

        return header;
    }

    public RequestOrchestrator.Operation toOperation(Proposals__c proposal) {
        RequestOrchestrator.Operation operation = new RequestOrchestrator.Operation();

        operation.crc = Integer.ValueOf(proposal.crcGroup__c);

        operation.crcCliente = Integer.valueOf(proposal.crcCliente__c);
        if (!Test.isRunningTest()) {
            ClientLimitInboundService service = new ClientLimitInboundService(
                operation.crc,
                operation.crcCliente,
                false
            );
            service.callService();

            ClientLimit client = service.getIdLimitResult();

            System.debug('client: ' + client);

            operation.idLimite = Integer.valueOf(proposal.idLimite__c);
            operation.sqLimiteAlocacao = Integer.valueOf(proposal.sqLimiteAlocacao__c);

            if(client != null && client.out_response != null && client.out_response.data != null){
                for (ClientLimit.Data data : client.out_response.data) {
                    if (data.sequencialLimite == operation.idLimite) {
                        valorLimiteClean = data.valorLimiteClean;
                    }
                }
            }
        }

        operation.idLimiteCancelado = proposal.idLimitCancel__c;
        operation.cdOperacaoOriginal = Integer.valueOf(
            proposal.OriginalOperation__c
        );
        operation.carencia = Integer.valueOf(proposal.Graceperiod__c);
        operation.amortizacao =
            parsePaymentFrequencyId.get(proposal.paymentFrequency__c) +
            '|' +
            Integer.valueOf(proposal.pmtsmain__c);
        operation.pagamentoEncargos =
            parsePaymentChargesId.get(proposal.paymentCharges__c) +
            '|' +
            Integer.valueOf(proposal.pmtsauxiliary__c);

        return operation;
    }

    public RequestOrchestrator.Boleta toBoleta(
        Proposals__c proposal,
        CalculateIOF calculateIOF
    ) {
        RequestOrchestrator.Boleta boleta = new RequestOrchestrator.Boleta();

        boleta.TipoBoleta = 6;
        boleta.WorkflowId = 6;
        boleta.contrato = proposal.NumeroContrato__c;
        boleta.cdInstanciaIntegracaoCRM = 0;
        boleta.modalidadeComplementar = 17;
        boleta.tpOperBoleta = Integer.valueOf(proposal.TipoOperBoleta__c);
        boleta.valorBruto = proposal.GroosValue__c;
        DateTime issuanceDate = toDateTime(proposal.Issuancedate__c);
        boleta.dataEmissao = issuanceDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss');
        boleta.prazo = calculateIof.data[calculateIof.data.size() - 1].calendarDays;
        List<String> splitedDate = calculateIof.data[calculateIof.data.size() - 1].dueDate.split('-');
        boleta.dataVencimento = toDateTime(
            Date.newInstance(
                Integer.valueOf(splitedDate[2]),
                Integer.valueOf(splitedDate[1]),
                Integer.valueOf(splitedDate[0])
            )
        ).formatGMT('yyyy-MM-dd\'T\'HH:mm:ss');
        boleta.tipoRemuneracao = Integer.valueOf(proposal.TypeRemuneration__c);
        boleta.tipoTaxa = Integer.valueOf(proposal.RateType__c);
        boleta.periodicidadeTaxa = Integer.valueOf(proposal.periodicRate__c);
        boleta.dataTac = toDateTime(proposal.Issuancedate__c).formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'');
        boleta.valorTac = proposal.TacValue__c;
        boleta.valorTaxa = proposal.rate__c;
        boleta.cdLimite = Integer.valueOf(proposal.idLimite__c);
        boleta.cdGrupoGarantia = Integer.valueOf(proposal.cdGrupoGarantia__c);
        boleta.dcAvalistasSelecionados = '';
        boleta.dcGarantiasJuridicas = proposal.dcGarantiasJuridico__c;
        boleta.vlVdu = proposal.VduValue__c;
        boleta.dcEntradaJson = '';

        return boleta;
    }

    public RequestOrchestrator.Nsl toNsl(
        List<RequestOrchestrator.Guarantee> guarantees,
        Proposals__c proposal
    ) {
        Id idProposta = proposal.Id;

        List<Avalista__c> avalistas = [
            SELECT
            Id,
            AvalistaId__c,
            Name,
            CPFCNPJ__c,
            GrupoGarantidor__c,
            PercentualExigido__c,
            Obrigatorio__C,
            NomeGarantidor__c,
            IdGarantidor__c,
            EditarInPlace__c,
            IdCliente__C,
            CompoeRating__c,
            Rating__c,
            RegimeCasamento__c,
            Tipo__c,
            AvalistaAtivo__c,
            Ativo__c,
            Estado_civil__c,
            NomeConjuge__c,
            CpfConjuge__c,
            Alterado__c
            FROM Avalista__c
            WHERE Proposta__c = :idProposta AND Alterado__c = true
        ];

        GrupoGarantiaAvalitaRequest.GrupoGarantiaAvalita grupo = new GrupoGarantiaAvalitaRequest.GrupoGarantiaAvalita();

        if(avalistas.size() > 0){
            GrupoGarantidor__c grupoGarantidor = [
                SELECT
                Name__c,
                idGrupo__c,
                idGrupoEconomico__c,
                QtdMinimaExidoAval__c,
                Incrementacao__c
                FROM GrupoGarantidor__c
                WHERE Id = :avalistas[0].GrupoGarantidor__c
                LIMIT 1
            ];
            grupo.idGrupo = integer.valueOf(grupoGarantidor.IdGrupo__c);
            grupo.idGrupoEconomico = integer.valueOf(
                grupoGarantidor.IdGrupoEconomico__c
            );
            grupo.nomeGrupo = grupoGarantidor.Name__c;
            grupo.qtdMinimaExidoAval = integer.valueOf(
                grupoGarantidor.QtdMinimaExidoAval__c
            );
            grupo.incrementacao = grupoGarantidor.Incrementacao__c;
        }

        List<GrupoGarantiaAvalitaRequest.Avalistas> avalistasArr = new List<GrupoGarantiaAvalitaRequest.Avalistas>();

        if(avalistas != null) {
            for (Avalista__c avalist : avalistas) {
                GrupoGarantiaAvalitaRequest.Avalistas avalista = new GrupoGarantiaAvalitaRequest.Avalistas();

                if(avalist.AvalistaId__c != null){
                    avalista.id = integer.valueOf(avalist.AvalistaId__c);
                }

                if (avalist.CPFCNPJ__c != null) {
                    avalista.CPFCnpj = avalist.CPFCNPJ__c;
                }

                if (avalist.Name != null) {
                    avalista.nomeAvalista = avalist.Name;
                }

                if (avalist.PercentualExigido__c != null) {
                    avalista.percentualExigido = Integer.valueOf(avalist.PercentualExigido__c.intValue());
                }

                if (avalist.Obrigatorio__c != null) {
                    avalista.obrigatorio = avalist.Obrigatorio__C;
                }
                if (avalist.NomeGarantidor__c != null) {
                    avalista.tipoGarantidor.nome = avalist.NomeGarantidor__c;
                }

                if (avalist.IdGarantidor__c != null) {
                    avalista.tipoGarantidor.id = Integer.valueOf(avalist.IdGarantidor__c);
                }

                if (avalist.EditarInPlace__c != null) {
                    avalista.editarInPlace = avalist.EditarInPlace__c;
                }

                if (avalist.IdCliente__c != null) {
                    avalista.idCliente = Integer.valueOf(avalist.IdCliente__C);
                }
                if (avalist.CompoeRating__c != null) {
                    avalista.compoeRating = boolean.ValueOf(avalist.CompoeRating__c);
                }
                if (avalist.Rating__c != null) {
                    avalista.ratingCredito = String.valueOf(avalist.Rating__c);
                }
                if (avalist.RegimeCasamento__c != null) {
                    avalista.regimeCasamento = avalist.RegimeCasamento__c;
                }
                if (avalist.Tipo__c != null) {
                    avalista.tipoPessoa = avalist.Tipo__c;
                }
                if (avalist.AvalistaAtivo__c != null) {
                    avalista.avalistaAtivo = avalist.AvalistaAtivo__c;
                }
                if (avalist.Ativo__c != null) {
                    avalista.ativo = avalist.Ativo__c;
                }
                if (avalist.Estado_civil__c != null) {
                    avalista.nomeEstadoCivil = String.valueOf(avalist.Estado_civil__c);
                }
                if (avalist.NomeConjuge__c != null) {
                    avalista.nomeConjuge = String.valueOf(avalist.NomeConjuge__c);
                }
                if (avalist.CpfConjuge__c != null) {
                    avalista.cpfConjuge = String.ValueOf(avalist.CpfConjuge__c);
                }
                if (avalist.Alterado__c != null) {
                    avalista.alterado = avalist.Alterado__c;
                }

                avalistasArr.add(avalista);
            }
        }

        grupo.Avalistas = avalistasArr;

        RequestOrchestrator.Nsl nsl = new RequestOrchestrator.Nsl();
        nsl.grupoGarantiaAvalita = grupo;
        nsl.garantias = guarantees;
        nsl.atributos = getAtributos();
        nsl.tipoLimiteAtributo = Integer.valueOf(orchestratorIntegrationConfig.LimitTypeAttribute__c);
        system.debug('orquestrator1 '+ requestOrchestrator);
        return nsl;
    }

    public List<RequestOrchestrator.Atributo> getAtributos() {
        List<RequestOrchestrator.Atributo> atributos = new List<RequestOrchestrator.Atributo>();
        system.debug('atributos '+ atributos);

        atributos.add(
            new RequestOrchestrator.Atributo(
                4,
                String.valueOf(requestOrchestrator?.Operacao?.CrcCliente)
            )
        ); //Empresa
        atributos.add(
            new RequestOrchestrator.Atributo(
                6,
                String.valueOf(requestOrchestrator?.boleta?.prazo)
            )
        ); //Prazo
        atributos.add(
            new RequestOrchestrator.Atributo(
                9,
                String.valueOf(requestOrchestrator?.Operacao?.Carencia)
            )
        ); //Carência de Principal
        atributos.add(
            new RequestOrchestrator.Atributo(
                10,
                requestOrchestrator?.operacao?.pagamentoEncargos
            )
        ); // Pagamento de Encargos
        atributos.add(
            new RequestOrchestrator.Atributo(
                11,
                requestOrchestrator?.operacao?.amortizacao
            )
        ); // Amortização do Principal
        atributos.add(new RequestOrchestrator.Atributo(8, orchestratorIntegrationConfig.Product__c)); //Produto
        atributos.add(new RequestOrchestrator.Atributo(37, 'Renegociação Mega 2'));
        atributos.add(new RequestOrchestrator.Atributo(20, '0')); //Carência de Encargos
        atributos.add(new RequestOrchestrator.Atributo(27, 'true')); //Acompanha Vencimento
        system.debug('atributos ' + atributos);

        if(proposal.paymentFrequency__c ) {
            List<RequestOrchestrator.DcEntradaJson> parcelas = (List<RequestOrchestrator.DcEntradaJson>)JSON.deserialize(requestOrchestrator?.Boleta?.DcEntradaJson, List<RequestOrchestrator.DcEntradaJson>.class);
 
            String descritptionParcels = '';
            for(RequestOrchestrator.DcEntradaJson parcela : parcelas){
                for(RequestOrchestrator.IOF pagamento : parcela.fluxoPagamentos){
                    descritptionParcels += String.format('Parcela {0}: {1} - R$ {2};', new String[]{ pagamento.NrParcela, pagamento.DtFinal, pagamento.VlrPresente });
                }
            }
 
            atributos.add(new RequestOrchestrator.Atributo(16, descritptionParcels)); //Parcelas irregular
 
        }
        system.debug('atributosirregular' + atributos);

        return atributos;
    }

    public List<RequestOrchestrator.Guarantee> toGuarantees(
        List<Guarantee__c> guarantees
    ) {
        List<RequestOrchestrator.Guarantee> parsedGuarantees = new List<RequestOrchestrator.Guarantee>();

        if (guarantees.isEmpty())
            return parsedGuarantees;

        for (Guarantee__c guarantee : guarantees) {
            if(guarantee.Guarantee__c != null){
                parsedGuarantees.add(toGuarantee(guarantee));
            }
        }

        return parsedGuarantees;
    }

    public RequestOrchestrator.Guarantee toGuarantee(Guarantee__c guarantee) {
        RequestOrchestrator.Guarantee parsedGuarantee = new RequestOrchestrator.Guarantee();

        parsedGuarantee.baseExigido = Integer.valueOf(
            guarantee.RequirementBasis__c
        );
        parsedGuarantee.cdGarantia = Integer.valueOf(guarantee.Guarantee__c);
        parsedGuarantee.comentario = '';
        parsedGuarantee.flPossuiComentarioRelevante = false;
        parsedGuarantee.grupoGarantidor = Integer.valueOf(guarantee.Guarantee__c) == 22 ? -1 : 0; // para o grupo de avalistas deve ser enviado -1 e reais 0
        parsedGuarantee.idAtributoGarantia = guarantee.idAtributoGarantia__c != null ? Integer.valueOf(
            guarantee.idAtributoGarantia__c
        ) : -1;
        parsedGuarantee.moeda = String.isBlank(guarantee.Currency__c)
            ? 1
            : Integer.valueOf(guarantee.Currency__c);
        parsedGuarantee.percentualExigido = guarantee.Percentage__c == null
            ? 0
            : guarantee.Percentage__c;

        if (parsedGuarantee.baseExigido == 1 && parsedGuarantee.cdGarantia == 22) {
            parsedGuarantee.moeda = String.isBlank(guarantee.Currency__c)
                ? 1
                : Integer.valueOf(guarantee.Currency__c);
            parsedGuarantee.percentualExigido = 0;
            parsedGuarantee.valorExigido = valorLimiteClean == null
                ? 0
                : valorLimiteClean;
        } else if (
            parsedGuarantee.baseExigido == 1 &&
            parsedGuarantee.cdGarantia != 22
        ) {
            parsedGuarantee.moeda = String.isBlank(guarantee.Currency__c)
                ? 1
                : Integer.valueOf(guarantee.Currency__c);
            parsedGuarantee.percentualExigido = 0;
            parsedGuarantee.valorExigido = guarantee.valueGarantee__c == null
                ? 0
                : guarantee.valueGarantee__c;
        } else if (parsedGuarantee.baseExigido != 1) {
            parsedGuarantee.moeda = 0;
            parsedGuarantee.percentualExigido = guarantee.Percentage__c == null
                ? 0
                : guarantee.Percentage__c;
            parsedGuarantee.valorExigido = 0;
        }

        parsedGuarantee.idFamiliaGrupo = Integer.valueOf(guarantee.family__c);

        return parsedGuarantee;
    }

    public RequestOrchestrator.DcEntradaJson toDcEntradaJson(
        List<RequestOrchestrator.IOF> iofs,
        Proposals__c proposal
    ) {
        RequestOrchestrator.DcEntradaJson dcEntradaJson = new RequestOrchestrator.DcEntradaJson();

        dcEntradaJson.cdFormaLiquidacao = 1;
        dcEntradaJson.observacoes = proposal.unified__c
            ? proposal.ObeservationOrquestrator__c
            : '';
        dcEntradaJson.flTransferenciaRecurso = true;
        dcEntradaJson.vlPercentualIndexador = 100.0;
        dcEntradaJson.flUtilizaDemilitador = 1;
        dcEntradaJson.cdTaxaIndexador = 1;
        dcEntradaJson.fluxoPagamentos = iofs;

        return dcEntradaJson;
    }

    public List<RequestOrchestrator.IOF> toIOF(
        CalculateIOF calculateIof,
        Proposals__c proposal
    ) {
        List<RequestOrchestrator.IOF> iofs = new List<RequestOrchestrator.IOF>();

        if (calculateIof == null || calculateIof.data.isEmpty()){
            return iofs;
        }

        for (CalculateIOF.Data data : calculateIof.data) {
            iofs.add(toIOF(data, proposal));
        }

        return iofs;
    }

    public RequestOrchestrator.IOF toIOF(
        CalculateIOF.Data calculateIof,
        Proposals__c proposal
    ) {
        RequestOrchestrator.IOF iof = new RequestOrchestrator.IOF();

        iof.dcJurosSobre = 'Saldo Devedor';
        iof.tpJurosSobre = 'D';
        iof.img = 'img_ok.gif';
        iof.msg = 'Parcela ok';
        iof.nrParcela = calculateIof.tranches;
        iof.vlrFuturo = 0;
        iof.vlrIoc = calculateIof.trancheIof;
        iof.vlrPresente = calculateIof.amortization;
        iof.nrPrazo = calculateIof.calendarDays;
        List<String> splitedDate = calculateIOF.dueDate.split('-');
        DateTime issuanceDate = toDateTime(proposal.Issuancedate__c);
        iof.dtInicial = issuanceDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss');
        iof.dtFinal = toDateTime(
            Date.newInstance(
                Integer.valueOf(splitedDate[2]),
                Integer.valueOf(splitedDate[1]),
                Integer.valueOf(splitedDate[0])
            )
        )
            .formatGMT('yyyy-MM-dd\'T\'HH:mm:ss');
        return iof;
    }

    @TestVisible
    private Datetime toDateTime(Date toDate) {
        return DateTime.newInstance(toDate.year(), toDate.month(), toDate.day());
    }
}
Editor is loading...
Leave a Comment