Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
22 kB
4
Indexable
Never
/**
 * @description       :
 * @author            : Hersilio Belini de Oliveira
 * @group             :
 * @last modified on  : 03-05-2024
 * @last modified by  : ChangeMeIn@UserSettingsUnder.SFDoc
 **/
public with sharing class BucketTriggerHandlerHelper {

    private static final String BKT_CLASSIFICACAO_MONITORADA = 'Classificação Monitorada';

    private static final String BKT_SITUACAO_CREDITO = 'SITUACAO_CREDITO';

    private static final Id recordTypeSolicitacaoParecer = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName()
        .get('SolicitacaoParecer')
        .getRecordTypeId();

    private static final Id recordTypeCorporate = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName()
        .get('SolicitacaoRevisao')
        .getRecordTypeId();

    private static List<AcaoBucket__c> acoesBuketDefault;

    private static Map<String,String> alertLevelLabelMap;

    static {
        acoesBuketDefault = [
            SELECT
            Bucket__C,
                Nivelalerta__c,
                toLabel(Nivelalerta__c) NivelalertaLabel,
                TipoMonitoramento__c,
                ActionType__c,
                Status__c,
                EventName__c,
                WorkingDays__c,
                Subject__c,
                NotificacionTitle__c,
                NotificationBody__c,
                ActionTimeDays__c,
                RecordTypeId,
                BlockReason__c,
                ParameterType__c,
                Description__c,
                Observacao__c,
                Bucket__r.Name,
                Name,
                (SELECT BucketAction__c, DataType__c, FieldWithRelationship__c, JsonKey__c, ParameterValue__c, SalesforceField__c, SalesforceObject__c FROM ParametrosAcao__r)
                FROM AcaoBucket__c WHERE Bucket__r.Name = 'Default' AND Status__c = 'Ativo'];

        List<Schema.PicklistEntry> values = Bucket__c.AlertLevel__c.getDescribe().getPicklistValues();
        for(Schema.PicklistEntry sp : values){
            if(alertLevelLabelMap == null){
                alertLevelLabelMap = new Map<String, String>();
            }

            alertLevelLabelMap.put(sp.getValue(), sp.getLabel());
        }
    }

    public static void updateMonitoringBucketAlertLevelAndMonitoringTypeAndCreateCustomerActions(Map<Id, Bucket__c> newValuesMap, Map<Id, Bucket__c> oldValuesMap) {
        Set<Id> accountIds = new Set<Id>();
        Map<Id, Boolean> accHasSituacaoCreditoMap = new Map<Id, Boolean>();

        for (Bucket__c bucket : newValuesMap.values()) {

            if (oldValuesMap == null || checkAlertLeverOrMonitoringChanges(bucket, oldValuesMap.get(bucket.Id))){
                accountIds.add(bucket.Account__c);
            }

            if(bucket.MonitoringType__c == BKT_SITUACAO_CREDITO && !accHasSituacaoCreditoMap.containsKey(bucket.Account__c)){
                accHasSituacaoCreditoMap.put(bucket.Account__c, true);
            }
        }

        if (accountIds.isEmpty()){
            return;
        }

        List<Bucket__c> accountBuckets = BucketDAO.selectByAccountId(accountIds);
        Map<Id, Bucket__c> bucketMonitoramentoMap = new Map<Id, Bucket__c>();
        Map<Id, Map<String, Bucket__c>> accountBucketsNameMap = new Map<Id, Map<String, Bucket__c>>();

        for(Bucket__c bkt: accountBuckets){
            if(!accountBucketsNameMap.containsKey(bkt.Account__c)){
                accountBucketsNameMap.put(bkt.Account__c, new Map<String, Bucket__c>());
            }

            if(!accountBucketsNameMap.get(bkt.Account__c).containsKey(bkt.Name)){
                accountBucketsNameMap.get(bkt.Account__c).put(bkt.Name, bkt);

                if(bkt.Name == BKT_CLASSIFICACAO_MONITORADA){
                    bucketMonitoramentoMap.put(bkt.Id, bkt);
                }
            }

            if(bkt.MonitoringType__c == BKT_SITUACAO_CREDITO && !accHasSituacaoCreditoMap.containsKey(bkt.Account__c)){
                accHasSituacaoCreditoMap.put(bkt.Account__c, true);
            }
        }

        insertNewMonitoringBuckets(accountIds, accountBucketsNameMap, bucketMonitoramentoMap);

        List<Bucket__c> bucketsMonitoringToUpdate = updateBucketMonitoringTypeAndAlertLevel(bucketMonitoramentoMap, newValuesMap, oldValuesMap, accountBucketsNameMap, accHasSituacaoCreditoMap);
        if (!bucketsMonitoringToUpdate.isEmpty()) {
            updateAccountsWithBucketMonitoring(bucketsMonitoringToUpdate);

            TriggerHandler.bypass('BucketTriggerHandler');
            update bucketsMonitoringToUpdate;
            TriggerHandler.clearBypass('BucketTriggerHandler');
        }

        // Cria ações do cliente
        createActionsBucketsMonitoring(bucketMonitoramentoMap);
        createCorporateCase(accountBuckets);
    }

    private static void updateAccountsWithBucketMonitoring(List<Bucket__c> bucketsMonitoringToUpdate){

        List<Account> accountsToUpdate = new List<Account>();

        Set<Id> accIds = new Set<Id>();

        for(Bucket__c bktUpdated : bucketsMonitoringToUpdate){
            accIds.add(bktUpdated.Account__r.EconomicGroup__c);
        }

        Map<Id, Account> accGroups = new Map<Id, Account>([SELECT Id, Bucket__r.Prioridade_Alerta__c, Bucket__r.Prioridade_Bucket__c FROM Account WHERE Id IN: accIds]);

        for(Bucket__c bktUpdated : bucketsMonitoringToUpdate){
            Account accGroup = accGroups.get(bktUpdated.Account__r.EconomicGroup__c);

            if(accGroup != null && (accGroup.Bucket__c == null || accGroup.Bucket__r.Prioridade_Alerta__c < bktUpdated.Prioridade_Alerta__c || accGroup.Bucket__r.Prioridade_Bucket__c < bktUpdated.Prioridade_Bucket__c)){
                accGroup.Bucket__c = bktUpdated.Id;
                accountsToUpdate.add(accGroup);
            }
        }

        //Verificar se possui classificação monitora vinculada na conta
        for (Bucket__c bucket : bucketsMonitoringToUpdate) {
            if(bucket.Account__r.Bucket__c == null || bucket.Account__r.Bucket__c != bucket.Id){
                accountsToUpdate.add(new Account(Id = bucket.Account__c, Bucket__c = bucket.Id));
            }
        }

        if(!accountsToUpdate.isEmpty()){
            TriggerHandler.bypass('AccountTriggerHandler');
            upsert accountsToUpdate;
            TriggerHandler.clearBypass('AccountTriggerHandler');
        }

    }

    public static void createActionsBucketsMonitoring(Map<Id, Bucket__c> bucketMonitoramentoMap){

        Set<Id> accountIds = new Set<Id>();

        for(Bucket__c bucket : bucketMonitoramentoMap.values()){
            accountIds.add(bucket.Account__c);
        }

        List<AcaoBucket__c> bucketActions = insertAcoesClassificacaoMonitorada(bucketMonitoramentoMap);

        Map<Id, AcaoCliente__c> existingCustomerActions = AcaoClienteDAO.selectByClientAndStatusDoingOrQueue(accountIds);

        List<Case> accountCases = CaseDAO.selectByAccountIdAndCustomerActionAndRecordTypeId(accountIds, existingCustomerActions.keySet(), recordTypeSolicitacaoParecer);

        List<Case> casesToUpdate = new List<Case>();
        List<AcaoCliente__c> customerActions = new List<AcaoCliente__c>();

        customerActions = AcaoClienteService.updateExistingCustomerActionsAndCasesStatus(existingCustomerActions.values(), accountCases, customerActions, casesToUpdate);
        customerActions = populateCustomerActionsList(customerActions, bucketActions, bucketMonitoramentoMap );

        if(!customerActions.isEmpty()) {
            upsert customerActions;

            Set<Id> acaoBucketsId = new Set<Id>();

            for(AcaoCliente__c acaoCliente : customerActions){
                acaoBucketsId.add(acaoCliente.BucketAction__c);
            }

            List<ParametrosAcao__c> parametrosToInsert = createParametersBuckets(bucketActions, acaoBucketsId);

            if(!parametrosToInsert.isEmpty()){
                insert parametrosToInsert;
            }
        }

        if(!casesToUpdate.isEmpty()){
            TriggerHandler.bypass('CaseTriggerHandler');
            update casesToUpdate;
            TriggerHandler.clearBypass('CaseTriggerHandler');
        }
    }

    private static void insertNewMonitoringBuckets(Set<Id> accountIds, Map<Id, Map<String, Bucket__c>> accountBucketsNameMap, Map<Id, Bucket__c> bucketMonitoramentoMap){

        List<Bucket__c> monitoringBucketsToInsert = new List<Bucket__c>();

        for (Id accId : accountIds) {
            Map<String, Bucket__c> bucketNames = accountBucketsNameMap.get(accId);

            if (!bucketNames.containsKey(BKT_CLASSIFICACAO_MONITORADA)){
                monitoringBucketsToInsert.add(new Bucket__c(Name = BKT_CLASSIFICACAO_MONITORADA, Account__c = accId));
            }
        }

        if (!monitoringBucketsToInsert.isEmpty()) {
            TriggerHandler.bypass('BucketTriggerHandler');
            insert monitoringBucketsToInsert;
            TriggerHandler.clearBypass('BucketTriggerHandler');

            for(Bucket__c bkt : monitoringBucketsToInsert){
                accountBucketsNameMap.get(bkt.Account__c).put(bkt.Name, bkt);
                bucketMonitoramentoMap.put(bkt.Id, bkt);
            }
        }
    }

    private static List<AcaoCliente__c> populateCustomerActionsList(List<AcaoCliente__c> newCustomerActions, List<AcaoBucket__c> bucketActions, Map<Id, Bucket__c> bucketMonitoramentoMap) {

        for (AcaoBucket__c bucketAction : bucketActions) {
            String actionName = bucketAction.TipoMonitoramento__c + ' (' + bucketAction.Nivelalerta__c + ') - ' + bucketAction.ActionType__c;

            Bucket__c monitoringBucket = bucketMonitoramentoMap.get(bucketAction.Bucket__c);

            Boolean alertLevelAndMonitoringTypeAreEquals =
            bucketAction.Nivelalerta__c == monitoringBucket.AlertLevel__c && bucketAction.TipoMonitoramento__c == monitoringBucket.MonitoringType__c;

            if (alertLevelAndMonitoringTypeAreEquals){

                Date dateToExecuteAction = AcaoClienteService.calculateClientActionDate(bucketAction);

                AcaoClienteService.createClientActions(
                    newCustomerActions,
                    monitoringBucket,
                    null,
                    bucketAction,
                    dateToExecuteAction,
                    actionName
                    );
            }
        }

        return newCustomerActions;
    }

    private static Boolean checkAlertLeverOrMonitoringChanges (Bucket__c newBucketValue, Bucket__c oldBucketValue) {
        return newBucketValue?.AlertLevel__c != oldBucketValue?.AlertLevel__c;
    }

    private static Bucket__c updateMonitoringBucket(Bucket__c monitoringBucket, Bucket__c sourceBucket) {
        monitoringBucket.PreviousMonitoringType__c = monitoringBucket.MonitoringType__c;
        monitoringBucket.PreviousAlertLevel__c = alertLevelLabelMap.get(monitoringBucket.AlertLevel__c);
        monitoringBucket.MonitoringType__c = sourceBucket.MonitoringType__c;
        monitoringBucket.AlertLevel__c = sourceBucket.AlertLevel__c;
        monitoringBucket.ClassificacaoMonitorada__c = sourceBucket.AlertLevel__c;
        return monitoringBucket;
    }

    private static List<Bucket__c> updateBucketMonitoringTypeAndAlertLevel (
        Map<Id, Bucket__c> bucketMonitoramentoMap,
        Map<Id, Bucket__c> newValuesMap,
        Map<Id, Bucket__c> oldValuesMap,
        Map<Id, Map<String, Bucket__c>> accountBucketsNameMap,
        Map<Id, Boolean> accHasSituacaoCreditoMap) {

        List<Bucket__c> bucketsToUpdate = new List<Bucket__c>();

        for(Id bktId : bucketMonitoramentoMap.keySet()){

            Bucket__c monitoringBucket = bucketMonitoramentoMap.get(bktId);

            if (monitoringBucket.Classificacao_Monitorada_Manual__c && !hasBuketInList(bucketsToUpdate, monitoringBucket)) {
                Map<String, Bucket__c> accountBucketMap = accountBucketsNameMap.get(monitoringBucket.Account__c);
                for (String bktName : accountBucketMap.keySet()) {

                    Bucket__c accountBucket = accountBucketMap.get(bktName);

                    if(accountBucket.Name == BKT_CLASSIFICACAO_MONITORADA){
                        continue;
                    }

                    if (accountBucket.MonitoringType__c == monitoringBucket.MonitoringType__c) {
                        accountBucket.Classificacao_Monitorada_Manual__c = true;
                        bucketsToUpdate.add(accountBucket);
                    }
                }

                monitoringBucket.Classificacao_Monitorada_Manual__c = false;

                if (!hasBuketInList(bucketsToUpdate, monitoringBucket)){
                    bucketsToUpdate.add(monitoringBucket);
                }

                return bucketsToUpdate;
            }
        }

        for (Id accId : accountBucketsNameMap.keySet()) {

            Map<String, Bucket__c> allAccountBucksMap = accountBucketsNameMap.get(accId);

            if (allAccountBucksMap == null || allAccountBucksMap.isEmpty()){
                continue;
            }

            Bucket__c monitoringBucket = getMonitoringBucket(allAccountBucksMap);

            if(!accHasSituacaoCreditoMap.containsKey(accId)){

                Bucket__c newBktMonitoramento = bucketMonitoramentoMap.get(monitoringBucket.Id);

                if(newBktMonitoramento != null && newBktMonitoramento.Prioridade_Alerta__c > 4){
                    monitoringBucket = newBktMonitoramento;

                    Bucket__c oldBktMonitoramento = oldValuesMap.get(monitoringBucket.Id);

                    if(oldBktMonitoramento != null && newBktMonitoramento.Prioridade_Alerta__c == oldBktMonitoramento.Prioridade_Alerta__c){
                        bucketMonitoramentoMap.remove(monitoringBucket.Id); // BUG removido para não criar ações de buckets que alterou para um nivel menor
                    }

                    continue;
                }
            }

            Decimal maiorPrioridadeAlerta = 0;
            for(Bucket__c bkt : allAccountBucksMap.values()){
                if(bkt.Name == BKT_CLASSIFICACAO_MONITORADA){
                    continue;
                }

                Bucket__c newBkt = newValuesMap.get(bkt.Id) != null ? newValuesMap.get(bkt.Id) : bkt;
                maiorPrioridadeAlerta = newBkt.Prioridade_Alerta__c > maiorPrioridadeAlerta ? newBkt.Prioridade_Alerta__c : maiorPrioridadeAlerta;
            }

            Bucket__c bktMaiorPrioridade;
            for(Bucket__c bkt : allAccountBucksMap.values()){
                if(bkt.Name == BKT_CLASSIFICACAO_MONITORADA){
                    continue;
                }

                Bucket__c newBkt = newValuesMap.get(bkt.Id) != null ? newValuesMap.get(bkt.Id) : bkt;

                if(newBkt.Prioridade_Alerta__c == maiorPrioridadeAlerta){
                    bktMaiorPrioridade = bktMaiorPrioridade == null || bktMaiorPrioridade.Prioridade_Bucket__c < newBkt.Prioridade_Bucket__c
                    ? newBkt
                    : bktMaiorPrioridade;
                }
            }

            // verifica se houve alteração de tipo de monitoramento ou nivel de alerta
            if(bktMaiorPrioridade != null && (monitoringBucket.AlertLevel__c != bktMaiorPrioridade.AlertLevel__c || monitoringBucket.MonitoringType__c != bktMaiorPrioridade.MonitoringType__c)){
                updateMonitoringBucket(monitoringBucket, bktMaiorPrioridade);
                bucketsToUpdate.add(monitoringBucket);
            } else {
                bucketMonitoramentoMap.remove(monitoringBucket.Id); // BUG removido para não criar ações de buckets que alterou para um nivel menor
            }
        }

        return bucketsToUpdate;
    }

    private static Bucket__c getMonitoringBucket(Map<String, Bucket__c> bucketMap){
        for(String bktName : bucketMap.keySet()){
            if(bktName == BKT_CLASSIFICACAO_MONITORADA){
                return bucketMap.get(bktName);
            }
        }

        return null;
    }

    private static Boolean hasBuketInList(List<Bucket__c> bktList, Bucket__c bkt){
        for(Bucket__c currentBkt : bktList){
            if(currentBkt.Id == bkt.Id){
                return true;
            }
        }

        return false;
    }

    public static List<AcaoBucket__c> insertAcoesClassificacaoMonitorada(Map<Id, Bucket__c> bucketMonitoramentoMap){

        List<AcaoBucket__c> acaoBktsToUpdate = new List<AcaoBucket__c>();
        for(AcaoBucket__c acaoBktOld : AcaoBucketDAO.selectActiveActionsByBucketId(bucketMonitoramentoMap.keySet())){
            acaoBktOld.Status__c = 'Cancelado';
            acaoBktsToUpdate.add(acaoBktOld);
        }

        if(!acaoBktsToUpdate.isEmpty()){
            update acaoBktsToUpdate;
        }

        List<AcaoBucket__c> acoesBktToInsert = new List<AcaoBucket__c>();

        for (Bucket__c bkt : bucketMonitoramentoMap.values()) {
            for (AcaoBucket__c acaoBktDefault : acoesBuketDefault) {
                if(acaoBktDefault.Nivelalerta__c == bkt.AlertLevel__c && acaoBktDefault.TipoMonitoramento__c == bkt.MonitoringType__c){
                    AcaoBucket__c acaoBktCloned = acaoBktDefault.clone(false, false, false, false);
                    acaoBktCloned.Bucket__c = bkt.Id;
                    acoesBktToInsert.add(acaoBktCloned);
                }
            }
        }

        if (!acoesBktToInsert.isEmpty()) {
            insert acoesBktToInsert;
        }

        return acoesBktToInsert;
    }

    private static List<ParametrosAcao__c> createParametersBuckets(List<AcaoBucket__c> bucketActions, Set<Id> acaoBucketsId){
        List<ParametrosAcao__c> parametrosToInsert = new List<ParametrosAcao__c>();

        try {

            Map<Id, AcaoBucket__c> acaoBucketMap = new Map<Id, AcaoBucket__c>();

            for(AcaoBucket__c bktAction: bucketActions){
                acaoBucketMap.put(bktAction.Id, bktAction);
            }

            for(Id acaoBucketId : acaoBucketsId){
                List<ParametrosAcao__c> paramsAcao = getParametroAcao(acaoBucketMap.get(acaoBucketId));

                for(ParametrosAcao__c paramAcao : paramsAcao){
                    ParametrosAcao__c paramAcaoCloned = paramAcao.clone(false, false, false, false);
                    paramAcaoCloned.BucketAction__c = acaoBucketId;
                    parametrosToInsert.add(paramAcaoCloned);
                }
            }

        } catch (Exception ex) {
            System.debug('[createParametersBuckets]error: ' + ex.getMessage() + ' - ' + ex.getStackTraceString());
        }

        return parametrosToInsert;
    }

    private static List<ParametrosAcao__c> getParametroAcao(AcaoBucket__c acaoBucket){
        if(acaoBucket == null){
            return new List<ParametrosAcao__c>();
        }

        for(AcaoBucket__c acaoBktDefault : acoesBuketDefault){
            if(acaoBktDefault.Nivelalerta__c == acaoBucket.Nivelalerta__c &&  acaoBktDefault.TipoMonitoramento__c == acaoBucket.TipoMonitoramento__c && acaoBucket.ActionType__c == acaoBktDefault.ActionType__c){
                return acaoBktDefault.ParametrosAcao__r;
            }
        }

        return new List<ParametrosAcao__c>();
    }

    private static void createCorporateCase (List<Bucket__c> accountBuckets) {
        Map<Id, Case> casesToInsertMap = new Map<Id, Case>();

        List<ConfiguracaoSegmento__mdt> segmentsInfos = [
            SELECT
                Label,
                AcaoManual__c,
                AssuntoCaso__c,
                CodigoIdentificador__c,
                DescricaoCaso__c,
                FilaAtendimento__c
            FROM ConfiguracaoSegmento__mdt
            WHERE AcaoManual__c = true
        ];

        if (segmentsInfos.isEmpty()) {
            return;
        }

        Map<String, ConfiguracaoSegmento__mdt> segmentsInfosMap = new Map<String, ConfiguracaoSegmento__mdt>();

        for (ConfiguracaoSegmento__mdt currentSegmentInfo : segmentsInfos) {
            segmentsInfosMap.put(currentSegmentInfo.CodigoIdentificador__c, currentSegmentInfo);
        }

        for (Bucket__c currentBucket : accountBuckets) {
            ConfiguracaoSegmento__mdt accountSegmentInfo = segmentsInfosMap.get(currentBucket.Account__r.SegmentoEmpresa__c);

            if (accountSegmentInfo == null) {
                continue;
            }

            if (!casesToInsertMap.containsKey(currentBucket.Account__c)) {
                casesToInsertMap.put(
                    currentBucket.Account__c,
                    new Case(
                        RecordTypeId = recordTypeCorporate,
                        Status = 'Novo',
                        AccountId = currentBucket.Account__c,
                        Subject = accountSegmentInfo.AssuntoCaso__c,
                        OwnerId = accountSegmentInfo.FilaAtendimento__c,
                        Description = accountSegmentInfo.DescricaoCaso__c
                    )
                );
            }
        }

        if (!casesToInsertMap.values().isEmpty()) {
            insert casesToInsertMap.values();
        }
    }
}
Leave a Comment