Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
124 kB
20
Indexable
Never
public without sharing class CEP_LC_DedicatedProcessWizard {
    private static final CEP_QR_AtecoTranscode atecoQr = CEP_QR_AtecoTranscode.getInstance();
    private static final CEP_QR_IvaConfiguration ivaQr = CEP_QR_IvaConfiguration.getInstance();
    private static final CEP_QR_Accisa accisaQr= CEP_QR_Accisa.getInstance();
    private static final CEP_QR_CityRegistry cityRegistryQr = CEP_QR_CityRegistry.getInstance();
    private static final CEP_QR_ClimaticZone climaticQr = CEP_QR_ClimaticZone.getInstance();
    private static final CEP_QR_Taxes imposteQr = CEP_QR_Taxes.getInstance();
    private static final CEP_QR_AdditionalRegional additionaQr =CEP_QR_AdditionalRegional.getInstance();
    private static OpportunityServiceItemQueries osiQuery = OpportunityServiceItemQueries.getInstance();
    private static OpportunityQueries oppQuery = OpportunityQueries.getInstance();
    private static ServicePointQueries servicePointQuery = ServicePointQueries.getInstance();
    private static final AccountQueries accountQuery = AccountQueries.getInstance();
    private static Constants constantSrv = Constants.getAllConstants();

    private static final String DIST_REMI_CODE_KEY = 'distRemicode';
    private static final String DIST_P_IVA_KEY = 'distpIva';

    @AuraEnabled
    public static Map<String,Object> insertOsi(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        if(!CEP_UTL_Permissions.isUserOnline(UserInfo.getUserId())){
            response.put('error',true);
            response.put('errorMsg','Impossibile salvare. Si prega di aggiornare lo stato di presenza sull\'omnichannel e riprovare');
        }
        String osiParams = params.get('OSI');
        String codeAteco = params.get('codeAteco');
        String atecoId = params.get('atecoId');
        String actualVoltageLevel = params.get('actualVoltageLevel');
        String isMassMarketString = params.get('isMassMarket');
        Boolean isMassMarket = String.isNotBlank(isMassMarketString) && Boolean.valueOf(isMassMarketString);
        System.debug('ATECO ' + codeAteco);
        System.debug('OSI FROM PARAMS ' + osiParams);
        try{
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        if(codeAteco!=null && String.isNotBlank(codeAteco)){
        ateco = atecoQr.atecoTranscode(codeAteco); 
        }
        if(atecoId != null && String.isNotBlank(atecoId)){
            ateco = atecoQr.atecoTranscodeById(atecoId); 
        }
        System.debug('ATECO OBJ' + ateco);
        OpportunityServiceItem__c osi = (OpportunityServiceItem__c) JSON.deserialize(osiParams,OpportunityServiceItem__c.class);
        System.debug('OSI DESERIALIZED ' + osi);
        Boolean isLargeWorld = FeatureManagement.checkPermission('CEP_Large_Sme_Permission') || FeatureManagement.checkPermission('CEP_Small_Business_Permission') ;
        System.debug('isLargeWorld      '  + isLargeWorld );
        if(osi!=null){
            //if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_ATTIVAZIONE_PROCESS) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SUBENTRO_PROCESS)){
            if(osi.Process__c.equalsIgnoreCase( 'Modifica potenza e tensione' ) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_ATTIVAZIONE_PROCESS) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SUBENTRO_PROCESS)){
                String tensione1 = osi.VoltageLevel__c!=null ? osi.VoltageLevel__c.containsIgnoreCase('monofase') ? 'Monofase' : 'Trifase' : '';
                String tensione2 = actualVoltageLevel!=null ? actualVoltageLevel.containsIgnoreCase('monofase') ? 'Monofase' : 'Trifase' : '';
                String voltageReq = osi.VoltageLevel__c!=null ? osi.VoltageLevel__c.substring( 0, 2 ) : '';
                String voltageAct = actualVoltageLevel!=null ? actualVoltageLevel.substring( 0, 2 ) : '';

                System.debug('tensione 1      '  + tensione1 + ' tensione 2  ' + tensione2);
                if( osi.Process__c != 'Modifica potenza e tensione' && (osi.VoltageLevel__c != actualVoltageLevel || ( !isLargeWorld && ((osi.VoltageLevel__c != null && osi.VoltageLevel__c.containsIgnoreCase('MT')) || (actualVoltageLevel != null && actualVoltageLevel.containsIgnoreCase('MT'))))) ){
                    response.put('isOrdinario', true);
                    response.put('message', 'Il punto non è a preventivo rapido i costi verranno comunicati successivamente');
                    osi.QuoteType__c = '';
                    // osi.QuoteStatus__c = 'Da inviare a distributore';
                    // return response;
                }else{

                    if( osi.Process__c == 'Modifica potenza e tensione' 
                        && ( tensione1 != tensione2 //FASE!!!!
                            || voltageAct != voltageReq
                            ||  osi.IsPowerBeyond__c != osi.IsAvaiablePowerBeyond__c
                            //|| ( String.isNotBlank( osi.RequestedContractualPower__c ) && Double.valueOf( osi.RequestedContractualPower__c ) > 6 && osi.ContractualPower__c <= 6 )
                            || ( String.isNotBlank( osi.RequestedContractualPower__c ) && Double.valueOf( osi.RequestedContractualPower__c ) > 6 )
                            || ( String.isNotBlank( osi.RequestedContractualPower__c ) && osi.ContractualPower__c > 6 && Double.valueOf( osi.RequestedContractualPower__c ) <= 6 ) ) ){

                        response.put('isOrdinario', true);
                        response.put('message', 'Il punto non è a preventivo rapido i costi verranno comunicati successivamente');
                        osi.QuoteType__c = '';
                        // osi.QuoteStatus__c = 'Da inviare a distributore';

                        return response;
                    }

                        //UnusedLocalVariable QuoteType__c preventivo = new QuoteType__c();
                    Boolean isPowerBeyond = osi.IsPowerBeyond__c != null && osi.IsPowerBeyond__c;
                    Double potenzaDisponibileRichiest;
                    if(isPowerBeyond){
                        potenzaDisponibileRichiest = Double.valueOf(osi.RequestedContractualPowerBeyond__c);
                    }else{
                        potenzaDisponibileRichiest = Double.valueOf(osi.RequestedAvailablePower__c);
                    }
                    String variazioneDiPotenza = potenzaDisponibileRichiest == osi.AvailablePower__c ? 'NO' : 'SI';
                    if(variazioneDiPotenza == 'SI'){
                        Double potenzaDisponibile = osi.AvailablePower__c;
                        String thresholdAvailablePower = CEP_QR_TipoPreventivo.getInstance().getThresholdAvaiablePowerByVoltageLevel(tensione1);
                        Double threshold = (thresholdAvailablePower!=null && thresholdAvailablePower != '') ? Double.valueOf(thresholdAvailablePower) : potenzaDisponibile;
                        String operator1  = '';
                        String operator2  = '';
                        System.debug('variazione di potenza      '  + variazioneDiPotenza);
                        System.debug('potenza disponibile richiesta      '  + potenzaDisponibileRichiest);
                        System.debug('potenza disponibile      '  + potenzaDisponibile);
                        System.debug('thresold      '  +  threshold);
                        if(potenzaDisponibile  <= threshold  || potenzaDisponibileRichiest <= threshold )
                            operator1 = 'Minore uguale di';
                        if(potenzaDisponibile  > threshold  || potenzaDisponibileRichiest > threshold )
                            operator2 = 'Maggiore di';  

                        System.debug('operator 1      '  +  operator1 + ' operator 2  ' + operator2);    
                        List<QuoteType__c> quotesType = new List<QuoteType__c>();
                        quotesType = CEP_QR_TipoPreventivo.getInstance().getTipoPreventivo(osi.Process__c,variazioneDiPotenza,operator1,operator2,threshold);
                        Boolean isOrdinario = false;
                        for(QuoteType__c qt : quotesType ){
                            if(qt.Type__c == 'Ordinario'){
                                isOrdinario = true;
                                break; 
                            }
                        }
                        System.debug('ordinarioooooooooooooooooooooooooooooooo ' + isOrdinario);
                        if(isOrdinario){
                            osi.QuoteType__c = '';
                            // osi.QuoteStatus__c = 'Da inviare a distributore';
                            response.put('isOrdinario', isOrdinario);
                            response.put('message', 'Il punto non è a preventivo rapido i costi verranno comunicati successivamente');
                            // return response;   
                        }else{
                            osi.QuoteType__c = 'Rapido';
                            osi.QuoteStatus__c = 'Preventivo Perfezionato';
                        }
                    }else{
                        osi.QuoteType__c = 'Rapido';
                        osi.QuoteStatus__c = 'Preventivo Perfezionato';
                    }

                }
               
            }

            if(osi.RecordTypeId == Constants.getAllConstants().OSIRecordTypes.get('Gas')){
                osi.QuoteType__c = 'Rapido';
                osi.QuoteStatus__c = 'Preventivo Perfezionato';
            }
            //LD ADD
            if( osi.Process__c.equalsIgnoreCase( 'Modifica potenza e tensione' ) ){

                return response;
            }
            //UnusedLocalVariable Integer noOfDays = 0;//osi.ActDate__c.daysBetween( osi.RevenueAgencyRegisteredDate__c );
            if(osi.ActDate__c != null){
                if(osi.RevenueAgencyRegisteredDate__c < osi.ActDate__c){
                System.debug('Data regis. presso Ag.Entrate: ' + osi.RevenueAgencyRegisteredDate__c);
                System.debug('Data Atto: ' + osi.ActDate__c);
                response.put('error', true);
                response.put('errorMsg', 'Data regis. presso Ag.Entrate non può essere precedente alla data Data Atto');
                return response;
            }
        }
            
        if(osi.ExpectedAnnualWithdrawal__c != null && osi.ExpectedAnnualWithdrawal__c < 1){
            System.debug('Prelievo annuo previsto: ' + osi.ExpectedAnnualWithdrawal__c);
            response.put('error', true);
            response.put('errorMsg', 'Prelievo annuo previsto non può essere minore di 1');
            return response;
        } 
            List<Accisa__c> accise = new List<Accisa__c>();
            if(osi.Excise__c != null && String.isNotBlank(osi.Excise__c)){
                accise = accisaQr.getAcciseByDescription(osi.Excise__c);
            }
            if(ateco!=null && ateco.Id!=null && String.isNotBlank(ateco.Id)){
                osi.AtecoDescription__c = ateco.ClientAteco__c;
                osi.CodeAteco__c = ateco.Code__c;
                //osi.AtecueCode__c = ateco.AtecueCode__c;
            }
            if(accise != null && accise.size() > 0){
                osi.AccisaCode__c = accise[0].AccisaCode__c;
            }
            if(osi.DistributorVATNumber__c == null || String.isBlank(osi.DistributorVATNumber__c)){
                String idCode = '%' + osi.ServicePointCode__c.substring(0,5) + '%';
                List<PODDistributorAlignment__c> pdas = CEP_QR_PODDistributorAlignment.getInstance().getByIdentificationCodeList(idCode);
                String distributorVat = '';
                if(pdas!=null && pdas.size()>0){
                    distributorVat = pdas[0].DistributorVATNumber__c;
                }
                osi.DistributorVATNumber__c  = distributorVat;
            }
            List<OpportunityServiceItem__c> osis = new List<OpportunityServiceItem__c>();
            Account acc = accountQuery.findAccount(osi.Account__c);
            if(!isMassMarket) {
                setOsiContractType(osi, acc);
            }
            if(osi.Id != null && String.isNotBlank(osi.Id))
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            else
                CEP_SRV_OpportunityServiceItem.insertOsi(osi);
            osis = osiQuery.getOSIsByOpportunityId(osi.Opportunity__c);
            if(!isMassMarket) {
                updateAccountAteco(osi, ateco);
            }
            // Account acc = AccountQueries.getInstance().findAccount(osi.Account__c); 
            // if( osis != null && osis.size() == 1){
            //     if(ateco.Code__c != null &&  acc != null && String.isNotBlank(acc.Id) &&(( osi.ContractType__c != null && String.isNotBlank(osi.ContractType__c) && osi.ContractType__c != 'Persona fisica') ||(acc.RecordType.DeveloperName != null && acc.RecordType.DeveloperName =='CEP_RT_Organization' ))){
            //         acc.AtecoName__c = ateco.ClientAteco__c;
            //         acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
            //         acc.Classification__c = ateco.Classification__c;
            //         Database.update(acc);
            //     }  
            // }
            response.put('error', false);
            response.put('osi', osi);
        }
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }

        return response;

    }

    @AuraEnabled
    public static Map<String,Object> insertOsiSwitching(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        try{
        String osiParams = params.get('OSI');
        String codeAteco = params.get('codeAteco');
        String atecoId = params.get('atecoId');
        String isMassMarketString = params.get('isMassMarket');
        Boolean isMassMarket = String.isNotBlank(isMassMarketString) && Boolean.valueOf(isMassMarketString);
        Boolean isFromCommunity = null!=params.get('isFromCommunity') && 'true' == params.get('isFromCommunity') ? true : false;
        // String actualVoltageLevel = params.get('actualVoltageLevel');
        System.debug('ATECO ' + codeAteco);
        System.debug('OSI FROM PARAMS ' + osiParams);
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        if(codeAteco!=null && String.isNotBlank(codeAteco)){
            ateco = atecoQr.atecoTranscode(codeAteco); 
        }
        if(atecoId != null && String.isNotBlank(atecoId)){
            ateco = atecoQr.atecoTranscodeById(atecoId); 
        }
        System.debug('ATECO OBJ' + ateco);
        OpportunityServiceItem__c osi = (OpportunityServiceItem__c) JSON.deserialize(osiParams,OpportunityServiceItem__c.class);
        Opportunity opp = oppQuery.getOpportunityById(osi.Opportunity__c);
        System.debug('OSI DESERIALIZED ' + osi);
        Boolean isLargeWorld = FeatureManagement.checkPermission('CEP_Large_Sme_Permission') || FeatureManagement.checkPermission('CEP_Small_Business_Permission');
        System.debug('isLargeWorld      '  + isLargeWorld );
        if(osi!=null){
            // if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SWITCHING_WIN_PROCESS) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS)){
            //     String tensione1 = osi.VoltageLevel__c!=null ? osi.VoltageLevel__c.containsIgnoreCase('monofase') ? 'Monofase' : 'Trifase' : '';
            //     // String tensione2 = actualVoltageLevel!=null ? actualVoltageLevel.containsIgnoreCase('monofase') ? 'Monofase' : 'Trifase' : '';
            //     System.debug('tensione 1      '  + tensione1);
            //     if((!isLargeWorld && (osi.VoltageLevel__c != null && osi.VoltageLevel__c.containsIgnoreCase('MT'))) ){
            //         response.put('error', true);
            //         response.put('isOrdinario', true);
            //         response.put('message', 'Impossibile salvare il punto perché non a preventivazione rapida. Modificare i dati o procedere su Siebel');
            //         return response;
            //     }
            //     // QuoteType__c preventivo = new QuoteType__c();
            //     // Boolean isPowerBeyond = osi.IsPowerBeyond__c != null;
            //     // Double potenzaDisponibileRichiest;
            //     // if(isPowerBeyond){
            //     //     potenzaDisponibileRichiest = Double.valueOf(osi.RequestedContractualPowerBeyond__c);
            //     // }else{
            //     //     potenzaDisponibileRichiest = Double.valueOf(osi.RequestedAvailablePower__c);
            //     // } 
            // }
            osi.QuoteType__c = 'Rapido';
            osi.QuoteStatus__c = 'Preventivo Perfezionato';
            
            if( (osi.Process__c == 'Predisposizione con attivazione permanente') || (osi.Process__c == 'Predisposizione con attivazione temporanea - straordinaria') || (osi.Process__c == 'Predisposizione con attivazione temporanea - cantiere')){
            osi.QuoteType__c = '';
            osi.QuoteStatus__c = '';
            }
            if(osi.ExpectedAnnualWithdrawal__c != null && osi.ExpectedAnnualWithdrawal__c < 1){
                System.debug('Prelievo annuo previsto: ' + osi.ExpectedAnnualWithdrawal__c);
                response.put('error', true);
                response.put('errorMsg', 'Prelievo annuo previsto non può essere minore di 1');
                return response;
            }     
            List<Accisa__c> accise = new List<Accisa__c>();
            if(osi.Excise__c != null && String.isNotBlank(osi.Excise__c)){
                accise = accisaQr.getAcciseByDescription(osi.Excise__c);
            }
            if(ateco!=null && ateco.Id!=null && String.isNotBlank(ateco.Id)){
                osi.AtecoDescription__c = ateco.ClientAteco__c;
                osi.CodeAteco__c = ateco.Code__c;
                osi.AtecueCode__c = ateco.AtecueCode__c;
            }
            if(accise != null && accise.size() > 0){
                osi.AccisaCode__c = accise[0].AccisaCode__c;
            }
            if(osi.DistributorVATNumber__c == null || String.isBlank(osi.DistributorVATNumber__c)){
                String idCode = '%' + osi.ServicePointCode__c.substring(0,5) + '%';
                List<PODDistributorAlignment__c> pdas = CEP_QR_PODDistributorAlignment.getInstance().getByIdentificationCodeList(idCode);
                String distributorVat = '';
                if(pdas!=null && pdas.size()>0){
                    distributorVat = pdas[0].DistributorVATNumber__c;
                }
                osi.DistributorVATNumber__c  = distributorVat;
            }
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS)){
                ServicePoint__c servicePoint = servicePointQuery.getAddressByKey(osi.ServicePointCode__c);
                if(servicePoint != null){
                    setOsiAddress(osi,servicePoint);
                }
            }
            List<OpportunityServiceItem__c> osis = new List<OpportunityServiceItem__c>();
            Account acc = accountQuery.findAccount(osi.Account__c);
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OPPORTUNITY_SERVICE_ITEM_PROCESS_CAMBIO_USO)){
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' : 
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
             //   Map<String,Object> ivaResponse = ivaSelectedEle(type,osi.Usage__c, osi.RequestedIndustrialSector__c, 'Electric');
                Map<String,Object> atecoResponse = atecueSelected(osi.Usage__c,  osi.RequestedIndustrialSector__c);
                ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
                if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                    Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) osi.VATClass__c = osiIva.get('IvaCode__c');
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) osi.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
                }
             /*   if(ivaResponse != null && ivaResponse.get('iva') != null){
                    IvaConfiguration__c iva = (IvaConfiguration__c) ivaResponse.get('iva');
                    osi.VATTreatment__c = iva.Description__c;
                    osi.VATClass__c = iva.IvaCode__c;
                    if(iva.Rate__c != null){
                        osi.VATRate__c = Decimal.valueOf(iva.Rate__c);
                    }
                }*/
                if(atecoResponse != null && atecoResponse.get('ateco') != null){
                    AtecoTranscode__c atecue = (AtecoTranscode__c) atecoResponse.get('ateco');
                    if(atecue.AtecueCode__c != null){
                        osi.AtecueCode__c = String.valueOf(atecue.AtecueCode__c);
                    }
                }
                if(String.isBlank(acc.AtecoName__c) || String.isBlank(acc.AtecoDescription__c)){
                    acc.AtecoName__c = 'Altre attività  professionali, scientifiche e tecniche nca';
                    acc.AtecoDescription__c = '74.90';
                    Database.update(acc);
                }
                if(sp != null){
                    osi.VoltageLevel__c = sp.VoltageLevel__c;
                    osi.Voltage__c = sp.Voltage__c;
                    if(sp.AvailablePower__c != null){
                        osi.AvailablePower__c = sp.AvailablePower__c;
                        osi.RequestedAvailablePower__c = String.valueOf(sp.AvailablePower__c).replace('.', ',');
                    } else if(sp.ContractualPower__c != null) {
                        osi.AvailablePower__c = sp.ContractualPower__c*1.1;
                        osi.RequestedAvailablePower__c = String.valueOf(sp.ContractualPower__c*1.1).replace('.', ',');
                    }
                    if(sp.VoltageLevel__c != null){
                        osi.PowerPhase__c = sp.VoltageLevel__c.equalsIgnoreCase('bt monofase') ? 'Monofase' : 'Trifase';
                    }
                    if(sp.ContractualPower__c != null){
                        if(sp.ContractualPower__c > 30 || (sp.DistributorVATNumber__c == '05779711000' && sp.ContractualPower__c > 15)){
                            osi.IsAvaiablePowerBeyond__c = true;
                            osi.ContractualPowerBeyond__c = sp.ContractualPower__c;
                        }else{
                            osi.IsAvaiablePowerBeyond__c = false;
                            osi.ContractualPower__c = sp.ContractualPower__c;
                            osi.RequestedContractualPower__c = String.valueOf(sp.ContractualPower__c).replace('.', ',');
                        }
                    }
                }
            }
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SWITCHING_WIN_PROCESS)){
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' : 
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
              /*  Map<String,Object> ivaResponse = new Map<String,Object>();
                if(osi.RecordType.DeveloperName == 'Electric')
		            ivaResponse = ivaSelectedEle(type,osi.Usage__c, osi.RequestedIndustrialSector__c, 'Electric');
	            if(osi.RecordType.DeveloperName == 'Gas')
		            ivaResponse = ivaSelectedGas(osi.TISGUseType__c, osi.PDRType__c, osi.RecordType.DeveloperName);*/
                ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
               /* if(ivaResponse != null && ivaResponse.get('iva') != null){
                    IvaConfiguration__c iva = (IvaConfiguration__c) ivaResponse.get('iva');
                    osi.VATTreatment__c = iva.Description__c;
                    osi.VATClass__c = iva.IvaCode__c;
                    if(iva.Rate__c != null){
                        osi.VATRate__c = Decimal.valueOf(iva.Rate__c);
                    }
                }*/
            }
            if(osi.Process__c == 'SWITCHING WIN' && isMassMarket){
                osi.EffectiveDate__c = CEP_UTL_Date.calcSupplyStartDateSwitchingReset(Date.today());
            }
            if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) osi.VATClass__c = osiIva.get('IvaCode__c');
                if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) osi.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
            }
            if(!isMassMarket) {
                setOsiContractType(osi, acc);
            }
            if(String.isNotBlank(params.get('startTime'))){
                String[] startTime = params.get('startTime').split(':');
                osi.StartTime__c = Time.newInstance( Integer.valueOf(startTime[0]),
                                                        Integer.valueOf(startTime[1]),
                                                        0,
                                                        0);
            }
            if(String.isNotBlank(params.get('endTime'))){
                String[] endTime = params.get('endTime').split(':');
                osi.EndTime__c = Time.newInstance( Integer.valueOf(endTime[0]),
                                                    Integer.valueOf(endTime[1]),
                                                    0,
                                                    0);
            }
            if(osi.Id != null && String.isNotBlank(osi.Id))
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            else
                CEP_SRV_OpportunityServiceItem.insertOsi(osi);
            osis = osiQuery.getOSIsByOpportunityId(osi.Opportunity__c);
            // Account acc = AccountQueries.getInstance().findAccount(osi.Account__c); 
            if(!isMassMarket) {
                updateAccountAteco(osi, ateco);
            }
            for(OpportunityServiceItem__c o : osis){
                if(o.Id == osi.Id){
                    ServicePoint__c sp = (ServicePoint__c) getPreviousProduct(o.Account__c, o.RecordType.DeveloperName, o.ServicePointCode__c).get('servicePoint');
                    if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS) 
                    || (osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SWITCHING_WIN_PROCESS) && !isFromCommunity) 
                    || (osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_USO_PROCESS))
                    || (osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_MODIFICA_PDR_PROCESS))
                    || (osi.Process__c.toUppercase() == 'CAMBIO PRODOTTO CROSS BRAND')){//NTT W3
                        if(sp!=null && sp.CurrentAsset__r!=null){
                            String oldContractAccount = sp.CurrentAsset__r.ContractAccount__c;
                            String oldBillingProfile = sp.CurrentAsset__r.ContractAccount__r.BillingProfile__c;
                            osi.OldContractAccount__c = oldContractAccount;
                            osi.OldBillingProfile__c = oldBillingProfile;
                            osi.ContractAccount__c = sp.CurrentAsset__r.ContractAccount__r.PaymentTerms__c == opp.PaymentTerms__c ? oldContractAccount : isMassMarket ? oldContractAccount :  null;
                            osi.BillingProfile__c =  sp.CurrentAsset__r.ContractAccount__r.PaymentTerms__c == opp.PaymentTerms__c ? oldBillingProfile : isMassMarket ? oldBillingProfile : null;
                            osi.VATClass__c = sp.CurrentAsset__r.VATClass__c;
                            osi.VATTreatment__c = sp.CurrentAsset__r.VATTreatment__c;
                        }
                        if(osi.ContractAccount__c == null){
                            response.put('error', true);
                            response.put('errorMsg', 'Contract Account non trovato sull\'Asset o con termini di pagamento diversi da quelli dell\'opporunity');
                        }
                    }
                }
            }
            
            if(osi.Process__c == 'Modifica Tipologia PDR') {
                List<OpportunityServiceItem__c> osiList = (List<OpportunityServiceItem__c>) CEP_UTL_SObject.getListExecuteRequest('OpportunityServiceItem__c',  
                'Id,Process__c, Account__r.Segment__c, Account__r.SellingCharge__c,Account__r.RecordType.DeveloperName, Account__r.JointVenture__r.JointVentureCode__c,Account__r.JointVenture__r.AdministrativeSalesCharge__c,Account__r.Name, Opportunity__r.SalesCharges__c', 
                'Id =\''+ String.escapeSingleQuotes(osi.Id) + '\'', 
                null);

                osi.AdministrativeSalesCharges__c = CEP_UTL_ProcessWizard.getAdministrativeSalesCharges(osiList[0]);
            }

            if(osis!=null && osi!=null && osi.Id!=null){
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            }
    
            // if( osis != null && osis.size() == 1){
            //     if(ateco.Code__c != null &&  acc != null && String.isNotBlank(acc.Id) &&(( osi.ContractType__c != null && String.isNotBlank(osi.ContractType__c) && osi.ContractType__c != 'Persona fisica') ||(acc.RecordType.DeveloperName != null && acc.RecordType.DeveloperName =='CEP_RT_Organization' ))){
            //         acc.AtecoName__c = ateco.ClientAteco__c;
            //         acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
            //         acc.Classification__c = ateco.Classification__c;
            //         Database.update(acc);
            //     }  
            // }      
            response.put('error', false);
            response.put('osi', osi);
        }
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        
        return response;
    }
    /*
    @AuraEnabled
    public static Map<String,Object> insertOsiAttivazioneTecnica(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        try{
        String osiParams = params.get('OSI');
        String codeAteco = params.get('codeAteco');
        String atecoId = params.get('atecoId');
        String isMassMarketString = params.get('isMassMarket');
        Boolean isMassMarket = String.isNotBlank(isMassMarketString) && Boolean.valueOf(isMassMarketString);
        Boolean isFromCommunity = null!=params.get('isFromCommunity') && 'true' == params.get('isFromCommunity') ? true : false;
        // String actualVoltageLevel = params.get('actualVoltageLevel');
        System.debug('ATECO ' + codeAteco);
        System.debug('OSI FROM PARAMS ' + osiParams);
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        if(codeAteco!=null && String.isNotBlank(codeAteco)){
            ateco = atecoQr.atecoTranscode(codeAteco);
        }
        if(atecoId != null && String.isNotBlank(atecoId)){
            ateco = atecoQr.atecoTranscodeById(atecoId);
        }
        System.debug('ATECO OBJ' + ateco);
        OpportunityServiceItem__c osi = (OpportunityServiceItem__c) JSON.deserialize(osiParams,OpportunityServiceItem__c.class);
        Opportunity opp = oppQuery.getOpportunityById(osi.Opportunity__c);
        System.debug('OSI DESERIALIZED ' + osi);
        Boolean isLargeWorld = FeatureManagement.checkPermission('CEP_Large_Sme_Permission') || FeatureManagement.checkPermission('CEP_Small_Business_Permission');
        System.debug('isLargeWorld      '  + isLargeWorld );
        if(osi!=null){
            if(osi.ExpectedAnnualWithdrawal__c != null && osi.ExpectedAnnualWithdrawal__c < 1){
                System.debug('Prelievo annuo previsto: ' + osi.ExpectedAnnualWithdrawal__c);
                response.put('error', true);
                response.put('errorMsg', 'Prelievo annuo previsto non può essere minore di 1');
                return response;
            }
            List<Accisa__c> accise = new List<Accisa__c>();
            if(osi.Excise__c != null && String.isNotBlank(osi.Excise__c)){
                accise = accisaQr.getAcciseByDescription(osi.Excise__c);
            }
            if(ateco!=null && ateco.Id!=null && String.isNotBlank(ateco.Id)){
                osi.AtecoDescription__c = ateco.ClientAteco__c;
                osi.CodeAteco__c = ateco.Code__c;
                osi.AtecueCode__c = ateco.AtecueCode__c;
            }
            if(accise != null && accise.size() > 0){
                osi.AccisaCode__c = accise[0].AccisaCode__c;
            }
            if(osi.DistributorVATNumber__c == null || String.isBlank(osi.DistributorVATNumber__c)){
                String idCode = '%' + osi.ServicePointCode__c.substring(0,5) + '%';
                List<PODDistributorAlignment__c> pdas = CEP_QR_PODDistributorAlignment.getInstance().getByIdentificationCodeList(idCode);
                String distributorVat = '';
                if(pdas!=null && pdas.size()>0){
                    distributorVat = pdas[0].DistributorVATNumber__c;
                }
                osi.DistributorVATNumber__c  = distributorVat;
            }
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS)){
                ServicePoint__c servicePoint = servicePointQuery.getAddressByKey(osi.ServicePointCode__c);
                if(servicePoint != null){
                    setOsiAddress(osi,servicePoint);
                }
            }
            List<OpportunityServiceItem__c> osis = new List<OpportunityServiceItem__c>();
            Account acc = accountQuery.findAccount(osi.Account__c);
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OPPORTUNITY_SERVICE_ITEM_PROCESS_CAMBIO_USO)){
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' :
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
             //   Map<String,Object> ivaResponse = ivaSelectedEle(type,osi.Usage__c, osi.RequestedIndustrialSector__c, 'Electric');
                Map<String,Object> atecoResponse = atecueSelected(osi.Usage__c,  osi.RequestedIndustrialSector__c);
                ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
                if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                    Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) osi.VATClass__c = osiIva.get('IvaCode__c');
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) osi.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
                }
             
                if(atecoResponse != null && atecoResponse.get('ateco') != null){
                    AtecoTranscode__c atecue = (AtecoTranscode__c) atecoResponse.get('ateco');
                    if(atecue.AtecueCode__c != null){
                        osi.AtecueCode__c = String.valueOf(atecue.AtecueCode__c);
                    }
                }
                if(String.isBlank(acc.AtecoName__c) || String.isBlank(acc.AtecoDescription__c)){
                    acc.AtecoName__c = 'Altre attività  professionali, scientifiche e tecniche nca';
                    acc.AtecoDescription__c = '74.90';
                    Database.update(acc);
                }
                if(sp != null){
                    osi.VoltageLevel__c = sp.VoltageLevel__c;
                    osi.Voltage__c = sp.Voltage__c;
                    if(sp.AvailablePower__c != null){
                        osi.AvailablePower__c = sp.AvailablePower__c;
                        osi.RequestedAvailablePower__c = String.valueOf(sp.AvailablePower__c).replace('.', ',');
                    } else if(sp.ContractualPower__c != null) {
                        osi.AvailablePower__c = sp.ContractualPower__c*1.1;
                        osi.RequestedAvailablePower__c = String.valueOf(sp.ContractualPower__c*1.1).replace('.', ',');
                    }
                    if(sp.VoltageLevel__c != null){
                        osi.PowerPhase__c = sp.VoltageLevel__c.equalsIgnoreCase('bt monofase') ? 'Monofase' : 'Trifase';
                    }
                    if(sp.ContractualPower__c != null){
                        if(sp.ContractualPower__c > 30 || (sp.DistributorVATNumber__c == '05779711000' && sp.ContractualPower__c > 15)){
                            osi.IsAvaiablePowerBeyond__c = true;
                            osi.ContractualPowerBeyond__c = sp.ContractualPower__c;
                        }else{
                            osi.IsAvaiablePowerBeyond__c = false;
                            osi.ContractualPower__c = sp.ContractualPower__c;
                            osi.RequestedContractualPower__c = String.valueOf(sp.ContractualPower__c).replace('.', ',');
                        }
                    }
                }
            }
            if(osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS) || osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SWITCHING_WIN_PROCESS)){
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' :
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
              
               // ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
              
            }
            if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) osi.VATClass__c = osiIva.get('IvaCode__c');
                if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) osi.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
            }
            if(!isMassMarket) {
                setOsiContractType(osi, acc);
            }
            if(osi.Id != null && String.isNotBlank(osi.Id))
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            else
                CEP_SRV_OpportunityServiceItem.insertOsi(osi);
            osis = osiQuery.getOSIsByOpportunityId(osi.Opportunity__c);
            // Account acc = AccountQueries.getInstance().findAccount(osi.Account__c);
            if(!isMassMarket) {
                updateAccountAteco(osi, ateco);
            }
            for(OpportunityServiceItem__c o : osis){
                if(o.Id == osi.Id){
                    ServicePoint__c sp = (ServicePoint__c) getPreviousProduct(o.Account__c, o.RecordType.DeveloperName, o.ServicePointCode__c).get('servicePoint');
                    if((osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS) && sp.CurrentAsset__r!=null &&  (isMassMarket || sp.CurrentAsset__r.ContractAccount__r.PaymentTerms__c == opp.PaymentTerms__c)) || (osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_SWITCHING_WIN_PROCESS) && !isFromCommunity) || (osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_USO_PROCESS) && sp.CurrentAsset__r!=null && sp.CurrentAsset__r.ContractAccount__r.PaymentTerms__c == opp.PaymentTerms__c)){
                        if(sp!=null && sp.CurrentAsset__r!=null){
                            String oldContractAccount = sp.CurrentAsset__r.ContractAccount__c;
                            String oldBillingProfile = sp.CurrentAsset__r.ContractAccount__r.BillingProfile__c;
                            osi.OldContractAccount__c = oldContractAccount;
                            osi.OldBillingProfile__c = oldBillingProfile;
                            osi.ContractAccount__c = oldContractAccount;
                            osi.BillingProfile__c = oldBillingProfile;
                            osi.VATClass__c = sp.CurrentAsset__r.VATClass__c;
                            osi.VATTreatment__c = sp.CurrentAsset__r.VATTreatment__c;
                        }
                    }
                }
            }
            if(osis!=null && osi!=null && osi.Id!=null){
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            }

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

        return response;
    } */

    private static void updateAccountAteco(OpportunityServiceItem__c osi, AtecoTranscode__c ateco) {
        if(ateco != null && osi.Account__c != null && ateco.ClientAteco__c != null && ateco.AtecoDescriptionClient__c != null) {
            Account acc = new Account(Id = osi.Account__c);
            acc.AtecoName__c = ateco.ClientAteco__c;
            acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
            Database.update(acc);
        }    
                    
    }
    @TestVisible
    private static void setOsiContractType(OpportunityServiceItem__c osi, Account acc) {
        if(null == acc){
            return;
        }
        String accDeveloperName = acc.RecordTypeDeveloperName__c;
        if(accDeveloperName == constantSrv.ACCOUNT_RECORDTYPE_RESELLER_END_CUSTOMER) {
            String reqUsageCat = osi.Usage__c;
           if(acc.Type == constantSrv.ACCOUNT_TYPE_PERSONA_FISICA) {
               String fiscalCode = acc.FiscalCode__c;
               String vatNumber = acc.VATNumber__c;
               Boolean isOtherOrPublicUsage = reqUsageCat == 'Altri us' || reqUsageCat == 'Illuminazione Pubblica';
               if(String.isNotBlank(fiscalCode) && !fiscalCode.isNumeric() && String.isNotBlank(reqUsageCat)) {
                    if(reqUsageCat == 'Domestico' || (isOtherOrPublicUsage && String.isBlank(vatNumber))) {
                        osi.ContractType__c = constantSrv.OSI_CONTRACT_TYPE_PERSONA_FISICA;
                    } else if(isOtherOrPublicUsage && String.isNotBlank(vatNumber)) {
                        osi.ContractType__c = constantSrv.OSI_CONTRACT_TYPE_DITTA_INDIVIDUALE;
                    }
               }
           }
        }    
                    
    }

    @AuraEnabled
    public static Map<String,Object> insertOsiVoltura(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        List<Accisa__c> accisa =new List<Accisa__c>(); 
        List<Taxes__c> taxis = new List<Taxes__c>();
        try{
        String osiParams = params.get('OSI');
        String codeAteco = params.get('codeAteco');
        String atecoId = params.get('atecoId');
        Boolean isCommercialCounterPart = params.get('isCommercialCounterPart')!=null && params.get('isCommercialCounterPart').equalsIgnoreCase('SI');
        // String actualVoltageLevel = params.get('actualVoltageLevel');
        System.debug('ATECO ' + codeAteco);
        System.debug('OSI FROM PARAMS ' + osiParams);
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        if(codeAteco!=null && String.isNotBlank(codeAteco)){
            ateco = atecoQr.atecoTranscode(codeAteco); 
        }
        if(atecoId != null && String.isNotBlank(atecoId)){
            ateco = atecoQr.atecoTranscodeById(atecoId); 
        }
        System.debug('ATECO OBJ' + ateco);
        OpportunityServiceItem__c osi = (OpportunityServiceItem__c) JSON.deserialize(osiParams,OpportunityServiceItem__c.class);
        Opportunity opp = oppQuery.getOpportunityById(osi.Opportunity__c);
        System.debug('OSI DESERIALIZED ' + osi);

        if(osi!=null && osi.ServicePointCode__c!=null){
            osi.QuoteType__c = 'Rapido';
            osi.QuoteStatus__c = 'Preventivo Perfezionato';
            ServicePoint__c servicePointAdress = servicePointQuery.getAddressByKey(osi.ServicePointCode__c);
            if(servicePointAdress != null){
                    setOsiAddress(osi,servicePointAdress);
            }
            //START GET Servicepoint WITHOUT SHARING
            String selectedFields = 'Id, DistributorVATNumber__c,InstalledPotentiality__c,RequestedPotentiality__c,Voltage__c, VoltageLevel__c, AvailablePower__c, ContractualPower__c,CurrentAsset__r.AccountId,CurrentAsset__r.Product2Id';
            String clauseCondition = 'Key__c =\'' + osi.ServicePointCode__c +'\'';
            ServicePoint__c sp = null;
            List<ServicePoint__c> spList= (List<ServicePoint__c>)CEP_UTL_SObject.getListExecuteRequest('ServicePoint__c',selectedFields,clauseCondition,null);
            if(!spList.isEmpty()){
                sp = spList.get(0);
            }
            //END GET Servicepoint WITHOUT SHARING
            if(sp != null){
                osi.InstalledPotentiality__c = sp.InstalledPotentiality__c;
                osi.RequestedPotentiality__c = sp.RequestedPotentiality__c;
                if(sp.AvailablePower__c != null){
                    osi.AvailablePower__c = sp.AvailablePower__c;
                    osi.RequestedAvailablePower__c = String.valueOf(sp.AvailablePower__c).replace('.', ',');
                } else if(sp.ContractualPower__c != null) {
                    osi.AvailablePower__c = sp.ContractualPower__c*1.1;
                    osi.RequestedAvailablePower__c = String.valueOf(sp.ContractualPower__c*1.1).replace('.', ',');
                }
                if(sp.ContractualPower__c != null){
                    osi.ContractualPower__c = sp.ContractualPower__c;
                    osi.RequestedContractualPower__c = String.valueOf(sp.ContractualPower__c).replace('.', ',');
                }
                if(osi.Process__c.toLowerCase() == Constants.getAllConstants().OSI_VOLTURA_MORTIS_CAUSA_PROCESS.toLowerCase() ||
                        osi.Process__c.toLowerCase() == Constants.getAllConstants().OSI_VOLTURA_FUSIONE_INCORPORAZIONE_PROCESS.toLowerCase()){
                    if(sp.CurrentAsset__r.Product2Id == null || String.isBlank(sp.CurrentAsset__r.Product2Id)){
                        response.put('error', true);
                        response.put('errorMsg', 'Errore Base Dati : Sull\'Asset associato alla fornitura : ' + osi.ServicePointCode__c + ' non è presente un prodotto');
                        return response;
                    }
                    osi.Product__c = sp.CurrentAsset__r.Product2Id;
                    if (osi.Process__c.toLowerCase() == Constants.getAllConstants().OSI_VOLTURA_FUSIONE_INCORPORAZIONE_PROCESS.toLowerCase()) {
                        list<quote> quoteList = new list<quote>();
                        list<QuoteLineItem> quoteLineItemList = new list<QuoteLineItem>();
                            quoteList = [select id from quote where OpportunityId = :osi.opportunity__c limit 1];
                            if (quoteList.size() > 0 && quoteList[0].id != null) {
                                quoteLineItemList = [select id, Product2Id from QuoteLineItem where QuoteId = :quoteList[0].id limit 1];
                                if (quoteList.size() > 0 && quoteLineItemList[0].Product2Id != null) {
                                    if (quoteLineItemList[0].Product2Id != sp.CurrentAsset__r.Product2Id) {
                                        osi.Product__c = quoteLineItemList[0].Product2Id;
                                    }
                                }
                            }
                    }
                }
                osi.Asset__c = sp.CurrentAsset__c;
                List<AccountContactRelation> acr = AccountContactRelationQueries.getInstance().listByAccountIdAndRoles(sp.CurrentAsset__r.AccountId);
                if(acr != null && acr.size()>0){
                    osi.TransferredContact__c = acr[0].ContactId;
                }
            }
        }

        if(osi!=null){
            String descriptionAccisa = '';
            if(osi.PointIstatCode__c!=null && String.isNotEmpty(osi.PointIstatCode__c)){
                taxis = imposteQr.getIstat(osi.PointIstatCode__c);
                if(taxis != null && taxis.size()>0){
                    osi.RegionalAdition__c = taxis[0].AdditionalCode__c;
                    accisa =  accisaQr.getAcciseByCode(taxis[0].AccisaCode__c);
                    if(accisa!=null && accisa.size()>0){
                        descriptionAccisa = accisa[0].Description__c;
                        osi.Excise__c = descriptionAccisa;
                        osi.AccisaCode__c = taxis[0].AccisaCode__c;
                    }
                }    
            }
            if(osi.ExpectedAnnualWithdrawal__c != null && osi.ExpectedAnnualWithdrawal__c < 1){
                System.debug('Prelievo annuo previsto: ' + osi.ExpectedAnnualWithdrawal__c);
                response.put('error', true);
                response.put('errorMsg', 'Prelievo annuo previsto non può essere minore di 1');
                return response;
            }     
            if(ateco!=null && ateco.Id!=null && String.isNotBlank(ateco.Id)){
                osi.AtecoDescription__c = ateco.ClientAteco__c;
                osi.CodeAteco__c = ateco.Code__c;
                osi.AtecueCode__c = ateco.AtecueCode__c;
                
            }

            if(osi.process__c =='Voltura Tecnica' && osi.CorrectionEffectiveDate__c==null && osi.EffectiveDate__c!=null ){
                osi.CorrectionEffectiveDate__c = osi.EffectiveDate__c;
            }

            if(osi.DistributorVATNumber__c == null || String.isBlank(osi.DistributorVATNumber__c)){
                String distributorVat = '';
                if(osi.RecordTypeId!=null && osi.RecordTypeId == Constants.getAllConstants().OSIRecordTypes.get('Electric')){
                    String idCode = '%' + osi.ServicePointCode__c.substring(0,5) + '%';
                    List<PODDistributorAlignment__c> pdas = CEP_QR_PODDistributorAlignment.getInstance().getByIdentificationCodeList(idCode);
                    if(pdas!=null && pdas.size()>0){
                        distributorVat = pdas[0].DistributorVATNumber__c;
                    }
                }
                if(osi.RecordTypeId!=null && osi.RecordTypeId == Constants.getAllConstants().OSIRecordTypes.get('Gas')){
                    ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
                    if(sp!=null)
                        distributorVat = sp.DistributorVATNumber__c;
                }
                System.debug('DISTRIBUTOR VAT NUMBER ' + distributorVat);
                osi.DistributorVATNumber__c  = distributorVat;
            }
            List<OpportunityServiceItem__c> osis = new List<OpportunityServiceItem__c>();
            if(osi.Id != null && String.isNotBlank(osi.Id))
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            else
                CEP_SRV_OpportunityServiceItem.insertOsi(osi);
            
            osis = osiQuery.getOSIsByOpportunityId(osi.Opportunity__c);
            Account acc = AccountQueries.getInstance().findAccount(osi.Account__c); 
    
            if( osis != null && osis.size() > 0){
                if(ateco.Code__c != null &&  acc != null && String.isNotBlank(acc.Id) &&(( osi.ContractType__c != null && String.isNotBlank(osi.ContractType__c) && osi.ContractType__c != 'Persona fisica') ||(acc.RecordType.DeveloperName != null && acc.RecordType.DeveloperName =='CEP_RT_Organization' ))){
                    acc.AtecoName__c = ateco.ClientAteco__c;
                    acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
                    acc.Classification__c = ateco.Classification__c;
                    Database.update(acc);
                }
            }
            if(osi.Id!=null){
                OpportunityServiceItem__c tmp = OpportunityServiceItemQueries.getInstance().getById(osi.Id);                
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' : 
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
                Map<String,Object> ivaResponse = new Map<String,Object>();
                if(tmp.RecordType.DeveloperName == 'Electric')
                    //ivaResponse = ivaSelectedEle(type,tmp.Usage__c, tmp.RequestedIndustrialSector__c, tmp.RecordType.DeveloperName);
                if(tmp.RecordType.DeveloperName == 'Gas'){
                   // ivaResponse = ivaSelectedGas(tmp.TISGUseType__c, tmp.PDRType__c, tmp.RecordType.DeveloperName);
                    if(acc != null && acc.Segment__c != Constants.getAllConstants().ACCOUNT_SEGMENT_MASS_MARKET && String.isBlank(tmp.SupplyEnergyService__c)){
                        tmp.SupplyEnergyService__c = 'NO';
                    }
                }
               /* if(ivaResponse.get('iva')!=null){
                    tmp.VATClass__c = ((IvaConfiguration__c)ivaResponse.get('iva')).IvaCode__c;
                    tmp.VATRate__c = Decimal.valueOf(((IvaConfiguration__c)ivaResponse.get('iva')).Rate__c);
                }*/
                if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                    Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) tmp.VATClass__c = osiIva.get('IvaCode__c');
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) tmp.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
                }

                if(isCommercialCounterPart!=null && osi.Process__c.equalsIgnoreCase(Constants.getAllConstants().OSI_VOLTURA_CON_SWITCHING_PROCESS)){
                    List<CEP_ProcessOmTranscode__mdt> ompt = CEP_QR_ProcessOmTranscode.getInstance().getOMTranscode(osi.Process__c, isCommercialCounterPart);
                    if(ompt!=null && ompt.size()>0){
                        tmp.ProcessOM__c = ompt[0].ProcessOM__c;
                    }
                }
                else{
                    tmp.ProcessOM__c = tmp.Process__c;
                }
                DatabaseService.getInstance().updateSObject(tmp);
            }
            /*for(OpportunityServiceItem__c o : osis){
                if(o.Id == osi.Id){
                    ServicePoint__c sp = (ServicePoint__c) getPreviousProduct(o.Account__c, o.RecordType.DeveloperName, o.ServicePointCode__c).get('servicePoint');
                    if(sp.CurrentAsset__r!=null && sp.CurrentAsset__r.ContractAccount__r.PaymentTerms__c == opp.PaymentTerms__c){
                        if(sp!=null && sp.CurrentAsset__r!=null){
                            String oldContractAccount = sp.CurrentAsset__r.ContractAccount__c;
                            String oldBillingProfile = sp.CurrentAsset__r.ContractAccount__r.BillingProfile__c;
                            osi.OldContractAccount__c = oldContractAccount;
                            osi.OldBillingProfile__c = oldBillingProfile;
                            osi.ContractAccount__c = oldContractAccount;
                            osi.BillingProfile__c = oldBillingProfile;
                            osi.VATClass__c = sp.CurrentAsset__r.VATClass__c;
                            osi.VATTreatment__c = sp.CurrentAsset__r.VATTreatment__c;
                        }
                    }
                }
            }*/
            response.put('error', false);
            response.put('osi', osi);
        }
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        
        return response;
    }

    @AuraEnabled
    public static Map<String,Object> insertOsiAttivazioneTecnicaRemiDirette(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        List<Accisa__c> accisa =new List<Accisa__c>(); 
        List<Taxes__c> taxis = new List<Taxes__c>();
        try{
        String osiParams = params.get('OSI');
        Boolean isCommercialCounterPart = params.get('isCommercialCounterPart')!=null && params.get('isCommercialCounterPart').equalsIgnoreCase('SI');
        // String actualVoltageLevel = params.get('actualVoltageLevel');
        System.debug('OSI FROM PARAMS ' + osiParams);
        OpportunityServiceItem__c osi = (OpportunityServiceItem__c) JSON.deserialize(osiParams,OpportunityServiceItem__c.class);
        Opportunity opp = oppQuery.getOpportunityById(osi.Opportunity__c);
        System.debug('OSI DESERIALIZED ' + osi);

        if(osi!=null && osi.ServicePointCode__c!=null){
            osi.QuoteType__c = 'Rapido';
            osi.QuoteStatus__c = 'Preventivo Perfezionato';
            ServicePoint__c servicePointAdress = servicePointQuery.getAddressByKey(osi.ServicePointCode__c);
            if(servicePointAdress != null){
                    setOsiAddress(osi,servicePointAdress);
            }
            //START GET Servicepoint WITHOUT SHARING
            String selectedFields = 'Id, DistributorVATNumber__c,InstalledPotentiality__c,RequestedPotentiality__c,Voltage__c, VoltageLevel__c, AvailablePower__c, ContractualPower__c,CurrentAsset__r.AccountId,CurrentAsset__r.Product2Id';
            String clauseCondition = 'Key__c =\'' + osi.ServicePointCode__c +'\'';
            ServicePoint__c sp = null;
            List<ServicePoint__c> spList= (List<ServicePoint__c>)CEP_UTL_SObject.getListExecuteRequest('ServicePoint__c',selectedFields,clauseCondition,null);
            if(!spList.isEmpty()){
                sp = spList.get(0);
            }
            //END GET Servicepoint WITHOUT SHARING
            if(sp != null){
                osi.InstalledPotentiality__c = sp.InstalledPotentiality__c;
                osi.RequestedPotentiality__c = sp.RequestedPotentiality__c;
                if(sp.AvailablePower__c != null){
                    osi.AvailablePower__c = sp.AvailablePower__c;
                    osi.RequestedAvailablePower__c = String.valueOf(sp.AvailablePower__c).replace('.', ',');
                } else if(sp.ContractualPower__c != null) {
                    osi.AvailablePower__c = sp.ContractualPower__c*1.1;
                    osi.RequestedAvailablePower__c = String.valueOf(sp.ContractualPower__c*1.1).replace('.', ',');
                }
                if(sp.ContractualPower__c != null){
                    osi.ContractualPower__c = sp.ContractualPower__c;
                    osi.RequestedContractualPower__c = String.valueOf(sp.ContractualPower__c).replace('.', ',');
                }
                if(osi.Process__c.toLowerCase() == Constants.getAllConstants().OSI_VOLTURA_MORTIS_CAUSA_PROCESS.toLowerCase() ||
                        osi.Process__c.toLowerCase() == Constants.getAllConstants().OSI_VOLTURA_FUSIONE_INCORPORAZIONE_PROCESS.toLowerCase()){
                    if(sp.CurrentAsset__r.Product2Id == null || String.isBlank(sp.CurrentAsset__r.Product2Id)){
                        response.put('error', true);
                        response.put('errorMsg', 'Errore Base Dati : Sull\'Asset associato alla fornitura : ' + osi.ServicePointCode__c + ' non è presente un prodotto');
                        return response;
                    }
                    osi.Product__c = sp.CurrentAsset__r.Product2Id;
                }
                osi.Asset__c = sp.CurrentAsset__c;
                List<AccountContactRelation> acr = AccountContactRelationQueries.getInstance().listByAccountIdAndRoles(sp.CurrentAsset__r.AccountId);
                if(acr != null && acr.size()>0){
                    osi.TransferredContact__c = acr[0].ContactId;
                }
            }
        }

        if(osi!=null){
            String descriptionAccisa = '';
            if(osi.PointIstatCode__c!=null && String.isNotEmpty(osi.PointIstatCode__c)){
                taxis = imposteQr.getIstat(osi.PointIstatCode__c);
                if(taxis != null && taxis.size()>0){
                    osi.RegionalAdition__c = taxis[0].AdditionalCode__c;
                    accisa =  accisaQr.getAcciseByCode(taxis[0].AccisaCode__c);
                    if(accisa!=null && accisa.size()>0){
                        descriptionAccisa = accisa[0].Description__c;
                        osi.Excise__c = descriptionAccisa;
                        osi.AccisaCode__c = taxis[0].AccisaCode__c;
                    }
                }    
            }
            if(osi.ExpectedAnnualWithdrawal__c != null && osi.ExpectedAnnualWithdrawal__c < 1){
                System.debug('Prelievo annuo previsto: ' + osi.ExpectedAnnualWithdrawal__c);
                response.put('error', true);
                response.put('errorMsg', 'Prelievo annuo previsto non può essere minore di 1');
                return response;
            }     
            if(osi.DistributorVATNumber__c == null || String.isBlank(osi.DistributorVATNumber__c)){
                String distributorVat = '';
                if(osi.RecordTypeId!=null && osi.RecordTypeId == Constants.getAllConstants().OSIRecordTypes.get('Electric')){
                    String idCode = '%' + osi.ServicePointCode__c.substring(0,5) + '%';
                    List<PODDistributorAlignment__c> pdas = CEP_QR_PODDistributorAlignment.getInstance().getByIdentificationCodeList(idCode);
                    if(pdas!=null && pdas.size()>0){
                        distributorVat = pdas[0].DistributorVATNumber__c;
                    }
                }
                if(osi.RecordTypeId!=null && osi.RecordTypeId == Constants.getAllConstants().OSIRecordTypes.get('Gas')){
                    ServicePoint__c sp = ServicePointQueries.getInstance().getByKey(osi.ServicePointCode__c);
                    if(sp!=null)
                        distributorVat = sp.DistributorVATNumber__c;
                }
                System.debug('DISTRIBUTOR VAT NUMBER ' + distributorVat);
                osi.DistributorVATNumber__c  = distributorVat;
            }
            List<OpportunityServiceItem__c> osis = new List<OpportunityServiceItem__c>();
            if(osi.Id != null && String.isNotBlank(osi.Id))
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            else
                CEP_SRV_OpportunityServiceItem.insertOsi(osi);
            
            osis = osiQuery.getOSIsByOpportunityId(osi.Opportunity__c);
            Account acc = AccountQueries.getInstance().findAccount(osi.Account__c); 
            if(osi.Id!=null){
                OpportunityServiceItem__c tmp = OpportunityServiceItemQueries.getInstance().getById(osi.Id);                
                String type = acc.RecordType.DeveloperName == 'CEP_RT_PhysicalPerson' ? 'Persona Fisica/Ditta Individuale' : 
                                acc.RecordType.DeveloperName == 'CEP_RT_Organization' || acc.RecordType.DeveloperName == 'Business' ? 'Organizzazione' : '*';
                Map<String,Object> ivaResponse = new Map<String,Object>();
                if(tmp.RecordType.DeveloperName == 'Electric')
                    //ivaResponse = ivaSelectedEle(type,tmp.Usage__c, tmp.RequestedIndustrialSector__c, tmp.RecordType.DeveloperName);
                if(tmp.RecordType.DeveloperName == 'Gas'){
                   // ivaResponse = ivaSelectedGas(tmp.TISGUseType__c, tmp.PDRType__c, tmp.RecordType.DeveloperName);
                    if(acc != null && acc.Segment__c != Constants.getAllConstants().ACCOUNT_SEGMENT_MASS_MARKET && String.isBlank(tmp.SupplyEnergyService__c)){
                        tmp.SupplyEnergyService__c = 'NO';
                    }
                }
               /* if(ivaResponse.get('iva')!=null){
                    tmp.VATClass__c = ((IvaConfiguration__c)ivaResponse.get('iva')).IvaCode__c;
                    tmp.VATRate__c = Decimal.valueOf(((IvaConfiguration__c)ivaResponse.get('iva')).Rate__c);
                }*/
                if (osi.Commodity__c != null && string.isNotBlank(osi.VATTreatment__c)) {
                    Map<String, String> osiIva = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(osi.Commodity__c, osi.VATTreatment__c);
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('IvaCode__c') != null) tmp.VATClass__c = osiIva.get('IvaCode__c');
                    if (osiIva.containsKey('IvaCode__c') && osiIva.get('Rate__c') != null) tmp.VATRate__c = decimal.valueOf(osiIva.get('Rate__c'));
                }
                DatabaseService.getInstance().updateSObject(tmp);
            }
            response.put('error', false);
            response.put('osi', osi);
        }
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        
        return response;
    }

    @AuraEnabled
    public static Map<String,Object> checkDistributorVAT(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        try{
        String osiId = params.get('osiId');
        System.debug('OSI ID ' + osiId);
        OpportunityServiceItem__c osi = new OpportunityServiceItem__c();
        // Controllo su piva distributore
            osi = osiQuery.getById(osiId);
            if(osi.DistributorName__c!=null && String.isNotEmpty(osi.DistributorName__c) && 
            osi.REMICode__c!=null && String.isNotEmpty(osi.REMICode__c) && 
                (osi.DistributorVATNumber__c == null || String.isEmpty(osi.DistributorVATNumber__c)) &&
                    osi.PointIstatCode__c!=null && String.isNotEmpty(osi.PointIstatCode__c)){
                        System.debug('RETRIEVE DISTR');
                        System.debug(osi.DistributorName__c);
                        System.debug(osi.PointIstatCode__c);
                        osi.DistributorVATNumber__c = CEP_LC_DedicatedProcessWizard.retrieveDistributorVat(osi.PointIstatCode__c,osi.DistributorName__c);
                        System.debug('RETRIEVE DISTR RES ' + osi.DistributorVATNumber__c);
                        if(osi.DistributorVATNumber__c!=null)
                            CEP_SRV_OpportunityServiceItem.updateOsi(osi);
                    }
                    response.put('error', false);
            } catch(Exception ex){
            response.put('error', true);
			response.put('errorMsg', ex.getMessage());
			response.put('errorTrace', ex.getStackTraceString());
            }
        return response;
    }

    public static String retrieveDistributorVat(String istatCode, String distributorName){
        Map<String,Object> res = callEbdm(istatCode);
        if(res!=null && ((Map<String,String>)res.get(DIST_P_IVA_KEY)).get(distributorName)!=null){
            System.debug('DISTR PIVA MAP ' + (Map<String,String>)res.get(DIST_P_IVA_KEY));
            return ((Map<String,String>)res.get(DIST_P_IVA_KEY)).get(distributorName);
        }
        return null;
    }
    

    @AuraEnabled(cacheable = false)
	public static Object  prescreening(String accountId, String oppId){
		Map<String,Object> response = new Map<String,Object>();
        response = CEP_UTL_CervedCachingCheck.Prescreening(accountId);
        CreditCheck__c check= new CreditCheck__c();
        String esito;
        Account acc = new Account();
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        try{
            // CACHE NON PRESENTE
            if(!(Boolean)response.get('prescreening')){
                // invoco il servizio
                check = CEP_SRV_CreditPreCheckCER01.invokePreCheck(oppId);
                // la chiamata va a buon fine
                if(check!= null && check.ResultCode__c!=null){
                    // leggo l'esito sritto sull'opp
                    esito = OpportunityQueries.getInstance().getCreditCheckStatusOpportunity(oppId).PrescreeningStatus__c;
                    //Opportunity opp = new Opportunity(Id = oppId);
                    //opp.Prescreening__c = check.Id;
                    //DatabaseService.getInstance().updateSObject(opp);
                    // ko lavorabile - creo l'attività per BO
                    // EDIT 03/03/2020 VS : L'activity viene creata dal metodo di invocazione del servizio
                    /*if(esito.containsIgnoreCase('ko lavorabile')){
                        Utils.createCervedBackOfficeActivity(oppId);
                        response.put('koLavorabile', true);
                    }*/
                    response.put('error', false);
                    response.put('esito', esito);
                    response.put('precheckResponse', check);
                    response.put('codiceAteco', check.Ateco__c);
                    //Se ateco e presente scrivo su account 
                    if(check.Ateco__c != null && accountId!=null){
                        ateco = atecoQr.atecoTranscode(check.Ateco__c);
                        acc.Id = accountId;
                        acc.AtecoName__c = ateco.ClientAteco__c;
                        acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
                        acc.Classification__c = ateco.Classification__c;
                        DatabaseService.getInstance().updateSObject(acc);
                    }
                }
                // la chiamata non va a buon fine
                else{
                    response.put('error', true);
                    response.put('esito', 'TECHNICAL ERROR');
                    response.put('precheckResponse', check);
                }
            }
            // RECUPERO ESITO DA CACHE
            else{
                // Se l'opportunity da cache è diversa da quella attuale
                if((String)response.get('oppId')!=null && (String)response.get('oppId')!=oppId){
                    // scrivo l'esito sull'opp
                    Opportunity opp = new Opportunity(Id=oppId);
                    opp.PrescreeningStatus__c = (String)response.get('esito');
                    if(((CreditCheck__c)response.get('creditCheck'))!=null){
                        CreditCheck__c cc = CEP_QR_CreditCheck.getInstance().getAllFieldsById(((CreditCheck__c)response.get('creditCheck')).Id);
                        System.debug('>>>cc: ' + cc);
                        if(cc.Opportunity__c != opp.Id){
                            CreditCheck__c ccClone = cc.clone(false, true, false, false);
                            ccClone.Opportunity__c = opp.Id;
                            DatabaseService.getInstance().insertSObject(ccClone);
                            System.debug('>>>ccClone: ' + ccClone);
                            opp.Prescreening__c = ccClone.Id;
                            System.debug('>>>opp: ' + opp);
                        }
                    }
                    opp.PrescreeningDate__c = System.Date.today();
                    DatabaseService.getInstance().updateSObject(opp);
                    // ko lavorabile - creo l'attività per BO
                    if(((String)response.get('esito')).containsIgnoreCase('ko lavorabile')){
                        Utils.createCervedBackOfficeActivity(oppId);
                        response.put('koLavorabile', true);
                    }
                    response.put('error', false);
                    // recupero l'ateco da account
                    String codiceAteco = AccountQueries.getInstance().getAccountAtecoDescription(accountId);
                    response.put('codiceAteco', codiceAteco); // mocked
                    response.put('atecoObj', atecoQr.atecoTranscodeByDescriptionClient(codiceAteco));
                }
                // Opportunity da cache è quella attuale - prescreening già richiesto
                else{
                    response.put('preescreeningAlreadyRequired', true);
                }
            }
        }catch(Exception e){
            response.put('error', true);
            response.put('esito', 'TECHNICAL ERROR');
            response.put('errorMsg', e.getMessage() + ' '  + e.getStackTraceString());
        }
		return response;
    }

    @AuraEnabled(cacheable = false)
	public static Object  getDefaultAteco(String accountId){
		Map<String,Object> response = new Map<String,Object>();
        AtecoTranscode__c ateco = new AtecoTranscode__c();
        try{
            List<Account>  accounts = (List<Account>)CEP_UTL_SObject.getListExecuteRequest('Account', 'AtecoName__c', 'Id=\'' + accountId+ '\'', null);
            String codiceAteco = accounts[0].AtecoName__c;
            response.put('codiceAteco', codiceAteco);
            response.put('atecoObj', atecoQr.getByClientAtecoWithSameDesc(codiceAteco));
        }catch(Exception e){
            response.put('error', true);
            response.put('errorMsg', e.getMessage() + ' '  + e.getStackTraceString());
        }
		return response;
    }
    
    @AuraEnabled
    public static Map<String,Object> atecTranscode(String codeAteco, String accountId, String contractType){
        Map<String,Object> response = new Map<String,Object>();
        try{
            AtecoTranscode__c ateco = new AtecoTranscode__c();
            //UnusedLocalVariable Account acc = new Account();
            if(String.isBlank(codeAteco)){
                throw new WrtsException(System.Label.MissingParameter);
            } 
            ateco = atecoQr.atecoTranscode(codeAteco);
            // if(ateco.Code__c != null &&  accountId != null && String.isNotBlank(accountId) && contractType != null && String.isNotBlank(contractType) && contractType != 'Persona fisica'){
            //     acc.Id = accountId;
            //     acc.AtecoName__c = ateco.ClientAteco__c;
            //     acc.AtecoDescription__c = ateco.AtecoDescriptionClient__c;
            //     acc.Classification__c = ateco.Classification__c;
            //     Database.update(acc);
            // }
            response.put('error', false);
            response.put('ateco', ateco);
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }

        return response;

    }

    @AuraEnabled
    public static Map<String,Object> atecueSelected(String usage, String industry){
        Map<String,Object> response = new Map<String,Object>();
        try{
            AtecoTranscode__c ateco = new AtecoTranscode__c();
            if(usage != null && String.isNotBlank(usage) && industry != null && String.isNotBlank(industry)){
                ateco = atecoQr.getAtecoByUsageIndustry(usage , industry);
                System.debug('systemmmmmm atecoooooooo ' + ateco);
            }else {
                throw new WrtsException(System.Label.MissingParameter);
            }
            response.put('error', false);
            response.put('ateco', ateco);
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }

        return response;
    }

    @AuraEnabled
    public static Map<String,Object> getAtecoManualValues(){
        Map<String,Object> response = new Map<String,Object>();
        List<AtecoTranscode__c> atecoValues = new List<AtecoTranscode__c>();
        try{
            atecoValues = atecoQr.getAtecosByCode('%MANUALE%');
            response.put('error', false);
            response.put('atecoValues', atecoValues);
            System.debug('ATECO VALUES' + atecoValues);
        }
        catch(Exception e){
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }

        return response;
    }

    @AuraEnabled
    public static Map<String,Object> checkProcessCompatibility(Map <String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        Map<String,String> input = new Map<String,String>();
        try{
            input.put('podPdr', params.get('podPdr'));
            input.put('startingProcess', params.get('startingProcess'));
            input.put('channel', params.get('channel'));
            input.put('commodity', params.get('commodity'));
            input.put('distributor', params.get('distributor'));
            Boolean isTitoloIV = params.get('isTitoloIV')!=null && params.get('isTitoloIV').containsIgnoreCase('si');
            if(input.get('startingProcess').containsIgnoreCase('voltura')){
                if(Constants.getAllConstants().OSI_VOLTURE_TITOLO_3.containsIgnoreCase(input.get('startingProcess'))){
                    input.put('startingProcess', 'Voltura Titolo 3');
                }
                if(Constants.getAllConstants().OSI_VOLTURE_TITOLO_4.containsIgnoreCase(input.get('startingProcess'))){
                    input.put('startingProcess', isTitoloIV ? 'Voltura Titolo 4' : 'Voltura Titolo 3');
                }
            }
            Map<String,Object> incompatibilitySrvResMap = CEP_UTL_CompatibilityMatrix.getCompatibility(input);
            response.put('incompatibility', incompatibilitySrvResMap.get('incompatibility'));
            response.put('records', incompatibilitySrvResMap.get('records'));
            response.put('incompatibleObject', incompatibilitySrvResMap.get('incompatibleObject'));
            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 Map<String,Object> ivaSelectedEle(String accountType, String usage, String industry,String commodity){
        Map<String,Object> response = new Map<String,Object>();
        IvaConfiguration__c iva = new IvaConfiguration__c();
        try {
            if(accountType != null && String.isNotBlank(accountType) && usage != null && String.isNotBlank(usage) && industry != null && String.isNotBlank(industry)&& commodity != null && String.isNotBlank(commodity))
               iva = ivaQr.getIvaByEle(accountType,usage,industry,commodity);
               else {
                throw new WrtsException(System.Label.MissingParameter);
                 }
               response.put('error', false);
               response.put('iva', iva);
        } catch (Exception e) {
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static Map<String,Object> ivaSelectedGas(String tipoTisg, String tipPdr, String commodity){
        Map<String,Object> response = new Map<String,Object>();
        IvaConfiguration__c iva = new IvaConfiguration__c();
        try {
            if(tipoTisg != null && String.isNotBlank(tipoTisg) && tipPdr !=null && String.isNotBlank(tipPdr)&& commodity !=null && String.isNotBlank(commodity)){
                iva =ivaQr.getIvaByGas(tipoTisg,tipPdr,commodity);
                System.debug('IVA ' +iva);
                response.put('error',false);
                response.put('iva', iva);
            } else {
                throw new WrtsException(System.Label.MissingParameter);
            }
           System.debug('fdfgdkgdgriopturiturhjkbnlngeeeeeeeeveeeeeeee tipo tisg ' + tipoTisg + '  tipo pdr ' + tipPdr);
        } catch (Exception e) {
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        return response;
    }
    //SS - AENRTI-894 - 18/01/2021 - START
    @AuraEnabled
    public static Map<String, Object> callEbdm(String istatCode){
        System.debug('callEbdm istatCode= ' +istatCode);

        Map<String, List<String>> distRemicode = new Map<String, List<String>>();
        Map<String, String> distpIva = new Map<String, String>();
        Map<String, Object> res = new Map<String, Object>();
        Map<String, String> richiestaDistributoreRemiHeader = new Map<String, String>{
            'PIATTA_SORG'   => 'SF',
            'PIATTA_DEST'   => 'EBDM',
            'DATA_RICH'     => String.valueOf(DateTime.now()),
            'DATA_PUBBL'    => String.valueOf(DateTime.now()),
            'COD_SERVIZIO'  => 'ISU30',
            'COD_FLUSSO'    => '0050'
        };     
        Map<String, String> richiestaDistributoreRemiPosizione = new Map<String, String>{
            'COMMODITY' => 'GAS',
            'ISTAT_FOR' => istatCode
            //'ISTAT_FOR' => '058091'
        };

        System.debug('@@richiestaDistributoreRemiHeader ' + richiestaDistributoreRemiHeader);
        System.debug('@@richiestaDistributoreRemiPosizione ' + richiestaDistributoreRemiPosizione);
        
        try {

            CEP_UTL_EbdmCallout service = new CEP_UTL_EbdmCallout();
            Object obj = service.invokeEbdmSync(richiestaDistributoreRemiHeader, richiestaDistributoreRemiPosizione);
            String objSerialize = Json.serialize(obj);
            CEP_WS_EDM01_EbdmSchema.ebdmResponse_element response = (CEP_WS_EDM01_EbdmSchema.ebdmResponse_element) json.deserialize(objSerialize,CEP_WS_EDM01_EbdmSchema.ebdmResponse_element.class);
            System.debug('response = ' +response);

            String distributor;
            String remiCode;
            String pIvaDistr;

            for(CEP_WS_EDM01_EbdmSchema.itemTbPos_element element : response.TbPos.itemTbPos){

                if(('NOME_DISTRIBUTORE').equalsIgnoreCase(element.NomeCampo)){
                    distributor = element.ValoreCampo;
                }
                if(('COD_REMI').equalsIgnoreCase(element.NomeCampo)){
                    remiCode = element.ValoreCampo;
                }
                if(('PIVA_DISTR').equalsIgnoreCase(element.NomeCampo)){
                    pIvaDistr = element.ValoreCampo;
                }
                if(String.isNotBlank(distributor) && String.isNotBlank(remiCode)) {
                    List<String> remidoceList = new List<String>();
                    remidoceList.add(remiCode);
                    distRemicode.put(distributor, remidoceList);
                    distpIva.put(distributor, pIvaDistr);
                    distributor = '';
                    remiCode= '';
                    pIvaDistr='';
                    break;
                }
            }
            System.debug('distRemicode ' +distRemicode);

            String stIdLeva = 'DISREMI0X';
            for(Integer i = 1; i < 10; i++){
                String replacement = String.valueOf(i);
                String currentIdLeva = stIdLeva.replace('X', replacement);
                System.debug('currentIdLeva ' +currentIdLeva);
                System.debug('response ' +response);
                System.debug('response.TbOut ' +response.TbOut);
                System.debug('response.TbOut.itemTbOut ' +response.TbOut.itemTbOut);
                for(CEP_WS_EDM01_EbdmSchema.itemTbOut_element element : response.TbOut.itemTbOut){

                    if(currentIdLeva.equalsIgnoreCase(element.IdLeva) && ('NOME_DISTRIBUTORE').equalsIgnoreCase(element.IdAttributo)){
                        distributor = element.ValoreAttributo;
                        System.debug('distributor' +distributor);
                    }
                    if(currentIdLeva.equalsIgnoreCase(element.IdLeva) && ('COD_REMI').equalsIgnoreCase(element.IdAttributo)){
                        remiCode = element.ValoreAttributo;
                        System.debug('remiCode' +remiCode);
                    }
                    if(currentIdLeva.equalsIgnoreCase(element.IdLeva) && ('PIVA_DISTR').equalsIgnoreCase(element.IdAttributo)){
                        pIvaDistr = element.ValoreAttributo;
                        System.debug('pIvaDistr' +pIvaDistr);
                    }
                    if(String.isNotBlank(distributor) && String.isNotBlank(remiCode)) {
                        if(distpIva.get(distributor)==null || distpIva.get(distributor) == pIvaDistr)
                            distpIva.put(distributor, pIvaDistr);
                        List<String> rmlist = new List<String>();
                        if(null != distRemicode.get(distributor)) {
                            rmlist = distRemicode.get(distributor);
                            if(!rmlist.contains(remiCode)){
                                rmlist.add(remiCode);
                                distRemicode.put(distributor, rmlist);
                                distributor = '';
                                remiCode= '';
                                pIvaDistr='';
                                break;
                            }
                        } else {
                            rmlist.add(remiCode);
                            distRemicode.put(distributor, rmlist);
                            if(distpIva.get(distributor)==null || distpIva.get(distributor) == pIvaDistr)
                                distpIva.put(distributor, pIvaDistr);
                            distributor = '';
                            remiCode= '';
                            pIvaDistr='';
                            break; 
                        }
                        res.put('remiCodeList', rmlist); 
                        
                    }
                }
                System.debug('itezarione ' +i +'distRemicode ' +distRemicode); 
            }
            System.debug('@@@ distRemicode ' +distRemicode);

            res.put(DIST_REMI_CODE_KEY, distRemicode);
            res.put(DIST_P_IVA_KEY, distpIva);
            res.put('pIvaDistr', pIvaDistr); 
            res.put('distributorName', distributor); 
            res.put('response' , JSON.serialize(response));
            return res;

         } catch (Exception e) {
            System.debug('Exception callEbdm: ' + e.getMessage() + ' ' + e.getStackTraceString());
            return null;
        }	 
    }

    @AuraEnabled
    public static Map<String, Object> updateOpportunityPrescreeningStatus(String prescreeningStatus, String oppId){
        Map<String,Object> response = new Map<string,Object>();
        Opportunity opp = new Opportunity();
        try {
            if(prescreeningStatus != null && String.isNotBlank(prescreeningStatus) && oppId != null && String.isNotBlank(oppId)){
                opp.PrescreeningStatus__c = prescreeningStatus;
                opp.Id = oppId;
                DatabaseService.getInstance().updateSObject(opp);
                response.put('error', false);
                response.put('opp', opp);
            }else{
                response.put('error', true);
            }
                      
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage());
            response.put('errorStacktrace', e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static Map<String,Object> getCadastalCode(String cityName){
        Map<String,Object> response = new Map<String,Object>();
        CityRegistry__c city = new CityRegistry__c();
        try {
            if(cityName != null && String.isNotBlank(cityName)){
                city = cityRegistryQr.findByCityName(cityName);
                response.put('error', false);
                response.put('city', city);
            } else {
                throw new WrtsException(System.Label.MissingParameter);
            }
            
        } catch (Exception e ) {
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        return response;
    }
    @AuraEnabled
    public static Map<String,Object> getCap(String postalCode){
        Map<String,Object> response = new Map<String,Object>();
        List<Accisa__c> accisa =new List<Accisa__c>(); 
        List<Taxes__c> taxis = new List<Taxes__c>();
        // ClimaticZoneCity__c climaticzone = new ClimaticZoneCity__c();
        // List<ClimaticZoneCity__c> zone = new List<ClimaticZoneCity__c>();
        try {
            if(postalCode != null && String.isNotBlank(postalCode)){
                taxis = imposteQr.getIstat(postalCode);
                if(taxis != null && taxis.size()>0){
                    accisa =  accisaQr.getAcciseByCode(taxis[0].AccisaCode__c);
                    String descriptionAccisa = '';
                    if(accisa!=null && accisa.size()>0){
                        descriptionAccisa = accisa[0].Description__c;
                    }

                    response.put('error', false);
                    response.put('taxis',taxis);
                    response.put('descriptionAccisa',descriptionAccisa);
                }else{
                    response.put('error', true);
                    response.put('errorMsg', 'Non sono stati trovati dati imposte per l\'istat ' + postalCode);
            
                }
                // climaticzone= climaticQr.getPostalCode(postalCode)[0];
                // zone = climaticQr.getPostalCodeFromCassaMezzogiono(postalCode);
                // Boolean isCassa = zone.size() > 0; 
               
                // response.put('climaticzone', climaticzone);
                // response.put('isCassa', isCassa);
            }

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

    }

    @AuraEnabled
    public static Map<String,Object> addizionaleRegionale(String uso , String zone, String regione ){
        Map<String, Object> response = new Map<String, Object>();
        AdditionalRegion__c addizionale = new AdditionalRegion__c();
        List<AdditionalRegion__c> addizionali = new List<AdditionalRegion__c>();
        try {
            if(uso != null && String.isNotBlank(uso) && zone != null && String.isNotBlank(zone) && regione != null && String.isNotBlank(regione)){
                if(uso == 'Uso Tecnologico'){
                   uso = 'Uso Industriale';
                }
                addizionali= additionaQr.getAddizionale(uso,zone,regione);
                System.debug('ADDIZIONALI ' + addizionali);
                if(addizionali.size()>0)
                    addizionale = additionaQr.getAddizionale(uso,zone,regione)[0];
                response.put('error', false);
                response.put('addizionale', addizionale);
            }
        } catch (Exception e) {
            response.put('error', true);
			response.put('errorMsg', e.getMessage());
			response.put('errorTrace', e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static List<Map<String,Object>> getIvaPickList(String commodity){
        List<Map<String,Object>> response = new List<Map<String,Object>>();
        try {
            if(commodity != null && String.isNotBlank(commodity))
            response = CEP_QR_IvaConfiguration.getInstance().getIvaDescriptions(commodity);
            
        } catch (Exception e ) {
            System.debug('e.getMessage() ----> ' + e.getMessage());
            System.debug('errorStackTraceString -----> ' + e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static Map<String,Object> getIvaRateAndCode(String commodity,String description){
        Map<String,Object> response = new Map<String,Object>();
        try {
            if(commodity != null && String.isNotBlank(commodity) && description != null && String.isNotBlank(description))
            response = CEP_QR_IvaConfiguration.getInstance().getIvaRateAndCode(commodity,description);
            
        } catch (Exception e ) {
            System.debug('e.getMessage() ----> ' + e.getMessage());
            System.debug('errorStackTraceString -----> ' + e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static Map<String, Object> recoverDistributorVatNumber(String opportunityId) {

        return recoverDistributorVatNumber(opportunityId, false);
    }

    public static Map<String, Object> recoverDistributorVatNumber(String opportunityId, Boolean isFunnelBasso){
        Map<String, Object> res = new Map<String, Object>();
        res.put('error', false);
        List<Boolean> osiWithDistributerVatNumbr = new List<Boolean>();
        //UnusedLocalVariable Boolean blockOpportunity = false;
        Map<String, Object>  returnValue = null;
        try {
            List<OpportunityServiceItem__c> osiList = osiQuery.getOsiWithoutDistributorVatNumber(opportunityId);
            List<OpportunityServiceItem__c> osiListToUpdate = new List<OpportunityServiceItem__c>();
            for(OpportunityServiceItem__c osi : osiList){
                returnValue = callEbdm(osi.PointIstatCode__c);
                if(returnValue != null && !returnValue.isEmpty()) {
                Map<String, List<String>> distRemicode = ( Map<String, List<String>>) returnValue.get(DIST_REMI_CODE_KEY);
                Map<String, String> distpIva = (Map<String, String>) returnValue.get(DIST_P_IVA_KEY);
                String distributerKey ;
                for(String key : distpIva.keySet()) {
                    distributerKey = key;
                    break;
                }
                if(String.isNotBlank(distributerKey)) {
                    OpportunityServiceItem__c updatedOsi = new OpportunityServiceItem__c(Id = osi.Id);
                    Boolean updated = false;
                    if(isFunnelBasso) {

                        updatedOsi.DistributorName__c = distributerKey;
                        updated = true;
                    }
                    List<String> remiCodes = distRemicode.get(distributerKey);
                    if(remiCodes != null && !remiCodes.isEmpty()) { 
                        updatedOsi.RemiCode__c = remiCodes.get(0);
                        updated = true;
                    }
                    String distributerVatNumber = distpIva.get(distributerKey);
                    if(String.isNotBlank(distributerVatNumber)) {
                        updatedOsi.DistributorVATNumber__c = distributerVatNumber;
                        updated = true;
                        osiWithDistributerVatNumbr.add(true);
                    }
                    if(updated) {
                        osiListToUpdate.add(updatedOsi);
                    }
                }
            }
            }
            if(!osiListToUpdate.isEmpty()){
                update osiListToUpdate;
            }
            Boolean blocckOpportunity = osiWithDistributerVatNumbr.size() != osiList.size();
            res.put('blockOpportunity', blocckOpportunity);
        } catch (Exception e) {
            System.debug('e.getMessage() ----> ' + e.getMessage());
            System.debug('errorStackTraceString -----> ' + e.getStackTraceString());
            res.put('error', true);
            res.put('errorMessage', e.getMessage()); 
            res.put('errorStackTraceString', e.getStackTraceString());
        }
        return res;

    }

    @AuraEnabled
    public static Map<String,Object> retrieveAtecueDescriptionById(String atecoId){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        String atecueDescription;
        try {
            atecueDescription = CEP_QR_AtecoTranscode.getInstance().retrieveAtecueDescriptionById(atecoId);
            response.put('atecueDescription', atecueDescription);
        } catch (Exception e ) {
            System.debug('e.getMessage() ----> ' + e.getMessage());
            System.debug('errorStackTraceString -----> ' + e.getStackTraceString());
            response.put('error', true);
            response.put('errorMessage', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());
        }
        return response;
    }

    @AuraEnabled
    public static  Map<String,Object> getPreviousProduct(String accountID, String commodity, String servicePointCode){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        try {
            ServicePoint__c servicePoint;
            if(commodity.equalsIgnoreCase('Gas')){
                servicePoint = servicePointQuery.getPreviousProductGas(accountID,servicePointCode);
                response.put('servicePoint', servicePoint);
            }else if(commodity.equalsIgnoreCase('Electric')){
                servicePoint = servicePointQuery.getPreviousProductEle(accountID,servicePointCode);
                response.put('servicePoint', servicePoint);
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMessage', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }

    @TestVisible
    private static void handleBusinessGreen(OpportunityServiceItem__c osi){
        Boolean isBusiness = FeatureManagement.checkPermission('CEP_Large_Sme_Permission') 
        || FeatureManagement.checkPermission('CEP_Small_Business_Permission')
        || FeatureManagement.checkPermission('CEP_CP_AgencyReseller')
        || FeatureManagement.checkPermission('CEP_Large_Aema_Permission')
        || FeatureManagement.checkPermission('CEP_isUmbriaEnergy');
        if(isBusiness){
            List<CEP_SRV_CPQ.OptionalComponent> listOptionEle = CEP_SRV_CPQ.getOptionalComponents(osi.Id);
            if(!listOptionEle.isEmpty()){
                for(CEP_SRV_CPQ.OptionalComponent ele : listOptionEle){
                    osi.GreenPower__c = ele.sapCode == 'EV' ? 'SI' : '';
                    osi.CO2__c = ele.sapCode == 'CO2_GAS' ? 'SI' : '';
                }
                CEP_SRV_OpportunityServiceItem.updateOsi(osi);
            }
        }  
    }

    @AuraEnabled
    public static Id getApproverId(){
        Id userId = UserInfo.getUserId();
        Id step1 = [SELECT Id, ManagerId FROM User WHERE Id =: userId].ManagerId;
        Id step2 = [SELECT Id, ManagerId FROM User WHERE Id =: step1].ManagerId;
        if(step2 == null)
            return step1;
        else
            return step2;
        /*
        Id userId = UserInfo.getUserId();
        String role = [SELECT Id, UserRole.DeveloperName FROM User WHERE Id =: userId].UserRole.DeveloperName;
        String approverRole;
        if(role == 'CEP_KAM_SME')
            approverRole = 'CEP_Direttore_Commerciale_SME';
        else if(role == 'CEP_KAM')
            approverRole = 'CEP_Direttore_Commerciale';
        else if(role == 'CEP_KAM_AEMA')
            approverRole = 'CEP_Direttore_Commerciale_AEMA';
        else if(role == 'CEP_KAM_UE')
            approverRole = 'CEP_Direttore_Commerciale_UE';
        Id approverId = [SELECT Id, UserRole.DeveloperName FROM User WHERE UserRole.DeveloperName =: approverRole LIMIT 1].Id;
        return approverId;
        */
    }


    @AuraEnabled
    public static  Map<String,Object> getPreviousTraderName(String Piva){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        try {
            String traderName = osiQuery.getPreviousTraderName(Piva);
            response.put('name',traderName);
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }

    @AuraEnabled
    public static  Map<String,Object> getUsoTecnologicoEnabled(){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        Boolean isEnabled = true;
        try {
            isEnabled = CEP_QR_UsoTecnologicoEnabled.getInstance().getUsoTecnologicoEnabled();
            response.put('enabled',isEnabled);
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }

    


    @AuraEnabled
    public static  Map<String,Object> checkAccountResidence(String accountid, String pod){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        List<Asset> accountAssets = new List<Asset>();
        try {
            if(accountid != null){
                if(pod != null){
                    accountAssets = [SELECT ID, ResidentialFlag__c FROM Asset WHERE AccountId =: accountid
                                                AND Commodity__c = 'Electric' AND Status = 'Attivo' AND ServicePointCode__c != :pod];
                }else {
                    accountAssets = [SELECT ID, ResidentialFlag__c FROM Asset WHERE AccountId =: accountid AND Commodity__c = 'Electric' AND Status = 'Attivo'];
                }
                if(accountAssets != null){
                    for(Asset asset: accountAssets){
                        if(asset.ResidentialFlag__c){
                            response.put('hasResidence',true);
                            break;
                        }
                    }
                }
            }else {
                response.put('error', true);
                response.put('errorMsg', 'Manca l\'id del Account!'); 
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }

    @AuraEnabled
    public static  Map<String,Object> getCadastralData(String servicePointId, String accountId){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        OpportunityServiceItem__c cadastralData;
        try {
            if(servicePointId != null){
                List<ServicePoint__c> servicePoint = [SELECT Id, CurrentAsset__r.OriginCase__r.OpportunityServiceItem__c FROM ServicePoint__c WHERE ID =: servicePointId AND Account__c =: accountId AND CurrentAsset__r.OriginCase__c <> null];
                if(servicePoint != null && servicePoint.size() > 0 && servicePoint.get(0).CurrentAsset__r.OriginCase__r.OpportunityServiceItem__c != null){
                    List<OpportunityServiceItem__c> osi = osiQuery.getCadastralDataById(servicePoint.get(0).CurrentAsset__r.OriginCase__r.OpportunityServiceItem__c);
                    if(osi!= null && osi.size() > 0) {
                        cadastralData = osi.get(0);
                    }
                }
            } 
            response.put('cadastralData', cadastralData);
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }
	@AuraEnabled
    public static Map<String,Object> getSearchAccounts(String firstName,String lastName,String codeFiscal,String partitaIva,String company){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        String query;
        try {
            if((firstName != '' && firstName != null) || (lastName != '' && lastName != null) ||(codeFiscal != '' && codeFiscal != null) 
               ||(partitaIva != '' && partitaIva != null) || (company != '' && company != null)){
                query = 'Select Id,Name,FirstName__c,LastName__c,FiscalCode__c,VATNumber__c,CompanyName__c FROM Account WHERE Id <> NULL ';
                if(firstName != '' && firstName != null) {
                    query += ' AND FirstName__c =:firstName ';
                }
                if(lastName != '' && lastName != null) {
                    query += ' AND LastName__c =:lastName';
                }
                if(codeFiscal != '' && codeFiscal != null) {
                    query += ' AND FiscalCode__c=:codeFiscal';
                }
                if(partitaIva != '' && partitaIva != null) {
                    query += ' AND VATNumber__c =:partitaIva';
                }
                if(company != '' && company != null) {
                    query += ' AND CompanyName__c=:company';
                }
                query += ' AND AccountRole__c includes (\'BSE\') ';
            }
           
            if(query!=null){
                List<Account> accounts = Database.query(query);
                response.put('data', accounts);
            }else{
                response.put('data', null);
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
            response.put('errorStackTraceString', e.getStackTraceString());        
        }
        return response;
    }

    
    @AuraEnabled
    public static  Map<String,Object> getAccountById(String accountId){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        response.put('account', null);
        try {
            if(accountid != null && accountid!=''){
                Account  account= [Select Id, FirstName__c, LastName__c, CompanyName__c, VATNumber__c, FiscalCode__c,Phone,AtecoName__c,MailingStreetType__c,
                                    MailingStreetName__c,MailingStreetNumber__c,ResidentialStreetNumberExtn__c,MailingPostalCode__c,
                                    MailingLocality__c,MailingProvince__c,MailingCountry__c,PersonOtherAddress 
                                    FROM Account WHERE Id =: accountId  ];
                 
                response.put('account', account);
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
        }
        return response;
    }

    @AuraEnabled
    public static  Map<String,Object> getAccountByAssetId(String pod){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        response.put('accountUscente', null);
        try {
            if(pod != null && pod!=''){
                String sObjectNameAsset = 'Asset';
                String selectedFieldsAsset = 'Account.Id';
                String clauseConditionAsset = 'ServicePointKey__c = \''+pod+'\'';
                List<Asset> assetList = CEP_UTL_SObject.getListExecuteRequest(sObjectNameAsset,selectedFieldsAsset,clauseConditionAsset,null);
                Asset asset = assetList.get(0);
                String accountId = asset.Account.Id;
                
                String sObjectNameAccount = 'Account';
                String selectedFieldsAccount = 'Id, Code__c, FirstName__c, LastName__c, CompanyName__c, VATNumber__c, FiscalCode__c,Phone,AtecoName__c';
                String clauseConditionAccount = 'Id = \''+accountId+'\'';
                system.debug('accountId ' + accountId);
                List<Account> accountUscenteList = CEP_UTL_SObject.getListExecuteRequest(sObjectNameAccount,selectedFieldsAccount,clauseConditionAccount,null);
                if(accountUscenteList != null)system.debug('accountUscenteList ' + accountUscenteList);
                Account accountUscente = accountUscenteList.get(0);

                response.put('accountUscente', accountUscente);
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
        }
        return response;
    }
    @AuraEnabled
    public static  Map<String,Object> getAccountBeneficiarioByAssetPod(String pod){
        Map<String,Object> response = new Map<String,Object>();
        response.put('error', false);
        response.put('accountBeneficiario', null);
        try {
            if(pod != null && pod!=''){
                String sObjectNameAsset = 'Asset';
                String selectedFieldsAsset = 'BeneficiaryAccount__c';
                String clauseConditionAsset = 'ServicePointKey__c = \'' + pod + '\'';
                List<Asset> assetList = CEP_UTL_SObject.getListExecuteRequest(sObjectNameAsset, selectedFieldsAsset, clauseConditionAsset, null);
                Asset asset = assetList.get(0);
                String accountId = asset?.BeneficiaryAccount__c;

                String sObjectNameAccount = 'Account';
                String selectedFieldsAccount = 'Id, Code__c, FirstName__c, LastName__c, CompanyName__c, VATNumber__c, FiscalCode__c,Phone,AtecoName__c';
                String clauseConditionAccount = 'Id = \'' + accountId + '\'';
                List<Account> accountUscenteList = CEP_UTL_SObject.getListExecuteRequest(sObjectNameAccount, selectedFieldsAccount, clauseConditionAccount, null);
                Account accountBeneficiario = accountUscenteList.get(0);

                response.put('accountBeneficiario', accountBeneficiario);
            }
        } catch (Exception e) {
            response.put('error', true);
            response.put('errorMsg', e.getMessage()); 
        }
        return response;
    }
    @TestVisible
    public static void setOsiAddress(OpportunityServiceItem__c osi, ServicePoint__c servicePoint){
            osi.PointStreetName__c = servicePoint.PointStreetName__c;
            osi.PointStreetNumber__c = servicePoint.PointStreetNumber__c;
            osi.PointStreetNumberExtn__c = servicePoint.PointStreetNumberExtn__c;
            osi.PointPostalCode__c = servicePoint.PointPostalCode__c;
            osi.PointCity__c = servicePoint.PointCity__c;
            osi.PointCountry__c = servicePoint.PointCountry__c;
            osi.PointStreetType__c = servicePoint.PointStreetType__c;
            osi.PointApartment__c = servicePoint.PointApartment__c;
            osi.PointBuilding__c = servicePoint.PointBuilding__c;
            osi.PointLocality__c = servicePoint.PointLocality__c;
            osi.PointProvince__c = servicePoint.PointProvince__c;
            osi.PointFloor__c = servicePoint.PointFloor__c;
            osi.PointAddressNormalized__c = servicePoint.PointAddressNormalized__c;
            osi.PointIstatCode__c = servicePoint.PointIstatCode__c;
            osi.PointCadastralCode__c = servicePoint.PointCadastralCode__c;
            osi.PointStaircase__c = servicePoint.PointStaircase__c;
            osi.PointAt__c = servicePoint.PointAt__c;
            osi.PointAddressForced__c = servicePoint.PointAddressForced__c;
            osi.PointAddressForcedBy__c = servicePoint.PointAddressForcedBy__c;
            osi.PointStreetNumberType__c = servicePoint.PointStreetNumberType__c;
    }
    @AuraEnabled
    public static Map<String,Object> checkResidenceAndUsageFromAsset(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        String COMMODITY_ELE = 'Electric';
        String COMMODITY_GAS = 'Gas';
        String USAGE_DOMMESTICO = 'Domestico';
        String USAGE_DOMMESTICO_CLIENTE = 'PDR nella titolarità di un cliente domestico';
        String USAGE_DOMMESTICO_CONDOMINIO = 'PDR relativo a un condominio con uso domestico';
        try{
            response.put('error', false);
            response.put('errorToShow', false);
            String pod = (String) params.get('pod');
            String commodity = (String) params.get('commodity');
            ServicePoint__c servicePoint = [SELECT Id, CurrentAsset__r.Usage__c,CurrentAsset__r.ResidentialFlag__c, PDRType__c FROM ServicePoint__c WHERE Key__c =: pod ];
            if(servicePoint !=null){
                if(commodity.equalsIgnoreCase(COMMODITY_ELE)){
                    if(servicePoint.CurrentAsset__c == null || servicePoint.CurrentAsset__r.Usage__c == null || !servicePoint.CurrentAsset__r.Usage__c.equalsIgnoreCase(USAGE_DOMMESTICO) || servicePoint.CurrentAsset__r.ResidentialFlag__c != true){
                        response.put('errorToShow', true);
                    }
                }else{
                    if(servicePoint.PDRType__c == null || (!servicePoint.PDRType__c.equalsIgnoreCase(USAGE_DOMMESTICO_CLIENTE) && !servicePoint.PDRType__c.equalsIgnoreCase(USAGE_DOMMESTICO_CONDOMINIO))){
                        response.put('errorToShow', true);
                    }
                }
            }
            } catch(Exception ex){
                response.put('error', true);
			    response.put('errorMsg', ex.getMessage());
			    response.put('errorTrace', ex.getStackTraceString());
            }
        return response;
    }

    @AuraEnabled
    public static Asset getContractAccount(String assetId){
         Asset ass = [SELECT ContractAccount__c, ContractAccount__r.PaymentTerms__c FROM Asset WHERE Id =: assetId];
         return ass;
    }

    @AuraEnabled
    public static Map<String,Object> checkVolturaCambioControparteCommerciale(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        String assetId = params.get('assetId');
        String accId = params.get('accountId');
        Account acc = [SELECT Segment__c, Name, JointVenture__r.Name, Account.RecordTypeDeveloperName__c FROM Account WHERE Id =: accId];
        response.put('isVolturaCambioControparteCommerciale', false);
        try{
            if(acc != null && acc.Segment__c == 'Mass Market'){
                Asset a = new Asset();
                if(assetId!=null && String.isNotBlank(assetId)){
                    a = CEP_QR_Asset.getInstance().getById(assetId);
                    if(a!=null /*&& a.DistributorName__c!=null && !a.DistributorName__c.equalsIgnoreCase('acea distribuzione spa') */&& a.AccountId != null && a.Account.RecordType.DeveloperName.equalsIgnoreCase('cep_rt_resellerendcustomer')){
                        response.put('isVolturaCambioControparteCommerciale', true);
                    }
                }
                response.put('error', false);
                response.put('asset', a);
            } else {
                Asset a = new Asset();
                if(assetId!=null && String.isNotBlank(assetId)){
                    a = CEP_QR_Asset.getInstance().getById(assetId);
                    if(acc != null && acc.RecordTypeDeveloperName__c != 'CEP_RT_Reseller'){                        
                        if(a!=null && (a.Status == 'Attivo' || a.Status == 'Sospeso') && a.Account.JointVenture__r.Name != acc.JointVenture__r.Name){
                            response.put('isVolturaCambioControparteCommerciale', true);
                        }
                    } else {
                        if(a!=null && (a.Status == 'Attivo' || a.Status == 'Sospeso') && a.Account.Name != acc.Name){
                            response.put('isVolturaCambioControparteCommerciale', true);
                        }
                    }
                }
                response.put('error', false);
                response.put('asset', a);
            }
        }
        catch(Exception e){
            response.put('error', true);
            response.put('errorMsg', e.getMessage());
            response.put('errorTrace', e.getStackTraceString());
        }
        return response;
    }
    
    @AuraEnabled
    public static Map<String,Object> checkPdrAttivazioneRemiDirette(Map<String,String> params){
        Map<String,Object> response = new Map<String,Object>();
        try{
            String RemiDirette = 'RemiDirette';
            String RinnovoRemiDirette = 'RinnovoRemiDirette';
            String RemiDiretteORinnovo = (String) params.get('RemiDiretteORinnovo');
            response.put('error', false);   
            Boolean isForRemiDirette = RemiDiretteORinnovo.equalsIgnoreCase(RemiDirette);
            Boolean isForRinnovoRemiDirette = RemiDiretteORinnovo.equalsIgnoreCase(RinnovoRemiDirette);
            String pod = (String) params.get('pod');
            String accId = params.get('accountId');
            String  podTobeSearched= pod.substring(0,5);
            String podTobeSaved = '';
            String likeOperator = podTobeSearched + '%';
            System.debug('isForRemiDirette: '+isForRemiDirette);
            System.debug('isForRinnovoRemiDirette: '+isForRinnovoRemiDirette);
            if(isForRemiDirette){
                OpportunityServiceItem__c osi = osiQuery.getLatestOpportunityServiceItem(likeOperator);
                if(osi != null){
                    //String last = pod.substring(5, s1.length());
                    Integer parseString = osiQuery.getIntFromServicePointCode(osi.ServicePointCode__c);
                    //Integer parseString = Integer.valueOf(last);
                    System.debug('parseString: '+parseString);
                    Integer incremented = parseString+1;
                    String incrementedInteger = String.valueOf(incremented);
                    Integer numberOfZeroToBeAdded = (pod.length() -5) - incrementedInteger.length();
                    System.debug('zeroToBeAdded: '+numberOfZeroToBeAdded);
                    String valueOfZeros = '';
                    for(Integer i=0;i<numberOfZeroToBeAdded;i++){
                        valueOfZeros += '0';
                    }
                    podTobeSaved = pod.substring(0,5)+valueOfZeros+incrementedInteger;
                    System.debug('podTobeSaved :' + podTobeSaved);
                }
                if(String.isBlank(podTobeSaved)){
                    podTobeSaved = pod;
                }
            }
            else if(isForRinnovoRemiDirette){
                List<Asset> asset = CEP_QR_Asset.getInstance().getAssetByAccountIdAndPod(accId, pod);
                if(!asset.isEmpty() ){
                    podTobeSaved = asset[0].ServicePointCode__c;
                }
            }
            response.put('podTobeSaved', podTobeSaved);
            response.put('isForRinnovoRemiDirette', isForRinnovoRemiDirette);
            } catch(Exception ex){
                response.put('error', true);
			    response.put('errorMsg', ex.getMessage());
			    response.put('errorTrace', ex.getStackTraceString());
            }
        return response;
    }
    
    @AuraEnabled
    public static Map<String, Object> ConfrontoProdotti(string assetId, string opportunityId) {
        Map<String, Object> response = new Map<String, Object>();
        list<quote> quoteList = new list<quote>();
        list<QuoteLineItem> quoteLineItemList = new list<QuoteLineItem>();
        system.debug('apex ConfrontoProdotti');
        system.debug('apex assetId ' + assetId);
        system.debug('apex opportunityId ' + opportunityId);
        try {
            system.debug('sono nel try ');
            response.put('error', false);
            if (string.isnotblank(opportunityId) && string.isnotblank(assetId)) {
                system.debug('sono nel 1 ');
                quoteList = [select id from quote where OpportunityId = :opportunityId limit 1];
                if (quoteList.size() > 0 && quoteList[0].id != null) {
                    system.debug('sono nel 2 ');
                    quoteLineItemList = [select id, Product2Id from QuoteLineItem where QuoteId = :quoteList[0].id limit 1];
                    if (quoteList.size() > 0 && quoteLineItemList[0].Product2Id != null) {
                        system.debug('sono nel 3 ');
                        if (quoteLineItemList[0].Product2Id != assetId) {
                            response.put('ProdottiUguali', false);
                            system.debug('apex ConfrontoProdotti false');
                        } else {
                            response.put('ProdottiUguali', true);
                            system.debug('apex ConfrontoProdotti true');
                        }

                    }
                }

            }
        } catch (Exception ex) {
            system.debug(LoggingLevel.ERROR, 'ex.getMessage() '+ ex.getMessage());
            system.debug(LoggingLevel.ERROR, 'ex.getStackTraceString() '+ ex.getStackTraceString());
            response.put('error', true);
            response.put('errorMsg', ex.getMessage());
            response.put('errorTrace', ex.getStackTraceString());
        }
        return response;
    }
}