• Shri Raj
  • SMARTIE
  • 1054 Points
  • Member since 2014

  • Chatter
    Feed
  • 27
    Best Answers
  • 3
    Likes Received
  • 5
    Likes Given
  • 31
    Questions
  • 357
    Replies
I am looking to change the color of the buttons in the hightlights panel to red or green depending on if they are completed. The buttons are screen flows and we have check boxes to indicate completion.
There are 6mem"s assigned under a North America role. When we are creating a user under the North America role there a assigning to Crop protection Queue membership, So the automatic assignment to Queue should be removed and user to be assigned to Queue manually... What should be the solution..
public class ScheduleMessageBatch implements Database.Batchable<SObject>{
    
    
    public Database.queryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator('Select Id, DeliveryStatus__c, Source__c, ScheduledAt__c, MessageText__c, ToNumber__c, FromNumber__c From MessageHistory__c where DeliveryStatus__c = \'Scheduled\' AND Source__c = \'Drip Campaign\' AND ScheduledAt__c <= Datetime.now()');
        
    }
    public void execute(Database.BatchableContext BC, List<MessageHistory__c> messagehistoryList )  {
        
        
        for(MessageHistory__c mh : messagehistoryList) {
            MessageDesk mD = new MessageDesk();
            MessageInfo mi = new MessageInfo(mh);
            mD.sendSMS(mi);
        }
        
    }
    public void finish(Database.BatchableContext BC)
    {
        
    }
}
Hello Team,

I am getting the following error - 
This page has an error. You might just need to refresh it. Action failed: c:ContactListSearch$controller$searchKeyChange [Cannot read properties of undefined (reading 'setParams')] Failing descriptor: {c:ContactListSearch$controller$searchKeyChange} 
while running the app with the following code.

QuickContacts.app
<aura:application>
    <link href='/resource/bootstrap/' rel="stylesheet"/>
    <div class="navbar navbar-default navbar-static-top" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <a href="#" class="navbar-brand">Lightning Contacts</a>
            </div>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <c:ContactListSearch/>
                <c:ContactList/>
            </div>
        </div>
    </div>
</aura:application>

ContactList.cmp
<aura:component controller="ContactController">
    <aura:attribute name="contacts" type="Contact[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:handler event="c:SearchKeyEvent" action="{!c.searchKeyChange}"/>
    <ul class="list-group">
        <aura:iteration items="{!v.contacts}" var="contact">
            <li class="list-group-item">
                <a href="{! '#contact/' + contact.Id }">
                    <p>{!contact.Name}</p>
                    <p>{!contact.Phone}</p>
                </a>
            </li>
        </aura:iteration>
    </ul>
</aura:component>

ContactListController.js
({
    doInit : function(component, event)
    {
        var action=component.get("c.findAll");
        action.setCallback(this,function(a)
                           {
                               component.set("v.contacts",a.getReturnValue());    
                           });
    $A.enqueueAction(action);
    },
    searchKeyChange: function(component, event) {
        var searchKey = event.getParam("searchKey");
        var action = component.get("c.findByName");
        action.setParams({
          "searchKey": searchKey
        });
        action.setCallback(this, function(a) {
            component.set("v.contacts", a.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})

ContactListSearch.cmp
<aura:component >
    <input type="text" class="form-control" placeholder="Search" onkeyup="{!c.searchKeyChange}"/>
</aura:component>

SearchKeyEvent.evt
<aura:event type="APPLICATION" access="global">
    <aura:attribute name="searchKey" type="String"/>
</aura:event>

ContactListSearchController.js
({
        searchKeyChange : function(component, event, helper) {
        
        var myEvent = $A.get("e.c:SearchKeyChange");
        myEvent.setParams({"searchKey":event.target.value});
        myEvent.fire();
   
    }
    })

Can anyone please help me to find the error?
Hi, 
  I am trying to write SOQL for below case but facing  issue "Semi join sub-selects are only allowed at the top level WHERE expressions and not in nested WHERE expressions".

Use case is to retreive the opportunity where Amount > 1000 (OR) OpportunityFieldHistory where FIELD='StageName' AND CreatedDate  LAST_N_DAYS:14.

My Query:

SELECT Id, Name from opportunity where  Amount > 1000 OR Id IN(SELECT OpportunityId from OpportunityFieldHistory WHERE Field='StageName' AND CreatedDate=LAST_N_DAYS:14))

Can you please help, how this can be acheived.
I wrote an apex class which works fine. However, the test class keeps failing with the error: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Email body is required.: [] Not sure what I am doing wrong. Can you please help? I have attached my code and test class below

global class XYZLetter {   
    global static void sendLetter(List<String> recordId) {
        
//Get Files from ContentDocumentLink Object
    List<ContentDocumentLink> cdls = [select Id,ContentDocumentId,ContentDocument.Title,LinkedEntity.Name From ContentDocumentLink where LinkedEntityId=:recordId AND ContentDocument.Title LIKE 'xyz%'];
    
    Set<Id> contentDocumentIds = new Set<Id>();
    for (ContentDocumentLink cdl : cdls) {
        contentDocumentIds.add(cdl.ContentDocumentId);
    }   
        
    List<Id> attachmentIds = new List<Id>();    
//Get all related contentVersion file     
    List<ContentVersion> documents = ([SELECT Id FROM ContentVersion WHERE isLatest = true AND ContentDocumentId IN :contentDocumentIds]);
    for (ContentVersion doc : documents) {
        attachmentIds.add(doc.Id);
    }
    
//Get details on the Application    
   Card__c pcard = [SELECT Id,Letter_Failed__c, RecordTypeId FROM Card__c WHERE Id=:recordId];
   
    String cardholderContactId=pcard.Card_Applicant__c;

//-********************
 
    if(attachmentIds.size()==0){
        EmailTemplate NoXYZ = [SELECT id FROM EmailTemplate WHERE developerName = 'Letter_Not_Found'];
        
        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'oxyxSF@COMPANY.COM'];
        String[] ccAddresses = new String[] {'cardinquiries@company.com'};
        
        //Apex Single email message
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        if ( owea.size() > 0 ) {
            mail.setOrgWideEmailAddressId(owea.get(0).Id);
        }    
      
        mail.setTemplateID(NoXYZ.id);//templateID
        mail.setTargetObjectId(cardholderContactId);// contact Id of cardholder
        mail.setCcAddresses(ccAddresses);
        //No attachment found here, so no need to try and attach mail.setEntityAttachments(attachmentIds);
        mail.setWhatId(pcard.Id);  
        Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email for XYZ Letter not found was sent successfully.');
            } else {
                System.debug('The email for XYZ Letter not found failed to send: '+ results[0].errors[0].message);
                 pcard.XYZ_Letter_Failed__c = true;
             }
     
              Update pcard;
   }//end if attachmentIds.size()==0 (Send 'XYZ Letter Not Found' Template end)
//-********************

//-********************
   //Otherwise, end message as expected
    else {
        Id pcardRTypeId = [SELECT Id FROM RecordType WHERE sObjectType='Card__c' AND developerName ='PCard_Approval'].Id;
        Id finRTypeId = [SELECT Id FROM RecordType WHERE sObjectType='Card__c' AND developerName ='Information_Updates'].Id;

        EmailTemplate pcardET = [SELECT id FROM EmailTemplate WHERE developerName = 'X3_Approved'];
        EmailTemplate finET = [SELECT id FROM EmailTemplate WHERE developerName = 'X20_Information_Update_Approved'];
        EmailTemplate SingleFinET = [SELECT id FROM EmailTemplate WHERE developerName = 'X201_Single_Information_Update_Approved'];
        EmailTemplate MonthlyFinET = [SELECT id FROM EmailTemplate WHERE developerName = 'X202_Monthly_Information_Update_Approved'];
        
        String et;
        if (pcard.RecordTypeId == pcardRTypeId){
            et = pcardET.Id;
        }
        else if (pcard.RecordTypeId == finRTypeId){
            //et = finET.Id;
            if (pcard.Monthly_Purchase_Card_Update__c && pcard.Single_Purchase_Card_Update__c){
                et = finET.Id;
            }
            else if(pcard.Monthly_Purchase_Card_Update__c){
                et = MonthlyfinET.Id;
            }
            else if(pcard.Single_Purchase_Card_Update__c){
                et = SingleFinET.Id;
            }
        }

       
        

        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'XYZsalesforce@COMPANY.COM'];
  
        String[] ccAddresses = new String[] {'p-cardinquiries@COMPANY.COM'};
      
        if (pcard.PCard_Supervisor__c != null){
           ccAddresses.add(pcard.PCard_Supervisor__c);
        }
        if (pcard.Approving_Official_Lookup__c != null){
           ccAddresses.add(pcard.Approving_Official_Lookup__c);
        }
        
        List<String> idList = new List<String>();
        Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE NAME =:pcard.CPublic_Group__c];
        for (GroupMember gm : g.groupMembers) {
            idList.add(gm.userOrGroupId);
        }
        
        User[] usr = [SELECT email FROM user WHERE id IN :idList];
        for(User u : usr) {
            ccAddresses.add(u.Id);
        }
  
    //Apex Single email message
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        if ( owea.size() > 0 ) {
            mail.setOrgWideEmailAddressId(owea.get(0).Id);
        }    

    mail.setTemplateID(et);//templateID
    mail.setTargetObjectId(cardholderContactId);// contact Id of cardholder
    mail.setCcAddresses(ccAddresses);
    mail.setEntityAttachments(attachmentIds);
    mail.setWhatId(pcard.Id);  // card recordId
        
    Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {mail};
    Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        if (results[0].success) {
           System.debug('The email was sent successfully.');
        } else {
           System.debug('The email failed to send: '+ results[0].errors[0].message);
        }

        
    }

Here is the test class:
@isTest
public class DPALetterTest {
    static testMethod void sendEmailwithAttachment() {
        Test.startTest();
        
        EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'X3_PCard_Approved'];
        Id pcardRTypeId = [SELECT Id FROM RecordType WHERE sObjectType='PCard__c' AND developerName ='PCard_Approval'].Id;
        Id finRTypeId = [SELECT Id FROM RecordType WHERE sObjectType='Purchase_Card__c' AND developerName ='Information_Updates'].Id;
       // String pcardRTypeId = recTypeId.Id;
        
        Account acc = new Account();
        acc.Name='ABCTest';
        insert acc;

        String profileName1 = 'Card Application User';
        
        User admin = [SELECT Id, Username, UserRoleId FROM User WHERE Profile.Name = 'System Administrator' AND UserRole.Name='XYZSystem Admin' LIMIT 1];
       
        System.runAs(admin){

            User u1 = new User(
                ProfileId = ([SELECT Id FROM Profile WHERE Name=:profileName1].Id),
                LastName = 'user1',
                Email = 'test.user1@test.com',
                Username = 'test.ccpuser1@test.com',
                CompanyName = 'XYZ',            
                Alias = 'alias',          
                TimeZoneSidKey = 'America/Los_Angeles',
                EmailEncodingKey = 'UTF-8',
                LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US'             
            );
            insert u1;

            User u2 = new User(
                ProfileId = ([SELECT Id FROM Profile WHERE Name=:profileName1].Id),
                LastName = 'user2',
                Email = 'test.user2@test.com',
                Username = 'test.ccpuser2@test.com',
                CompanyName = 'CBER',            
                Alias = 'alias',          
                TimeZoneSidKey = 'America/Los_Angeles',
                EmailEncodingKey = 'UTF-8',
                LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US'             
            );
            insert u2;

         Group gp = [SELECT ID FROM Group WHERE Name='PCard XYZ CCP Group'];   
        GroupMember gpm = new GroupMember();
        gpm.GroupId = gp.Id;
        gpm.UserOrGroupId = u1.Id;            
        Database.insert(gpm);

        Contact applicant1 = new Contact(firstName='test', lastName = 'applicant11',accountId=acc.id, email ='test.applicant11@abctest.com');
        insert applicant1;
        Contact supervisor1 = new Contact(firstName='test', lastName = 'supervisor12',accountId=acc.id, email ='test.supervisor12@abctest.com');
        insert supervisor1;  
        Contact ao1 = new Contact(firstName='test', lastName = 'ao11',accountId=acc.id, email ='test.ao11@abctest.com');
        insert ao1;              
        
        Card__c app1 = new Card__c(); 
        
        app1.RecordTypeId = pcardRTypeId;
        app1.Cardholder_Name__c  = 'Test Applicant11';
        app1.Cardholder_Email_Address__c='Test.Applicant11@abctest.com';
        app1.PCard_Applicant__c = applicant1.Id;
        app1.PCard_Supervisor__c = supervisor1.Id;
        app1.Approving_Official_Lookup__c = ao1.Id;      
        insert app1; 
            
        Purchase_Card__c app2 = new Purchase_Card__c(); 
        
        app2.RecordTypeId = finRTypeId;
        app2.Cardholder_Name__c  = 'Test Applicant11';
        app2.Cardholder_Email_Address__c='Test.Applicant11@abctest.com';
        app2.Card_Applicant__c = applicant1.Id;
        app2.Card_Supervisor__c = supervisor1.Id;
        app2.Approving_Official_Lookup__c = ao1.Id;
        insert app2; 
   
          
            // Insert Salesforce Files using Apex Class:
         //Create Document
        ContentVersion cv = new ContentVersion();
        cv.Title = 'XYZ Test Document';
        cv.PathOnClient = 'TestDocument.pdf';
        cv.VersionData = Blob.valueOf('Test Content');
        cv.IsMajorVersion = true;
        Insert cv;
                            
             //Get Content Documents
    Id conDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cv.Id].ContentDocumentId;
 
    //Create ContentDocumentLink 
    ContentDocumentLink cdl = New ContentDocumentLink();
    cdl.LinkedEntityId = app1.Id;
    cdl.ContentDocumentId = conDocId;
    cdl.shareType = 'V';
    cdl.Visibility = 'AllUsers';
    Insert cdl; 
            
    ContentDocumentLink cdl2 = New ContentDocumentLink();
    cdl2.LinkedEntityId = app2.Id;
    cdl2.ContentDocumentId = conDocId;
    cdl2.shareType = 'V';
    cdl2.Visibility = 'AllUsers';
    Insert cdl2; 
                       
        
         Integer emailbefore = Limits.getEmailInvocations();

         List<String> recordIds=new List<String>{app1.Id};  
         List<String> finRecordIds=new List<String>{app2.Id};  
         XYZLetter.sendLettXYZer(recordIds);   
         XYZLetter.sendXYZLetter(finRecordIds);    
  
        system.assertNotEquals(emailbefore,Limits.getEmailInvocations(),'should have decreased');
        Test.stopTest();         
        
    }
}

}
TLDR; Instead of native form submission for web2lead form, I am using REST API to hit the https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8 endpoint with form data in the request body to submit the Web2Lead form. And it's getting CORS error.
---
While the raw form looks like this
 
<form action="https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">


I have built the form using some custom components in React and providing the below `handleSubmit` handler to it to submit the form.
const actionUrl =
    'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';

  const handleSubmit = async (formValues) => {
    try {
      await axios.post(actionUrl, formValues, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      });
    } catch (error) {
      console.error(error);
    }
  };

And this axios request is getting CORS error on the browser although I added the domain to the whitelist on the security settings.
Are Web2Lead forms intended to be submitted as a native form always? Is there a way to submit this form using axios without getting the CORS error?
Keep getting "Choose a different report type. This one has no common fields with the other report types in this joined report." when trying to join with a custom object.
Does anyone know what this error means when trying to Name and Describe your recommendation in Einstein Recommendation Builder?User-added image
Is there any way to bypass lookup filter validation for specific user ?
Hello, 
I am trying to write several formulas to use in a flow to check if a date is in between a range. The issue is I want it to be sustainable and only compare the Month and Day only, not the year. 

Example:
say the input date field is March 1, 2023

I want to know if it's equal to or greater than January 11 and less than or equal to April 10th and not include the year. 

Is this possible?

Tried something like this and it failed: 

AND(
MONTH({!$Record.Comp_Approved_Date__c}) >= 1,
MONTH({!$Record.Comp_Approved_Date__c}) <= 4,
DAY({!$Record.Comp_Approved_Date__c})  >= 11,
DAY({!$Record.Comp_Approved_Date__c})  <= 10
)
I need to access the SHOPPER API which needs the access_token, but I didn't find the document which suggests how I can do that or any other alternate way to do it.
Thanks 

I am unable to update [patch] standardvalueset through tooling api and here's request body but receiving bad id 4 and malformed id

 

Request Body:

{
 
"Metadata" : {
      "sorted" : false,
      "standardValue" : [ {
        "allowEmail" : null,
        "closed" : null,
        "color" : null,
        "converted" : null,
        "cssExposed" : null,
        "default" : false,
        "description" : null,
        "forecastCategory" : null,
        "groupingString" : null,
        "highPriority" : null,
        "isActive" : null,
        "label" : "Agriculture",
        "probability" : null,
        "reverseRole" : null,
        "reviewed" : null,
        "urls" : null,
        "valueName" : "Agriculture",
        "won" : null
      }, {
        "allowEmail" : null,
        "closed" : null,
        "color" : null,
        "converted" : null,
        "cssExposed" : null,
        "default" : false,
        "description" : null,
        "forecastCategory" : null,
        "groupingString" : null,
        "highPriority" : null,
        "isActive" : null,
        "label" : "Chemicals1",
        "probability" : null,
        "reverseRole" : null,
        "reviewed" : null,
        "urls" : null,
        "valueName" : "Chemicals1",
        "won" : null
      } ],
      "urls" : null
    },
     "FullName" : "Test",
    "MasterLabel" : "Test"
  } 
 

I have below code. I need to generate a csv file to show to results of 'userdetaillist'.

public class UserService {
    private static String profileName = 'Chatter Free User';
    private static String ps7Name = 'Test Chatter Free7';
   Public static List<UserDetail> userDetailList = new List<UserDetail>();
    
    
    private static List<String> ps1_ps10NameList = new List<String>{
        'Test Chatter Free1','Test Chatter Free2','Test Chatter Free3','Test Chatter Free4','Test Chatter Free5','Test Chatter Free6','Test Chatter Free7','Test Chatter Free8','Test Chatter Free9','Test Chatter Free10'};
    
    
    public static List<UserDetail> getUserPermissionDetails(){
        
      Map<Id, User> userMap = new Map<Id, User>([SELECT Id
                                  FROM User
                                  WHERE Profile.Name = :profileName and Id IN (SELECT AssigneeId 
                                                   FROM PermissionSetAssignment
                                                   WHERE PermissionSet.label = :ps7Name and PermissionSet.IsOwnedByProfile =false)]);
        //System.debug(usermap);
     Map<Id, List<String>> permissionSetMap = new Map<Id, List<String>>();
        
        for(PermissionSetAssignment psa : [SELECT AssigneeId, PermissionSet.label
                                              FROM PermissionSetAssignment
                                              WHERE AssigneeId = : userMap.keySet()
                                                  AND (PermissionSet.label IN :ps1_ps10NameList
                                                     OR PermissionSet.label NOT IN :ps1_ps10NameList)and PermissionSet.IsOwnedByProfile =false
                                              ORDER BY AssigneeId, PermissionSet.label])
        {
            List<String> tempList = new List<String>();
               if(permissionSetMap.containsKey(psa.AssigneeId))
                tempList = permissionSetMap.get(psa.AssigneeId);
            
            tempList.add(psa.PermissionSet.label);
            
            permissionSetMap.put(psa.AssigneeId, tempList);
                    
        }

        return evaluateUser(permissionSetMap);
        
    }
    
    
    private static List<UserDetail> evaluateUser(Map<Id, List<String>> permissionSetMap){

        Boolean additional;

        List<UserDetail> userDetailList = new List<UserDetail>();

        List<String> foundList = new List<String>();        
        for(Id id : permissionSetMap.keySet())
        {
            UserDetail ud = new UserDetail();
            additional = false;
            /*system.debug(permissionSetMap.get(id));*/
            foundList.clear();

            for(String str : permissionSetMap.get(id)){
            
                if(!ps1_ps10NameList.contains(str)){
                    additional = true;
                }else{
                    foundList.add(str);
                }
                /*system.debug(userDetailList);*/
            }            
            
            ud.Id = id;
            ud.permissionSetList = permissionSetMap.get(id);
            
            if(additional && ps1_ps10NameList.size() == foundList.size())
                ud.status = 'No Change And Additional';
            else if(additional && ps1_ps10NameList.size() != permissionSetMap.get(id).size())
                ud.status = 'Missing And Additional';
            else if(!additional && ps1_ps10NameList.size() != foundList.size())
                ud.status = 'Missing';
            else if(!additional && ps1_ps10NameList.size() == foundList.size())          
                ud.status = 'No Change';
                
            userDetailList.add(ud);
        }
        System.debug(JSON.serializePretty(userDetailList));
            return userDetailList;
       
       
    }
    
    public class UserDetail {
        
        public Id id;
        public List<String> permissionSetList;
        public String status;
    } 
   
}
 
public class ApexCollection {
    
public static void apexMethod(string a)
{
    
    String[] arr=new String[]{'A','B','C','D','A'};
        integer s1=integer.valueOf(arr);  
       System.debug( 'intVal value is ' + s1 );

error: Method does not exist or incorrect signature: void apexMethod() from the type ApexCollection.

I am getting error on this code, please response.
when a customer sends emails to 2 different groups, then when an agent tries to reply then defaults to picking 1st mail id from the "To address" as default "From Address", Now agent requests irrespective  "To address" they want their group's mailbox.

 
Reading through the documentation (https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_organization.htm), the Organization object should have a field DefaultTerritoryAccountAccess. However when I query /services/data/v46.0/sobjects/Organization/describe, DefaultTerritoryAccountAccess isn't in the returned fields, and when I include it in a soql query, I get the below error:

"errorCode":"INVALID_FIELD","error_description":"","message":"\nDefaultLeadAccess, DefaultOpportunityAccess, DefaultTerritoryAccountAccess FROM\n ^\nERROR at Row:1:Column:125\nNo such column 'DefaultTerritoryAccountAccess' on entity 'Organization'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names.
Hi there,
Hope all is fine for you. I'm working on Integrations between ERP and Salesforce and willing to use Composite Resources to transfer Orders from our ERP to Salesforce.
Issue is that, even if it works most of the time, I'm having issues when Order contains more than X number of lines as Composite API allows up to 25 Subrequests only. I then discovered the Composite Graph API which raised this limit to 500, which was then pretty much OK, until I figured out that my subrequests were not executed in Order. Looking into documentation, I found the CollateSubrequests parameter, but this one seems to be only available in Composite API (back to the limit of 25 subrequests).
Does anybody know if there is a way to guarantee the order of execution for my subrequests in a Composite Graph API (for some Business reasons, I have to respect this order of execution which requires me to update the Order first (to Unlock it), then Delete Some Order Lines (which has to happen before I change the Currency on the Order), then Update the Order again (for currency), then re-Insert my Order Lines, then finally update my Order (to Lock it back).

Thanks in advance for your advices here

Cédric
I have below requirment - 
Train and Coach are 2 objects. Where I need to build logic based on train schedule and availibility. From UI side admin can add the coach to the train. 

Train (Parent Object - From, To, Timings)
Coach (Child Object - From, To, Timings) Field is there. 

Now from UI side when user book the tickets. based on given 3 fields I need to add coachs in the train. lets say next week on monday there will 3 trains are schedule from X to Y location. now today we see many passanger book the train from X to Y location. so basically, based on timings I need to add number of coaches in next week train so I can accomodate all customers. Its not like 1 train run with 5-6 coach, while other train runs with 30-35 coach. there has to balance. 

Please let me know if need further clarification in scenario.