Untitled
unknown
plain_text
2 years ago
55 kB
1
Indexable
Never
/** * @author Ersi Dule (ersi.dule@webresults.it) * @date 14/07/2020 * @description CEP_SRV_OrderManagementCreation – Class that implements the logics for the creation of the order management chanin * @history Ersi Dule - 14/07/2020 - Created the class */ public with sharing class CEP_SRV_OrderManagementCreation { private static Map<String, String> caseRecordTypeIdsByDeveloperName = CEP_UTL_RecordType.getRecordTypeInfosForObject(Schema.Case.getSObjectType()); private static Map<String, String> integrationCaseRecordTypeIdsByDeveloperName = CEP_UTL_RecordType.getRecordTypeInfosForObject(Schema.IntegrationCase__c.getSObjectType()); /** * @author Ersi Dule (ersi.dule@webresults.it) * @date 14/07/2020 * @description createOrderManagementChain - creates the order management chain * @param1 opportunityIds - the set containing the ids of the opportunities * @return Object */ public static Object createOrderManagementChain(Set<Id> opportunityIds){ //NTT W3 Boolean vas = false; System.debug('CEP_SRV_OrderManagementCreation::createOrderManagementChain::opportunityIds='+JSON.serializePretty(opportunityIds)); List<Case> casesToInsert = new List<Case>(); List<IntegrationCase__c> integrationCasesToInsert = new List<IntegrationCase__c>(); List<OpportunityServiceItem__c> osiToUpdate = new List<OpportunityServiceItem__c>(); String profileId = UserInfo.getProfileId(); List<Profile> userProfileList = [SELECT Id, Name FROM Profile WHERE Id = :profileId]; Profile userProfile = userProfileList[0]; String switchEleRt = CEP_UTL_RecordType.getRecordTypeIdByDeveloperName('CEP_RT_SwitchInEle', 'IntegrationCase__c'); String switchGasRt = CEP_UTL_RecordType.getRecordTypeIdByDeveloperName('CEP_RT_SwitchInGas', 'IntegrationCase__c'); Savepoint savePoint = Database.setSavepoint(); Integer counter = 0; Boolean hasDisactivationPostponed = false; String codsubServ = ''; try{ Map<Id, Opportunity> opptiesById = OpportunityQueries.getInstance().getOppsWithOpportunityServiceItemsForCreateOder(opportunityIds); List<Id> badOsiIds = removeOSIVasActivation(opptiesById); System.debug('CEP_SRV_OrderManagementCreation::createOrderManagementChain::opptiesById='+JSON.serializePretty(opptiesById)); List<Contract> contracts = ContractQueries.getInstance().listByOpptyIds(opportunityIds); // 29-09-2021 CERCO GLI SWICHING ELE CHE DEVONO DIVENTARE CONTROPARTI COMMERCIALI List<OpportunityServiceItem__c> osiToCheckProcess = new List<OpportunityServiceItem__c>(); if(!opptiesById.isEmpty()){ for(Id oppId : opptiesById.keySet()){ Opportunity oppty = opptiesById.get(oppId); osiToCheckProcess.addAll(oppty.OpportunityServiceItems__r); } } List<OpportunityServiceItem__c> opportunityServiceItems = new List<OpportunityServiceItem__c> (); map<Id,OpportunityServiceItem__c> controcommerMap = CEP_UTL_ContropartiCommerciali.checkAccountOSI(osiToCheckProcess); System.debug('controcommerMap = '+JSON.serialize(controcommerMap)); /////////////////////////////////////////////////////////// // query recupero Id vasCaseId = [SELECT id FROM RecordType WHERE DeveloperName = 'RT_SmartServices' AND SobjectType = 'Case' LIMIt 1].id; String vasAccount; String vasType; String Subalterno; String Particella; String CodiceComune; String Comune; String Provincia; String RagioneSociale; String Foglio; String TipoInst; String Prodotto; String CessioneCredito; String Cap; String IndInst; String NomeProdotto; String NomeProdotto2; String UlterioriServizi; String LavoriExtra; Decimal TotaleFattura; Decimal TotaleImponibile; String IVA; Decimal Manodopera; Decimal Beni; Decimal Importo; Decimal Detrazione; String ChiaveCPQ; Decimal prezzoLavoriExtra; Decimal percentDetraction; Id oppoid; String oppchannel; //subalterno opp, particella su opp CodiceComune = osi.CadastralMunicipalityCode__c; if(!opptiesById.isEmpty()){ for(Id oppId : opptiesById.keySet()){ System.debug('@@oppId ' + oppId); Opportunity oppty = opptiesById.get(oppId); opportunityServiceItems = oppty.OpportunityServiceItems__r; Subalterno = oppty.NTT_Subalterno__c; Particella = oppty.NTT_Particella__c; Foglio = oppty.NTT_Foglio__c; ChiaveCPQ = oppty.Name; oppoid = oppId; oppchannel = oppty.Channel__c; for (OpportunityServiceItem__c osi : opportunityServiceItems) { system.debug('*** riga 68'); //NTT W3 System.debug('Valore osi ::: ' + osi.RecordType.DeveloperName); if(osi.RecordType.DeveloperName == 'NTT_Smart_Service') { vas = true; Provincia = osi.MailingProvince__c ; vasAccount = osi.Account__c; VasType = osi.NTT_Tipologia_Prodotto__c; Comune = osi.MailingCity__c; TipoInst = osi.NTT_Tipologia_Intervento__c; Prodotto = osi.Descr_Materiale__c; CessioneCredito = osi.NTT_Cessione_del_credito__c; Cap = osi.MailingPostalCode__c; IndInst = osi.MailingAddress__c; percentDetraction = osi.NTT_Perc_Detrazione__c; NomeProdotto = osi.NTT_Nome_Prodotto__c;NomeProdotto2 = osi.Product__r.Name; UlterioriServizi = osi.NTT_Ulteriori_servizi__c; IVA = osi.NTT_IVA__c; Manodopera = osi.NTT_Manodopera_e_beni_non_sign__c; Beni = osi.NTT_Beni_significativi__c; TotaleFattura = osi.NTT_Totale_fattura__c; TotaleImponibile = osi.NTT_Totale_imponibile__c; Importo = osi.NTT_Importo_da_pagare__c; Detrazione = osi.NTT_Importo_da_pagare__c; prezzoLavoriExtra = osi.NTT_Prezzo_lavori_extra__c; } if ((osi.RecordType.DeveloperName == 'CEP_RT_VAS' && osi.Status__c == 'Rifiutato') || osi.OrderCreated__c || badOsiIds.contains(osi.Id) || osi.RethinkingStatus__c=='Ripensato') { continue; } if(counter >= 100){ break; } codsubServ = osi.CodSubServ__c; counter++; System.debug('@@osi.id ' + osi.Id); Case processCase = new Case(); if(!controcommerMap.isEmpty() && controcommerMap.containsKey(osi.Id)){ osi.Process__c = controcommerMap.get(osi.Id).Process__c; osi.ContractDate__c = System.today(); } if(!vas) { processCase.RecordTypeId = trascodeProcessToRecordType(osi.Process__c, osi.RecordType.DeveloperName, 'Case'); } else { processCase.RecordTypeId = vasCaseId; } if('Disattivazione'.equalsIgnoreCase(osi.Process__c) && isDeactivationPostponed(osi.RecordType.developername, osi.DeactivationDate__c) ){ hasDisactivationPostponed = true; } if('Switching Win'.equalsIgnoreCase(osi.Process__c) ){ osi.ContractDate__c = System.today(); } if(processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_ShiftMeter').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_RateChange').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_CheckMeasurementGroupEle').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_CheckMeasurementGroupGas').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_QuoteGas').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_VoltageCheck').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_ChangePhasePower').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_PressureCheck').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_Prescription').getRecordTypeId() || processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_TaxBreak').getRecordTypeId() ) { processCase.Phase__c = Constants.getAllConstants().CASE_PHASE_WORKING; processCase.Status = Constants.getAllConstants().CASE_STATUS_WORKING; processCase.HistoricalResidenceData__c = osi.HistoricalResidenceData__c; processCase.Residence__c = osi.Residence__c; processCase.EffectiveDateFrom__c = osi.EffectiveDate__c; }else{ processCase.Phase__c = Constants.getAllConstants().CASE_PHASE_START; processCase.Status = Constants.getAllConstants().CASE_STATUS_TO_SEND; } if (processCase.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_Prescription').getRecordTypeId() ){ processCase.Phase__c = 'BOZZA'; } processCase.Subject = osi.Process__c; processCase.Opportunity__c = oppty.Id; processCase.Channel__c = oppty.Channel__c; processCase.SubChannel__c = oppty.SubChannel__c; processCase.Brand__c = oppty.Brand__c; //FI field added processCase.ChannelDetail__c = oppty.ChannelDetail__c; processCase.MatrixChannelAgency__c = oppty.MatrixChannelAgency__c; processCase.SubAgency__c = oppty.SubAgency__c; processCase.Structure__c = oppty.Structure__c; processCase.OmniChannelOperator__c = oppty.OmniChannelOperator__c; // processCase.Contact__c = oppty.ContactId; processCase.AssetId = osi.Asset__c; processCase.OpportunityServiceItem__c = osi.Id; processCase.ServicePoint__c = osi.ServicePoint__c; processCase.ServicePointCode__c = osi.ServicePointCode__c; processCase.ContractAccount__c = osi.ContractAccount__c; processCase.BillingProfile__c = osi.BillingProfile__c; processCase.DeactivationDate__c = osi.DeactivationDate__c; if(('Offerta B2B'.equalsIgnoreCase(oppty.RequestType__c) || 'Da Accordo Quadro'.equalsIgnoreCase(oppty.RequestType__c)) && oppty.Account.Segment__c != 'Reseller'){ processCase.AccountId = osi.Account__c; }else{ processCase.AccountId = oppty.AccountId; } if(osi.Process__c.containsIgnoreCase('voltura')){ processCase.PreviousAccount__c = osi.Asset__r?.AccountId; } if(osi.Process__c.containsIgnoreCase('Switching Win cc')){ processCase.PreviousAccount__c = osi.PreviousAccount__c; } processCase.Contract__c = !contracts.isEmpty() ? contracts[0].Id : null; if(oppty.Account.Segment__c == Constants.getAllConstants().ACCOUNT_SEGMENT_RESELLER){ processCase.FinalAccount__c = osi.Account__c; } String refPerfezionamento; if(oppty.ContactDigitalCompletion__c!=null){ refPerfezionamento = oppty.ContactDigitalCompletion__c; } else{ if(oppty.CustomerInteraction__c != null){ refPerfezionamento = oppty.CustomerInteraction__r.Contact__c; } } processCase.ContactDigitalCompletion__c = refPerfezionamento; processCase.Email__c = oppty.Email__c; //LD field added processCase.ShiftDistance__c = osi.ShiftDistance__c; processCase.QuoteType__c = osi.QuoteType__c; processCase.DistributorAdministrativeCharges__c = osi.DistributorAdministrativeCharges__c; processCase.AdministrativeSalesCharges__c = osi.AdministrativeSalesCharges__c; processCase.OverallCharges__c = osi.OverallCharges__c; processCase.DistributorCharges__c = osi.DistributorCharge__c; processCase.PastCharges__c = osi.PastCharges__c; processCase.PowerAmount__c = osi.PowerAmount__c; processCase.VATRate__c = osi.VATRate__c; processCase.Taxable__c = osi.Taxable__c; processCase.Stamp__c = osi.Stamp__c; processCase.CompletionMode__c = oppty.CompletionMode__c; //processCase.ContactDigitalCompletion__c = oppty.ContactDigitalCompletion__c; processCase.ContactDigitalCompletionDraft__c = oppty.ContactDigitalCompletionDraft__c; processCase.VATAmount__c = osi.VAT__c; processCase.Amount__c = osi.TotalQuoteAmount__c; processCase.Commodity__c = osi.Commodity__c; if(osi.Process__c == 'Disattivazione' && osi.DeactivationDate__c == Date.today()){ processCase.ImmediateDeactivation__c = true; } String opptySegment = ''; if (!String.isBlank(oppty.Id)) { list<Opportunity> opptys = new List<Opportunity>(); opptys = [SELECT Segment__c FROM Opportunity WHERE Id = :oppty.Id]; if (string.isNotBlank(opptys[0].Segment__c))opptySegment = opptys[0].Segment__c; } //NTT W3 if(osi.Process__c != 'CAMBIO PRODOTTO' && osi.Process__c !='CAMBIO PRODOTTO CROSS BRAND'){ if(osi.Process__c == 'Modifica Tipologia PDR') { processCase.CalculatedSupplyStartDate__c = System.today(); } else { processCase.CalculatedSupplyStartDate__c = osi.EffectiveDate__c; } }else{ if (oppty.Account.Segment__c != 'Mass Market') { processCase.CalculatedSupplyStartDate__c = osi.EffectiveDate__c; }else{ DateTime sign = oppty.SignatureDate__c; if(sign==null){ sign = oppty.LastModifiedDate; } Integer year = sign.year(); Integer month = sign.month()+1; processCase.CalculatedSupplyStartDate__c = date.newInstance(year, month, 1); } } System.debug('@@processCase ' +processCase); casesToInsert.add(processCase); osi.OrderCreated__c = true; osiToUpdate.add(osi); } } System.debug('@@casesToInsert:' + casesToInsert); System.debug('@@osiToUpdate:' + osiToUpdate); DatabaseService.getInstance().insertSObject(casesToInsert); CEP_TRH_OpportunityServiceItem.bypass('CEP_BypassOpportunityServiceItemTrigger'); System.debug('Prima update osi.Process__c'); DatabaseService.getInstance().updateSObject(osiToUpdate); System.debug('Dopo update osi.Process__c'); CEP_TRH_OpportunityServiceItem.clearBypass('CEP_BypassOpportunityServiceItemTrigger'); Map<Id, Opportunity> opptiesWithCasesById = OpportunityQueries.getInstance().getOpportunitiesWithCases(opportunityIds); Map<Id,List<IntegrationCase__c>> childIntCaseOfCase = OpportunityQueries.getInstance().checkIntegrationCaseAssociatedToCase(opportunityIds); System.debug('@@ opptiesWithCasesById = '+JSON.serializePretty(opptiesWithCasesById)); //creazione commessa solo se variabile = true String id_commessa; if(vas) { Commessa__c commessa = new Commessa__c(Chiave_Prodotto_CPQ__c = ChiaveCPQ, Indirizzo_Installazione__c = IndInst, Cap_Installazione__c = Cap ,Comune_Installazione__c = Comune , Cessione_Credito__c = CessioneCredito , Quantita__c = 1 , Stato__c = 'Nuovo', Subalterno__c = Subalterno, Particella__c = Particella, Tipologia_VAS__c = vasType, Accountid__c = vasAccount, Codice_Comune__c = CodiceComune, Provincia_Installazione__c = Provincia, Foglio__c = Foglio, Tipo_Installazione__c = TipoInst , Prodotto__c = Prodotto ); //Tipologia_VAS__c = osi.NTT_Tipologia_Prodotto__c); if(vasType == 'RDO') { //Aggiunta degli 11 campi della commessa commessa.prodotto__c = NomeProdotto; commessa.Ulteriori_servizi__c = UlterioriServizi; commessa.Beni_significativi__c = Beni; commessa.Manodopera_e_beni_non_sign__c = Manodopera; //commessa.Lavori_Extra__c = LavoriExtra; commessa.Prezzo_Lavori_Extra__c = prezzoLavoriExtra; commessa.Iva__c = Decimal.valueOf(IVA); commessa.Perc_Detrazione__c = percentDetraction; //commessa.imponibile__c = TotaleImponibile; //commessa.Prezzo_Manodopera__c = Manodopera; }else if( vasType == 'Caldaia' || vasType == 'Condizionatore'){ Decimal beniSignificativi = [SELECT id,name, SBQQ__ProductName__c, Price__c FROM SBQQ__QuoteLine__c where SBQQ__Quote__r.SBQQ__Opportunity2__r.name = : ChiaveCPQ AND SBQQ__ProductName__c = 'Prezzo prodotto iva esclusa' LIMIT 1]?.Price__c; Decimal manodoperaEBeniNonSign = [SELECT id,name, SBQQ__ProductName__c, Price__c FROM SBQQ__QuoteLine__c where SBQQ__Quote__r.SBQQ__Opportunity2__r.name = : ChiaveCPQ AND SBQQ__ProductName__c = 'Prezzo servizio Iva esclusa' LIMIT 1]?.Price__c; commessa.Beni_significativi__c = beniSignificativi; commessa.Manodopera_e_beni_non_sign__c = manodoperaEBeniNonSign; commessa.Iva__c = Decimal.valueOf(IVA); commessa.prodotto__c = NomeProdotto2; commessa.Perc_Detrazione__c = CessioneCredito == 'Bonus Casa 50%'? 50 : CessioneCredito == 'Ecobonus 65%'? 65 : 0; } Database.insert(commessa); id_commessa = commessa.id; System.debug('Commessa ::: ' + commessa); for(case c : casesToInsert) { c.commessa__c = id_commessa; } Database.update(casesToInsert); if(oppchannel == 'Punti Fisici') { wrts_prcgvr.Interfaces_1_0.IActivityIntegration ActivityIntegration = (wrts_prcgvr.Interfaces_1_0.IActivityIntegration) wrts_prcgvr.VersionManager.newClassInstance('ActivityIntegration'); DatabaseService databaseSrv = DatabaseService.getInstance(); // createFromTemplate invocation CEP_QR_Activity activityQuery = CEP_QR_Activity.getInstance(); wrts_prcgvr__ActivityTemplate__c template = activityQuery.getTemplateByName('Commessa Activity'); wrts_prcgvr__Activity__c[] activities; if(!Test.isRunningTest()){ activities = (wrts_prcgvr__Activity__c[]) ActivityIntegration.createFromTemplate((String)template.wrts_prcgvr__Code__c, null); } wrts_prcgvr__Activity__c act = !Test.isRunningTest() ? activities.get(0) : new wrts_prcgvr__Activity__c(); System.debug('Inserita activity'); act.Opportunity__c = oppoid; if(!Test.isRunningTest()) databaseSrv.insertSObject(act); System.debug('>>>> act: ' + act); } } // query rt case - Select id, DeveloperName, SobjectType from RecordType WHERE DeveloperName = 'RT_SmartServices' AND SobjectType = 'Case' LIMIt 1 for(Id opptyId : opptiesWithCasesById.keySet()){ Opportunity oppty = opptiesWithCasesById.get(opptyId); List<Case> childrenCases = oppty.Cases__r; for(Case processCase : childrenCases){ if (childIntCaseOfCase.get(processCase.id) != null && !childIntCaseOfCase.get(processCase.id).isEmpty()){ system.debug('*** ci sono figli'); continue; } System.debug('CEP_SRV_OrderManagementCreation::createOrderManagementChain::processCase='+JSON.serializePretty(processCase)); IntegrationCase__c intCase = new IntegrationCase__c(); // VAS if(vas){ intCase.Commessaid__c = id_commessa; } // intCase.Phase__c = 'START'; intCase.Case__c = processCase.Id; if(!vas){ intCase.CreatedByRCG3__c = userProfile.Name == 'CEP_IntegrationUser' && processCase.Subject == 'Switching per Ripristino'; intCase.Asset__c = processCase.AssetId; } intCase.Account__c = processCase.AccountId; intCase.PreviousAccount__c = processCase.PreviousAccount__c; //da modificare con il rt nuovo degli smart service System.debug('RT SMART SERVICE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@'); List <Case> vasCase = [SELECT id, OpportunityServiceItem__r.RecordType.DeveloperName FROM Case WHERE opportunity__c = : opptyId AND OpportunityServiceItem__r.RecordType.DeveloperName <> '']; if(vasCase[0].OpportunityServiceItem__r.RecordType.DeveloperName == 'NTT_Smart_Service') { vas = true; } System.debug('VAS CASE LIST ' + vasCase); if(!vas) { intCase.RecordTypeId = trascodeProcessToRecordType(processCase.OpportunityServiceItem__r.Process__c, processCase.OpportunityServiceItem__r.RecordType.DeveloperName, 'IntegrationCase__c'); } else { intcase.RecordTypeId = '0123O0000012wHuQAI'; } intCase.Status__c = 'Bozza'; if(!vas){intCase.ServicePoint__c = processCase.ServicePoint__c; } intCase.ContractAccount__c = processCase.ContractAccount__c; intCase.BillingProfile__c = processCase.BillingProfile__c; intCase.ContactDigitalCompletion__c = processCase.ContactDigitalCompletion__c; String orderCreationStatus = 'In Attesa'; if(processCase.OpportunityServiceItem__r.Antichurn__c && 'Attivo'==processCase.OpportunityServiceItem__r.ServicePoint__r.CurrentAsset__r.Status){ orderCreationStatus = 'In attesa cessazione'; } if('Disattivazione'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) && isDeactivationPostponed(processCase.OpportunityServiceItem__r.RecordType.DeveloperName, processCase.OpportunityServiceItem__r.DeactivationDate__c)){ orderCreationStatus = 'Avvio posticipato'; } intCase.OrderCreationStatus__c = orderCreationStatus; //controllare gli osi vas e vedere se sono popolati if(!vas){ intCase.DistributorName__c = processCase.OpportunityServiceItem__r.DistributorName__c; intCase.DistributorVatNumber__c = processCase.OpportunityServiceItem__r.DistributorVatNumber__c; intCase.REMICode__c = processCase.OpportunityServiceItem__r.REMICode__c; } intCase.OpportunityServiceItem__c = processCase.OpportunityServiceItem__c; System.debug('intCase.OpportunityServiceItem__c = '+intCase.OpportunityServiceItem__c); intCase.Opportunity__c = processCase.Opportunity__c; intCase.Brand__c = processCase.Brand__c; intCase.RequestedDate__c = processCase.OpportunityServiceItem__r.CreatedDate.date(); intCase.SignatureDate__c = oppty.LastModifiedDate.date(); intCase.PayableAmount__c = processCase.OpportunityServiceItem__r.TotalQuoteAmount__c; intCase.InsuranceNumber__c = processCase.OpportunityServiceItem__r.InsuranceNumber__c; intCase.SwitchSkipPreCheck__c = processCase.OpportunityServiceItem__r.SwitchSkipPreCheck__c != null ? processCase.OpportunityServiceItem__r.SwitchSkipPreCheck__c : 'NO'; intCase.ContractAccountChanged__c = processCase.OpportunityServiceItem__r.ContractAccountChanged__c; intCase.DeactivationDate__c = processCase.DeactivationDate__c; intCase.TransferredContact__c = processCase.OpportunityServiceItem__r.TransferredContact__c; intCase.QuoteTypeIntegration__c = processCase.QuoteType__c; intCase.PowerAmount__c = processCase.PowerAmount__c; intCase.AdministrativeSalesCharges__c = processCase.AdministrativeSalesCharges__c; intCase.DistributorAdministrativeCharges__c = processCase.DistributorAdministrativeCharges__c; intCase.Taxable__c = processCase.Taxable__c; intCase.VATRate__c = processCase.VATRate__c; intCase.CodSubServ__c = codsubServ; intCase.QuoteStatus__c = processCase.OpportunityServiceItem__r.QuoteStatus__c; String payment = processCase.Account.Payment__c!=null ? processCase.Account.Payment__c : 'Anticipato' ; intCase.Payment__c = getPayment(processCase.Account.Segment__c, processCase.Opportunity__r.RequestType__c, payment); intCase.AggregateBilling__c = processCase.Account.AggregateBilling__c; intCase.TechnicalDataReceivingDate__c = processCase.Opportunity__r.SupplyStartDate__c; if('Disattivazione'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) ){ intCase.BillingInCycle__c = 'SI'; } if('Attivazione'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) || 'Subentro'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) || processCase.OpportunityServiceItem__r.Process__c.containsIgnoreCase('Predisposizione')){ intCase.BillingInCycle__c = 'NO'; } if('Attivazione'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) || 'Subentro'.equalsIgnoreCase(processCase.OpportunityServiceItem__r.Process__c) || processCase.OpportunityServiceItem__r.Process__c.containsIgnoreCase('Predisposizione')){ intCase.Print__c = getPrint(processCase.Account.Segment__c, processCase.Opportunity__r.RequestType__c); } if(hasDisactivationPostponed){ intCase.ProgressStatus__c = 'Da Inviare - In attesa decorrenza termini'; } // 29-06-2021 Skip ANC for Cambio Prodotto(MM) if the CA is Inherited from asset //NTT W3 if(processCase.OpportunityServiceItem__r.Process__c.containsIgnoreCase(Constants.getAllConstants().OSI_CAMBIO_PRODOTTO_PROCESS) || processCase.OpportunityServiceItem__r.Process__c.toUppercase() == 'CAMBIO PRODOTTO CROSS BRAND'){ System.debug('ANC SKIPPEDDDDD'); //intCase.ANCSkipped__c = processCase.OpportunityServiceItem__r.OldContractAccount__c == processCase.OpportunityServiceItem__r.ContractAccount__c; //NTT W3 if((processCase.OpportunityServiceItem__r.OldContractAccount__c!=null && String.isNotEmpty(processCase.OpportunityServiceItem__r.OldContractAccount__c) && processCase.OpportunityServiceItem__r.OldContractAccount__c != processCase.OpportunityServiceItem__r.ContractAccount__c && oppty.Account.Segment__c != 'Mass Market') || (processCase.OpportunityServiceItem__r.Process__c.toUppercase() == 'CAMBIO PRODOTTO CROSS BRAND')){ intCase.CodSubServ__c = 'CP_CA'; } } /* if(intCase.RecordTypeId == switchEleRt || intCase.RecordTypeId == switchGasRt){ intCase.SwitchDate__c = processCase.CalculatedSupplyStartDate__c; } */ if('CEP_RT_PDC'== oppty.RecordType.DeveloperName ){ intCase.OpportunityPdcAgencyCode__c = oppty.AgencyCode__c; intCase.OpportunityAgencyName__c = oppty.AgencyFormula__c; } integrationCasesToInsert.add(intCase); } } System.debug('@@integrationCasesToInsert: ' + integrationCasesToInsert); // DatabaseService.getInstance().insertSObject(integrationCasesToInsert); // List<Case> caseVasToUpdate =new List<Case>(); // for(Case c : casesToInsert){ // if(c.RecordTypeId != Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_VAS').getRecordTypeId()){ // for(Case c1 : casesToInsert){ // if(c1.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_VAS').getRecordTypeId()){ // if(c1.OpportunityServiceItem__r.ServicePointCode__c == c.OpportunityServiceItem__r.ServicePointCode__c){ // c1.CalculatedSupplyStartDate__c = System.today(); // if(!caseVasToUpdate.contains(c1)){ // caseVasToUpdate.add(c1); // } // } // } // } // } // } // System.debug('VAS Cases ' + caseVasToUpdate); // DatabaseService.getInstance().updateSObject(caseVasToUpdate); List<Case> casePrescriptionToUpdate =new List<Case>(); for(Case c : casesToInsert){ if(c.RecordTypeId == Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('CEP_RT_Prescription').getRecordTypeId() ){ c.Phase__c = Constants.getAllConstants().CASE_PHASE_WORKING; c.Status = Constants.getAllConstants().CASE_STATUS_WORKING; casePrescriptionToUpdate.add(c); } } if(!casePrescriptionToUpdate.isEmpty()){ DatabaseService.getInstance().updateSObject(casePrescriptionToUpdate); } DatabaseService.getInstance().insertSObject(integrationCasesToInsert); map<Id,OpportunityServiceItem__c> osiMap = new map<Id,OpportunityServiceItem__c>(); for(OpportunityServiceItem__c osi : opportunityServiceItems ){ osiMap.put(osi.Id,osi); System.debug('testa id:'+osi.Id+' - '+osi.process__c); } map<Id, IntegrationCase__c> ICToUpdate = new map<Id, IntegrationCase__c>(); map<Id, IntegrationCase__c> mapOnlyPrestazione = getMapOnlyICdiPrestazione(integrationCasesToInsert); map<Id, IntegrationCase__c> mapOnlyVAS = getMapOnlyICVAS(integrationCasesToInsert); for(IntegrationCase__c Ic : mapOnlyPrestazione.values()){ for(IntegrationCase__c Ic1 : mapOnlyVAS.values()){ if(osiMap.get(ic1.OpportunityServiceItem__c).ServicePointCode__c == osiMap.get(ic.OpportunityServiceItem__c).ServicePointCode__c){ Ic1.ParentIC__c = Ic.Id; System.debug('Ic.Id = '+Ic.Id); if(!ICToUpdate.containsKey(Ic1.Id)){ ICToUpdate.put(Ic1.Id,Ic1); } } } } //System.debug('VAS Cases ' + ICToUpdate); CEP_TRH_OpportunityServiceItem.bypass('CEP_BypassIntegrationCaseTrigger'); DatabaseService.getInstance().updateSObject(ICToUpdate.values()); CEP_TRH_OpportunityServiceItem.clearBypass('CEP_BypassIntegrationCaseTrigger'); } else{ throw new OrderManagementServiceException('No opportunities found with the specified ids'); } if(!System.isBatch() && !Test.isRunningTest()){ sendToEbdm(opportunityIds); } if(hasDisactivationPostponed){ List<IntegrationCase__c> toPostpone = [SELECT id FROM integrationcase__c WHERE Process__c = 'Disattivazione' AND Opportunity__c in : opportunityIds AND DeactivationDate__c != today]; if(!toPostpone.isEmpty()){ Set<Id> intCaseIds = new Set<Id>(); List<ReminderService.ReminderServiceRequestWrapper> reminderWrapper = new List<ReminderService.ReminderServiceRequestWrapper>(); for(IntegrationCase__c ic : toPostpone){ intCaseIds.add(ic.Id); ReminderService.ReminderServiceRequestWrapper wrapObject = new ReminderService.ReminderServiceRequestWrapper(); wrapObject.recordRelatedId = ic.id; wrapObject.reminderCodes = new List<String> {'StartOmDissattivazione'}; reminderWrapper.add(wrapObject); } ReminderService reminderService = new ReminderService(); reminderService.insertReminder(reminderWrapper); List<CustomReminder__c> crs = [Select id, Expiration_Date__c, IntegrationCase__r.DeactivationDate__c,IntegrationCase__r.Commodity__c from CustomReminder__c where Status__c = 'Pending' and IntegrationCase__c in: intCaseIds]; for(CustomReminder__c cr : crs){ if(cr.IntegrationCase__r.Commodity__c.equalsIgnoreCase('Gas')) { cr.Expiration_Date__c = Date.today().daysBetween(cr.IntegrationCase__r.DeactivationDate__c) > 28 ? cr.IntegrationCase__r.DeactivationDate__c.addDays(-28) : Date.today(); } else { cr.Expiration_Date__c = Date.today().daysBetween(cr.IntegrationCase__r.DeactivationDate__c) > 30 ? cr.IntegrationCase__r.DeactivationDate__c.addDays(-30) : Date.today(); } } DatabaseService.getInstance().updateSObject(crs); } } } catch(OrderManagementServiceException exp){ Database.rollback(savePoint); System.debug('@@OrderManagementServiceException: ' + exp.getMessage()); System.debug('@@OrderManagementServiceException stack: ' + exp.getStackTraceString()); throw exp; } catch(Exception exp){ Database.rollback(savePoint); System.debug('@@Exception: ' + exp.getMessage()); System.debug('@@Exception stack: ' + exp.getStackTraceString()); throw exp; } return null; } @TestVisible private static String getPayment(String segment, String requestType, String defaultValue){ if(segment == 'Mass Market'){ return 'Anticipato'; } else if(segment == 'Small Business'){ if(requestType == 'A Listino'){ return 'Anticipato'; } else{ return defaultValue; } } else if(segment=='Business'){ return defaultValue; } return defaultValue; } @TestVisible private static String getPrint(String segment, String requestType){ if(segment == 'Mass Market'){ return 'Bollettino'; } else if(segment=='Business' || segment=='Reseller'){ return 'Fattura'; } else if(segment == 'Small Business'){ if(requestType == 'A Listino'){ return 'Bollettino'; } else{ return 'Fattura'; } } return 'Bollettino'; } private static map<Id,IntegrationCase__c> getMapOnlyICdiPrestazione(List<IntegrationCase__c> integrationCasesToInsert){ map<Id,IntegrationCase__c> mapToRet = new map<Id,IntegrationCase__c>(); for(IntegrationCase__c Ic : integrationCasesToInsert){ if(Ic.RecordTypeId != Schema.SObjectType.IntegrationCase__c.getRecordTypeInfosByDeveloperName().get('CEP_RT_VAS').getRecordTypeId()){ mapToRet.put(ic.Id,ic); } } return mapToRet; } private static map<Id,IntegrationCase__c> getMapOnlyICVAS(List<IntegrationCase__c> integrationCasesToInsert){ map<Id,IntegrationCase__c> mapToRet = new map<Id,IntegrationCase__c>(); for(IntegrationCase__c Ic : integrationCasesToInsert){ if(Ic.RecordTypeId == Schema.SObjectType.IntegrationCase__c.getRecordTypeInfosByDeveloperName().get('CEP_RT_VAS').getRecordTypeId()){ mapToRet.put(ic.Id,ic); } } return mapToRet; } private static Boolean isDeactivationPostponed(String commodity, Date deactivationDate){ if('Electric'.equalsIgnoreCase(commodity)){ return Date.today().daysBetween(deactivationDate) > 30; } if('Gas'.equalsIgnoreCase(commodity)){ return Date.today().daysBetween(deactivationDate) > 28; } return false; } @TestVisible private static Boolean getIsBloccatoPdc(Case processCase, Opportunity oppty){ List<String> rts = new List<String>{'SwitchIn_ELE', 'SwitchIn_GAS','ProductChange_ELE','ProductChange_GAS'}; return oppty.RecordType.DeveloperName == 'CEP_RT_PDC' && oppty.StageName == 'Attesa Ripensamento' && (oppty.SubChannel__c == 'Door to Door cartaceo' || oppty.Channel__c == 'Teleselling') && rts.contains(processCase.RecordType.DeveloperName); } public static Id trascodeProcessToRecordType(String osiProcess, String osiRecordTypeDeveloperName, String objectType){ System.debug('CEP_SRV_OrderManagementCreation::trascodeProcessToRecordType::osiProcess='+osiProcess); System.debug('CEP_SRV_OrderManagementCreation::trascodeProcessToRecordType::osiRecordTypeDeveloperName='+osiRecordTypeDeveloperName); System.debug('CEP_SRV_OrderManagementCreation::trascodeProcessToRecordType::objectType='+objectType); System.debug('NTTW3 query rt'); CEP_ProcessRecordTypeTrascoding__mdt trascoding = new CEP_ProcessRecordTypeTrascoding__mdt(); if(CEP_ProcessRecordTypeTrascoding__mdt.SObjectType.getDescribe().isAccessible()){ trascoding = [ SELECT OpportunityServiceItemProcess__c, ObjectType__c, RecordTypeDeveloperName__c, Commodity__c FROM CEP_ProcessRecordTypeTrascoding__mdt WHERE OpportunityServiceItemProcess__c =: osiProcess AND Commodity__c =: osiRecordTypeDeveloperName AND ObjectType__c =: objectType]; } if(trascoding == null){ throw new OrderManagementServiceException('Missing record type configuration for this process'); } else{ String developerName = trascoding.RecordTypeDeveloperName__c; if('Case'.equalsIgnoreCase(objectType)){ return caseRecordTypeIdsByDeveloperName.get(developerName); } else{ return integrationCaseRecordTypeIdsByDeveloperName.get(developerName); } } } @TestVisible private static Id trascodeProcessToRecordType(String osiProcess, String objectType){ System.debug('CEP_SRV_OrderManagementCreation::trascodeProcessToRecordType::osiProcess='+osiProcess); System.debug('CEP_SRV_OrderManagementCreation::trascodeProcessToRecordType::objectType='+objectType); CEP_ProcessRecordTypeTrascoding__mdt trascoding = [ SELECT OpportunityServiceItemProcess__c, ObjectType__c, RecordTypeDeveloperName__c, Commodity__c FROM CEP_ProcessRecordTypeTrascoding__mdt WHERE OpportunityServiceItemProcess__c =: osiProcess AND ObjectType__c =: objectType]; if(trascoding == null){ throw new OrderManagementServiceException('Missing record type configuration for this process'); } else{ String developerName = trascoding.RecordTypeDeveloperName__c; if('Case'.equalsIgnoreCase(objectType)){ return caseRecordTypeIdsByDeveloperName.get(developerName); } else{ return integrationCaseRecordTypeIdsByDeveloperName.get(developerName); } } } public static void startOrderManagment(Set<Id> opportunityIds){ System.debug('Start Order Managment'); Map<Id, Opportunity> opptiesById = OpportunityQueries.getInstance().getOpportunitiesWithOpportunityServiceItems(opportunityIds); List<String> intContractAccountGroupedIds = new List<String>(); if(!opptiesById.isEmpty()){ Set<Id> intContractAccountIds = new Set<Id>(); Set<Id> processCaseIds = new Set<Id>(); List<IntegrationCase__c> intCasesToUpdate = new List<IntegrationCase__c>(); Map<Id, Opportunity> opptiesWithCasesById = OpportunityQueries.getInstance().getOpportunitiesWithCases(opportunityIds); for(Id opptyId : opptiesWithCasesById.keySet()){ Opportunity oppty = opptiesWithCasesById.get(opptyId); Id recordTypeId = oppty.RecordTypeId; Id massMarketRecordId = CEP_UTL_RecordType.getRecordTypeIdByDeveloperName(Constants.getAllConstants().OPPORTUNITY_RECORD_TYPE_MASS_MARKET, 'Opportunity'); /*if(recordTypeId == massMarketRecordId){ List<Case> childrenCases = oppty.Cases__r; for(Case processCase : childrenCases){ processCaseIds.add(processCase.Id); } intCasesToUpdate = Database.query('Select Id FROM IntegrationCase__c WHERE Case__c IN :processCaseIds'); }else{*/ //List<String> intContractAccountGroupedIds = new List<String>(); AggregateResult[] caIds = Database.query('SELECT ContractAccount__c,Id FROM IntegrationCase__c WHERE Opportunity__c = :opptyId AND Phase__c=\'START\' AND ContractAccount__c <> \'\' AND ANCSkipped__c=false GROUP BY ContractAccount__c,Id'); Map<String, String> contractAccIdIntCaseId = new Map<String, String>(); System.debug('caIds: ' + caIds); for (AggregateResult ar : caIds) { System.debug('ContractAccount__c ID: ' + ar.get('ContractAccount__c')); System.debug('Id: ' + ar.get('Id')); contractAccIdIntCaseId.put(String.valueOf(ar.get('ContractAccount__c')),String.valueOf(ar.get('Id'))); } System.debug('contractAccIdIntCaseId.value: ' + contractAccIdIntCaseId.values()); intContractAccountGroupedIds.addAll(contractAccIdIntCaseId.values()); /*List<IntegrationCase__c> intCAncSkipped = Database.query('SELECT Id FROM IntegrationCase__c WHERE Opportunity__c = :opptyId AND Phase__c=\'START\' AND ANCSkipped__c=true'); for(IntegrationCase__c ic : intCAncSkipped){ intContractAccountGroupedIds.add(ic.id); }*/ System.debug('intContractAccountGroupedIds: ' + intContractAccountGroupedIds); if(intContractAccountGroupedIds.isEmpty()){ throw new OrderManagementServiceException('Non ci sono ordini da inviare sull\'opportunità'); } //} } String fieldsToQuery = ''; SObjectType intCaseDesc = Schema.getGlobalDescribe().get('IntegrationCase__c'); Map<String,Schema.SObjectField> intCaseFields = intCaseDesc.getDescribe().fields.getMap(); for(String key : intCaseFields.keySet()){ fieldsToQuery += key+','; } fieldsToQuery = fieldsToQuery.removeEnd(','); String intStringContractAccountGroupedIds = '('; for(String intContractAccount : intContractAccountGroupedIds){ intStringContractAccountGroupedIds += '\''+intContractAccount+'\''+','; } intStringContractAccountGroupedIds = intStringContractAccountGroupedIds.removeEnd(','); intStringContractAccountGroupedIds = intStringContractAccountGroupedIds + ')'; System.debug('** intStringContractAccountGroupedIds' + intStringContractAccountGroupedIds); String queryUpdateIC = 'SELECT '+fieldsToQuery+' '; queryUpdateIC += 'FROM IntegrationCase__c '; queryUpdateIC += 'WHERE Id IN '+intStringContractAccountGroupedIds+' '; System.debug('** queryUpdateIC' + queryUpdateIC); CEP_BA_StartOrderManagment batchToRun = new CEP_BA_StartOrderManagment(queryUpdateIC); Database.executeBatch(batchToRun, 1); } else{ throw new OrderManagementServiceException('No opportunities found with the specified ids'); } } /** * startOrderManagment Single paramether method for being @AuraEnabled * @param opportunityId opportunityId */ @AuraEnabled public static void startOrderManagment(Id opportunityId){ Set<Id> opportunityIdsSet = new Set<Id>{opportunityId}; startOrderManagment(opportunityIdsSet); } @TestVisible public static void sendToEbdm(Set<Id> opportunityIds){ System.debug('@@CEP_SRV_OrderManagementCreation.sendToEbdm'); String opportunityIdsStr = '('; for(Id opptyId : opportunityIds){ opportunityIdsStr += '\''+Id.valueOf(opptyId)+'\','; } opportunityIdsStr = opportunityIdsStr.removeEnd(','); opportunityIdsStr += ')'; String fieldsToQuery = ''; SObjectType intCaseDesc = Schema.getGlobalDescribe().get('IntegrationCase__c'); Map<String,Schema.SObjectField> intCaseFields = intCaseDesc.getDescribe().fields.getMap(); for(String key : intCaseFields.keySet()){ fieldsToQuery += key+','; } fieldsToQuery = fieldsToQuery.removeEnd(','); String queryToStartOM = 'SELECT '+fieldsToQuery+' '; queryToStartOM += 'FROM IntegrationCase__c '; queryToStartOM += 'WHERE OrderCreationStatus__c = \'In Attesa\' '; //queryToStartOM += 'AND Case__r.OpportunityServiceItem__r.ImmediateActivation__c=\'SI\' '; queryToStartOM += 'AND Case__r.Opportunity__c in '+opportunityIdsStr+' '; queryToStartOM += 'AND (OpportunityRecordType__c = \'CEP_RT_MassMarket\' OR OpportunityRecordType__c = \'CEP_RT_Generic\' OR OpportunityRecordType__c = \'CEP_RT_PDC\' OR OpportunityRecordType__c = \'CEP_RT_Movimentazioni\' OR OpportunityRecordType__c = \'CEP_RT_VAS\' OR OpportunityRecordType__c = \'CEP_RT_Minimal\') '; queryToStartOM += 'AND SystemModstamp = TODAY '; System.debug('@@queryToStartOM' + queryToStartOM); // TODO : add OrderCreationStatus__c='Inviato' in phase manager CEP_BA_StartOrderManagment batchToRun = new CEP_BA_StartOrderManagment(queryToStartOM); List<Opportunity> oppty = [SELECT Id,Name FROM Opportunity WHERE Id IN:opportunityIds AND SubChannel__c = 'Door to door app']; if(oppty.isEmpty()) { Database.executeBatch(batchToRun, 1); } else { System.scheduleBatch(batchToRun, oppty[0].Name, 1, 1); } } /** * @description method for retrieve all osi that don't need a Case * @author lorenzo.orlanducci@webresults.it | 26-05-2021 * @param oppMap * @return List<Id> **/ public static List<Id> removeOSIVasActivation(Map<Id, Opportunity> oppMap){ List<Id> badOsiIds = new List<Id>(); for(Opportunity op : oppMap.values()){ for(OpportunityServiceItem__c osi : op.OpportunityServiceItems__r){ if(op.RecordType.DeveloperName=='CEP_RT_VAS' && osi.RecordType.DeveloperName=='CEP_RT_VAS' && osi.ParentOSI__c!=null && osi.ParentOSI__r.RecordType.DeveloperName!='CEP_RT_VAS'){ badOsiIds.add(osi.ParentOSI__c); } } } return badOsiIds; } public class OrderManagementServiceException extends Exception {} }