Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
40 kB
0
Indexable
Never
/**
 * @description       : 
 * @author            : ChangeMeIn@UserSettingsUnder.SFDoc
 * @group             : 
 * @last modified on  : 08-18-2021
 * @last modified by  : ChangeMeIn@UserSettingsUnder.SFDoc
**/
public without sharing class OpportunityQueries {

    public static OpportunityQueries getInstance() {
        return (OpportunityQueries) ServiceLocator.getInstance(OpportunityQueries.class);
    }

    public Opportunity getById(String OpportunityId) {
        List<Opportunity> opportunityList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityList = [
                SELECT Id, Name, Pricebook2Id, RecordTypeId, Type, AccountId, Account.Name, StageName, CloseDate, CompanyDivision__c,  CustomerInteraction__c,
                    ContractId, Contract.Opportunity__r.ContractAccount__c, Contract.Opportunity__r.ContractAccount__r.Account__c, Contract.Opportunity__r.ContractAccount__r.BillingProfile__c,
                    Contract.Opportunity__r.ContractAccount__r.Site__c, Contract.Opportunity__r.ContractAccount__r.Type__c,CustomerInteraction__r.Contact__c,RequestType__c,ContractSignedDate__c, Phase__c, BillingProfile__c, Contact__c,  ContractAccount__c,
                    DifferentMailingAddressFlag__c, DifferentCommunicationAddressFlag__c, DifferentBillingAddressFlag__c, Channel__c,FinalClientContract__c, Duration__c, AcceptanceDate__c,
                    RecordType.DeveloperName, Asset__c, Asset__r.AccountId, MailingAddress__c,Segment__c, ViewState__c,
                    (
                        SELECT Id, ServicePointCode__c, RecordType.DeveloperName, Product__c,Account__c,
                               Distributor__c, BillingProfile__c, OldBillingProfile__c, ContractAccount__c, Trader__c, PointAddressNormalized__c, PointStreetType__c,
                               PointStreetName__c, PointStreetNumber__c, PointStreetNumberExtn__c, PointApartment__c, PointBuilding__c, PointCity__c,
                               PointCountry__c, PointFloor__c, Market__c, NonDisconnectable__c, PointLocality__c,
                               PointPostalCode__c, PointProvince__c, Voltage__c, VoltageLevel__c, PressureLevel__c,
                               Pressure__c, PowerPhase__c, ConversionFactor__c, ContractualPower__c, ServiceSite__c, SiteAddressKey__c,
                               SiteAddressNormalized__c, SiteApartment__c, SiteBuilding__c,SiteCity__c, SiteCountry__c, SiteFloor__c,
                               SiteStreetType__c, SiteLocality__c, SitePostalCode__c, SiteProvince__c, SiteStreetName__c, SiteStreetNumber__c,
                               SiteStreetNumberExtn__c, AvailablePower__c, EstimatedConsumption__c, ServicePoint__r.CurrentSupply__c,
                               ServicePoint__r.CurrentSupply__r.CompanyDivision__c, RethinkingStatus__c, PreviousProduct__c, PreviousProduct__r.ClassAdditionalOption__c,
                               ContractAccount__r.BillingProfileActivationOnGoing__c,ContractAccount__r.BillingProfile__c,OldContractAccount__c, Process__c,
                               Product__r.ClassAdditionalOption__c, ContractAccount__r.Account__c, ContractAccount__r.AssetCounter__c, ContractAccount__r.Balance__c, 
                               ContractAccount__r.BillingFrequency__c, ContractAccount__r.ChannelType__c, ContractAccount__r.Commodity__c, ContractAccount__r.CompanyDivision__c, 
                               ContractAccount__r.DetailedBillModifiedDate__c, ContractAccount__r.DetailedBill__c, ContractAccount__r.DirectDebitActivationDate__c, 
                               ContractAccount__r.DirectDebitAuth__c, ContractAccount__r.DirectDebitEndDate__c, ContractAccount__r.EndDate__c, ContractAccount__r.NotExpiredBalance__c,
                               ContractAccount__r.NotLoadableBalance__c, ContractAccount__r.PEC__c, ContractAccount__r.PaymentTerms__c, ContractAccount__r.PostalDelivery__c, 
                               ContractAccount__r.RecipientCode__c, ContractAccount__r.ReducePostalDelivery__c, ContractAccount__r.Segment__c, ContractAccount__r.SendEmailOn__c, 
                               ContractAccount__r.SendSMSOn__c, ContractAccount__r.Site__c, ContractAccount__r.StartDate__c, ContractAccount__r.Status__c, ContractAccount__r.Type__c, 
                               ContractAccount__r.WebBill__c, ContractAccount__r.ClosingType__c, ContractAccount__r.DividedPaymentRequest__c, ContractAccount__r.InvoiceExpirationDate__c, 
                               ContractAccount__r.InvoicePaymentDate__c, ContractAccount__r.ServicePointCode__c,
                               ContractAccount__r.LastRequestedDomiciliationStatus__c, ContractAccount__r.SitePicklist__c, ContractAccount__r.RecipientPEC__c, 
                               ContractAccount__r.AdministrativeContact__c, ContractAccount__r.DeliveryChannel__c, ContractAccount__r.Email__c
                        FROM OpportunityServiceItems__r
                    ),
                    (
                        SELECT Id, Product2Id, ProductCode,
                            Product2.Id, Product2.Name, Product2.RecordType.DeveloperName, Product2.RecordType.Name, Product2.Description,
                            Product2.Image__c, Product2.Family
                        FROM OpportunityLineItems
                    )
                FROM Opportunity
                WHERE Id = :OpportunityId
        ];
        }

        return opportunityList.get(0);
    }

    /**
    * @author INSA BADJI
    * @description  Select an Opportunity by Id
    *
    * @param opportunityId Id of Opportunity
    */
    public Opportunity getOpportunityById(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn =  [
                SELECT Id, Name, StageName,ContractSignedDate__c, OpenDate__c, Segment__c, Pricebook2Id, CreatedById, OwnerId, ContractAccount__c, RecordType.DeveloperName,
                        CompanyDivision__c,CompanyDivision__r.Name,CustomerInteraction__c, CreditCheckFullStatus__c, Commodity__c, FixingType__c, GreenPower__c,
                        AccountId,ContractId, ContactDigitalCompletion__c, CompletionMode__c, Email__c, ViewState__c, RecordTypeId, Channel__c, Contact__r.Email, Process__c,
                        ConfirmationCall__c, BillingProfile__c, Contact__c, Phase__c, DifferentMailingAddressFlag__c, DifferentCommunicationAddressFlag__c,
                        DifferentBillingAddressFlag__c, OpprtunityType__c, Duration__c, ConsumptionType__c, PricingType__c, SupplyStartDate__c, SupplyEndDate__c,
                        TotalVolumesPeak__c, TotalVolumesOffPeak__c, TotalVolumesF0__c, TotalVolumesF1__c, TotalVolumesF2__c, TotalVolumesF3__c,RequestType__c, FinalClientContract__c,
						TotalMargin__c, PaymentTerms__c, Warranty__c, WarrantyValue__c, WarrantyDepositValue__c, StartDateValidity__c, EndDateValidity__c,
						StartDateAccordoQuadro__c, EndDateAccordoQuadro__c, Account.Segment__c, OpportunityNumber__c, Rate__c, Address__c, SalesCharges__c, SalesChargesType__c, 
                        PrescreeningStatus__c, ScipafiOutcome__c, CancellationReason__c, CloseDate, ContactDigitalCompletion__r.Name ,SubChannel__c,AddressNormalized__c,Apartment__c,
                        At__c,Building__c,CadastralCode__c,City__c,Country__c,Floor__c,IstatCode__c,Locality__c,PostalCode__c,Province__c,Staircase__c,StreetName__c,StreetNumber__c,
                        StreetNumberExtn__c,StreetType__c, CustomerInteraction__r.Contact__c , CustomerInteraction__r.Contact__r.IndividualId, CustomerInteraction__r.Contact__r.Email, Account.Vatnumber__c,OpportunityRenewed__c,RenewalDate__c,Renewed__c,
                        SignatureDate__c, BirthDate__c, LastName__c, FirstName__c, Gender__c, BirthCity__c, BirthProvince__c, ForeignFiscalCode__c, VatNumber__c, FiscalCode__c, ResidentialCity__c,
						ResidentialIstatCode__c, ResidentialProvince__c, ResidentialPostalCode__c, ResidentialStreetNumber__c, ResidentialStreetName__c, DocumentType__c, DocumentReleasedDate__c,
						DocumentNumber__c, DocumentExpirationDate__c, DocumentReleasedBy__c, PreferredContact__c, MobilePhone__c
                FROM Opportunity
                WHERE Id = :opportunityId
        ];
        }
        return opportunityReturn;
        
	}

    public Opportunity getOpportunityByIdForUpdate(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn = [
                SELECT Id, Name, StageName,ContractSignedDate__c, Segment__c, Pricebook2Id, CreatedById, OwnerId, ContractAccount__c, RecordType.DeveloperName,
                        CompanyDivision__c,CompanyDivision__r.Name,CustomerInteraction__c, CreditCheckFullStatus__c, Commodity__c, FixingType__c,
                        AccountId,ContractId, ContactDigitalCompletion__c, CompletionMode__c, Email__c, ViewState__c, RecordTypeId, Channel__c,
                        ConfirmationCall__c, BillingProfile__c, Contact__c, Phase__c, DifferentMailingAddressFlag__c, DifferentCommunicationAddressFlag__c,
                        DifferentBillingAddressFlag__c, OpprtunityType__c, Duration__c, ConsumptionType__c, PricingType__c, SupplyStartDate__c, SupplyEndDate__c,
                        TotalVolumesPeak__c, TotalVolumesOffPeak__c, TotalVolumesF0__c, TotalVolumesF1__c, TotalVolumesF2__c, TotalVolumesF3__c,RequestType__c, FinalClientContract__c,
						TotalMargin__c, PaymentTerms__c, Warranty__c, WarrantyValue__c, WarrantyDepositValue__c, StartDateValidity__c, EndDateValidity__c,
						StartDateAccordoQuadro__c, EndDateAccordoQuadro__c, Account.Segment__c, OpportunityNumber__c, Rate__c, Address__c, SalesCharges__c, SalesChargesType__c, 
                        PrescreeningStatus__c, ScipafiOutcome__c, CancellationReason__c, CloseDate, ContactDigitalCompletion__r.Name ,SubChannel__c,AddressNormalized__c,Apartment__c,
                        At__c,Building__c,CadastralCode__c,City__c,Country__c,Floor__c,IstatCode__c,Locality__c,PostalCode__c,Province__c,Staircase__c,StreetName__c,StreetNumber__c,
                        StreetNumberExtn__c,StreetType__c, CustomerInteraction__r.Contact__c , CustomerInteraction__r.Contact__r.IndividualId, Account.Vatnumber__c,OpportunityRenewed__c,RenewalDate__c,Renewed__c
                FROM Opportunity
                WHERE Id = :opportunityId
                FOR UPDATE
        ];
        }
        return opportunityReturn; 
        
	}
	
    public List<Opportunity> listOpportunityByIds(Set<Id> oppIds) {
        List<Opportunity> opportunityList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityList =  [SELECT Id, Channel__c, SubChannel__c, ConfirmationCall__c, PdcCodeAutoNumber__c, SiebelRowId__c, RecordType.DeveloperName, AccountId, TotalMargin__c, StageName, Account.Segment__c, OpportunityNumber__c, Account.OwnerId, OwnerId
                    FROM Opportunity WHERE Id IN:oppIds];
        }
        return opportunityList; 
    }


    /**
        * @author       Ersi Dule (ersi.dule@webresults.it)
        * @date         14/07/2020
        * @description  getOpportunityWithOpportunityServiceItems -  queries a set of opportunities and their related osi 
        * @param1       opportunityIds - Set of opportunity ids
        * @return       Map<Id, Opportunity>
    */
    public Map<Id, Opportunity> getOpportunitiesWithOpportunityServiceItems(Set<Id> opportunityIds){
        Map<Id, Opportunity> opportunitiesById = new Map<Id, Opportunity> ([
            SELECT Id, Name, AccountId, Account.Name, Channel__c, ContactId, StageName, CloseDate, CompanyDivision__c, ContractId, CustomerInteraction__c,
                CustomerInteraction__r.Contact__c,RequestType__c,ContractSignedDate__c, RecordTypeId, RecordType.DeveloperName,Brand__c,
                ContactDigitalCompletion__c, Email__c, SubChannel__c, ChannelDetail__c, Agency__c, MatrixChannelAgency__c, SubAgency__c, Structure__c, OmniChannelOperator__c,
                ContactDigitalCompletionDraft__c,CompletionMode__c, ElectricSuppliesNumber__c, GasSuppliesNumber__c, Account.Segment__c, SignatureDate__c,LastModifiedDate,
                
                (
                    SELECT Id, Status__c, Asset__c, Asset__r.AccountId, ServicePointCode__c, RecordType.DeveloperName, Product__c,Account__c,Account__r.FiscalCode__c,Account__r.VATNumber__c,Account__r.ParentId,Account__r.Parent.Segment__c,
                           Distributor__c, BillingProfile__c, ContractAccount__c, Trader__c, PointAddressNormalized__c, PointStreetType__c,
                           PointStreetName__c, PointStreetNumber__c, PointStreetNumberExtn__c, PointApartment__c, PointBuilding__c, PointCity__c,
                           PointCountry__c, PointFloor__c, Market__c, NonDisconnectable__c, PointLocality__c,
                           PointPostalCode__c, PointProvince__c, Voltage__c, VoltageLevel__c, PressureLevel__c,CodSubServ__c,
                           Pressure__c, PowerPhase__c, ConversionFactor__c, ContractualPower__c, DeactivationDate__c,
                           AvailablePower__c, EstimatedConsumption__c, Process__c, ServicePoint__c, OrderCreated__c, DistributorVatNumber__c,
                           REMICode__c, ShiftDistance__c, QuoteType__c, DistributorAdministrativeCharges__c, AdministrativeSalesCharges__c, 
                           OverallCharges__c, DistributorCharge__c, PastCharges__c, PowerAmount__c, VATRate__c, MailingProvince__c,
                           Taxable__c, VAT__c, TotalQuoteAmount__c, Stamp__c, EffectiveDate__c, HistoricalResidenceData__c, Residence__c,ParentOSI__c,ParentOSI__r.RecordType.DeveloperName,RethinkingStatus__c
                    FROM OpportunityServiceItems__r
                )
            FROM Opportunity
            WHERE Id IN :opportunityIds ]);

            return opportunitiesById;
    }

    /**
        * @author       Ersi Dule (ersi.dule@webresults.it)
        * @date         14/07/2020
        * @description  getOpportunityWithOpportunityServiceItems -  queries a set of opportunities and their related osi 
        * @param1       opportunityIds - Set of opportunity ids
        * @return       Map<Id, Opportunity>
    */
    public Map<Id, Opportunity> getOpportunitiesWithCases(Set<Id> opportunityIds){
        Map<Id, Opportunity> opportunitiesById = new Map<Id, Opportunity> ([
            SELECT Id, Antichurn__c, RequestType__c, AccountId, RecordType.DeveloperName,Brand__c, SignatureDate__c,LastModifiedDate, StageName, SubChannel__c, Channel__c,AgencyCode__c,AgencyFormula__c,Account.Segment__c,
                (
                    SELECT Id,  Subject, CalculatedSupplyStartDate__c,Opportunity__r.RequestType__c,Opportunity__r.SupplyStartDate__c, AssetId, PreviousAccount__c, AccountId, ServicePoint__c, BillingProfile__c, ContractAccount__c,Account.Segment__c, DeactivationDate__c,
                            ContactDigitalCompletion__c, RecordType.DeveloperName, OpportunityServiceItem__r.Process__c, OpportunityServiceItem__r.Antichurn__c,OpportunityServiceItem__r.ServicePoint__r.CurrentAsset__r.Status,Brand__c,Account.AggregateBilling__c,
                            OpportunityServiceItem__r.RecordType.DeveloperName,OpportunityServiceItem__r.TransferredContact__c, OpportunityServiceItem__r.DistributorName__c,OpportunityServiceItem__r.InsuranceNumber__c,
                            OpportunityServiceItem__r.DistributorVATNumber__c, OpportunityServiceItem__r.REMICode__c, OpportunityServiceItem__c, Opportunity__c,Taxable__c,VATRate__c,OpportunityServiceItem__r.DeactivationDate__c,
                            OpportunityServiceItem__r.CreatedDate, OpportunityServiceItem__r.TotalQuoteAmount__c, OpportunityServiceItem__r.OldContractAccount__c,QuoteType__c,AdministrativeSalesCharges__c,DistributorAdministrativeCharges__c,Account.Payment__c,
                            OpportunityServiceItem__r.ContractAccount__c,OpportunityServiceItem__r.BillingInCycle__c,OpportunityServiceItem__r.Stamp__c,OpportunityServiceItem__r.Print__c, OpportunityServiceItem__r.SwitchSkipPreCheck__c, OpportunityServiceItem__r.ContractAccountChanged__c,PowerAmount__c,OpportunityServiceItem__r.QuoteStatus__c
                    FROM Cases__r 
                    WHERE RecordType.DeveloperName = 'Activation_ELE' OR
                    RecordType.DeveloperName = 'Activation_GAS' OR
                    RecordType.DeveloperName = 'CEP_RT_TakeoverEle' OR
                    RecordType.DeveloperName = 'CEP_RT_TakeoverGas' OR
                    RecordType.DeveloperName = 'CEP_RT_ShiftMeter' OR
                    RecordType.DeveloperName = 'CEP_RT_RateChange' OR
                    RecordType.DeveloperName = 'CEP_RT_ActivationPredisposition' OR
                    RecordType.DeveloperName = 'CEP_RT_CheckMeasurementGroupEle' OR
                    RecordType.DeveloperName = 'CEP_RT_CheckMeasurementGroupGas' OR
                    RecordType.DeveloperName = 'CEP_RT_VoltageCheck' OR
                    RecordType.DeveloperName = 'CEP_RT_PressureCheck' OR
                    RecordType.DeveloperName = 'SwitchIn_GAS' OR
                    RecordType.DeveloperName = 'SwitchIn_ELE' OR 
                    RecordType.DeveloperName = 'CEP_RT_ChangePhasePower' OR 
                    RecordType.DeveloperName = 'CEP_RT_DeactivationProcess' OR 
                    RecordType.DeveloperName = 'CEP_RT_VAS' OR
                    RecordType.DeveloperName = 'CEP_RT_PrestazioniSuImpianto' OR
                    RecordType.DeveloperName = 'ProductChange_ELE' OR
                    RecordType.DeveloperName = 'CEP_RT_QuoteGas' OR
                    RecordType.DeveloperName = 'ProductChange_GAS' OR 
                    RecordType.DeveloperName = 'CEP_RT_DeactivationProcess' OR 
                    RecordType.DeveloperName = 'CEP_RT_UsageChange' OR
                    RecordType.DeveloperName = 'Transfer_ELE' OR
                    RecordType.DeveloperName = 'Transfer_GAS' OR 
                    RecordType.DeveloperName = 'CEP_RT_ContropartiCommerciali' OR 
                    RecordType.DeveloperName = 'CEP_RT_Movimentazioni' OR
                    RecordType.DeveloperName = 'CEP_RT_PredisposizioneEle' OR
                    RecordType.DeveloperName = 'CEP_RT_TaxBreak' OR
                    RecordType.DeveloperName = 'CEP_RT_Prescription' OR
                    RecordType.DeveloperName = 'CEP_RT_SetupWithoutActivation' OR
                    //ntt w3
                    RecordType.DeveloperName = 'CP_CB_ELE' OR
                    RecordType.DeveloperName = 'CP_CB_GAS' OR
                    RecordType.DeveloperName = 'RT_SmartServices'
                )
            FROM Opportunity
            WHERE Id IN :opportunityIds ]);

            return opportunitiesById;
    }

    public Map<Id,List<IntegrationCase__c>> checkIntegrationCaseAssociatedToCase(Set<Id> opportunityIds){
        Map<Id,List<IntegrationCase__c>> icChildeToCase = new Map<Id,List<IntegrationCase__c>>();
        List<case> listCase = new List<case>();
        Map<Id, Opportunity> opportunitiesById = new Map<Id, Opportunity> ([
            SELECT Id, AccountId, RecordType.DeveloperName, SignatureDate__c,LastModifiedDate,
                (
                    SELECT Id, AssetId, AccountId, ServicePoint__c, BillingProfile__c, ContractAccount__c, 
                            ContactDigitalCompletion__c, RecordType.DeveloperName, OpportunityServiceItem__r.Process__c,
                            OpportunityServiceItem__r.RecordType.DeveloperName, OpportunityServiceItem__r.DistributorName__c,
                            OpportunityServiceItem__r.DistributorVATNumber__c, OpportunityServiceItem__r.REMICode__c, OpportunityServiceItem__c, Opportunity__c,
                            OpportunityServiceItem__r.CreatedDate, OpportunityServiceItem__r.TotalQuoteAmount__c
                    FROM Cases__r 
                    WHERE RecordType.DeveloperName = 'Activation_ELE' OR
                    RecordType.DeveloperName = 'Activation_GAS' OR
                    RecordType.DeveloperName = 'CEP_RT_TakeoverEle' OR
                    RecordType.DeveloperName = 'CEP_RT_TakeoverGas' OR
                    RecordType.DeveloperName = 'SwitchIn_GAS' OR
                    RecordType.DeveloperName = 'SwitchIn_ELE' OR 
                    RecordType.DeveloperName = 'CEP_RT_VAS' OR
                    RecordType.DeveloperName = 'ProductChange_ELE' OR
                    RecordType.DeveloperName = 'ProductChange_GAS' OR 
                    RecordType.DeveloperName = 'CEP_RT_UsageChange' OR
                    RecordType.DeveloperName = 'CEP_RT_DeactivationProcess' OR
                    RecordType.DeveloperName = 'CEP_RT_PredisposizioneEle' OR
                    RecordType.DeveloperName = 'Transfer_ELE' OR
                    RecordType.DeveloperName = 'CEP_RT_Movimentazioni' OR
                    RecordType.DeveloperName = 'CEP_RT_ContropartiCommerciali' OR
                    RecordType.DeveloperName = 'CEP_RT_SetupWithoutActivation' OR
                    RecordType.DeveloperName = 'Transfer_GAS'
                )
            FROM Opportunity
            WHERE Id IN :opportunityIds ]);
        List<Id> idCases = new List<Id>();
        for(Id oppId : opportunitiesById.keySet()){
            Opportunity oppty = opportunitiesById.get(oppId);
            listCase = oppty.Cases__r;
            //caseChild.put(oppId,oppId.cases__r);
            for(Case cs : listCase){
                idCases.add(cs.Id);
            }
        }
        Map<Id, Case> caseWithIntegrationCase = new Map<Id, Case>();
        if(Case.SObjectType.getDescribe().isAccessible()){
            caseWithIntegrationCase = new  Map<Id, Case>([SELECT Id, (SELECT id,OpportunityServiceItem__r.OldContractAccount__c,OpportunityServiceItem__r.ContractAccount__c from IntegrationCases__r) FROM Case WHERE ID IN :idCases]);
        } 
        List<IntegrationCase__c> listIC = new List<IntegrationCase__c>();
        for(Id caseId : caseWithIntegrationCase.keySet()){
            Case cs = caseWithIntegrationCase.get(caseId);
            listIC = cs.IntegrationCases__r;
            icChildeToCase.put(caseId,listIC);
        }
        /*
        if (!icChildeToCase.isEmpty()){
            return true;
        }else{
            return false;
        }*/
        return icChildeToCase;

    }

    public List<Opportunity> listOpportunitiesByInteractionAndCustomer(String interactionId, String accountId){
        List<Opportunity> output = new List<Opportunity>(); 
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
        output = [SELECT Id, Name, StageName,ContractSignedDate__c,
                        CompanyDivision__c,CompanyDivision__r.Name,CustomerInteraction__c,
                        AccountId,ContractId, ContactDigitalCompletion__c, CompletionMode__c, Email__c, ViewState__c
                        from Opportunity 
                        where CustomerInteraction__r.Interaction__c =:interactionId
                        and CustomerInteraction__r.Customer__c =:accountId WITH SECURITY_ENFORCED];
        }
        return output;
	}

    public List<Opportunity> listOpportunitiesByAccountStageAndRethinkingRight(String accountId){
        List<Opportunity> oppties = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
        oppties = [SELECT Id, Name, StageName,ContractSignedDate__c,
                        CompanyDivision__c,CompanyDivision__r.Name,CustomerInteraction__c,
                        AccountId,ContractId, ContactDigitalCompletion__c, CompletionMode__c, Email__c, ViewState__c
                        FROM Opportunity WHERE AccountId =: accountId AND StageName IN ('Attesa Ripensamento',
                        'Attesa Credit Check Full', 'Attesa Rilavorazione', 'Chiusa Vinta')
                        AND RethinkingRight__c = 'Si' WITH SECURITY_ENFORCED];
        }
        return oppties;
    }

    public List<Opportunity> findByAccoutSegment(String segment, String requestType, List<ID> accountId, String stageName){
        List<Opportunity> oppties = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
        oppties = [SELECT 
                        Id, Name, StageName
                        FROM 
                            Opportunity 
                        WHERE 
                            Account.Segment__c = :segment 
                            AND RequestType__c = :requestType 
                            AND AccountId IN :accountId
                            AND StageName = :stageName];
        }
        return oppties;
    }


    public List<Opportunity> findByAccoutSegmentAndStage(String segment, List<String> requestType, List<ID> accountId, List<String> stageNameList){
        List<Opportunity> oppties = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
        oppties = [SELECT 
                        Id, Name, StageName
                        FROM 
                            Opportunity 
                        WHERE 
                            Account.Segment__c = :segment 
                            AND RequestType__c IN :requestType 
                            AND AccountId IN :accountId
                            AND StageName IN :stageNameList];
        }
        return oppties;
    }



    public List<Opportunity> getOpportunitiesByFiscalCodeOrVatNumber(String accountId, String tipoControllo) {
        if(tipoControllo!=null && String.isNotBlank(tipoControllo) && tipoControllo == 'Prescreening'){
            return getOpportunitiesWithPrescreening(accountId);
        }
        if(tipoControllo!=null && String.isNotBlank(tipoControllo) && tipoControllo == 'Credit Check Full'){
            return getOpportunitiesWithCreditCheck(accountId);
        }
        return null;
    }

    public List<Opportunity> getOpportunitiesWithPrescreening(String accountId) {
        List<Opportunity> opportunityList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityList = [
                SELECT id, PrescreeningStatus__c, PrescreeningDate__c, CreditCheckFullStatus__c, CreditCheckFullRequestDate__c 
                FROM Opportunity
                WHERE PrescreeningDate__c != null
                AND PrescreeningStatus__c != null
                AND PrescreeningStatus__c != 'In Corso'
                AND PrescreeningStatus__c != 'Errore'
                AND AccountId =: accountId
                ORDER BY CreatedDate desc
        ];
    } 

        return opportunityList;
    }

    public List<Opportunity> getOpportunitiesWithCreditCheck(String accountId) {
        List<Opportunity> opportunityList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityList = [
                SELECT id, PrescreeningStatus__c, PrescreeningDate__c, CreditCheckFullStatus__c, CreditCheckFullRequestDate__c 
                FROM Opportunity
                WHERE CreditCheckFullRequestDate__c != null
                AND CreditCheckFullStatus__c != null
                AND CreditCheckFullStatus__c != 'In Corso'
                AND CreditCheckFullStatus__c != 'Errore'
                AND CreditCheckFullStatus__c != 'Forzato'
                AND AccountId =: accountId
                ORDER BY CreatedDate desc
        ];
    }

        return opportunityList;
    }
    
    public Opportunity getOppHeaderCheck(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn =  [
                SELECT Id, Name, Channel__c, Account.Id, Account.Code__c, Account.RecordType.Name, Account.FiscalCode__c, Account.VATNumber__c,
                Account.CompanyName__c, Account.FirstName__c, Account.LastName__c, Account.CervedCode__c, Account.MarketType__c,
                Account.Segment__c, Account.AgencyCode__c, Account.BusinessType__c,
                SubChannel__c, AccountType__c, FiscalCode__c, VATNumber__c, IndividualCompanyName__c, CompanyName__c, FirstName__c, LastName__c, OpportunityNumber__c,
                AgencyCode__c
                FROM Opportunity
                where Id =: opportunityId 
        ];
        }
        return opportunityReturn; 
    }

    public Opportunity getOppFullCheck(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn =  [
                SELECT Id, Name, Warranty__c, WarrantyValue__c, Channel__c,AccountId, Account.Code__c, Account.RecordType.Name, Account.FiscalCode__c, Account.VATNumber__c,
                Account.CompanyName__c, Account.FirstName__c, Account.LastName__c, Account.CervedCode__c, Account.MarketType__c,
                Account.Segment__c, Account.AgencyCode__c, Account.ResidentialPostalCode__c, Account.ResidentialProvince__c,
                Account.ResidentialStreetName__c, Account.ResidentialLocality__c, Account.ResidentialStreetNumber__c, Account.ResidentialIstatCode__c, 
                Account.ResidentialCity__c, Account.Phone, Account.Email__c, Account.JointVenture__c,Account.JointVenture__r.JointVentureCode__c,Company_Code__c,Segment__c,
                ResidentialPostalCode__c, ResidentialProvince__c, ResidentialStreetName__c, ResidentialStreetNumber__c, /*ResidentialIstatCode__c,*/ ResidentialCity__c,/*, ResidentialLocality__c*/
                MobilePhone__c, Email__c
                FROM Opportunity
                where Id =: opportunityId
        ];
        }
        return opportunityReturn; 
    }

    public List<Opportunity> getOppFullCheck(List<String> opportunityIdList) {
        List<Opportunity> opportunityList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityList=  [
                SELECT Id, Name, Warranty__c, WarrantyValue__c, Channel__c,AccountId, Account.Code__c, Account.RecordType.Name, Account.FiscalCode__c, Account.VATNumber__c,
                Account.CompanyName__c, Account.FirstName__c, Account.LastName__c, Account.CervedCode__c, Account.MarketType__c,
                Account.Segment__c, Account.AgencyCode__c, Account.ResidentialPostalCode__c, Account.ResidentialProvince__c,
                Account.ResidentialStreetName__c, Account.ResidentialLocality__c, Account.ResidentialStreetNumber__c, Account.ResidentialIstatCode__c, 
                Account.ResidentialCity__c, Account.Phone, Account.Email__c, Account.JointVenture__c,Account.JointVenture__r.JointVentureCode__c,Company_Code__c,Segment__c
                FROM Opportunity
                where Id =: opportunityIdList
        ];
        }
        return opportunityList; 
    }
    public List<Opportunity> getOppByFullChecks(Set<Id> creditCheckIds) {
        List<Opportunity> opp = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
        opp =  [
                SELECT Id,StageName, Name,CreditCheckFull__c
                FROM Opportunity
                where CreditCheckFull__c IN :  creditCheckIds 
                ];
        }
        return opp;      
    }

    public Opportunity getFieldOpportunityById(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn =  [
                SELECT Id, Agency__r.VATNumber__c, VatNumber__c, CheckActiveContract__c, ViewState__c
                FROM Opportunity
                WHERE Id =: opportunityId
        ];
        }
        return opportunityReturn; 
        
    }

    public Opportunity getCreditCheckStatusOpportunity(String opportunityId) {
        Opportunity opportunityReturn = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opportunityReturn =  [
                SELECT Id, PrescreeningStatus__c
                FROM Opportunity
                WHERE Id =: opportunityId
        ];
        }
        return opportunityReturn; 
    }

    /**
        * @author       Ersi Dule (ersi.dule@webresults.it)
        * @date         31/01/2020
        * @description  loadOpportunityContext -  queries an opportunity including its child records
        * @param1       opportunityIds - the id of the opportunity
        * @return       Opportunity
    */
    public Opportunity loadOpportunityContext(Id opportunityId){
        Opportunity opp = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opp = [ SELECT Id, StageName, Validation__c, CreditCheckFullStatus__c, AccountId,Account.Segment__c, MoreThan50Employees__c, AtLeastOneMedium__c, Turnover__c  , NoneOfAbove__c, DigitalCompletionStatus__c,RecordType.DeveloperName,ChannelDetail__c,SubChannel__c, Channel__c, SignatureDate__c,Process__c,
                                    ( SELECT Id, ImmediateActivation__c, RethinkingStatus__c, ServicePointCode__c, Process__c, ContractDate__c
                                      FROM OpportunityServiceItems__r
                                    ),
                                    ( SELECT Id, wrts_prcgvr__Status__c,wrts_prcgvr__ActivityTemplate__r.name,wrts_prcgvr__ActivityTemplate__c, wrts_prcgvr__ActivityTemplate__r.wrts_prcgvr__ObjectType__c
                                      FROM Activities__r
                                    ),
                                    ( SELECT Id, Status__c, Phase__c, ContractualAccountAndAnagraficOutcome__c, OrderCreationStatus__c
                                      FROM IntegrationCases__r)
                            FROM Opportunity
                            WHERE Id =: opportunityId limit 1];
        }
        
        return opp;
	}
	
	//AC: questa query deve essere così altrimenti il phaseManager va in errore
	public Opportunity getOpportunityForPhase(String id){
		String query = 'SELECT ' + String.escapeSingleQuotes(CEP_UTL_SObject.getAllFieldsForObject('Opportunity')) + ' ';
		query += 'FROM Opportunity ';
		query += 'WHERE Id = :id';
		return Database.query(query); 
	}

    public Opportunity takeOpportunity(Id opportunityId){
        Opportunity opp = new Opportunity();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opp = [
                SELECT Id, AccountId, MoreThan50Employees__c, AtLeastOneMedium__c, Turnover__c  , NoneOfAbove__c
                FROM Opportunity
                WHERE Id =: opportunityId
        ];
        }
        return opp;
    }
    
    public List<Opportunity> getOpportunityForScipafi(Id accountId){
        List<Opportunity> oppList = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            oppList = [
            SELECT Id, StageName, AccountId
            FROM Opportunity
            WHERE AccountId =: accountId
            ];
        }  
        return oppList;
    }

    public List<Opportunity> getOpportunitiesWithTouchPoints(Set<Id> opptiesId){
        List<Opportunity> opp = new List<Opportunity>();
        if(Opportunity.SObjectType.getDescribe().isAccessible()){
            opp =  [ 
                SELECT Id,
                    (SELECT LastModifiedDate 
                    FROM FilesMetadata__r 
                    WHERE RecordType.DeveloperName = 'CEP_RT_TouchPoint'
                    ORDER BY CreatedDate DESC )
                FROM Opportunity
                WHERE Id IN: opptiesId
                AND CompletionMode__c = 'Perfezionamento Digitale'
                WITH SECURITY_ENFORCED
        ];
        }
        return opp; 
    }

    public Map<Id, Opportunity> getOppsWithOpportunityServiceItemsForCreateOder(Set<Id> opportunityIds){
        Map<Id, Opportunity> opportunitiesById = new Map<Id, Opportunity> ([
            SELECT Id, Name, AccountId, Account.Name, Channel__c, ContactId, StageName, CloseDate, CompanyDivision__c, ContractId, CustomerInteraction__c,SupplyStartDate__c,
                CustomerInteraction__r.Contact__c,RequestType__c,ContractSignedDate__c, RecordTypeId, RecordType.DeveloperName,Brand__c,
                ContactDigitalCompletion__c, Email__c, SubChannel__c, ChannelDetail__c, Agency__c, MatrixChannelAgency__c, SubAgency__c, Structure__c, OmniChannelOperator__c,
                ContactDigitalCompletionDraft__c,CompletionMode__c, ElectricSuppliesNumber__c, GasSuppliesNumber__c, Account.Segment__c, SignatureDate__c,LastModifiedDate,
                AgencyCode__c,AgencyFormula__c, NTT_Subalterno__c, NTT_Particella__c, NTT_Foglio__c,
                Account.CompanyChannel__c, CreatedBy.DefaultChannel__c, CreatedBy.DefaultSubChannel__c, //NTT W3
                (
                    SELECT Id, Status__c, Asset__c, Asset__r.AccountId, ServicePointCode__c, RecordType.DeveloperName, Product__c,Account__c,Account__r.FiscalCode__c,Account__r.VATNumber__c,Account__r.ParentId,Account__r.Parent.Segment__c,
                          TaxBreak__c, TaxCode__c, VATClass__c, AccisaCode__c, Excise__c, RegionalAddTaxExemptionCode__c, FlagTax__c, Article__c,
                           Distributor__c, BillingProfile__c, ContractAccount__c, Trader__c, PointAddressNormalized__c, PointStreetType__c,
                           PointStreetName__c, PointStreetNumber__c, PointStreetNumberExtn__c, PointApartment__c, PointBuilding__c, PointCity__c,
                           PointCountry__c, PointFloor__c, Market__c, NonDisconnectable__c, PointLocality__c, Commodity__c,
                           PointPostalCode__c, PointProvince__c, Voltage__c, VoltageLevel__c, PressureLevel__c,CodSubServ__c,
                           Pressure__c, PowerPhase__c, ConversionFactor__c, ContractualPower__c, DeactivationDate__c, Descr_Materiale__c,
                           AvailablePower__c, EstimatedConsumption__c, Process__c, ServicePoint__c, OrderCreated__c, DistributorVatNumber__c,
                           REMICode__c, ShiftDistance__c, QuoteType__c, DistributorAdministrativeCharges__c, AdministrativeSalesCharges__c, MailingCity__c, MailingProvince__c, MailingPostalCode__c, MailingAddress__c, MailingIstatCode__c,
                           OverallCharges__c, DistributorCharge__c, PastCharges__c, PowerAmount__c, VATRate__c, PreviousAccount__c, NTT_Tipologia_Prodotto__c, NTT_Tipologia_Intervento__c, Product__r.Description , NTT_Cessione_del_credito__c,
                           Taxable__c, VAT__c, TotalQuoteAmount__c, Stamp__c, EffectiveDate__c, HistoricalResidenceData__c, Residence__c,ParentOSI__c,ParentOSI__r.RecordType.DeveloperName,RethinkingStatus__c, VATTreatment__c
                    FROM OpportunityServiceItems__r WHERE OrderCreated__c=false AND ( (ContractAccount__c <> '' AND RecordType.DeveloperName != 'CEP_RT_VAS') OR RecordType.DeveloperName = 'CEP_RT_VAS') ORDER BY CreatedDate LIMIT 1000
                )
            FROM Opportunity
            WHERE Id IN :opportunityIds ]);

            return opportunitiesById;
    }
}