Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
21 kB
1
Indexable
Never
public with sharing class CEP_LC_ConsentManagementWizard {
   
    private static final AccountQueries accountQuery = AccountQueries.getInstance();
    private static final CaseQueries caseQuery = CaseQueries.getInstance();
    private static final IndividualQueries individualQuery = IndividualQueries.getInstance();
    private static final CEP_QR_ConsentManagement consentQuery = CEP_QR_ConsentManagement.getInstance();
    private static final PrivacyChangeQueries privacyQuery = PrivacyChangeQueries.getInstance();
    private static ContactQueries contactQuery = ContactQueries.getInstance();

    private static final IndividualService individualSrv = IndividualService.getInstance();
    private static final CaseService caseSrv = CaseService.getInstance();
    private static final PrivacyChangeService privacySrv = PrivacyChangeService.getInstance(); 
    private static DatabaseService databaseSrv = DatabaseService.getInstance();
    private static OpportunityServiceItemQueries osiQuery = OpportunityServiceItemQueries.getInstance();
   
    private static Constants constantSrv = Constants.getAllConstants();
    private static String CASE_STATUS_DRAFT = constantSrv.CASE_STATUS_DRAFT;
    private static String CASE_STATUS_WAITING_COMPLETION = constantSrv.CASE_STATUS_WAITING_COMPLETION;
    private static String CASE_STATUS_CLOSED = constantSrv.CASE_STATUS_CLOSED;
    private static String CASE_STATUS_CHIUSO = constantSrv.CASE_STATUS_CHIUSO;
    
    private static String caseRecordTypeGestioneConsensi = constantSrv.CASE_RECORD_TYPE_GESTIONE_CONSENSI;
    private static String accountRecordTypeOrganizzazione = constantSrv.ACCOUNT_RECORDTYPE_ORGANIZZAZIONE;
    private static String process = constantSrv.OPPORTUNITY_REQUEST_TYPE_GESTIONE_CONSENSI;

    private static String COMPLETION_MODE_DIGITAL_COMPLETION = constantSrv.COMPLETION_MODE_DIGITAL_COMPLETION;
	private static String COMPLETION_MODE_DIGITAL_SIGNATURE = constantSrv.COMPLETION_MODE_DIGITAL_SIGNATURE;
    private static String COMPLETION_MODE_ONLINE = constantSrv.COMPLETION_MODE_ONLINE;
    private static String COMPLETION_MODE_VOCAL_ORDER = constantSrv.COMPLETION_MODE_VOCAL_ORDER;
    private static String CHANNEL_CALL_CENTER = constantSrv.INTERACTION_CHANNEL_CALL_CENTER;
    private static String CHANNEL_PUNTI_FISICI = constantSrv.INTERACTION_CHANNEL_PUNTI_FISICI;


    @AuraEnabled
    public static Object getIndividual(Map<String, String> params){
        Map<String,Object> response = new Map<String,Object>();
        try{
            String accountId = params.get('accountId');
            Individual ind = individualSrv.findIndividualByAccount(accountId);
            response.put('individual', ind);
            response.put('isError', false);
        }catch(Exception e) {
            response.put('isError', true);
            response.put('errorMsg', e.getMessage());
            response.put('errorTrace', e.getStackTraceString());
            return response; 
        }
        return response;
    }

    @AuraEnabled
    public static Object initialize (Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        Map<Id,Consent_Management__mdt> consents = new  Map<Id,Consent_Management__mdt>();
        Map<String,String> consentsData = new Map<String,String>();

        try{
            String accountId     =  params.get('accountId');
            String caseId        =  params.get('caseId');
            String campaignId    =  params.get('campaignId');
            if(String.isBlank(caseId)) {
                response.put('newCase', true);
            }
            consents = consentQuery.getConsentManagement();
            Set<Id> keys = consents.keySet();
            for(Id value : keys){
               String consentName =  consents.get(value).ConsentName__c;
               Decimal validity = consents.get(value).Validity__c;
               consentsData.put(consentName, validity.toPlainString());
            }
            Case myCase ;
            Individual individual;  
            //UnusedLocalVariable Opportunity opp;
			Account acc = accountQuery.findAccount(accountId);
		
            String defaultChannel = CEP_UTL_Permissions.getUserChannel(Userinfo.getUserId());
            String opptyId = params.get('opportunityId');
            String contactId;
            CustomerInteraction__c ci;
            Contact cnt;
            if(opptyId == null) {
                ci = CustomerInteractionQueries.getInstance().getLastInteractionByUserAndAccount(accountId,UserInfo.getUserId());
                if(ci!=null && ci.Contact__r !=null && ci.Contact__r.IndividualId != null){
                    individual = IndividualQueries.getInstance().findById(ci.Contact__r.IndividualId);
                } else {
                    if(ci == null) {
                        response.put('emptyInteractions', true);
                    }else if(ci.Contact__r == null) {
                        response.put('emptyContact', true);
                    }else if (ci.Contact__r.IndividualId == null) {
                        response.put('emptyIndividual', true);
                    }
                
                }
                System.debug('customer interaction'+ ci);
                System.debug('individual'+ individual);
            }
            else{
                System.debug('CEP_LC_ConsentManagmentWizard::initialize::opptyId='+opptyId);
                Map<String, Map<String,String>> oppty = CEP_UTL_SObject.getFieldsValuesByIds('Opportunity', new List<String>{'CustomerInteraction__r.Contact__r.IndividualId','CustomerInteraction__r.Contact__c'}, new Set<String>{opptyId});
                individual = IndividualQueries.getInstance().findById(oppty.get(opptyId).get('CustomerInteraction__r.Contact__r.IndividualId'));
                contactId = oppty.get(opptyId).get('CustomerInteraction__r.Contact__c');
                cnt = ContactQueries.getInstance().findById(contactId);
            }

            /*if(caseId == null && String.isBlank(caseId)){
                if(acc.RecordType.Name == 'Persona Fisica'){
                     myCase = caseSrv.createCase(accountId, 'Bozza');
                } else {
                    myCase = caseSrv.createCase(null, 'Bozza');
                }
            }*/
            String recordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get(caseRecordTypeGestioneConsensi).getRecordTypeId();
			myCase = new Case(Id = caseId);
			myCase.AccountId = accountId;
            myCase.RecordTypeId = recordTypeId;
            myCase.Status = CASE_STATUS_DRAFT;
            myCase.Contact__c = ci!=null ? ci.Contact__c : contactId;
            myCase.MailingApartment__c = ci!=null ? ci.Contact__r.CommunicationApartment__c : cnt.CommunicationApartment__c;
            myCase.MailingAt__c = ci!=null ? ci.Contact__r.CommunicationAt__c : cnt.CommunicationAt__c;
            myCase.MailingBuilding__c = ci!=null ? ci.Contact__r.CommunicationBuilding__c : cnt.CommunicationBuilding__c;
            myCase.MailingCadastralCode__c = ci!=null ? ci.Contact__r.CommunicationCadastralCode__c : cnt.CommunicationCadastralCode__c;
            myCase.MailingCity__c = ci!=null ? ci.Contact__r.CommunicationCity__c : cnt.CommunicationCity__c;
            myCase.MailingCountry__c = ci!=null ? ci.Contact__r.CommunicationCountry__c : cnt.CommunicationCountry__c;
            myCase.MailingFloor__c = ci!=null ? ci.Contact__r.CommunicationFloor__c : cnt.CommunicationFloor__c;
            myCase.MailingIstatCode__c = ci!=null ? ci.Contact__r.CommunicationIstatCode__c : cnt.CommunicationIstatCode__c;
            myCase.MailingLocality__c = ci!=null ? ci.Contact__r.CommunicationLocality__c : cnt.CommunicationLocality__c;
            myCase.MailingPostalCode__c = ci!=null ? ci.Contact__r.CommunicationPostalCode__c : cnt.CommunicationPostalCode__c;
            myCase.MailingProvince__c = ci!=null ? ci.Contact__r.CommunicationProvince__c : cnt.CommunicationProvince__c;
            myCase.MailingStaircase__c = ci!=null ? ci.Contact__r.CommunicationStaircase__c : cnt.CommunicationStaircase__c;
            myCase.MailingStreetName__c = ci!=null ? ci.Contact__r.CommunicationStreetName__c : cnt.CommunicationStreetName__c;
            myCase.MailingStreetNumber__c = ci!=null ? ci.Contact__r.CommunicationStreetNumber__c : cnt.CommunicationStreetNumber__c;
            myCase.MailingStreetNumberExtn__c = ci!=null ? ci.Contact__r.CommunicationStreetNumberExtn__c : cnt.CommunicationStreetNumberExtn__c;
            myCase.MailingStreetNumberType__c = ci!=null ? ci.Contact__r.CommunicationStreetNumberType__c : cnt.CommunicationStreetNumberType__c;
            myCase.MailingStreetType__c = ci!=null ? ci.Contact__r.CommunicationStreetType__c : cnt.CommunicationStreetType__c;
            if(params.get('opportunityId') != null) {
                myCase.Opportunity__c = params.get('opportunityId');
            }
            myCase.Subject = 'Gestione Consensi';
            // [ADC - Start Insert - Populate Lookup for Marketing Cloud]
            if(String.isNotBlank(campaignId)){
                myCase.Campaign__c = campaignId;
            }
            // [ADC - End Insert - Populate Lookup for Marketing Cloud]
			myCase = caseSrv.generateCase(myCase);
            if(myCase.PrivacyChange__c != null) {
                PrivacyChange__c privacyChange = privacyQuery.getPrivacyChangeById(myCase.PrivacyChange__c);
                if(privacyChange != null) {
                    response.put('privacyChange', privacyChange); 
                }
            }
            
            if(String.isBlank(caseId)){
				caseId = myCase.Id;
			}

			response.put('caseId', caseId);
			response.put('case', myCase);

            /*individual = individualSrv.findIndividualByAccount(accountId);
            if (individual == null) {
                individual = new Individual();  
            }*/
            response.put('contactId', ci != null ? ci.Contact__c : contactId);
            response.put('individual', individual);
            response.put('account', acc);
            response.put('accountId', acc.Id);
            response.put('error', false);
            response.put('consentsData', consentsData);
            response.put('process', process);
            response.put('completionModeOnline', COMPLETION_MODE_ONLINE);
            response.put('channel', defaultChannel);

        } catch (Exception e){
            response.put('error',true);
            response.put('errorMsg',e.getMessage());
            response.put('errorTrace',e.getStackTraceString());

        }
        return response;  
    }

    @AuraEnabled
    public static Object savePrivacyChangeConsent(Map<String,Object> params ) {
        Boolean solicitationCheck =(Boolean) params.get('solicitationCheck');
        Boolean thirdPartyCheck  = (Boolean) params.get('thirdPartyCheck');
        Boolean loyaltyCheck    = (Boolean)  params.get('loyaltyCheck');
        Boolean profilingCheck  = (Boolean)  params.get('profilingCheck');
        String individualId = (String) params.get('individualId');
        String caseId = (String) params.get('caseId');
        //UnusedLocalVariable String completionMode = (String) params.get('completionMode');        
        String link = (String) params.get('link');
            
        Map<String,Object> response = new Map<String,Object>();
        try {
                Individual individual = individualQuery.findById(individualId);
                Individual individualData = new Individual();
                individualData.Id = individualId;
                String channel = CEP_UTL_Permissions.getUserChannel(Userinfo.getUserId());
                String solicitation = (solicitationCheck) ?  individual.SolicitationConsent__c : null;
                String thirdParty = (thirdPartyCheck) ?  individual.ThirdPartySolicitationConsent__c : null;
                String loyality = (loyaltyCheck) ?  individual.LoyaltyConsent__c : null;
                String profiling = (profilingCheck) ?  individual.ProfilingConsent__c : null;
                individualData.SolicitationConsent__c = solicitation;
                individualData.ThirdPartySolicitationConsent__c = thirdParty;
                individualData.LoyaltyConsent__c = loyality;
                individualData.ProfilingConsent__c = profiling;
                PrivacyChange__c privacy = privacySrv.createPrivacyChangeFromIndividual(individualData, caseId, channel);
                Boolean isVocalOrder = String.isNotBlank(link);
                //UnusedLocalVariable String vocalOrderLink = link;
                Case myCase = new Case(Id = caseId);
                myCase.VocalOrder__c = isVocalOrder;
                //myCase.LinkVocalOrder__c = link;
                myCase.PrivacyChange__c = privacy.Id;
                databaseSrv.updateSObject(myCase);
                myCase = caseQuery.getById(caseId);
                privacy = privacyQuery.getPrivacyChangeById(privacy.Id);
                response.put('privacyChange', privacy); 
                response.put('myCase', myCase);
                response.put('error', false);

            } catch(Exception e){
                response.put('error',true);
                response.put('errorMsg',e.getMessage());
                response.put('errorTrace',e.getStackTraceString());
            }
        return response;
    }

    @AuraEnabled
    public static Object save(Map<String,Object> params ) {
        Savepoint savePoint = Database.setSavepoint();
        String individualId = (String) params.get('individualId');
        String caseId = (String) params.get('caseId');
        String completionMode = (String) params.get('completionMode');
        String privacyChangeId = (String) params.get('privacyChangeId');
        String contactId = (String) params.get('contactId');
        String channel = (String) params.get('channel');
        System.debug('CEP_LC_ConsentManagmentWizard::save::' +'contactId: ' + contactId+'-'+'individualId: '+individualId+'-'+'caseId: '+caseId+'-'+'completionMode: '+completionMode+'-'+'privacyChangeId: '+privacyChangeId+'-'+'channel: '+channel);
        Map<String,Object> response = new Map<String,Object>();
        try {
                String caseStatus;

                Map<String, Map<String, String>> caseObj = CEP_UTL_SObject.getFieldsValuesByIds('Case', new List<String>{'Opportunity__c', 'Opportunity__r.StageName'}, new Set<String>{caseId});

                if(completionMode == COMPLETION_MODE_DIGITAL_COMPLETION || completionMode == COMPLETION_MODE_DIGITAL_SIGNATURE) {
                    caseStatus = CASE_STATUS_WAITING_COMPLETION;
                } else if(String.isNotBlank(channel) && ((completionMode == COMPLETION_MODE_ONLINE && CHANNEL_PUNTI_FISICI.equalsIgnoreCase(channel)) ||
                (completionMode == COMPLETION_MODE_VOCAL_ORDER && channel == CHANNEL_CALL_CENTER))){
                    if(individualId!=null && privacyChangeId!=null && channel!=null){
                        individualSrv.updateIndividualConsentChannels(individualId,privacyChangeId,channel);
                    }
                    individualSrv.updateIndividualFromPrivacyChange(individualId, privacyChangeId);
                    caseStatus = CASE_STATUS_CHIUSO;
                }
                String caseCompletionMode;
                if(!caseObj.isEmpty() && !caseObj.get(caseId).isEmpty() && !String.isBlank(caseObj.get(caseId).get('Opportunity__c'))){
                    caseStatus = CASE_STATUS_CHIUSO;
                    caseCompletionMode = completionMode;
                }
                
                if(String.isNotBlank(caseStatus)) {
                    Case myCase = new Case(Id = caseId);
                    myCase.Status = caseStatus;
                    if(String.isNotBlank(caseCompletionMode)) {
                        myCase.CompletionMode__c = caseCompletionMode;
                    }
                    databaseSrv.updateSObject(myCase);
                    System.debug('Case is : ' + myCase);
                }
                
                if(contactId != null){
                    Case myCase = new Case(Id = caseId);
                    myCase.Contact__c = contactId;

                    // 07-04-2021 : ACTED-2613 - Il case è associato all'account del contact selezionato
                    // se l'account con lo stesso CF esiste
                    //----------------------------------------------------------------------------------
                    Contact cnt = ContactQueries.getInstance().findById(contactId);
                    if(cnt!=null && cnt.NationalIdentityNumber__c!=null){
                        Account ac = AccountQueries.getInstance().findByCf(cnt.NationalIdentityNumber__c);
                        if(ac!=null)
                            myCase.AccountId = ac.Id;
                    }
                    //----------------------------------------------------------------------------------
                    
                    databaseSrv.updateSObject(myCase);
                }

                if(completionMode == COMPLETION_MODE_DIGITAL_COMPLETION){
                    String process = 'Gestione Consensi';
                    String type = 'Perfezionamento Digitale';
                    
					CEP_SRV_TouchPoint touchPointSrv = CEP_SRV_TouchPoint.getInstance();
					Map<String,List<String>> inputParams = new Map<String,List<String>>();
					List<String> l = new List<String>();
					l.add(type);
					inputParams.put(caseId, l);
					touchPointSrv.startTouchPoint(process, inputParams);
                }

                if(caseStatus == CASE_STATUS_CHIUSO){
                    if(!caseObj.isEmpty() && !caseObj.get(caseId).isEmpty() && !String.isBlank(caseObj.get(caseId).get('Opportunity__c'))){
                        String stage = caseObj.get(caseId).get('Opportunity__r.StageName');
                        if('attesa perfezionamento'.equalsIgnoreCase(stage)){
                            CEP_UTL_AcquisitionProcesses.pushOpportunity(caseObj.get(caseId).get('Opportunity__c'));
                        }
                        
                    }
                }

                response.put('error', false);
            } catch(Exception e){
                Database.rollback(savePoint);
                response.put('error',true);
                response.put('errorMsg',e.getMessage());
                response.put('errorTrace',e.getStackTraceString());
            }
        return response;
    }

    @AuraEnabled
    public static List<OpportunityServiceItem__c> getOsiVas(String oppId) {
        String recordType = 'CEP_RT_Vas';
        List<OpportunityServiceItem__c> osiVasList = new List<OpportunityServiceItem__c>();
        osiVasList = [ SELECT Id,Name,ParentOSI__c,QuoteLine__r.SBQQ__Product__c,Product__r.Name,VASConsentAssurance__c, VASConsentFranchigia__c, VASConsentPersonalData__c FROM OpportunityServiceItem__c WHERE Opportunity__c = :oppId AND RecordType.DeveloperName =:recordType WITH SECURITY_ENFORCED ];//AND RecordType.DeveloperName =:recordType
        return (!osiVasList.isEmpty() && osiVasList.size() > 0) ? osiVasList : null;
    }

    @AuraEnabled
    public static List<OpportunityServiceItem__c> getOsiVasById(String osiVasId) {
        String recordType = 'CEP_RT_Vas';
        List<OpportunityServiceItem__c> osiVasList = new List<OpportunityServiceItem__c>();
        osiVasList = [ SELECT Id, Name,Product__r.Name, VASConsentAssurance__c, VASConsentFranchigia__c, VASConsentPersonalData__c FROM OpportunityServiceItem__c WHERE Id = :osiVasId AND RecordType.DeveloperName =:recordType WITH SECURITY_ENFORCED ];//AND RecordType.DeveloperName =:recordType
        return (!osiVasList.isEmpty() && osiVasList.size() > 0) ? osiVasList : null;
    }

    @AuraEnabled(cacheable = false)
    public static Map<String,Object> cancelOsiVas(Map<String,String> params) {
        Map<String,Object> response = new Map<String,Object>();
        String osiVasListIds = (String)params.get('osiVasListId');
        Savepoint sp = Database.setSavepoint();
        try {
            List<String> osiVasIds = (List<String>)JSON.deserialize(osiVasListIds, List<String>.class);
            System.debug('osiVasIds : '+ osiVasIds);
            List<OpportunityServiceItem__c> osiVasList = [SELECT Id, Name FROM OpportunityServiceItem__c WHERE Id IN :osiVasIds ];
            System.debug('opportunityServItemList before delete'+ osiVasList);
            if(!osiVasList.isEmpty()) {
                databaseSrv.deleteSObject(osiVasList);
            }
            response.put('error', false);
        } catch (Exception e) {
            Database.rollback(sp);
            response.put('error', true);
            response.put('errorMsg', e.getMessage());
            response.put('errorTrace', e.getStackTraceString());
        }     
        return response;
    }
  
}