• Kris Webster
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 16
    Questions
  • 14
    Replies
Good afternoon all ! I am attempting to schedule an API callout using the Database.Batchable method. 

I have all the code written and have attempted to schedule the class via the Salesforce Scheduler interface, however when the code was excecuted nothing happened to the records the code is supposed to update. ** When I run the class via ANONYMOUS APEX it works perfectly though... is there a better way to schedule this class ? 

Here is the API Callout class 
 
global class ZenefitsEmployees implements Database.Batchable<sObject> {
    
    public String query = 'Select ID, Name from Contact';

    global Database.QueryLocator start(Database.BatchableContext ctx) {
        return Database.getQueryLocator(query);
    }
    
    global void execute (Database.BatchableContext ctx, List<Contact> records) {

	string url = 'REMOVED FOR SECURTY PURPOSES';
	Integer int1 = 0;

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setHeader('Authorization', 'Bearer REMOVED FOR SECURITY PURPOSES');
    request.setEndpoint(url);
	request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserializes the JSON string into collections of posts.
        Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
        if (wrapper.containsKey('data')) {
            Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data');
            if(wrapper2.containsKey('data')) {
                List<Object> people = (List<Object>)wrapper2.get('data');
                for (Object peopleWrapper : people) {
                    Map<String,Object> Employees = (Map<String,Object>) peopleWrapper;
                    if(Employees.containsKey('last_name')){
                    String ZenefitsLastName = (String) Employees.get('last_name');
                    String ZenefitsFirstName = (String) Employees.get('first_name');
                    String ZenefitseEmployeeId = (String) Employees.get('id');
                    String ZenefitsEmail = (String) Employees.get('work_email');    
                        
                    List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200];
                            List<Contact> contactsToUpdate = new List<Contact>();
                        	for(Contact con : contactList){
                       			con.Zenefits_Id__c = ZenefitseEmployeeId;
                            	contactsToUpdate.add(con);
                        
                        		}
                        		update contactsToUpdate;
                            

                            	system.debug('Employees ' + Employees);
                            	system.debug('last name ' + ZenefitsLastName);
                        		system.debug('Employee id ' + ZenefitseEmployeeId);
                        		system.debug('first name ' + ZenefitsFirstName);
                            	system.debug('Contact list ' + contactList);
                            	system.debug('TEST ' + contactsToUpdate);
                   				}
               				}
            			}
           			return ;
        		}
        	return ;
    	}
    	return ;
	}
    
    global void finish(Database.BatchableContext ctx)
    {
   
      AsyncApexJob a = [SELECT Id, Status, ExtendedStatus, NumberOfErrors, JobItemsProcessed,
                          TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob WHERE Id =
                          :ctx.getJobId()];
   // Send an email to the Apex job's submitter notifying of job completion. 
    
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Apex Sharing Recalculation ' + a.Status);
   mail.setPlainTextBody
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures. The error is related to ' + a.ExtendedStatus);
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
           
    }    
}
And then I have a second scheduleable class that calls this class and theoretically executes the code.. 
 
global class GetPeople implements Schedulable {
      global void execute(SchedulableContext ctx) {
           database.executeBatch(new ZenefitsEmployees(),200);
      }
}
ANY HELP WOULD BE GREAT!! 
 
Good afternoon, 

I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this.. 

Here is my REST API class
 
string url = *****;
Integer int1 = 0;

String myProcedure1() {
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setHeader('Authorization', 'Bearer ****);
    request.setEndpoint(url);
	request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserializes the JSON string into collections of posts.
        Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
        if (wrapper.containsKey('data')) {
            Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data');
            if(wrapper2.containsKey('data')) {
                List<Object> people = (List<Object>)wrapper2.get('data');
                for (Object peopleWrapper : people) {
                    Map<String,Object> Employees = (Map<String,Object>) peopleWrapper;
                    if(Employees.containsKey('last_name')){
                    String ZenefitsLastName = (String) Employees.get('last_name');
                    String ZenefitsFirstName = (String) Employees.get('first_name');
                    String ZenefitseEmployeeId = (String) Employees.get('id');
                    String ZenefitsEmail = (String) Employees.get('work_email');    
                        
                    List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200];
                            List<Contact> contactsToUpdate = new List<Contact>();
                        	for(Contact con : contactList){
                       		con.Zenefits_Id__c = ZenefitseEmployeeId;
                            contactsToUpdate.add(con);
                        
                        }
                        update contactsToUpdate;
                            
                        
                        
					//we now need to find all contacts in SF that match the contacts in Employees
                    //once we have matches we need to synce each ID 
                   
                        
         
                            system.debug('Employees ' + Employees);
                            system.debug('last name ' + ZenefitsLastName);
                        	system.debug('Employee id ' + ZenefitseEmployeeId);
                        	system.debug('first name ' + ZenefitsFirstName);
                            system.debug('Contact list ' + contactList);
                            system.debug('TEST ' + contactsToUpdate);
                   			}
               			}
            		}
            
            return null;
        }
        return null;
    }
    return null;
}

void myProcedure2() {
    while (url != null) {
        System.debug('BEFORE URL: ' + url);
        url = myProcedure1();
        System.debug('AFTER URL: ' + url);
    }
}

myProcedure2();
I have gone ahead and taken out the URL and the Bearer headers for privacy purposes, but all else is there. 

For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !! 

Thanks in advance !! 
 
I am trying to query salesforce data based on information that I am pulling from our HR system via a REST API callout to the HR system. 

Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier. 

Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake. 
 
request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserializes the JSON string into collections of posts.
        Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
        if (wrapper.containsKey('data')) {
            Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data');
            if(wrapper2.containsKey('data')) {
                List<Object> people = (List<Object>)wrapper2.get('data');
                for (Object peopleWrapper : people) {
                    Map<String,Object> Employees = (Map<String,Object>) peopleWrapper;
                    if(Employees.containsKey('last_name')){
                    String ZenefitsLastName = (String) Employees.get('last_name');
                    String ZenefitsFirstName = (String) Employees.get('first_name');
                    String ZenefitseEmployeeId = (String) Employees.get('id');
                        
                        List<Contact> contactList = [SELECT Id, FirstName, LastName FROM Contact WHERE FirstName = Employees.get('first_name') LIMIT 200];
                        
					//we now need to find all contacts in SF that match the contacts in Employees
                    //once we have matches we need to synce each ID 
                   
                        
         
                            system.debug('Employees ' + Employees);
                            system.debug('last name ' + ZenefitsLastName);
                        	system.debug('Employee id ' + ZenefitseEmployeeId);
                        	system.debug('first name ' + ZenefitsFirstName);
                            system.debug('Contact list ' + contactList);
                            
                   			}
               			}
            		}
            
            return null;
        }
        return null;
    }
    return null;
}

 
I have a standard cladd, a schedulable class, and a test class. When I run my test on the test class the schedulable class passes 100% coverage, however the test calss still sits at 0% coverage, which tells me that the test class may not be testing the standard class at all?? I NEED HELP PLEASE haha. 

Here is the standard class 
 
global class TCApprovalCompliance implements Database.Batchable<sObject>
{
    
   global Database.queryLocator start(Database.BatchableContext ctx )
   {
        String str = 'SELECT Id, pse__Submitted__c, pse__Start_Date__c, pse__Approved__c FROM pse__Timecard_Header__c WHERE pse__Submitted__c = TRUE';
        
        return Database.getQueryLocator(str);
        
   }
    
    global void execute(Database.BatchableContext ctx, List<pse__Timecard_Header__c> nonApprovedTCs)
     {
        
       List<pse__Timecard_Header__c> TCList = new List<pse__Timecard_Header__c>();
       
       for(pse__Timecard_Header__c tcObj : nonApprovedTCs){
            tcObj.Approval_Compliance__c = true;
            TCList.add(tcObj);
          }
        
        update TCList;
     }
   
   global void finish(Database.BatchableContext ctx)
    {
   
      AsyncApexJob a = [SELECT Id, Status, ExtendedStatus, NumberOfErrors, JobItemsProcessed,
                          TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob WHERE Id =
                          :ctx.getJobId()];
   // Send an email to the Apex job's submitter notifying of job completion. 
    
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {a.CreatedBy.Email};
   mail.setToAddresses(toAddresses);
   mail.setSubject('Apex Sharing Recalculation ' + a.Status);
   mail.setPlainTextBody
   ('The batch Apex job processed ' + a.TotalJobItems +
   ' batches with '+ a.NumberOfErrors + ' failures. The error is related to ' + a.ExtendedStatus);
   Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
           
    }    
}

Here is the test class...
 
@isTest
public class TCApprovalCompliance_TEST  {

    static testMethod void testTCApprovalCompliance() {
       
        //loadSettings();
        disableTriggerHandlers(true);
        TestDataFactory.initPermissionControls();

        TestDataFactory.timecardHeaders = TestDataFactory.createTimecardHeaders(1, false);
        TestDataFactory.timecardHeaders[0].pse__Start_Date__c = date.parse('09/01/2019');
        TestDataFactory.timecardHeaders[0].pse__End_Date__c = date.parse('09/07/2019');
        TestDataFactory.TimecardHeaders[0].pse__Status__c = 'Submitted';
        TestDataFactory.TimecardHeaders[0].pse__Submitted__c = TRUE;
        TestDataFactory.TimecardHeaders[0].pse__Approved__c = FALSE;
        
        Test.startTest();
        insert TestDataFactory.timecardHeaders;
        system.debug('Cb is checked?? ' + testdatafactory.timecardHeaders[0].Approval_Compliance__c);
        system.debug('Start date is... ' + testdatafactory.timecardHeaders[0].pse__Start_Date__c);
        system.debug('submitted is... ' + testdatafactory.timecardHeaders[0].pse__Submitted__c);
        system.debug('approved is... ' + testdatafactory.timecardHeaders[0].pse__Approved__c);
        system.debug('The Id is... ' + testdatafactory.timecardHeaders[0].Id);
        Test.stopTest();

     TCApprovalCompliance_Schedulable TC1 = new TCApprovalCompliance_Schedulable();
        String sch = '0 0 23 * * ?'; 
        system.schedule('Test Update Contacts Check', sch, TC1); 

        
    }
        
        
    private static void loadSettings()
    {
        TestDataFactory.loadAllConfigGroupsOptionsValues();
        TestDataFactory.updateAsmTriggerSettings(TestDataFactory.getDefaultDisableAsmTriggerSettings());
        TestDataFactory.createSRPIntegrationSettings(true, true);
        TestDataFactory.createProjectTriggerSettings(true);
        TestDataFactory.createTimecardComplianceSettings(true);
        TestDataFactory.createCommonSettingsSettings(true);
    }


    private static void disableTriggerHandlers(boolean disableTimecardTriggers)
    {
        TriggerHandlerBase.disableAllTriggerHandlers(Account.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(Contact.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(pse__Region__c.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(pse__Practice__c.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(pse__Grp__c.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(pse__Proj__c.sObjectType);
        TriggerHandlerBase.disableAllTriggerHandlers(pse__Assignment__c.sObjectType);

        if (disableTimecardTriggers == true)
        {
            TriggerHandlerBase.disableAllTriggerHandlers(pse__Timecard_Header__c.sObjectType);
            TriggerHandlerBase.disableAllTriggerHandlers(pse__Timecard__c.sObjectType);
        }
    }
}

and here is the schedulable class..
 
global class TCApprovalCompliance_Schedulable implements Schedulable {
      global void execute(SchedulableContext ctx) {
           database.executeBatch(new TCApprovalCompliance(),200);
      }
}

 
Hey guys I am needing some help with the way I need to format this string query so it will look up the records I need it to. 

Basically I need the query to look up contacts that are on a billable assignment that also have Is Resource = TRUE, Is Resource Active = TRUE, and Exclude From Time Calculations = FALSE, and the Work Calandar = weekStartDay. 

I am able to perform this string in the Query editor and find the results I am looking for, but am unsure of the exact syntax that is needed in Apex. 

Here is what I have so far... 
 
string assignments = 'SELECT Id, pse__End_Date__c, pse__Resource__c, pse__Is_Billable__c, Today__c FROM pse__Assignment__c WHERE pse__Is_Billable__c = True AND pse__End_Date__c > TODAY'; 

        string queryString = 'SELECT Id, ' + 
                             '       Name ' + 
                             '  FROM Contact ' + 
                             ' WHERE Id Like: assignments.pse__Resource__c AND' + 
            				 '		 pse__Is_Resource__c = true AND ' + 
                             '       pse__Is_Resource_Active__c = true AND ' + 
                             '       pse__Exclude_From_Missing_Timecards__c = false AND ' +
                             '       pse__Work_Calendar__r.pse__Week_Start_Day__c = \'' + weekStartDay + '\' ';
In the first string I am finding all the assignments that are bilalble, and have an end date greater than TODAY. 

I am then hoping to find a list of contacts that aer found within the first string, by using the contact ID and comparing it to pse__Resource__c, which is a lookup field to contacts on the Assignment object. 

Any help would be GREATLY apprecaited!! 
 
I am trying to create a trigger that will populate a lookup field on a custom object called Levvel Forecat.

The basic criteria here is that when a new Levvel Forecast record is created with a specific record type I need to update Assignment__c (Lookup field to assignment (pse__assignment__c) object) with the current active assignment that the contact (lookup field to Contact record) on the levvel Forecast record is on.

So what I have done is trying to perform a select statement to store the contact id (Employee__c) on the Levvel Forecast record so we can use that in the second Select statement as a comparison.

I have then created a second SELECT statement to select the pse__Assignment__c WHERE the Contact Id on the assignment is EQUAL to the contact Id on the levvel Forecast.

Then I have a simple IF statement, and if it passed I am trying to insert that assignment ID into the Assignment__c field on the Levvel Forecast record.

CURENTLY in my test class I am getting the error saying that there is “Too many SOQL queries 101”

Any help would be greatly appreciated!

I have this methos inserted within my LevvelForecastTriggerHandler so i am sorry if it doesnt look like a conventional Trigger..

**** The method that is running all this is the "loadAssignment" method, and is also looking at the BULKBEFORE after the line that reads "if(trigger.isInsert)"....
 
/************************************************************************************************************************
// Name         LevvelForecastTriggerHandler
// Description  Standard trigger handler for LevvelForecastTrigger
// INITIAL    2019-Aug-16  KWEBB     Initial version
************************************************************************************************************************/
public without sharing class LevvelForecastTriggerHandler extends TriggerHandlerBase 
{
    //List for querying forecast periods for DELETE
    private List<Forecast_Periods__c> forecastPeriodList = new List<Forecast_Periods__c>();

    //list for storing all active assignemnts that are realted to the new forecast creations
    private List<pse__Assignment__c> assignmentList = new List<pse__Assignment__c>();

    /************************************************************************************************************
    // Name         bulkBefore
    // Description  Standard implementation of the TriggerHandler.bulkBefore() interface method.
    *************************************************************************************************************/
    public override void bulkBefore()
    {
        if (trigger.isDelete)
        {
            //store parent Levvel Forecast records that are about to be deleted 
            list<Id> forecastIds = new list<Id>();
            for(SObject so :trigger.old)
            {
                Levvel_Forecast__c forecast = (Levvel_Forecast__c)so;
                forecastIds.add(forecast.id);
            }

                //Now we need to query all child Forecast Period records related to the Levvel Forecast we are about to delete
                forecastPeriodList = [SELECT Id, Levvel_Forecast__c FROM Forecast_Periods__c WHERE Levvel_Forecast__c IN: forecastIds];
                system.debug('List of Forecast Periods ' + forecastPeriodList);
            }

        if(trigger.isInsert)
        {
            //store the LevvelForecast record for update 
            list<Id> forecastsToUpdate = new List<Id>();
            for(SObject so :trigger.new)
            {
               
                Levvel_Forecast__c newForecast = (Levvel_Forecast__c)so;
                if(newForecast.RecordTypeId == '0121N000000U6GYQA0' )
                {
                    forecastsToUpdate.add(newForecast.employee__c);
                }

            }

                //Now we need to query all the assignments 
                assignmentList = [SELECT id, pse__Resource__c FROM pse__Assignment__c WHERE pse__Resource__c IN: forecastsToUpdate];

            }
    }

    

    /************************************************************************************************************
    // Name         beforeInsert
    // Description  Standard implementation of the TriggerHandler.beforeInsert() interface method.
    *************************************************************************************************************/
    public override void beforeInsert (SObject so)
    {
        Levvel_Forecast__c newForecast = (Levvel_Forecast__c)so;

        loadAssignment(newForecast);
    }


    /************************************************************************************************************
    // Name         beforeDelete
    // Description  Standard implementation of the TriggerHandler.beforeInsert() interface method.
    *************************************************************************************************************/
    public override void beforeDelete(SObject so)
    {
        Levvel_Forecast__c oldForecast = (Levvel_Forecast__c)so;

        deleteForecastPeriods(oldForecast);
    }


     /************************************************************************************************************
    // Name         loadAssignment
    // Description  Helper method to validate resource requests on an opportunity
    *************************************************************************************************************/
    private void loadAssignment (Levvel_Forecast__c newForecast)
    {

        for (pse__Assignment__c ass :assignmentList )
        if(ass.pse__End_Date__c > newForecast.Today__c && ass.pse__Is_Billable__c == TRUE)
        {
            newForecast.employee__c = ass.pse__resource__c;
        }
    }

    /************************************************************************************************************
    // Name         deleteForecastPeriods
    // Description  Helper method to validate resource requests on an opportunity
    *************************************************************************************************************/
    private void deleteForecastPeriods (Levvel_Forecast__c oldForecast)
        {
            //Now we delete 
            delete forecastPeriodList;
        }
    }

 
I am trying to create an Apex class that will run every night and update a field on Contact based on specidic criteria.

Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c) 

I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL. 

There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night. 

Here is my code so far. 

Any help would be GREATLY APPRECIATED   
 
public class AssignmentToContact implements Database.Batchable<sObject> {
        
   global Database.queryLocator start(Database.BatchableContext ctx )
   {
       
        list<pse__Assignment__c> aid=New list<pse__Assignment__c>(); 
    	list<Contact> updatecontact = new list<Contact>();
       
    	for(pse__Assignment__c ass: Trigger.new){ 
        if(ass.pse__End_Date__c >= today__c && ass.pse__Is_Billable__c = TRUE){
            aid.add(ass.id);
        } 

        list<Contact> contactlist=[SELECT Id,Assignment__c FROM Contact WHERE id = :aid]; 
        for(Contact con: contactlist){ 
            con.Assignment__c=ass.Id; 
            updatecontact.add(con);
        }
    }
    update updatecontact; 
	}
}

//IF THE list is empty then the field on CONTACT should be NULL

 
I am attempting to upate a field on the Opportunity object with the project that gets created (that is associated to the opportunity) 

So basically the way things work is that when an opportunity is set to closed won a project gets created with a lookup relationship back to the opportunity. There is a field on the Project that automatically gets filled with the opportunity name, however the field on the Opportunity that is supposed to get filled with the project name is not being filled when the project is created. 

I have attempted to write some code to uopdate that field after the project is inserted. My logic seems correct however the field (Pse__Primary__Project__C) is not being uopdated with the project name. 

Here is the code.. 
 
public override void afterInsert(SObject so)
    {
        pse__proj__c newProj = (pse__proj__c)so;

        list <pse__proj__c> projects = [SELECT ID, Name, pse__Opportunity__c FROM pse__proj__c];
        list <opportunity> opportunities = [SELECT ID, Name, pse__Primary_Project__c FROM Opportunity];

        for (Opportunity opps : opportunities){

        if (newProj.Created_by_Opp__c == true)
        {
            opps.pse__Primary_Project__c = newProj.id;
            
        }

        }
    


ANy help would be MUCH appreciated!! THANKS IN ADVANCE! 
 
Hello Community ! I am attemptimng to deploy a Apex Trigger to update resource requests on Opportunites with a Project name and change the status of the request as well. I want all this to occur when the opportunity hits closed won. 

WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB.. 

What I am struggling with is deploying the code to Production.. 

When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all.. 

Here is my Code 
public override void afterUpdate(SObject oldSo, SObject so)
    {
        Opportunity newOpp = (Opportunity)so;
        Opportunity oldOpp = (Opportunity)oldSo;
        
        if (newOpp.StageName == Constants.OPTY_STAGE_CLOSED_WON && newopp.Does_Not_Need_Resource_Request__c == FALSE){

        list<pse__Resource_Request__c> resourceRequests = [select ID, pse__Opportunity__c, Pse__Status__c FROM pse__Resource_Request__c];
        list<opportunity> opps = [Select ID, pse__Primary_Project__c from Opportunity];
        boolean isValid = false;
        
        for (pse__Resource_Request__c resourceRequest : resourceRequests)
        {

            if (resourceRequest.pse__Opportunity__c == newOpp.Id)
            {
            
                //there is a resource request that has the opportunity id of the current opp meaning the opp is valid
                isValid = true;
                resourceRequest.pse__Project__c = newOpp.pse__Primary_Project__c;
                resourceRequest.pse__Status__c = 'Assigned';

            }
        } 
        // if we get out of the loop and isValid is false, it means there were 0 opps that matched the resource request
        // return error
         if (!isValid) {
            so.addError('Please add Resource Requests to this Opportunity before marking it as "Closed Won." If no Resource Requests need to be added to the Opportunity please check the "Does Not Need Resource Request" checkbox in order to Close Win.');
                }

            }
        }

And here is my Test Class to go along with it. 
 
@isTest static void aftUpTest() 
        {

        TestDataFactory.initPermissionControls();


        //Prep the data 
        TestDataFactory.projects = TestDataFactory.createprojects(2);
        TestDataFactory.opportunities = TestDataFactory.createOpportunities(2);
        TestDataFactory.createResourceRequests(1, TestDataFactory.opportunities[0], TRUE);

	system.test.startTest();
            
        TestDataFactory.opportunities[0].StageName = Constants.OPTY_STAGE_CLOSED_WON;
        TestDataFactory.opportunities[0].Does_Not_Need_Resource_Request__c = FALSE;
        TestDataFactory.opportunities[0].Create_Project__c = FALSE;
        TestDataFactory.opportunities[0].Info_Complete__c = TRUE;
        TestDataFactory.opportunities[0].Pse__Primary_Project__c = TestDataFactory.projects[0].id;

        update TestDataFactory.opportunities;



        system.test.stopTest();

        }
 }

In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created. 

With all this said the error message I am recieving when attempting to deploy the code to Production reads.. 


"Methods defined as TestMethod do not support Web service callouts 
Stack Trace: null"

PLEASE HELP. 


I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated! 
BREAKDOWN 
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value. 

Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP ! 
trigger Updatecampaign on pse__Expense_Report__c (before insert,before Update) {

// Local catches for bulkified data
    private map<Id, pse__Proj__c> projMap = new map<Id, pse__Proj__c>();      

   for (pse__Expense_Report__c er: Trigger.new) (

   		projectIds.add(er.Campaign_Expense__c);
   		}

   		for{pse__Proj__c pro: [select id, Campaign__c from pse__Proj__c where Campaign__c in :projectIds]}
   		{
   		projMap.put(pro.Campaign__c, projMap)
   		}

   			for (pse__Expense_Report__c er : Trigger.new)
   			{
   			er.Campaign_Expense__c=projMap.get(er.Campaign_Expense__c).Id;
   			
   			}
   		}

 
No one answered me on the previous post and I really need some help here so going for the repost. 

Hey guys, I have written this class to extend my Trigger Handler Base code, and have gotten the code to pass without any errors, however it is not doing exactly what I want it to do. 

BREAKDOWN 
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value. 

Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP ! 
 
/************************************************************************************************************************
// Name         ExpenseReportHandler 
// Description  Standard trigger handler for ExpenseReportHandler 
// Revisions    2018-Nov-20  kris.webster@levvel.io     Initial version
***********************************************************************************************************************/
public without sharing class ExpenseReportHandler extends TriggerHandlerBase
{
    // Local catches for bulkified data
    private map<id, pse__Proj__c> projMap = new map<id, pse__Proj__c>();      // key = record id


    /************************************************************************************************************
    // Name         bulkBefore
    // Description  Standard implementation of the TriggerHandler.bulkBefore() interface method.
    *************************************************************************************************************/
    public override void bulkBefore()
    {
        if (trigger.isInsert || trigger.isUpdate)
        {
            set<id> projIds = new set<id>();

            for (SObject so : trigger.new)
            {
                pse__Expense_Report__c er = (pse__Expense_Report__c)so;
                
                if (er.Campaign_Expense__c != null)
                {
                    projIds.add(er.Campaign_Expense__c);
                }
             }

            // Fetch accounts and their default attributes
            projMap = new map<Id, pse__Proj__c>(
                [SELECT Id, 
                        Campaign__c
                   FROM pse__Proj__c
                  WHERE Id IN :projIds]);
        }
    }
    /************************************************************************************************************
    // Name         beforeInsert
    // Description  Standard implementation of the TriggerHandler.afterInsert() interface method.
    *************************************************************************************************************/
    public override void beforeInsert(SObject so)
    {
        pse__Expense_Report__c newER = (pse__Expense_Report__c)so;

        setcamp(newER);
        
    }

    /************************************************************************************************************
    // Name         beforeUpdate
    // Description  Standard implementation of the TriggerHandler.afterUpdate() interface method.
    *************************************************************************************************************/
    public override void beforeUpdate(SObject oldSo, SObject so)
    {
        pse__Expense_Report__c newER = (pse__Expense_Report__c)so;

        setcamp(newER);
        
    }

    /************************************************************************************************************
    // Name         queueDeliveryManagerSync
    // Description  Helper method to sync delivery manger to parent opty
    *************************************************************************************************************/
    private void setcamp (pse__Expense_Report__c exprep)
    {
            // If the expense reports's campaign is blank, we fill it with the projects campaign
            if (exprep.Campaign_Expense__c == null && projMap.containsKey(exprep.pse__Project__c))
            {
                exprep.Campaign_Expense__c = projMap.get(exprep.pse__Project__c).Campaign__c;
            }            
        }
    }


 
Hey guys, I have written this class to extend my Trigger Handler Base code, and have gotten the code to pass without any errors, however it is not doing exactly what I want it to do. 

BREAKDOWN 
I have a object called Project (pse__Proj__c) that has a lookup field on it called campaign (Campaign__c). I also have another object called Expense Reports (pse__Expense_Report__c) that also has the same lookup field on it, buit with a different API name (Campaign_Expense__c). Basically what I need the code to do is that when a new expense report record is created I need the value that is found in the Campaign (Campaign__c) field (on the project object) to fill the campaign object on the expense report object with the same value. 

Here is the code I have, but it is not filling the field on the expense report object with the campaign. PLEASE HELP ! 

 
/************************************************************************************************************************
// Name         ExpenseReportHandler 
// Description  Standard trigger handler for ExpenseReportHandler 
// Revisions    2018-Nov-20  kris.webster@levvel.io     Initial version
***********************************************************************************************************************/
public without sharing class ExpenseReportHandler extends TriggerHandlerBase
{
    // Local catches for bulkified data
    private map<id, pse__Proj__c> projMap = new map<id, pse__Proj__c>();      // key = record id


    /************************************************************************************************************
    // Name         bulkBefore
    // Description  Standard implementation of the TriggerHandler.bulkBefore() interface method.
    *************************************************************************************************************/
    public override void bulkBefore()
    {
        if (trigger.isInsert || trigger.isUpdate)
        {
            set<id> projIds = new set<id>();

            for (SObject so : trigger.new)
            {
                pse__Expense_Report__c er = (pse__Expense_Report__c)so;
                
                if (er.Campaign_Expense__c != null)
                {
                    projIds.add(er.Campaign_Expense__c);
                }
             }

            // Fetch accounts and their default attributes
            projMap = new map<Id, pse__Proj__c>(
                [SELECT Id, 
                        Campaign__c
                   FROM pse__Proj__c
                  WHERE Id IN :projIds]);
        }
    }
    /************************************************************************************************************
    // Name         beforeInsert
    // Description  Standard implementation of the TriggerHandler.afterInsert() interface method.
    *************************************************************************************************************/
    public override void beforeInsert(SObject so)
    {
        pse__Expense_Report__c newER = (pse__Expense_Report__c)so;

        setcamp(newER);
        
    }

    /************************************************************************************************************
    // Name         beforeUpdate
    // Description  Standard implementation of the TriggerHandler.afterUpdate() interface method.
    *************************************************************************************************************/
    public override void beforeUpdate(SObject oldSo, SObject so)
    {
        pse__Expense_Report__c newER = (pse__Expense_Report__c)so;

        setcamp(newER);
        
    }

    /************************************************************************************************************
    // Name         queueDeliveryManagerSync
    // Description  Helper method to sync delivery manger to parent opty
    *************************************************************************************************************/
    private void setcamp (pse__Expense_Report__c exprep)
    {
            // If the expense reports's campaign is blank, we fill it with the projects campaign
            if (exprep.Campaign_Expense__c == null && projMap.containsKey(exprep.pse__Project__c))
            {
                exprep.Campaign_Expense__c = projMap.get(exprep.pse__Project__c).Campaign__c;
            }            
        }
    }

 
I am not finding a way to solve this issue. I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger. WHEN i say a specific contact I mean 1 contact record. SO I want the contact Kris Webster to fill the field Project_Manager__c on the campaign object when a new campaign record is created.. IS THIS POSSIBLE? would I need to build a SOQL of contcats first or what?? I cant seem to find an answer anywhere.. 

Here is what I have so far. 
trigger CampaignTrigger on Campaign (after insert) {

	for(Campaign camp:Trigger.New){
		if(camp.Project_Manager__c == null)
		camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? 
	}



}

 
I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger. 

Check out the code and you will see what I mean...

Any help would be MUCH APPRECIATED! Thanks guys! 
 
trigger CampaignTrigger on Campaign (after insert) {

	for(Campaign camp:Trigger.New){
		if(camp.Project_Manager__c == null)
		camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? 
	}



}

 
I wrote a trigger on a custom object called Project (Pse__proj__c).

Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True" 

My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked... 

Any help would be much appreciated !! 
 
trigger CreateBudgetForProject on pse__Proj__c (after insert){
    
    List<pse__Budget__c> Listbud = new List<pse__Budget__c>();
    
    for(pse__Proj__c pro : trigger.new)
    {
        if(Trigger.isUpdate)
        {
            if(pro.Created_by_Opp__c == True)
            {
                //Fields that will be filled on Budget
                listbud.add(new pse__Budget__c(name = pro.name, 
                                               pse__Amount__c = pro.Product_Budget_MAP__c,
                                               pse__Project__c = pro.Name,
                                               pse__Type__c = 'Customer Purcahse Order',
                                               pse__Status__c = 'Approved',
                                               pse__Effective_Date__c = pro.pse__Start_Date__c
                                              ));
            }
            if (Trigger.isInsert)
            {
                if(pro.Created_by_Opp__c == True)
                {
                    //Fill Mandatory Fields on Associated Budget Object 
                    listbud.add(new pse__Budget__c(name = pro.name, 
                                               pse__Amount__c = pro.Product_Budget_MAP__c,
                                               pse__Project__c = pro.Name,
                                               pse__Type__c = 'Customer Purcahse Order',
                                               pse__Status__c = 'Approved',
                                               pse__Effective_Date__c = pro.pse__Start_Date__c
                                              ));
                }
            }
        }
        if(listbud.size() > 0)
        {
            insert listbud;
        }
        }
    }

 
I am trying to write a trigger to do the following.. 

I have a custom object called Project with the API Name of - pse__Proj__c
I have another custom object called Budget with the API Name of - pse__Budget__c

What I want to do with the trigger is.. 

When a new project is created I want the project name to automatically fill a field on the budget object called project. The project field on the budget object is a lookiup field to the project object and has the API name of pse__Project__c. 

Later on I want to also incorporate the trigger to update a field on the budget object called Amount, that has the API name of 
pse__Amount__c with the value found on the Project object in the field called Prouct Budget MAP with the API name of Product_Budget_MAP__c. That can wait but I do need the first step implemented in order to move forward. 

HERE IS WHAT I HAVE SO FAR... Any help is much appreciated!! 


trigger updateBudgetProject on pse__Budget__c (after insert){
    
    List<pse__Budget__c> BudgetToUpdate = new list<pse__Budget__c>();
    
    for(pse__Budget__c bud : [select Id, pse__Proj__c.Id From pse__Budget__c Where Id IN : trigger.newMap.keyset()]){
        bud.pse__Project__c = bud.pse__Proj__c.name;
        BudgetsToUpdate.add(bud);
       }
    
    if(!BudgetsToUpdate.isEmpty())
        update BudgetsToUpdate;
Good afternoon, 

I have a API call class that is working as I need it to, however I am not trying to get the class to execute every night at 2 AM. I am trying to implement a schedulable class to call the API class and make it execute every night, but am a little unsure how to do this.. 

Here is my REST API class
 
string url = *****;
Integer int1 = 0;

String myProcedure1() {
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setHeader('Authorization', 'Bearer ****);
    request.setEndpoint(url);
	request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserializes the JSON string into collections of posts.
        Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
        if (wrapper.containsKey('data')) {
            Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data');
            if(wrapper2.containsKey('data')) {
                List<Object> people = (List<Object>)wrapper2.get('data');
                for (Object peopleWrapper : people) {
                    Map<String,Object> Employees = (Map<String,Object>) peopleWrapper;
                    if(Employees.containsKey('last_name')){
                    String ZenefitsLastName = (String) Employees.get('last_name');
                    String ZenefitsFirstName = (String) Employees.get('first_name');
                    String ZenefitseEmployeeId = (String) Employees.get('id');
                    String ZenefitsEmail = (String) Employees.get('work_email');    
                        
                    List<Contact> contactList = [SELECT Id, FirstName, LastName, Zenefits_ID__c, Email FROM Contact WHERE Email = :ZenefitsEmail LIMIT 200];
                            List<Contact> contactsToUpdate = new List<Contact>();
                        	for(Contact con : contactList){
                       		con.Zenefits_Id__c = ZenefitseEmployeeId;
                            contactsToUpdate.add(con);
                        
                        }
                        update contactsToUpdate;
                            
                        
                        
					//we now need to find all contacts in SF that match the contacts in Employees
                    //once we have matches we need to synce each ID 
                   
                        
         
                            system.debug('Employees ' + Employees);
                            system.debug('last name ' + ZenefitsLastName);
                        	system.debug('Employee id ' + ZenefitseEmployeeId);
                        	system.debug('first name ' + ZenefitsFirstName);
                            system.debug('Contact list ' + contactList);
                            system.debug('TEST ' + contactsToUpdate);
                   			}
               			}
            		}
            
            return null;
        }
        return null;
    }
    return null;
}

void myProcedure2() {
    while (url != null) {
        System.debug('BEFORE URL: ' + url);
        url = myProcedure1();
        System.debug('AFTER URL: ' + url);
    }
}

myProcedure2();
I have gone ahead and taken out the URL and the Bearer headers for privacy purposes, but all else is there. 

For anyone that has implemented a way to have an API call excecute every night on a daily basis please share your wisdome with me !! 

Thanks in advance !! 
 
I am trying to query salesforce data based on information that I am pulling from our HR system via a REST API callout to the HR system. 

Basically I am tring to find all contacts in my Salesforce org where the first name = the first name in the API Call. I know that first name is not specific enough, but I am starting here and once I can get records to match I will use a more unique identifier. 

Here is my code. I NEED HELP WITH LINE 28! I have left out authorization lines for privacy sake. 
 
request.setMethod('GET');
    HttpResponse response = http.send(request);
    // If the request is successful, parse the JSON response.
    if (response.getStatusCode() == 200) {
        // Deserializes the JSON string into collections of posts.
        Map<String,Object> wrapper = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
        if (wrapper.containsKey('data')) {
            Map<String, Object> wrapper2 = (Map<String,Object>) wrapper.get('data');
            if(wrapper2.containsKey('data')) {
                List<Object> people = (List<Object>)wrapper2.get('data');
                for (Object peopleWrapper : people) {
                    Map<String,Object> Employees = (Map<String,Object>) peopleWrapper;
                    if(Employees.containsKey('last_name')){
                    String ZenefitsLastName = (String) Employees.get('last_name');
                    String ZenefitsFirstName = (String) Employees.get('first_name');
                    String ZenefitseEmployeeId = (String) Employees.get('id');
                        
                        List<Contact> contactList = [SELECT Id, FirstName, LastName FROM Contact WHERE FirstName = Employees.get('first_name') LIMIT 200];
                        
					//we now need to find all contacts in SF that match the contacts in Employees
                    //once we have matches we need to synce each ID 
                   
                        
         
                            system.debug('Employees ' + Employees);
                            system.debug('last name ' + ZenefitsLastName);
                        	system.debug('Employee id ' + ZenefitseEmployeeId);
                        	system.debug('first name ' + ZenefitsFirstName);
                            system.debug('Contact list ' + contactList);
                            
                   			}
               			}
            		}
            
            return null;
        }
        return null;
    }
    return null;
}

 
I am trying to create an Apex class that will run every night and update a field on Contact based on specidic criteria.

Basically what I need to happen is for the system to query all assignemnts (pse__assignment__c) in the system with an end date (pse__End_Date__c) greater than TODAY (today__c) 

I then need to add that assignemnt to a custom field I have created on Contact if the assignment passes the criteria. If there are no assignments for the specific contact then I need the assignment field to be NULL. 

There is a lookup relationship between Assignemtn and Contact. In my code I think I am querying the assignments correctly but I am strugling with figuring out how to then associate that specific assignment with the correct contact. I am also struggling with how to make this Class a schedulable class that I am able to schedule to run every night. 

Here is my code so far. 

Any help would be GREATLY APPRECIATED   
 
public class AssignmentToContact implements Database.Batchable<sObject> {
        
   global Database.queryLocator start(Database.BatchableContext ctx )
   {
       
        list<pse__Assignment__c> aid=New list<pse__Assignment__c>(); 
    	list<Contact> updatecontact = new list<Contact>();
       
    	for(pse__Assignment__c ass: Trigger.new){ 
        if(ass.pse__End_Date__c >= today__c && ass.pse__Is_Billable__c = TRUE){
            aid.add(ass.id);
        } 

        list<Contact> contactlist=[SELECT Id,Assignment__c FROM Contact WHERE id = :aid]; 
        for(Contact con: contactlist){ 
            con.Assignment__c=ass.Id; 
            updatecontact.add(con);
        }
    }
    update updatecontact; 
	}
}

//IF THE list is empty then the field on CONTACT should be NULL

 
Hello Community ! I am attemptimng to deploy a Apex Trigger to update resource requests on Opportunites with a Project name and change the status of the request as well. I want all this to occur when the opportunity hits closed won. 

WITH that said I have written the code and have it executing fully in the Sandbox wihtout any erros, and have my code coverage passing 100% when I run the tests for the test class in the SB.. 

What I am struggling with is deploying the code to Production.. 

When I attempt to deplot the code I am recieving the following error and I am not sure why i am at all.. 

Here is my Code 
public override void afterUpdate(SObject oldSo, SObject so)
    {
        Opportunity newOpp = (Opportunity)so;
        Opportunity oldOpp = (Opportunity)oldSo;
        
        if (newOpp.StageName == Constants.OPTY_STAGE_CLOSED_WON && newopp.Does_Not_Need_Resource_Request__c == FALSE){

        list<pse__Resource_Request__c> resourceRequests = [select ID, pse__Opportunity__c, Pse__Status__c FROM pse__Resource_Request__c];
        list<opportunity> opps = [Select ID, pse__Primary_Project__c from Opportunity];
        boolean isValid = false;
        
        for (pse__Resource_Request__c resourceRequest : resourceRequests)
        {

            if (resourceRequest.pse__Opportunity__c == newOpp.Id)
            {
            
                //there is a resource request that has the opportunity id of the current opp meaning the opp is valid
                isValid = true;
                resourceRequest.pse__Project__c = newOpp.pse__Primary_Project__c;
                resourceRequest.pse__Status__c = 'Assigned';

            }
        } 
        // if we get out of the loop and isValid is false, it means there were 0 opps that matched the resource request
        // return error
         if (!isValid) {
            so.addError('Please add Resource Requests to this Opportunity before marking it as "Closed Won." If no Resource Requests need to be added to the Opportunity please check the "Does Not Need Resource Request" checkbox in order to Close Win.');
                }

            }
        }

And here is my Test Class to go along with it. 
 
@isTest static void aftUpTest() 
        {

        TestDataFactory.initPermissionControls();


        //Prep the data 
        TestDataFactory.projects = TestDataFactory.createprojects(2);
        TestDataFactory.opportunities = TestDataFactory.createOpportunities(2);
        TestDataFactory.createResourceRequests(1, TestDataFactory.opportunities[0], TRUE);

	system.test.startTest();
            
        TestDataFactory.opportunities[0].StageName = Constants.OPTY_STAGE_CLOSED_WON;
        TestDataFactory.opportunities[0].Does_Not_Need_Resource_Request__c = FALSE;
        TestDataFactory.opportunities[0].Create_Project__c = FALSE;
        TestDataFactory.opportunities[0].Info_Complete__c = TRUE;
        TestDataFactory.opportunities[0].Pse__Primary_Project__c = TestDataFactory.projects[0].id;

        update TestDataFactory.opportunities;



        system.test.stopTest();

        }
 }

In the test code the test data factory is creating an opp for me, and setting it all up to be ready to close win, and then the test data factory is creating a resource request for me with the associated opportunity on the respource request set to the same opportunity the test data factory just created. 

With all this said the error message I am recieving when attempting to deploy the code to Production reads.. 


"Methods defined as TestMethod do not support Web service callouts 
Stack Trace: null"

PLEASE HELP. 


I have spent 3 days trying to uncover the error and still nothing, so any help would be MUCH appreciated! 
I am trying to write a trigger that will populate a contact lookup field with a specific contact. I am struggling to figure out how to code the specific contact into the trigger. 

Check out the code and you will see what I mean...

Any help would be MUCH APPRECIATED! Thanks guys! 
 
trigger CampaignTrigger on Campaign (after insert) {

	for(Campaign camp:Trigger.New){
		if(camp.Project_Manager__c == null)
		camp.Project_Manager__c = WHAT DO I PUT HERE?? THE USERS ID? 
	}



}

 
I wrote a trigger on a custom object called Project (Pse__proj__c).

Basically I want the trigger to create a new budget (Pse__Budget__c) which is a seperate custom object, every time the checkbox "pro.Created_by_Opp__c == True" 

My trigger is not getting any errors in the dev org but it is not creating a new budget when the checkbox is checked... 

Any help would be much appreciated !! 
 
trigger CreateBudgetForProject on pse__Proj__c (after insert){
    
    List<pse__Budget__c> Listbud = new List<pse__Budget__c>();
    
    for(pse__Proj__c pro : trigger.new)
    {
        if(Trigger.isUpdate)
        {
            if(pro.Created_by_Opp__c == True)
            {
                //Fields that will be filled on Budget
                listbud.add(new pse__Budget__c(name = pro.name, 
                                               pse__Amount__c = pro.Product_Budget_MAP__c,
                                               pse__Project__c = pro.Name,
                                               pse__Type__c = 'Customer Purcahse Order',
                                               pse__Status__c = 'Approved',
                                               pse__Effective_Date__c = pro.pse__Start_Date__c
                                              ));
            }
            if (Trigger.isInsert)
            {
                if(pro.Created_by_Opp__c == True)
                {
                    //Fill Mandatory Fields on Associated Budget Object 
                    listbud.add(new pse__Budget__c(name = pro.name, 
                                               pse__Amount__c = pro.Product_Budget_MAP__c,
                                               pse__Project__c = pro.Name,
                                               pse__Type__c = 'Customer Purcahse Order',
                                               pse__Status__c = 'Approved',
                                               pse__Effective_Date__c = pro.pse__Start_Date__c
                                              ));
                }
            }
        }
        if(listbud.size() > 0)
        {
            insert listbud;
        }
        }
    }