• Gian Piere Vallejos
  • NEWBIE
  • 285 Points
  • Member since 2019
  • Salesforce Developer
  • Globant


  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 53
    Replies
Hello everybody.

I'm a new salesforce developer, and i'm facin my first real world problem in my company.

We have a custom object named "Solicitudes__c", is the detail side of a master relationship of another custom object.

I was asked to calculate the time between stages (Picklist field named "Etapas_de_solicitud__c" with 10 values).
My solution is use History object records to calculate the first date to enter one stage, and the last day touching that same stage for every stage. I had to create some sample records and move them through all stages.

Later i came out with this apex class:
public with sharing class SolicitudesTiempos {

    public static void tiempos(List<Solicitudes__c> solicitudes) {
        
        //transform the List to Set of Ids
        set<id> solicitudesIds = new set<Id>();
        for(solicitudes__c s : solicitudes){
            solicitudesIds.add(s.id);
        }

        //list used to update the Solicitudes__c records lateer
        List<Solicitudes__c> solicitudesActualizar = new List<Solicitudes__c>();

        //gather all Solicitudes__History records.
        list<Solicitudes__History> historialBuscado = [SELECT ParentId, NewValue, OldValue, CreatedDate
                                                        FROM Solicitudes__History 
                                                        WHERE ParentId =: solicitudesIds
                                                        AND Field = 'Etapas_de_Solicitud__c'
                                                        WITH SECURITY_ENFORCED
                                                        ORDER BY CreatedDate ASC];
                                               
                                                        
        // lists to store the history changes, accordingly.
        list<Solicitudes__History> historialCotizacion = new list<Solicitudes__History>();
        list<Solicitudes__History> historialAceptacion = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPreanalisis = new list<Solicitudes__History>();
        list<Solicitudes__History> historialDocumentos = new list<Solicitudes__History>();
        list<Solicitudes__History> historialCarga = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPendienteAnalizar = new list<Solicitudes__History>();
        list<Solicitudes__History> historialComite = new list<Solicitudes__History>();
        list<Solicitudes__History> historialCondicionada = new list<Solicitudes__History>();
        list<Solicitudes__History> historialAutorizada = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPendientedeFirma = new list<Solicitudes__History>();


        // loop throughout all solicitudes__history to store the appropiate history record to a list.
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Cotización' || s.OldValue == 'Cotización'){
                historialCotizacion.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Aceptación' || s.OldValue == 'Aceptación'){
                historialAceptacion.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Preanálisis' || s.OldValue == 'Preanálisis'){
                historialPreanalisis.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Documentos' || s.OldValue == 'Documentos'){
                historialDocumentos.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Aviso a sebas' || s.OldValue == 'Aviso a sebas'){
                historialCarga.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'pendiente de analizar' || s.OldValue == 'pendiente de analizar'){
                historialPendienteAnalizar.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'comite' || s.OldValue == 'comite'){
                historialComite.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'condicionado' || s.OldValue == 'condicionado'){
                historialCondicionada.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'autorizada' || s.OldValue == 'autorizada'){
                historialAutorizada.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'pendiente de firma' || s.OldValue == 'pendiente de firma'){
                historialPendientedeFirma.add(s);
            }
        }

        // loop to calcule every Solicitudes__c record time on each stage.
        for(Id s : solicitudesIds){

            Decimal tiempoCotizacion = SolicitudesTiempos.calcularTiempo(historialCotizacion, s);
            Decimal tiempoAceptacion = SolicitudesTiempos.calcularTiempo(historialAceptacion, s);
            Decimal tiempoPreanalisis = SolicitudesTiempos.calcularTiempo(historialPreanalisis, s);
            Decimal tiempoDocumentos = SolicitudesTiempos.calcularTiempo(historialDocumentos, s);
            Decimal tiempoCarga = SolicitudesTiempos.calcularTiempo(historialCarga, s);
            Decimal tiempoPendienteAnalizar = SolicitudesTiempos.calcularTiempo(historialPendienteAnalizar, s);
            Decimal tiempoComite = SolicitudesTiempos.calcularTiempo(historialComite, s);
            Decimal tiempoCondicionado = SolicitudesTiempos.calcularTiempo(historialCondicionada, s);
            Decimal tiempoAutorizada = SolicitudesTiempos.calcularTiempo(historialAutorizada, s);
            Decimal tiempoPendienteFirma = SolicitudesTiempos.calcularTiempo(historialPendientedeFirma, s);

            //store each calculation to the record's field and add it to a collection to update later.
            Solicitudes__c solicitud = new Solicitudes__c(Id = s, 
                                                            Tiempo_cotizacion__c=tiempoCotizacion,
                                                            Tiempo_Aceptacion__c=tiempoAceptacion,
                                                            Tiempo_preanalisis__c=tiempoPreanalisis,
                                                            Tiempo_Documentos__c=tiempoDocumentos,
                                                            Tiempo_Carga__c=tiempoCarga,
                                                            Tiempo_Por_analizar__c=tiempoPendienteAnalizar,
                                                            Tiempo_Comite__c=tiempoComite,
                                                            Tiempo_Condicionada__c=tiempoCondicionado,
                                                            Tiempo_Autorizada__c=tiempoAutorizada,
                                                            Tiempo_Pendiente_Firma__c=tiempoPendienteFirma);
            
            //add the new record to a collection to update later.
            solicitudesActualizar.add(solicitud);
        }
        
        //update the records
        update solicitudesActualizar;
    }


    //method to calculate time between stages.
    private static Decimal calcularTiempo (list<Solicitudes__History> historial, Id solicitudId){

        if(historial.size()>0 && historial != null){
            dateTime date1;
            dateTime date2;
            Decimal minutos;
            for(Solicitudes__History hist : historial){
                if(hist.ParentId == solicitudId && date1 == null){
                    date1 = hist.CreatedDate;
                }else if(hist.ParentId == solicitudId && date1 != null){
                    date2 = hist.CreatedDate;
                }
            }
            if(date1 != null && date2 != null){
                Long firstDate = date1.getTime();
                Long finalDate = date2.getTime();
                Decimal segundos = (finalDate-firstDate)/1000;
                minutos = segundos/60;
                return minutos;
            }else{
                return 0.00;
            }
        }else{
            return 0.00;
        }   
    }
}

Then i came out with an batch apex class:
public class SolicitudesTiemposBatch implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id FROM Solicitudes__c '+
                'WHERE CreatedDate >= 2022-01-01T00:00:00Z '+
                'ORDER BY CreatedDate ASC';
                return DataBase.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Solicitudes__c> scope){
        SolicitudesTiempos.tiempos(scope);
    }

    public void finish(database.BatchableContext bc){
    }
}

And create a Test class:
@isTest
public class SolicitudesTiemposBatchTest {
    @isTest(SeeAllData=true)
        static void test(){

            Test.startTest();
            SolicitudesTiemposBatch solicitudesBatch = new SolicitudesTiemposBatch();
            Database.executeBatch(solicitudesBatch, 200);
            Test.stopTest();
            
            System.assertEquals(199,[SELECT count() FROM Solicitudes__C], '199 solicitudes');
        }
}
And i get enough coverage to deploy production.
Code coverage

The problem is that when i'm trying to validate in production i see this problem: "System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point"

Any suggestions?
Our Org is new to creating and editing Apex code. We have run into an issue where the below Apex Class (4 years old) is preventing validation and deployment of any change packages that contain Apex. Based on what we know, this Apex Class is not tied to any Apex Triggers or automation and is purely a validation that was written when our Org was first created. We have checked for any related metadata to this Apex Class and the only related items are the 4 custom fields towards the bottom of the class and they are on the Contract object.

/**
* @author Conga Services
* @date
* @version 1.00
* @description ContractTest  - Test class for the [Name of class being tested] class
*/
@isTest
public with sharing class ContractTest {
    ///////////// ADD JAVA DOC AUTHOR, DATE, AND/OR VERSION TAGS TO METHODS WHEN THE VALUES DIFFER THAN THE CLASS LEVEL TAGS
    /**
    * @description setup - Test data setup method
    */
    @testSetup
    public static void setup(){
        /////// Create your test data here using TestingUtility helper methods
        List<Account> accounts = new List<Account>();
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.BillingStreet = '1234 Test Street';
        acc.BillingCity = 'Broomfield';
        acc.BillingState = 'CO';
        acc.BillingPostalCode = '80021';
        acc.BillingCountry = 'USA';
        accounts.add(acc);
        Account acc1 = new Account();
        acc1.Name = 'Account Test';
        acc1.BillingStreet = '4321 Test Street';
        acc1.BillingCity = 'Superior';
        acc1.BillingState = 'CO';
        acc1.BillingPostalCode = '80027';
        acc1.BillingCountry = 'USA';
        accounts.add(acc1);
        insert accounts;
        List<Contact> contacts = new List<Contact>();
        Contact contact = new Contact();
        contact.FirstName = 'Test';
        contact.LastName = 'Contact';
        contact.Email = 'test@contact.com';
        contacts.add(contact);
        Contact contact1 = new Contact();
        contact1.FirstName = 'Contact';
        contact1.LastName = 'Test';
        contact1.Email = 'contact@test.com';
        contacts.add(contact1);
        insert contacts;
    }
   
    /**
    * @description testMethod1 - Test Happy Path of code
    */
    public static testMethod void testMethod1() {
        // Get test data
        List<Account> accs = [SELECT Id FROM Account WHERE Name = 'Test Account'];
        List<Contact> cons = [SELECT Id FROM Contact WHERE Email = 'test@contact.com'];
        Contract contract = new Contract();
        contract.Contractor_Consultant_Name__c = 'Test Account';
        contract.BillingStreet = '1234 Test Street';
        contract.BillingCity = 'Broomfield';
        contract.BillingState = 'CO';
        contract.BillingPostalCode = '80021';
        contract.BillingCountry = 'USA';
        contract.Other_Party_Contact_Name__c = 'Test Contact';
        contract.Other_Party_Contact_Email__c = 'test@contact.com';
       
        //ApexPages.StandardController sc = new ApexPages.StandardController(td.Accounts[0]);
        //SubProjectViewController cn = new SubProjectViewController(sc);
        Test.startTest();
        insert contract;
        Contract c = [SELECT AccountId, Other_Party_Contact_Name_Lookup__c FROM Contract WHERE Id = :contract.Id][0];
        System.assertEquals(true, c.AccountId == accs[0].Id,'The fuzzy match did not find the appropriate account');
        System.assertEquals(true, c.Other_Party_Contact_Name_Lookup__c == cons[0].Id,'The fuzzy match did not find the appropriate contact');
        Test.stopTest();//will sync back up with async operations if future/batch called before this
    }  
}


We plan to comment out this code in Production so it will pass validation. The error message we are currently receiving is the following: 

System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point


Given all of this information, are there any obvious concerns we should have before deploying the commented out version in Production? Additionally, are there any tests we should run pre and post update? 

Thanks!
Can someone please help in writing test class for below apex class with 100% code coverage. thanks!

public static List<String> getUserName(List<String> currentOwnerValues) {
    List<String> ownerNames = new List<String>();
set<String> uniqueIds = new set<String>(); 
    for (String currentOwnerValue : currentOwnerValues) {
        String trimmedId = currentOwnerValue.trim();
       If(!string.isBlank(trimmedId)){
uniqueIds.add(trimmedId);
}
}

Map<String, User> userMap = new Map<String, User>();
if(uniqueIds.size()>0){
for(   User u = [SELECT Id, Name FROM User WHERE FederationIdentifier IN :uniqueIds];
}
for(String currentOwnerValue : currentOwnerValues){
String trimmedId = currentOwnerValue.trim();
User u = userMap.get(trimmedId);
string ownername;
         
            if (u != null) {
                ownerName = String.escapeSingleQuotes(u.Name);
            }
        } catch (Exception ex) {
            ownerName = String.escapeSingleQuotes(trimmedId);
        }
        ownerNames.add(ownerName);
    }
    return ownerNames;
}

 
rows = [
    {'Name': 'Name 1', 'Date': '06-Aug', 'Jan': 150, 'Feb': None, 'March': None, 'Apr': None, 'May': None},
    {'Name': 'Name 2', 'Date': '07-Aug', 'Jan': None, 'Feb': 100, 'March': 110, 'Apr': None, 'May': None},
    {'Name': 'Name 3', 'Date': '07-Aug', 'Jan': None, 'Feb': None, 'March': 400, 'Apr': 500, 'May': None},
]

def get_formatted_data(rows):
    data = []

    # For each row of rows
    for row in rows:

        # Loop through each key, value pair of row
        for key, val in row.items():
            data_dict = {
                'Name': row['Name'],
                'Date': row['Date']
            }
            if key not in ('Name', 'Date') and val:
                data_dict['Month'] = key
                data_dict['Rate'] = val
                data.append(data_dict)
    return data
Hi All,

Help me this, how to display records in lightning web components.using <table> tag.. import from apex class..

Thanks, Sesha.
Hi everyone,

We have a 'Rune rate' field which needs to be locked after it has been populated. I've figured that out with this validation rule:

AND(
ISCHANGED(Run_Rate__c),
NOT(ISBLANK(PRIORVALUE(Run_Rate__c)))
)
​​​​​​
Now i'm trying to exclude the system admin profile from this. I've tried using 

NOT($Profile.Name = "System Administrator")

but I'm not sure where to put it as I keep getting the 'missing )' error. Any ideas?

(I'm very new to formulas!)

Hi everyone,

We have an Apex job/batch which executes each week and deletes all Contact records whith a certain condition (let suppose, ActivationDate__c older than 24-months).

How should I edit this Apex job in order to send automatically an Email to a Salesforce user whenever it finishes to comunicate the result (such as: success or failure/exception)?

 

Thank you so much,

Skender

Hi,

I have a requirement,in a object i have to restrict for  crearting records on below case:
Suppose I have created a records and on custom field(Test_code__c) I have put value:"ABC",and start date-->29/11/2019
End date:->29/12/2019

So in next records if I tried to create the record with same value 'ABC',the Start date and End should not be overlaped.
Hi,

Thanks in Advance,
I want to create a date format like this November 29th, 2019 from date/Time field using Apex class.

I have just started learning LWC and trying to display a picklist of Account Names in a LWC ComboBox and the selected value should be displayed on the Placeholder and on a text line below the placeholder.

The issue is I am seeing the dropdown values but the selected value is not being displayed on the placeholder and not even on the text line below it. What am i doing wrong. 

Below is my code

JS Code

import { LightningElement, track, wire } from 'lwc';
import getAccList from '@salesforce/apex/test_LWCWireDemo.getAccList';

export default class Test_comboboxDemo extends LightningElement {

    @track value = ""
    @track accoption = [];

    get options(){
        return this.accoption;
    }

    connectedCallback(){
        getAccList()
        .then(result => {
            let arr = [];
            for(var i=0;i<result.length;i++){
                arr.push({value :result[i].Name, label :result[i].ID});
            }
            this.accoption = arr;

        })
        .catch(error => {
            console.log("error occurred");
        })
        
    }

    handleChange(event){
        this.value = event.detail.value;
    }

}

HTML
<template>
    <lightning-card title="Combo Box Demo">

        <lightning-combobox label="Account Status"
                            value={value}
                            placeholder="Select Account"
                            options={options}
                            onchange={handleChange}>
        </lightning-combobox>

        <p>Select Value is: {value}</p>
    </lightning-card>
</template>

Apex Class
public class test_LWCWireDemo {
    
	@AuraEnabled
    public static List<Account> getAccList(){
        
        List<Account> accList = [Select ID, Name from Account];
        return accList;
    }
    
}

 

Question is the same as the title.

I have a dashboard that is displaying a bar graph from a report.

In the report, there are no additional HTML tags shown. See here: (Some information blanked out for security purposes)

Salesforce report showing all HTML tags are being properly used and not shown.

When I show that same bargraph in the Dashboard view, it displays <br> tags on all of the Asset Product Line(s).

See here: Dashboard showing bug of HTML tags

Honestly, I don't know what else to call this except for a bug. Any thoughts/comments would be greatly appreciated, but honestly I probably just need to file a bug report for this issue.

Error-->Is coming that the allcars is not a function.but I want to retrive on patricular car from allcars.In this I have created Car1,Car2,and Car3 data,and put It into the AllCars={car1,car2,car3},If I want to use AllCar inside the filter on particular condition ,and I want to retrive the data of particular Car1 or car 2 or car 3 from the all car,but it saying all cars is not a function..How it will work please let me know.
 
Below the Code
public class DynamicRecordEditFormController {
    @AuraEnabled(cacheable=true)
    public static List<Schema.FieldSetMember> getFields(String fieldSetName, String objectName) {
        Schema.SObjectType sObjectType = Schema.getGlobalDescribe().get(objectName);
        Schema.FieldSet fieldSet = sObjectType.getDescribe().fieldsets.getMap().get(fieldSetName);
        return fieldSet.getFields();
    }
}

I would appreciate help with the following trigger question:


Write a trigger, Whenever an Opportunity is Created, Updated, Deleted, or Undeleted then Roll-Up the Opportunity amount to Account's Annual Revenue.

I have tried it with the handler class. I have just begun learning triggers, so I make a lot of silly mistakes. Any small help/guidance you can give will be helpful.

Trigger/Handle I wrote is:

 

Trigger: trigger PopulateOppAmntToAccAmnt on Opportunity (before insert) {

    if(Trigger.isInsert) {
        if(Trigger.isAfter) {
            CopyOppAmntToAccAmnt.populateAccAmnt(Trigger.new);
        }
    }
    
    if(Trigger.isDelete) {
        if(Trigger.isAfter) {
            CopyOppAmntToAccAmnt.populateAccAmnt(Trigger.old);
        }
    }
    
    if(Trigger.isUndelete) {
        if(Trigger.isAfter) {
            CopyOppAmntToAccAmnt.populateAccAmnt(Trigger.new);
        }
    }
    
    if(Trigger.isUpdate) {
        if(Trigger.isAfter) {
            CopyOppAmntToAccAmnt.populateAccAmnt(Trigger.new);
        }
    }  
}

 

Handle Class:
public class CopyOppAmntToAccAmnt {

    public static void populateAccAmnt(List<Opportunity> oppList) {
        
        Set<Id> accId = new Set<Id>();
        List<Account> accList = new List<Account>();
        
        for(Opportunity opp : oppList) {
            if(opp.AccountId != null) {
                accId.add(opp.AccountId);
            }
        }
        
        for(Account acc : [SELECT Id, Name, AnnualRevenue,
                          (SELECT Id, Name, Amount FROM Opportunities)
                          FROM Account WHERE Id IN: accId]) {
            acc.AnnualRevenue = acc.Opportunities.Amount;
                              accList.add(acc);
        }
    }
}

I have a number decimal field decimal created to calcuate the number of years and months (in decimal) on our Contract object. My formula is not calcuating the month in decimal correctly taking into account rounding. For instance I have a a record where the Dates are as follows:
Original Agreement Start Date : 9/1/2020
Original Agreement End Date: 12/31/2025
I would expect the Original Agreement Term (Years) to be 5.4 based on the rounding. The below formula is calculating the Original Agreement Term as 5.3. 

ROUND
(
    (YEAR({!$Record.Original_Agreement_End_Date__c}) - YEAR({!$Record.Original_Agreement_Start_Date__c}))
    +
    ((({!$Record.Original_Agreement_End_Date__c} - DATE(YEAR({!$Record.Original_Agreement_End_Date__c} ), 1, 1)) - 
({!$Record.Original_Agreement_Start_Date__c} - DATE(YEAR({!$Record.Original_Agreement_Start_Date__c}), 1, 1))) / 365),
    2
)

I have a custom event that is dispatched from my clild LWC 

Event dispached from child:

spinner(boolean){
    console.log('set spinner - ' + boolean);
    const spinner = new CustomEvent('spinnernotification', {
      display: boolean
    });
    this.dispatchEvent(spinner);  
  }

The event is being retrieved by the parent LWC but i am unable to read the display property, and am getting an undefined.

Console lines:

set spinner - false
called with display value undefined

Parent LWC:

displaySpinner(customEvent){
	
	if(null != customEvent){
		console.log('called with display value ' + customEvent.display);
		this.spinner = customEvent.display;
	}else{
		console.log('customEvent display is null');
		this.spinner = false;
	}
}

if i stringify the customEvent in the parent all i see is the below:

value {"isTrusted":false,"composed":false}

Hello everybody.

I'm a new salesforce developer, and i'm facin my first real world problem in my company.

We have a custom object named "Solicitudes__c", is the detail side of a master relationship of another custom object.

I was asked to calculate the time between stages (Picklist field named "Etapas_de_solicitud__c" with 10 values).
My solution is use History object records to calculate the first date to enter one stage, and the last day touching that same stage for every stage. I had to create some sample records and move them through all stages.

Later i came out with this apex class:
public with sharing class SolicitudesTiempos {

    public static void tiempos(List<Solicitudes__c> solicitudes) {
        
        //transform the List to Set of Ids
        set<id> solicitudesIds = new set<Id>();
        for(solicitudes__c s : solicitudes){
            solicitudesIds.add(s.id);
        }

        //list used to update the Solicitudes__c records lateer
        List<Solicitudes__c> solicitudesActualizar = new List<Solicitudes__c>();

        //gather all Solicitudes__History records.
        list<Solicitudes__History> historialBuscado = [SELECT ParentId, NewValue, OldValue, CreatedDate
                                                        FROM Solicitudes__History 
                                                        WHERE ParentId =: solicitudesIds
                                                        AND Field = 'Etapas_de_Solicitud__c'
                                                        WITH SECURITY_ENFORCED
                                                        ORDER BY CreatedDate ASC];
                                               
                                                        
        // lists to store the history changes, accordingly.
        list<Solicitudes__History> historialCotizacion = new list<Solicitudes__History>();
        list<Solicitudes__History> historialAceptacion = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPreanalisis = new list<Solicitudes__History>();
        list<Solicitudes__History> historialDocumentos = new list<Solicitudes__History>();
        list<Solicitudes__History> historialCarga = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPendienteAnalizar = new list<Solicitudes__History>();
        list<Solicitudes__History> historialComite = new list<Solicitudes__History>();
        list<Solicitudes__History> historialCondicionada = new list<Solicitudes__History>();
        list<Solicitudes__History> historialAutorizada = new list<Solicitudes__History>();
        list<Solicitudes__History> historialPendientedeFirma = new list<Solicitudes__History>();


        // loop throughout all solicitudes__history to store the appropiate history record to a list.
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Cotización' || s.OldValue == 'Cotización'){
                historialCotizacion.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Aceptación' || s.OldValue == 'Aceptación'){
                historialAceptacion.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Preanálisis' || s.OldValue == 'Preanálisis'){
                historialPreanalisis.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Documentos' || s.OldValue == 'Documentos'){
                historialDocumentos.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'Aviso a sebas' || s.OldValue == 'Aviso a sebas'){
                historialCarga.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'pendiente de analizar' || s.OldValue == 'pendiente de analizar'){
                historialPendienteAnalizar.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'comite' || s.OldValue == 'comite'){
                historialComite.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'condicionado' || s.OldValue == 'condicionado'){
                historialCondicionada.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'autorizada' || s.OldValue == 'autorizada'){
                historialAutorizada.add(s);
            }
        }
        for(Solicitudes__History s : historialBuscado){
            if(s.NewValue == 'pendiente de firma' || s.OldValue == 'pendiente de firma'){
                historialPendientedeFirma.add(s);
            }
        }

        // loop to calcule every Solicitudes__c record time on each stage.
        for(Id s : solicitudesIds){

            Decimal tiempoCotizacion = SolicitudesTiempos.calcularTiempo(historialCotizacion, s);
            Decimal tiempoAceptacion = SolicitudesTiempos.calcularTiempo(historialAceptacion, s);
            Decimal tiempoPreanalisis = SolicitudesTiempos.calcularTiempo(historialPreanalisis, s);
            Decimal tiempoDocumentos = SolicitudesTiempos.calcularTiempo(historialDocumentos, s);
            Decimal tiempoCarga = SolicitudesTiempos.calcularTiempo(historialCarga, s);
            Decimal tiempoPendienteAnalizar = SolicitudesTiempos.calcularTiempo(historialPendienteAnalizar, s);
            Decimal tiempoComite = SolicitudesTiempos.calcularTiempo(historialComite, s);
            Decimal tiempoCondicionado = SolicitudesTiempos.calcularTiempo(historialCondicionada, s);
            Decimal tiempoAutorizada = SolicitudesTiempos.calcularTiempo(historialAutorizada, s);
            Decimal tiempoPendienteFirma = SolicitudesTiempos.calcularTiempo(historialPendientedeFirma, s);

            //store each calculation to the record's field and add it to a collection to update later.
            Solicitudes__c solicitud = new Solicitudes__c(Id = s, 
                                                            Tiempo_cotizacion__c=tiempoCotizacion,
                                                            Tiempo_Aceptacion__c=tiempoAceptacion,
                                                            Tiempo_preanalisis__c=tiempoPreanalisis,
                                                            Tiempo_Documentos__c=tiempoDocumentos,
                                                            Tiempo_Carga__c=tiempoCarga,
                                                            Tiempo_Por_analizar__c=tiempoPendienteAnalizar,
                                                            Tiempo_Comite__c=tiempoComite,
                                                            Tiempo_Condicionada__c=tiempoCondicionado,
                                                            Tiempo_Autorizada__c=tiempoAutorizada,
                                                            Tiempo_Pendiente_Firma__c=tiempoPendienteFirma);
            
            //add the new record to a collection to update later.
            solicitudesActualizar.add(solicitud);
        }
        
        //update the records
        update solicitudesActualizar;
    }


    //method to calculate time between stages.
    private static Decimal calcularTiempo (list<Solicitudes__History> historial, Id solicitudId){

        if(historial.size()>0 && historial != null){
            dateTime date1;
            dateTime date2;
            Decimal minutos;
            for(Solicitudes__History hist : historial){
                if(hist.ParentId == solicitudId && date1 == null){
                    date1 = hist.CreatedDate;
                }else if(hist.ParentId == solicitudId && date1 != null){
                    date2 = hist.CreatedDate;
                }
            }
            if(date1 != null && date2 != null){
                Long firstDate = date1.getTime();
                Long finalDate = date2.getTime();
                Decimal segundos = (finalDate-firstDate)/1000;
                minutos = segundos/60;
                return minutos;
            }else{
                return 0.00;
            }
        }else{
            return 0.00;
        }   
    }
}

Then i came out with an batch apex class:
public class SolicitudesTiemposBatch implements Database.Batchable<SObject> {

    public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id FROM Solicitudes__c '+
                'WHERE CreatedDate >= 2022-01-01T00:00:00Z '+
                'ORDER BY CreatedDate ASC';
                return DataBase.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext bc, List<Solicitudes__c> scope){
        SolicitudesTiempos.tiempos(scope);
    }

    public void finish(database.BatchableContext bc){
    }
}

And create a Test class:
@isTest
public class SolicitudesTiemposBatchTest {
    @isTest(SeeAllData=true)
        static void test(){

            Test.startTest();
            SolicitudesTiemposBatch solicitudesBatch = new SolicitudesTiemposBatch();
            Database.executeBatch(solicitudesBatch, 200);
            Test.stopTest();
            
            System.assertEquals(199,[SELECT count() FROM Solicitudes__C], '199 solicitudes');
        }
}
And i get enough coverage to deploy production.
Code coverage

The problem is that when i'm trying to validate in production i see this problem: "System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point"

Any suggestions?
Our Org is new to creating and editing Apex code. We have run into an issue where the below Apex Class (4 years old) is preventing validation and deployment of any change packages that contain Apex. Based on what we know, this Apex Class is not tied to any Apex Triggers or automation and is purely a validation that was written when our Org was first created. We have checked for any related metadata to this Apex Class and the only related items are the 4 custom fields towards the bottom of the class and they are on the Contract object.

/**
* @author Conga Services
* @date
* @version 1.00
* @description ContractTest  - Test class for the [Name of class being tested] class
*/
@isTest
public with sharing class ContractTest {
    ///////////// ADD JAVA DOC AUTHOR, DATE, AND/OR VERSION TAGS TO METHODS WHEN THE VALUES DIFFER THAN THE CLASS LEVEL TAGS
    /**
    * @description setup - Test data setup method
    */
    @testSetup
    public static void setup(){
        /////// Create your test data here using TestingUtility helper methods
        List<Account> accounts = new List<Account>();
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.BillingStreet = '1234 Test Street';
        acc.BillingCity = 'Broomfield';
        acc.BillingState = 'CO';
        acc.BillingPostalCode = '80021';
        acc.BillingCountry = 'USA';
        accounts.add(acc);
        Account acc1 = new Account();
        acc1.Name = 'Account Test';
        acc1.BillingStreet = '4321 Test Street';
        acc1.BillingCity = 'Superior';
        acc1.BillingState = 'CO';
        acc1.BillingPostalCode = '80027';
        acc1.BillingCountry = 'USA';
        accounts.add(acc1);
        insert accounts;
        List<Contact> contacts = new List<Contact>();
        Contact contact = new Contact();
        contact.FirstName = 'Test';
        contact.LastName = 'Contact';
        contact.Email = 'test@contact.com';
        contacts.add(contact);
        Contact contact1 = new Contact();
        contact1.FirstName = 'Contact';
        contact1.LastName = 'Test';
        contact1.Email = 'contact@test.com';
        contacts.add(contact1);
        insert contacts;
    }
   
    /**
    * @description testMethod1 - Test Happy Path of code
    */
    public static testMethod void testMethod1() {
        // Get test data
        List<Account> accs = [SELECT Id FROM Account WHERE Name = 'Test Account'];
        List<Contact> cons = [SELECT Id FROM Contact WHERE Email = 'test@contact.com'];
        Contract contract = new Contract();
        contract.Contractor_Consultant_Name__c = 'Test Account';
        contract.BillingStreet = '1234 Test Street';
        contract.BillingCity = 'Broomfield';
        contract.BillingState = 'CO';
        contract.BillingPostalCode = '80021';
        contract.BillingCountry = 'USA';
        contract.Other_Party_Contact_Name__c = 'Test Contact';
        contract.Other_Party_Contact_Email__c = 'test@contact.com';
       
        //ApexPages.StandardController sc = new ApexPages.StandardController(td.Accounts[0]);
        //SubProjectViewController cn = new SubProjectViewController(sc);
        Test.startTest();
        insert contract;
        Contract c = [SELECT AccountId, Other_Party_Contact_Name_Lookup__c FROM Contract WHERE Id = :contract.Id][0];
        System.assertEquals(true, c.AccountId == accs[0].Id,'The fuzzy match did not find the appropriate account');
        System.assertEquals(true, c.Other_Party_Contact_Name_Lookup__c == cons[0].Id,'The fuzzy match did not find the appropriate contact');
        Test.stopTest();//will sync back up with async operations if future/batch called before this
    }  
}


We plan to comment out this code in Production so it will pass validation. The error message we are currently receiving is the following: 

System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.
Stack Trace: External entry point


Given all of this information, are there any obvious concerns we should have before deploying the commented out version in Production? Additionally, are there any tests we should run pre and post update? 

Thanks!
Hello Everyone,
I have one requirement to create one LWC component and fetch list of objects and its associated fields by creating two lightning comboboxes one for list of object and one for list of fields from selected object. Once user selects the field it should show the api name of the field. Can anyone please help me on the same. Thanks in advance
We have created an LWC component for use on Contact and Opportunity pages. In testing, the component works fine on those two pages, but a couple of customers have reported that the component installs fine on their Contact page, but not on their Opportunity page.

In the case of the Opportunity page, our component appears in the list of components, and they can drag it on to the page, but then a loader appears and the process never completes.

This has happened to at least two customers, so this does not appear to be an isolated issue.

Does anyone know what could cause this?
I need to use REST API to insert a record into a table called:

conference360__Event__c

This table has the follow four fields:

conference360__Event_Start_Date__c
conference360__Event_Start_Time__c
conference360__Event_End_Date__c
conference360__Event_End_Time__c

and I need put values in these fields when inserting a record into the table. 

The problem is that when inserting a record into this table, I always get the following error message for any of these four fields:

We can't save this record because the “Event & Case Creation from Room Booking” process failed. Give your Salesforce admin these details. 
This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: conference360.Event_Trigger: execution of AfterInsert\n\ncaused by: 
System.QueryException: Insufficient permissions: secure query included inaccessible field\n\n(conference360). You can look up ExceptionCode values in the SOAP API Developer Guide. 
Error ID: 2052924026-11322 (-1519010228)k up ExceptionCode values in the SOAP API Developer Guide. Error ID: 2052924026-11322 (-1519010228)",
"errorCode":"CANNOT_EXECUTE_FLOW_TRIGGER","fields":[]

How to solve this type of problem? I went to the setup and it seems that these fields are managed and I can't do anything that can fix the problem. Is there a place to configure these fields so that the REST API code can insert values into them?

I am new to Salesforce, and any input would be really appreciated.

Thank you!


 
From my controller, I need the retrieve all emails related to an specific opportunity.
I noticed when I create a new event as an email, I can grab it from the event object.
But that is an event, I'm looking for the actual email
I'm new to salesforce, so any help will be greatly appreciated!
My json reponse is:
{
  "totalSize": 1,
  "done": true,
  "records": [
    {
      "attributes": {
        "type": "Account",
        "url": "/services/data/v56.0/sobjects/Account/0017E00001N4y8FAAA"
      },
      "Id": "0017E00001N4y8FAAA",
      "Name": "Green Ltd",
      "BillingPostalCode": "SEW23"
    }
  ]
}

Java method to read the value:
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { response.append(inputLine);
}
in.close();
JSONParser parse = new JSONParser();
JSONObject jobj = (JSONObject) parse.parse(response.toString()); accId = (String) jobj.get("Id");

However I get value for accId = null.
Can someone please help in writing test class for below apex class with 100% code coverage. thanks!

public static List<String> getUserName(List<String> currentOwnerValues) {
    List<String> ownerNames = new List<String>();
set<String> uniqueIds = new set<String>(); 
    for (String currentOwnerValue : currentOwnerValues) {
        String trimmedId = currentOwnerValue.trim();
       If(!string.isBlank(trimmedId)){
uniqueIds.add(trimmedId);
}
}

Map<String, User> userMap = new Map<String, User>();
if(uniqueIds.size()>0){
for(   User u = [SELECT Id, Name FROM User WHERE FederationIdentifier IN :uniqueIds];
}
for(String currentOwnerValue : currentOwnerValues){
String trimmedId = currentOwnerValue.trim();
User u = userMap.get(trimmedId);
string ownername;
         
            if (u != null) {
                ownerName = String.escapeSingleQuotes(u.Name);
            }
        } catch (Exception ex) {
            ownerName = String.escapeSingleQuotes(trimmedId);
        }
        ownerNames.add(ownerName);
    }
    return ownerNames;
}