• Masechaba Maseli 8
  • NEWBIE
  • 50 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 9
    Replies
Hi all,

May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.  

Can someone take a look at what I may be doing wrong. This is the line where the error is originating. 

newSOWrappers.Add(new SOWrapper(shipmentOrder));
 
public class SOWrapper
    {
        public SOWrapper(Shipment_Order__c so, boolean recalculateCosts)
        {
            this.SO = so;
            this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c  FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c];
            this.Client = so.Account__r;

            if (recalculateCosts )
                recalculateCostings();
            else
                buildCostings();
        }

        public SOWrapper(Shipment_Order__c so)
        {
            this.SO = so;
            this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c];
            this.Client = so.Account__r;

            if (so.CPA_v2_0__c != null)

            buildCostings();
        }

        public Shipment_Order__c SO { set; get; }
        public CPA_v2_0__c CAP { set; get; }
        public Account Client { set; get; }
        private List<CPA_Costing__c> relatedCostings;
        private List<CPA_Costing__c> relatedCostingsIOR;
        private List<CPA_Costing__c> relatedCostingsEOR;
        private List<CPA_Costing__c> addedCostings;
        private List<CPA_Costing__c> updatedCostings;

        private Id recordTypeId = Schema.SObjectType.CPA_Costing__c.getRecordTypeInfosByName()
                .get('Display').getRecordTypeId();

        public void buildCostings()
        {
            relatedCostingsIOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c  FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'IOR' ];
            relatedCostingsEOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c  FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'EOR'];       
    
         
         If(SO.Service_Type__c == 'IOR') {
          
            List<CPA_Costing__c>  SOCPAcostingsIOR = relatedCostingsIOR.deepClone();
           
            for(CPA_Costing__c cost : SOCPAcostingsIOR)
            
            {
           
                cost.Shipment_Order_Old__c = SO.ID;
                cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c;
                cost.recordTypeID = recordTypeId;
                cost.VAT_Rate__c =  CAP.VAT_Rate__c;
                
                

                if (SO.Shipment_Value_USD__c != null)
                {
                    cost.Updating__c = !cost.Updating__c;
                    SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                }
            }
            addedCostings = SOCPAcostingsIOR;
        }
        
        Else If(SO.Service_Type__c == 'EOR') {
          
            List<CPA_Costing__c>  SOCPAcostingsEOR = relatedCostingsEOR.deepClone();
           
            for(CPA_Costing__c cost : SOCPAcostingsEOR)
            
            {
           
                cost.Shipment_Order_Old__c = SO.ID;
                cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c;
                cost.recordTypeID = recordTypeId;
                cost.VAT_Rate__c =  CAP.VAT_Rate__c; 

                if (SO.Shipment_Value_USD__c != null && (SO.FC_Total__c == null || SO.FC_Total__c == 0))
                {
                    cost.Updating__c = !cost.Updating__c;
                    SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                }
            }
            addedCostings = SOCPAcostingsEOR;
        }
        
        }


         public void recalculateCostings()
        {
            
            relatedCostings = [SELECT Name, Shipment_Order_Old__c, IOR_EOR__c,Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE Shipment_Order_Old__c =: SO.ID];
            System.debug('relatedCostings --- '+relatedCostings.size());
            
            List<CPA_Costing__c> delList = new List<CPA_Costing__c>();
            for(CPA_Costing__c var: relatedCostings )
            {
                if(var.Cost_Type__c == 'Variable'){
                    CPA_Costing__c del = new CPA_Costing__c();
                    del.id =var.id;
                    delList.add(del);                    
                }
            }
            

            
            updatedCostings = new List<CPA_Costing__c>();
            System.debug('updatedCostings --- '+updatedCostings.size());
            List<CPA_Costing__c>  relatedTemplateCPAcostings = [SELECT Name, IOR_EOR__c,Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, CPA_v2_0__r.VAT_Rate__c, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id ];
               
               List<CPA_Costing__c> updateCosting = new List<CPA_Costing__c >(); 
               Set<Id> ids = new Set<id>();
              for (CPA_Costing__c templateCost : relatedTemplateCPAcostings)
              {    
               
                  SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false);                       
                  System.debug('The cost id; ----------# '+templateCost.Id+' Amount:- '+templateCost.Amount__c);
                  for(CPA_Costing__c cost : relatedCostings){
                      if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name != cost.Name && templateCost.Cost_Type__c == cost.Cost_Type__c && templateCost.Applied_to__c == cost.Applied_to__c && templateCost.IOR_EOR__c == cost.IOR_EOR__c){
                           System.debug(' Do update: '+cost.Id+' the amount '+templateCost.Amount__c+'  --- name '+ templateCost.Name);
                            if(!ids.contains(cost.id) && templateCost.Amount__c > -1){
                                cost.Id = cost.Id;  
                                cost.Name =  templateCost.Name;
                                cost.Amount__c =  templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c;
                                cost.Ceiling__c = templateCost.Ceiling__c;
                                cost.Conditional_value__c = templateCost.Conditional_value__c;
                                cost.Condition__c = templateCost.Condition__c;
                                cost.Cost_Type__c = templateCost.Cost_Type__c;
                                cost.Floor__c = templateCost.Floor__c;
                                cost.Max__c = templateCost.Max__c;
                                cost.Min__c = templateCost.Min__c;
                                cost.Rate__c = templateCost.Rate__c;
                                cost.Variable_threshold__c = templateCost.Variable_threshold__c;
                                cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; 
                                cost.Cost_Category__c   = templateCost.Cost_Category__c ;                                  
                                cost.IOR_EOR__c = templateCost.IOR_EOR__c;                                
                                updateCosting.add(cost);
                                ids.add(cost.id);
                            }
                      }                   
                  }    
              }        
     if(!updateCosting.IsEmpty()){       
        update updateCosting;
     }
            List<CPA_Costing__c> updateCostList = new List<CPA_Costing__c>();
            for(CPA_Costing__c cost : relatedCostings)
            {
                cost.Updating__c = !cost.Updating__c;
                SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                  System.debug('The cost id; --------'+cost.Id+' Amount:- '+cost.Amount__c);
                  IF(cost.Amount__c == -1){
                                    

                  }
                System.debug(' --- cost '+cost.Amount__c);
                if (cost.Amount__c >= 0)
                {
                System.debug(' --- amount '+relatedTemplateCPAcostings);
                    for (CPA_Costing__c templateCost : relatedTemplateCPAcostings)
                    {
                    
                   
                    System.debug(' --- templateCost ');
                        if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name == cost.Name)
                        {
                            cost.Updating__c = !cost.Updating__c;
                            SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false);
                             System.debug(' --- templateCost2  '+templateCost.Amount__c);

                            if (templateCost.Amount__c > 0)
                            {
                             System.debug(' ---inside  '+templateCost.Amount__c);
                                cost.Amount__c =  templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c;
                                cost.Ceiling__c = templateCost.Ceiling__c;
                                cost.Conditional_value__c = templateCost.Conditional_value__c;
                                cost.Condition__c = templateCost.Condition__c;
                                cost.Cost_Type__c = templateCost.Cost_Type__c;
                                cost.Floor__c = templateCost.Floor__c;
                                cost.Max__c = templateCost.Max__c;
                                cost.Min__c = templateCost.Min__c;
                                cost.Rate__c = templateCost.Rate__c;
                                cost.Variable_threshold__c = templateCost.Variable_threshold__c;
                                cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c;
                                
                              system.debug('THE COST ' +  cost.ID+' '+cost.Name);  
                                
                            }
                        }
                    }
                }

                updatedCostings.Add(cost);
            }
                       
            if(!updateCostList.IsEmpty()){
                    insert updateCostList;
            }
        }
        
        
        

        public List<CPA_Costing__c> getApplicableCostings()
        {
            List<CPA_Costing__c> applicableCostings = new List<CPA_Costing__c>();
            if (addedCostings != null)
                for (CPA_Costing__c cost : addedCostings)
                    if (cost.Amount__c > -1 && cost.Shipment_Order_Old__c != null)
                        applicableCostings.Add(cost);
            if (updatedCostings != null)
                for (CPA_Costing__c cost : updatedCostings)
                    if (cost.Amount__c > -1)
                        applicableCostings.Add(cost);

            return applicableCostings;
        }
    }

public class CalculateCosts
{

    @InvocableMethod
    public static void createSOCosts(List<Id> SOIds)  
    
    
    {
        List<SOWrapper> newSOWrappers = new List<SOWrapper>();
        List<ID> SOsToUpdate = new List<Id>();
        
        List<Shipment_Order__c> shipmentOrder = [Select Id, Name,  Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c,
        FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c,
        TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c, Account__c, Service_Type__c, Total_Taxes__c FROM Shipment_Order__c where id IN :SOIds];
        
        List<Shipment_Order__c> SOs = new List<Shipment_Order__c>();

        List<CPA_Costing__c> costingsToAddUpdate = new List<CPA_Costing__c>();

        List<Shipment_Order__c> updatedSOs =
        [SELECt Id, Name,  Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c,
        FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c,
        TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c    FROM Shipment_Order__c  WHERE ID in: SOsToUpdate];
        
        newSOWrappers.Add(new SOWrapper(shipmentOrder));

        if (newSOWrappers.size() > 0 && shipmentOrder.size() > 0 )
       {
            for (SOWrapper wrp : newSOWrappers)
           {
                Shipment_Order__c SO;
               for (Shipment_Order__c SOToUpdate : updatedSOs)
                    if (SOToUpdate.ID == wrp.SO.ID)
                    {
      
        
                    SO = SOToUpdate;
                       break;
          
                  }

               costingsToAddUpdate.AddAll(wrp.getApplicableCostings());
                 
            }
            
           

            
        }
         Upsert costingsToAddUpdate;
        update SOs;
        
        
        
       }
            
                                                   
        
    }

 
Hi all
I am attempting to do a webservice call out from a visualforce page- currently I can see that it is connecting with the api but no information is being sent. Can someone please let me know what I am doing wrong.
public with sharing class AttachmentUploadController {

   public Shipment_Order__c shipmentOrder {get;set;}
   public String fileName {get;set;}
   public Blob fileBody {get;set;}
  
   public Customs_Clearance_Documents__c customsclearancedocs {get;set;}
  
    
    //constructor
    
    public AttachmentUploadController (ApexPages.StandardController controller) {
        this.shipmentOrder =  (Shipment_Order__c)controller.getRecord();                            
    
    }

 // creates a new Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Attachment__c obj = new Attachment__c ();
        obj.Shipment_Order__c = shipmentOrder.Id; 
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Contact_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = shipmentOrder.id;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf('attachment.body');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Contact_Attachment__c record
    *  2. Insert new Attachment with the new Contact_Attachment__c record as parent
    *  3. Update the Contact_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Attachment__c customAttachment = [select id from Attachment__c where id = :customAttachmentResult.getId()];
                
            update customAttachment;
           }
            
           
      return new PageReference('/apex/Attachment?id='+shipmentOrder.Id);
    }
    
    
    public PageReference Ephesoft() {
        Xmlstreamwriter xmlW = new Xmlstreamwriter();
            xmlW.writeStartDocument('utf-8','1.0');
            xmlW.writeStartElement(null,'BatchMetadata', null);
            
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'RecordID',null);
                    xmlW.writeCharacters(String.valueOf(attachment.Id));
                    xmlW.writeEndElement(); //Close RecordID
                    xmlW.writeEndElement(); //Close RecordID
                    
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'ParentID',null);
                    xmlW.writeCharacters(shipmentOrder.Id);
                    xmlW.writeEndElement(); //Close ParentID
                    xmlW.writeEndElement();
                    
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'ShipmentOrderNumber',null);
                    xmlW.writeCharacters(shipmentOrder.Name);
                    xmlW.writeEndElement(); //Close ShipmentOrderNumber
                    
                   xmlW.writeEndElement();
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'ShipmentOrderNumber',null);
                        xmlW.writeCharacters(shipmentOrder.Name);
                    xmlW.writeEndElement(); //Close ShipmentOrderNumber
                    xmlW.writeEndElement();
                    
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'SF_Incoterms',null);
                        xmlW.writeCharacters(shipmentOrder.Name);
                    xmlW.writeEndElement(); //Close SF_Incoterms
                    xmlW.writeEndElement();
                    
                    xmlW.writeStartElement(null,'Field',null);
                    xmlW.writeStartElement(null,'SF_NotifyParty',null);
                        xmlW.writeCharacters(shipmentOrder.Name);
                    xmlW.writeEndElement(); //Close SF_NotifyParty
                    xmlW.writeEndElement();
         xmlW.writeEndElement(); //Close BatchMetadata
         xmlW.writeEndDocument(); //Close XML document
   
         
    String xmlStringxmlRes = xmlW.getXmlString();
    System.debug('The XML :'+xmlW.getXmlString());     
    xmlW.close();


    
    String b64String = EncodingUtil.base64Encode(filebody);

// assemble the body payload
    String body = b64String + '\n';
    String body2 = (String.valueOf(xmlW));
    String bodyPayload = body + body2;

// send out the request
      HttpRequest req = new HttpRequest();
      req.setHeader('Content-Type', 'multipart/form-data; boundary=');
      req.setMethod('POST');
      req.setEndpoint('http://34.244.26.115:8080/dcma/rest/uploadBatch/BC8/file');
      req.setBody(bodyPayload);

    Http http = new Http();
      http.send(req);
       System.debug(req.toString());
    return null; 
    
    }    
    
   

}
 
<apex:page standardController="Shipment_Order__c" tabStyle="Shipment_Order__c" extensions="AttachmentUploadController">

 <apex:sectionHeader title="{!Shipment_Order__c.Name}" subtitle="Attach File"/>
 
 <apex:form id="form_Upload">
 <apex:pageBlock >

 <apex:pageBlockButtons >
   <apex:commandButton action="{!Cancel}" value="Cancel"/>
   <apex:commandButton action="{!Ephesoft}" value="Ephesoft"/>
 </apex:pageBlockButtons>
 <apex:pageMessages />
 
  <apex:pageBlockSection columns="1">
  
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="File" for="file_File"/>
      <apex:inputFile id="file_File" value="{!fileBody}" filename="{!fileName}"/>
    </apex:pageBlockSectionItem>
        
    
     
    
    
    <apex:pageBlockSectionItem >
      <apex:outputLabel value="" for="uploadBtn"/> 
      <apex:commandButton id="uploadBtn" value="Attach File" action="{!processUpload}" />
    </apex:pageBlockSectionItem> 
    
    
   
     
 
  </apex:pageBlockSection>
 
 </apex:pageBlock>


 </apex:form>

 <apex:relatedList list="CombinedAttachments" /> 
</apex:page>

 
Hi all

I have a batch class that I am gettin​g very litte test coverage for, can someone please assist. Lines 9 to 18 are not being covered.
global class ragStatusUpdate implements Database.Batchable<sObject>{

   global Database.QueryLocator start(Database.BatchableContext BC)

  {   string query = 'select id, Update_Rag_Status_Time__c from Shipment_Order__c  where Shipping_Status__c != \'POD Received\' AND Shipping_Status__c != \'On Hold\'AND Shipping_Status__c != \'Cancelled\'AND Shipping_Status__c != \'Shipment Pending\' AND Shipping_Status__c != \'Cancelled - With fees/costs\' AND Shipping_Status__c != \'Cancelled\'AND Shipping_Status__c != \'Cancelled - No fees/costs\' AND Shipping_Status__c != \'Customs Clearance Docs Received\' ';
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Shipment_Order__c>scope )
   {
list<Shipment_Order__c> SO = new list<Shipment_Order__c>();
        for(Shipment_Order__c s : scope)
           {
            s.Update_Rag_Status_Time__c  = TRUE;
            
             SO.add(s);
            }      
          update SO;
     }

   global void finish(Database.BatchableContext BC){

   }

}
 
@isTest
private class RagStatusTest {


static testMethod void testMethod1() {
    
        
        Account testClient = new account(Name='TestingClient',Client_Status__c = 'Prospect',Estimated_Vat__c = 123,CSE_IOR__c='0050Y000001LTZO');

        insert testClient;

        Contact testcontact = new Contact(LastName='Maseli',AccountId=testClient.Id);

        insert testcontact;
        
        country_price_approval__c cpa = new country_price_approval__c( name ='Serbia', Billing_term__c = 'DAP/CIF - IOR pays',  Airwaybill_Instructions__c = 'User IOR Address');
        insert cpa;
        
        IOR_Price_List__c testIOR = new IOR_Price_List__c();

        testIOR.Client_Name__c = testClient.Id;
        testIOR.Name = 'Serbia';
        testIOR.IOR_Fee__c = 1;
        
        insert testIOR;

        Shipment_Order__c shipmentOrder = new Shipment_Order__c();
        shipmentOrder.Account__c = testClient.Id;
        shipmentOrder.IOR_Price_List__c = testIOR.Id;
        shipmentOrder.Client_Contact_for_this_Shipment__c = testcontact.Id;
        shipmentOrder.Shipment_Value_USD__c = 123;
        shipmentOrder.Who_arranges_International_courier__c ='Client'; 
        shipmentOrder.Tax_Treatment__c ='DAP/CIF - IOR pays';
        shipmentOrder.Ship_to_Country__c = cpa.Id;
        shipmentOrder.Update_Rag_Status_Time__c = TRUE;
        
        insert shipmentOrder;

        
        
        Test.startTest();

        ragStatusUpdate batch = new ragStatusUpdate(); 
        database.executebatch(batch);
       
          
          

          Test.stopTest();
      }

    }

 
Hello Guys

I have a trigger below that is partially updating the record, may anyone assist me in figuring out what is causing the second update to Fail. 

It updates Ship_From_Zone1__c  and Hub_Ship_From_Zone__c  but not the shipto and the hubshipto Ids
trigger PopulateRegion on Shipment_Order__c (before insert, before update) {


for(Shipment_Order__c shipmentorder : Trigger.new) {

List<Ship_To__c> shipto= new List<Ship_To__c>();  
shipto = [Select Id from Ship_To__c WHERE Ship_To__c.Ship_From_Zone__c = :shipmentorder.Ship_From_Zone1__c  AND Ship_To__c.Name =:shipmentorder.Ship_From_Country__c ORDER BY Id LIMIT 1];
List<Ship_To__c> hubshipto = new List<Ship_To__c>(); 
hubshipto = [Select Id from Ship_To__c WHERE Ship_To__c.Ship_From_Zone__c = :shipmentorder.Hub_Ship_From_Zone__c AND Ship_To__c.Name =:shipmentorder.Hub_Country__c ORDER BY Id LIMIT 1];
    
If(shipmentorder.Hub_Shipment_Formula__c == False && shipmentorder.Ship_From_Country__c != null && shipto.size() > 0 ){


        string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
        shipmentorder.Ship_From_Zone1__c = region; 
        shipmentorder.Ship_to__c = shipto[0].Id;
}
    
  
    
    If(shipmentorder.Hub_Shipment_Formula__c == True && shipmentorder.Hub_Country__c != null && shipto.size() > 0)  { 
    
     
    string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
    string hubregion = Country_Region_List__c.getInstance(shipmentorder.Hub_Country__c).Region__c;
   
      shipmentorder.Ship_From_Zone1__c = region; 
      shipmentorder.Hub_Ship_From_Zone__c = hubregion; 
      shipmentorder.Ship_to__c = hubshipto[0].Id ;
      shipmentorder.From_Hub_Destination__c = shipto[0].Id ;

}

}

}


 
Hi all
I am not sure why I am getting this error on my trigger, may someone please point me in the right direction. 
 
trigger PopulateRegion on Shipment_Order__c (after insert, after update) {

for(Shipment_Order__c shipmentorder : Trigger.new) {

If(shipmentorder.Hub_Shipment_Formula__c == False ){

        string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
        shipmentorder.Ship_From_Zone1__c = region; 
}
    
    Else { 
    string region3 = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
    string region2 = Country_Region_List__c.getInstance(shipmentorder.HUB_Country_Formula__c).Region__c;
    shipmentorder.Ship_From_Zone1__c = region3;
    shipmentorder.Hub_Ship_From_Zone__c= region2;

}

}
}

 
Hi 

My scenario is that I would like to notify all contacts for an account about a new custom record being created. There is no relationship between the custom object and contacts. 

The code that I am using allows me to send the email but it is in the contact context and I am not certain how to set a SentToAddress and a TargetObjectId. 
 
public class SendEmailTemplatesToAccountContacts {

  @InvocableMethod
  public static void sendEmail(List<Account> acc) {
 
  Shipment_Order__c so = new Shipment_Order__c ();
    String sourceAccountId = String.valueOf(acc[0].Id);
    List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();
    List<Contact> contactsToEmail = [SELECT Id
                                     FROM   Contact
                                     WHERE  AccountId = :sourceAccountId];
    Id templateId = [SELECT Id, Name
                     FROM   EmailTemplate 
                     WHERE  Name = 'New Shipment Notification Supplier'].Id;

    for(Contact con: contactsToEmail){
    

      Messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
      email.setTemplateId(templateId);
      email.setTargetObjectId(con.Id);
      email.setSaveAsActivity(true); //or true if you want to save as an activity
      email.setSenderDisplayName('Sender Display Name'); //Here if you want to change the sender name
      emailsToSend.add(email);

    }
    Messaging.sendEmail(emailsToSend);
  }
  
}

 
Hi all

I have a trigger that creates new child records from a parent. Parent is called Roll Out and the Child is called Cost Estimate. I would like that should it be refired that it checks for existing records before so as it avoid duplication. The duplicate check should be on the value and the the desitnation. 

Any assistance with the duplication check and also ensuring that the code is bulkified will be appreciated.  
 
rigger AutoCreateCostEstimates on Roll_Out__c (after insert, after update) {

    List<Cost_Estimate__c> interviewers = new List<Cost_Estimate__c>();
    List<string> Temp;


    for (Roll_Out__c newPosition: Trigger.New) {
      if (newPosition.Destinations__c != null && newPosition.Create_Roll_Out__c == True){
            // split out the multi-select picklist using the semicolon delimiter
            for(String destinationlist: newPosition.Destinations__c.split(';')){
                interviewers.add(new Cost_Estimate__c(
                Client_Name__c = newPosition.Client_Name__c,
                Shipment_Value_in_USD__c = newPosition.Shipment_Value_in_USD__c,
                Destination__c = destinationlist,
                Roll_Out__c = newPosition.Id));
                
            }
        }
        
    }
    insert interviewers;
    
}

 
Hi all,

May I have some assistance with the below code , this works perfectly if one record is being created but when i create multiple records at the same time I get an error that the List has more than 1 row for assignment to SObject.  

Can someone take a look at what I may be doing wrong. This is the line where the error is originating. 

newSOWrappers.Add(new SOWrapper(shipmentOrder));
 
public class SOWrapper
    {
        public SOWrapper(Shipment_Order__c so, boolean recalculateCosts)
        {
            this.SO = so;
            this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c  FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c];
            this.Client = so.Account__r;

            if (recalculateCosts )
                recalculateCostings();
            else
                buildCostings();
        }

        public SOWrapper(Shipment_Order__c so)
        {
            this.SO = so;
            this.CAP = [SELECT Related_Costing_CPA__c, VAT_Rate__c FROM CPA_v2_0__c WHERE ID =: so.CPA_v2_0__c];
            this.Client = so.Account__r;

            if (so.CPA_v2_0__c != null)

            buildCostings();
        }

        public Shipment_Order__c SO { set; get; }
        public CPA_v2_0__c CAP { set; get; }
        public Account Client { set; get; }
        private List<CPA_Costing__c> relatedCostings;
        private List<CPA_Costing__c> relatedCostingsIOR;
        private List<CPA_Costing__c> relatedCostingsEOR;
        private List<CPA_Costing__c> addedCostings;
        private List<CPA_Costing__c> updatedCostings;

        private Id recordTypeId = Schema.SObjectType.CPA_Costing__c.getRecordTypeInfosByName()
                .get('Display').getRecordTypeId();

        public void buildCostings()
        {
            relatedCostingsIOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c  FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'IOR' ];
            relatedCostingsEOR = [SELECT Name, Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, IOR_EOR__c, VAT_applicable__c, Variable_threshold__c, VAT_Rate__c, CPA_v2_0__r.VAT_Rate__c  FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id AND IOR_EOR__c = 'EOR'];       
    
         
         If(SO.Service_Type__c == 'IOR') {
          
            List<CPA_Costing__c>  SOCPAcostingsIOR = relatedCostingsIOR.deepClone();
           
            for(CPA_Costing__c cost : SOCPAcostingsIOR)
            
            {
           
                cost.Shipment_Order_Old__c = SO.ID;
                cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c;
                cost.recordTypeID = recordTypeId;
                cost.VAT_Rate__c =  CAP.VAT_Rate__c;
                
                

                if (SO.Shipment_Value_USD__c != null)
                {
                    cost.Updating__c = !cost.Updating__c;
                    SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                }
            }
            addedCostings = SOCPAcostingsIOR;
        }
        
        Else If(SO.Service_Type__c == 'EOR') {
          
            List<CPA_Costing__c>  SOCPAcostingsEOR = relatedCostingsEOR.deepClone();
           
            for(CPA_Costing__c cost : SOCPAcostingsEOR)
            
            {
           
                cost.Shipment_Order_Old__c = SO.ID;
                cost.CPA_v2_0__c = CAP.Related_Costing_CPA__c;
                cost.recordTypeID = recordTypeId;
                cost.VAT_Rate__c =  CAP.VAT_Rate__c; 

                if (SO.Shipment_Value_USD__c != null && (SO.FC_Total__c == null || SO.FC_Total__c == 0))
                {
                    cost.Updating__c = !cost.Updating__c;
                    SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                }
            }
            addedCostings = SOCPAcostingsEOR;
        }
        
        }


         public void recalculateCostings()
        {
            
            relatedCostings = [SELECT Name, Shipment_Order_Old__c, IOR_EOR__c,Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE Shipment_Order_Old__c =: SO.ID];
            System.debug('relatedCostings --- '+relatedCostings.size());
            
            List<CPA_Costing__c> delList = new List<CPA_Costing__c>();
            for(CPA_Costing__c var: relatedCostings )
            {
                if(var.Cost_Type__c == 'Variable'){
                    CPA_Costing__c del = new CPA_Costing__c();
                    del.id =var.id;
                    delList.add(del);                    
                }
            }
            

            
            updatedCostings = new List<CPA_Costing__c>();
            System.debug('updatedCostings --- '+updatedCostings.size());
            List<CPA_Costing__c>  relatedTemplateCPAcostings = [SELECT Name, IOR_EOR__c,Shipment_Order_Old__c, Amount__c, Applied_to__c, Ceiling__c, Conditional_value__c, Condition__c, Floor__c, Cost_Category__c, Cost_Type__c, Max__c, Min__c, Rate__c, CostStatus__c, Updating__c, RecordTypeID, CPA_v2_0__r.VAT_Rate__c, VAT_Rate__c, VAT_applicable__c, Variable_threshold__c FROM CPA_Costing__c WHERE CPA_v2_0__c =: CAP.Id ];
               
               List<CPA_Costing__c> updateCosting = new List<CPA_Costing__c >(); 
               Set<Id> ids = new Set<id>();
              for (CPA_Costing__c templateCost : relatedTemplateCPAcostings)
              {    
               
                  SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false);                       
                  System.debug('The cost id; ----------# '+templateCost.Id+' Amount:- '+templateCost.Amount__c);
                  for(CPA_Costing__c cost : relatedCostings){
                      if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name != cost.Name && templateCost.Cost_Type__c == cost.Cost_Type__c && templateCost.Applied_to__c == cost.Applied_to__c && templateCost.IOR_EOR__c == cost.IOR_EOR__c){
                           System.debug(' Do update: '+cost.Id+' the amount '+templateCost.Amount__c+'  --- name '+ templateCost.Name);
                            if(!ids.contains(cost.id) && templateCost.Amount__c > -1){
                                cost.Id = cost.Id;  
                                cost.Name =  templateCost.Name;
                                cost.Amount__c =  templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c;
                                cost.Ceiling__c = templateCost.Ceiling__c;
                                cost.Conditional_value__c = templateCost.Conditional_value__c;
                                cost.Condition__c = templateCost.Condition__c;
                                cost.Cost_Type__c = templateCost.Cost_Type__c;
                                cost.Floor__c = templateCost.Floor__c;
                                cost.Max__c = templateCost.Max__c;
                                cost.Min__c = templateCost.Min__c;
                                cost.Rate__c = templateCost.Rate__c;
                                cost.Variable_threshold__c = templateCost.Variable_threshold__c;
                                cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c; 
                                cost.Cost_Category__c   = templateCost.Cost_Category__c ;                                  
                                cost.IOR_EOR__c = templateCost.IOR_EOR__c;                                
                                updateCosting.add(cost);
                                ids.add(cost.id);
                            }
                      }                   
                  }    
              }        
     if(!updateCosting.IsEmpty()){       
        update updateCosting;
     }
            List<CPA_Costing__c> updateCostList = new List<CPA_Costing__c>();
            for(CPA_Costing__c cost : relatedCostings)
            {
                cost.Updating__c = !cost.Updating__c;
                SOTriggerHelper.calculateSOCostingAmount(so, cost, false);
                  System.debug('The cost id; --------'+cost.Id+' Amount:- '+cost.Amount__c);
                  IF(cost.Amount__c == -1){
                                    

                  }
                System.debug(' --- cost '+cost.Amount__c);
                if (cost.Amount__c >= 0)
                {
                System.debug(' --- amount '+relatedTemplateCPAcostings);
                    for (CPA_Costing__c templateCost : relatedTemplateCPAcostings)
                    {
                    
                   
                    System.debug(' --- templateCost ');
                        if (templateCost.Cost_Category__c == cost.Cost_Category__c && templateCost.Name == cost.Name)
                        {
                            cost.Updating__c = !cost.Updating__c;
                            SOTriggerHelper.calculateSOCostingAmount(so, templateCost, false);
                             System.debug(' --- templateCost2  '+templateCost.Amount__c);

                            if (templateCost.Amount__c > 0)
                            {
                             System.debug(' ---inside  '+templateCost.Amount__c);
                                cost.Amount__c =  templateCost.VAT_applicable__c == TRUE ? templateCost.Amount__c * (1 + (CAP.VAT_Rate__c/ 100)): templateCost.Amount__c;
                                cost.Ceiling__c = templateCost.Ceiling__c;
                                cost.Conditional_value__c = templateCost.Conditional_value__c;
                                cost.Condition__c = templateCost.Condition__c;
                                cost.Cost_Type__c = templateCost.Cost_Type__c;
                                cost.Floor__c = templateCost.Floor__c;
                                cost.Max__c = templateCost.Max__c;
                                cost.Min__c = templateCost.Min__c;
                                cost.Rate__c = templateCost.Rate__c;
                                cost.Variable_threshold__c = templateCost.Variable_threshold__c;
                                cost.VAT_Rate__c = templateCost.CPA_v2_0__r.VAT_Rate__c;
                                
                              system.debug('THE COST ' +  cost.ID+' '+cost.Name);  
                                
                            }
                        }
                    }
                }

                updatedCostings.Add(cost);
            }
                       
            if(!updateCostList.IsEmpty()){
                    insert updateCostList;
            }
        }
        
        
        

        public List<CPA_Costing__c> getApplicableCostings()
        {
            List<CPA_Costing__c> applicableCostings = new List<CPA_Costing__c>();
            if (addedCostings != null)
                for (CPA_Costing__c cost : addedCostings)
                    if (cost.Amount__c > -1 && cost.Shipment_Order_Old__c != null)
                        applicableCostings.Add(cost);
            if (updatedCostings != null)
                for (CPA_Costing__c cost : updatedCostings)
                    if (cost.Amount__c > -1)
                        applicableCostings.Add(cost);

            return applicableCostings;
        }
    }

public class CalculateCosts
{

    @InvocableMethod
    public static void createSOCosts(List<Id> SOIds)  
    
    
    {
        List<SOWrapper> newSOWrappers = new List<SOWrapper>();
        List<ID> SOsToUpdate = new List<Id>();
        
        List<Shipment_Order__c> shipmentOrder = [Select Id, Name,  Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c,
        FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c,
        TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c, Account__c, Service_Type__c, Total_Taxes__c FROM Shipment_Order__c where id IN :SOIds];
        
        List<Shipment_Order__c> SOs = new List<Shipment_Order__c>();

        List<CPA_Costing__c> costingsToAddUpdate = new List<CPA_Costing__c>();

        List<Shipment_Order__c> updatedSOs =
        [SELECt Id, Name,  Insurance_Cost_CIF__c, Shipment_Value_USD__c, IOR_Fee_new__c, FC_IOR_and_Import_Compliance_Fee_USD__c, FC_Total_Customs_Brokerage_Cost__c,
        FC_Total_Handling_Costs__c, FC_Total_License_Cost__c, FC_Total_Clearance_Costs__c, FC_Insurance_Fee_USD__c, FC_Miscellaneous_Fee__c, On_Charge_Mark_up__c , FC_International_Delivery_Fee__c,
        TecEx_Shipping_Fee_Markup__c, CPA_v2_0__c, Chargeable_Weight__c    FROM Shipment_Order__c  WHERE ID in: SOsToUpdate];
        
        newSOWrappers.Add(new SOWrapper(shipmentOrder));

        if (newSOWrappers.size() > 0 && shipmentOrder.size() > 0 )
       {
            for (SOWrapper wrp : newSOWrappers)
           {
                Shipment_Order__c SO;
               for (Shipment_Order__c SOToUpdate : updatedSOs)
                    if (SOToUpdate.ID == wrp.SO.ID)
                    {
      
        
                    SO = SOToUpdate;
                       break;
          
                  }

               costingsToAddUpdate.AddAll(wrp.getApplicableCostings());
                 
            }
            
           

            
        }
         Upsert costingsToAddUpdate;
        update SOs;
        
        
        
       }
            
                                                   
        
    }

 
Hi all

I have a batch class that I am gettin​g very litte test coverage for, can someone please assist. Lines 9 to 18 are not being covered.
global class ragStatusUpdate implements Database.Batchable<sObject>{

   global Database.QueryLocator start(Database.BatchableContext BC)

  {   string query = 'select id, Update_Rag_Status_Time__c from Shipment_Order__c  where Shipping_Status__c != \'POD Received\' AND Shipping_Status__c != \'On Hold\'AND Shipping_Status__c != \'Cancelled\'AND Shipping_Status__c != \'Shipment Pending\' AND Shipping_Status__c != \'Cancelled - With fees/costs\' AND Shipping_Status__c != \'Cancelled\'AND Shipping_Status__c != \'Cancelled - No fees/costs\' AND Shipping_Status__c != \'Customs Clearance Docs Received\' ';
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<Shipment_Order__c>scope )
   {
list<Shipment_Order__c> SO = new list<Shipment_Order__c>();
        for(Shipment_Order__c s : scope)
           {
            s.Update_Rag_Status_Time__c  = TRUE;
            
             SO.add(s);
            }      
          update SO;
     }

   global void finish(Database.BatchableContext BC){

   }

}
 
@isTest
private class RagStatusTest {


static testMethod void testMethod1() {
    
        
        Account testClient = new account(Name='TestingClient',Client_Status__c = 'Prospect',Estimated_Vat__c = 123,CSE_IOR__c='0050Y000001LTZO');

        insert testClient;

        Contact testcontact = new Contact(LastName='Maseli',AccountId=testClient.Id);

        insert testcontact;
        
        country_price_approval__c cpa = new country_price_approval__c( name ='Serbia', Billing_term__c = 'DAP/CIF - IOR pays',  Airwaybill_Instructions__c = 'User IOR Address');
        insert cpa;
        
        IOR_Price_List__c testIOR = new IOR_Price_List__c();

        testIOR.Client_Name__c = testClient.Id;
        testIOR.Name = 'Serbia';
        testIOR.IOR_Fee__c = 1;
        
        insert testIOR;

        Shipment_Order__c shipmentOrder = new Shipment_Order__c();
        shipmentOrder.Account__c = testClient.Id;
        shipmentOrder.IOR_Price_List__c = testIOR.Id;
        shipmentOrder.Client_Contact_for_this_Shipment__c = testcontact.Id;
        shipmentOrder.Shipment_Value_USD__c = 123;
        shipmentOrder.Who_arranges_International_courier__c ='Client'; 
        shipmentOrder.Tax_Treatment__c ='DAP/CIF - IOR pays';
        shipmentOrder.Ship_to_Country__c = cpa.Id;
        shipmentOrder.Update_Rag_Status_Time__c = TRUE;
        
        insert shipmentOrder;

        
        
        Test.startTest();

        ragStatusUpdate batch = new ragStatusUpdate(); 
        database.executebatch(batch);
       
          
          

          Test.stopTest();
      }

    }

 
Hello Guys

I have a trigger below that is partially updating the record, may anyone assist me in figuring out what is causing the second update to Fail. 

It updates Ship_From_Zone1__c  and Hub_Ship_From_Zone__c  but not the shipto and the hubshipto Ids
trigger PopulateRegion on Shipment_Order__c (before insert, before update) {


for(Shipment_Order__c shipmentorder : Trigger.new) {

List<Ship_To__c> shipto= new List<Ship_To__c>();  
shipto = [Select Id from Ship_To__c WHERE Ship_To__c.Ship_From_Zone__c = :shipmentorder.Ship_From_Zone1__c  AND Ship_To__c.Name =:shipmentorder.Ship_From_Country__c ORDER BY Id LIMIT 1];
List<Ship_To__c> hubshipto = new List<Ship_To__c>(); 
hubshipto = [Select Id from Ship_To__c WHERE Ship_To__c.Ship_From_Zone__c = :shipmentorder.Hub_Ship_From_Zone__c AND Ship_To__c.Name =:shipmentorder.Hub_Country__c ORDER BY Id LIMIT 1];
    
If(shipmentorder.Hub_Shipment_Formula__c == False && shipmentorder.Ship_From_Country__c != null && shipto.size() > 0 ){


        string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
        shipmentorder.Ship_From_Zone1__c = region; 
        shipmentorder.Ship_to__c = shipto[0].Id;
}
    
  
    
    If(shipmentorder.Hub_Shipment_Formula__c == True && shipmentorder.Hub_Country__c != null && shipto.size() > 0)  { 
    
     
    string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
    string hubregion = Country_Region_List__c.getInstance(shipmentorder.Hub_Country__c).Region__c;
   
      shipmentorder.Ship_From_Zone1__c = region; 
      shipmentorder.Hub_Ship_From_Zone__c = hubregion; 
      shipmentorder.Ship_to__c = hubshipto[0].Id ;
      shipmentorder.From_Hub_Destination__c = shipto[0].Id ;

}

}

}


 
Hi all
I am not sure why I am getting this error on my trigger, may someone please point me in the right direction. 
 
trigger PopulateRegion on Shipment_Order__c (after insert, after update) {

for(Shipment_Order__c shipmentorder : Trigger.new) {

If(shipmentorder.Hub_Shipment_Formula__c == False ){

        string region = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
        shipmentorder.Ship_From_Zone1__c = region; 
}
    
    Else { 
    string region3 = Country_Region_List__c.getInstance(shipmentorder.Ship_From_Country__c).Region__c;
    string region2 = Country_Region_List__c.getInstance(shipmentorder.HUB_Country_Formula__c).Region__c;
    shipmentorder.Ship_From_Zone1__c = region3;
    shipmentorder.Hub_Ship_From_Zone__c= region2;

}

}
}

 
Hi 

My scenario is that I would like to notify all contacts for an account about a new custom record being created. There is no relationship between the custom object and contacts. 

The code that I am using allows me to send the email but it is in the contact context and I am not certain how to set a SentToAddress and a TargetObjectId. 
 
public class SendEmailTemplatesToAccountContacts {

  @InvocableMethod
  public static void sendEmail(List<Account> acc) {
 
  Shipment_Order__c so = new Shipment_Order__c ();
    String sourceAccountId = String.valueOf(acc[0].Id);
    List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();
    List<Contact> contactsToEmail = [SELECT Id
                                     FROM   Contact
                                     WHERE  AccountId = :sourceAccountId];
    Id templateId = [SELECT Id, Name
                     FROM   EmailTemplate 
                     WHERE  Name = 'New Shipment Notification Supplier'].Id;

    for(Contact con: contactsToEmail){
    

      Messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
      email.setTemplateId(templateId);
      email.setTargetObjectId(con.Id);
      email.setSaveAsActivity(true); //or true if you want to save as an activity
      email.setSenderDisplayName('Sender Display Name'); //Here if you want to change the sender name
      emailsToSend.add(email);

    }
    Messaging.sendEmail(emailsToSend);
  }
  
}

 
Hi all

I have a trigger that creates new child records from a parent. Parent is called Roll Out and the Child is called Cost Estimate. I would like that should it be refired that it checks for existing records before so as it avoid duplication. The duplicate check should be on the value and the the desitnation. 

Any assistance with the duplication check and also ensuring that the code is bulkified will be appreciated.  
 
rigger AutoCreateCostEstimates on Roll_Out__c (after insert, after update) {

    List<Cost_Estimate__c> interviewers = new List<Cost_Estimate__c>();
    List<string> Temp;


    for (Roll_Out__c newPosition: Trigger.New) {
      if (newPosition.Destinations__c != null && newPosition.Create_Roll_Out__c == True){
            // split out the multi-select picklist using the semicolon delimiter
            for(String destinationlist: newPosition.Destinations__c.split(';')){
                interviewers.add(new Cost_Estimate__c(
                Client_Name__c = newPosition.Client_Name__c,
                Shipment_Value_in_USD__c = newPosition.Shipment_Value_in_USD__c,
                Destination__c = destinationlist,
                Roll_Out__c = newPosition.Id));
                
            }
        }
        
    }
    insert interviewers;
    
}