Wednesday, October 29, 2014

VALIDATION RULES.....................

1.Only System Administrator can change the Record lead stage.


AND($User.ProfileId<>'00ew00000012G2I',
ISPICKVAL(nnr_Status__c,'In Progress'),
OR(ISPICKVAL(Stage__c,'6 AML Incomplete - Follow up required'),
ISPICKVAL(NewAccountsStage__c,'7 AML Approved')),
NOT(ISCHANGED(DC_Request_Status__c)),
NOT(ISCHANGED(DC_Requested__c)),
NOT(ISCHANGED(DC_Notes__c))
)


2.Tax ID must be a 11 digit number in Argentina



AND(!ISBLANK(Tax_ID__c),$Profile.Name !="System Administrator", $Profile.Name !="Integration",
AND(ISPICKVAL( Global_Region__c , "LA"),ISPICKVAL( Market__c , "Argentina"),!REGEX(Tax_ID__c, "[0-9]{11}")))

3.when lead is converting check the tax is not empty.



AND
(
AND( $Profile.Name != "System Administrator", $Profile.Name != "Integration"),
AND(
NOT(ISPICKVAL(Market__c,"hyd")),
OR(
AND(
$Profile.Name = "Sales",
$RecordType.Name = "Marketing Lead",
IsConverted
),$Profile.Name = "Sales"
),
ISBLANK( Tax_ID__c),
ISPICKVAL( Global_Region__c ,"nnr")
))

Manul Sharing The Record Throw Apex code in Trigger...........

trigger ShareRecordWithIM on nnr__c (after update)
{
    List<nnr__Share> shareList = new List<nnr__Share>();
    List<nnr__Share> deleteList = new List<nnr__Share>();
    nnr__Share ImpShare,ImpDelete;
    List<RecordType> MMRT = [SELECT Id FROM RecordType WHERE DeveloperName IN ('knr','wg')];
    Map<Id,Id> MMRTMap = new Map<Id,Id>{};
    String[] toAddress = new String[]{UserInfo.getUserEmail()};
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    Messaging.SingleEmailMessage email;
    Id oldRecShare;
   
    for(RecordType rt : MMRT)
        MMRTMap.put(rt.Id,rt.Id);
        
    for(nnr__c newRec : Trigger.new)
    {
        oldRecShare = trigger.oldMap.get(newRec.Id).Share_Record__c;
        if(newRec.Share_Record__c !=null && (oldRecShare != newRec.Share_Record__c) && MMRTMap.containsKey(newRec.RecordTypeId))
        {
           ImpShare = new nnr__Share();
           ImpShare.ParentId = newRec.Id;
           ImpShare.UserOrGroupId = newRec.Share_Record__c;
           ImpShare.AccessLevel = 'Edit';
           shareList.add(ImpShare);
          
           //send email to TL
            email = new Messaging.SingleEmailMessage();
            email.setToAddresses(toAddress);
            String IM = [SELECT Name FROM User WHERE Id =:newRec.Share_Record__c LIMIT 1].Name;
            email.setSubject(newRec.Opportunity_UniqueID__c+' Case Access Shared Notification');
            email.setHTMLBody('Hello,<br><br>Shared access to Implementation '+newRec.Name+' has been given to '+IM+'.<br><br>Kind regards,<br>Centralised Implementation Solutions '+newRec.Market_Referred__c);
            email.setSaveAsActivity(false);
            mails.add(email);
        }
        if((oldRecShare != null) && (oldRecShare != newRec.Share_Record__c) && MMRTMap.containsKey(newRec.RecordTypeId))
        {
            ImpDelete = [SELECT Id FROM nnr__Share WHERE UserOrGroupId =:oldRecShare AND ParentId =: newRec.Id];
            deleteList.add(ImpDelete);
        }  
    }
   
    try
    {
        if(shareList.size()>0)
            insert shareList;
        if(deleteList.size()>0)
            delete deleteList;
        if(mails != null)   
            //Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            Messaging.sendEmail(mails);
    }
    catch(Exception e)
    {
        System.debug('Following error occured while inserting sharing record: '+e);
    }
}


============================TEST CLASS=======================

@isTest

public class Test_ShareRecordWithIM
{
    static TestMethod void testSRIM()
    {       
        Profile p = [select id from profile where name='System Administrator'];   
       
        //User Insert
        User u = new user(alias = 'stdt', email='testsharerecorduser1@testorg.com', emailencodingkey='UTF-8', lastname='DPSRTest', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='testsharerecorduser1@testorg.com',Segment__c = 'Mid Market', Market__c = 'UK');
        Insert u;
       
        User u1 = new user(alias = 'stdt', email='test_share_record_user_2@testorg.com', emailencodingkey='UTF-8', lastname='DPSRTest', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='test_share_record_user_2@testorg.com',Segment__c = 'Mid Market', Market__c = 'UK');
        Insert u1;
       
       
        //Account Insert
       
        Account acc = new Account();
        acc.Name = 'Test Account';
        acc.AnnualRevenue = 12345;
        acc.CurrencyIsoCode = 'USD';
       
        Insert acc;
        test.starttest();   
        //Opportunity Record 1
        Opportunity opp = new Opportunity();
        opp.Name = 'Test Opp';
        opp.StageName = '7 - Contract Fully Executed';
        opp.Core_Product__c = 'Corporate Card';
        opp.Sub_Product__c = 'Gold';
        opp.Type = 'New';
        opp.CloseDate = System.now().date();
        opp.Opportunity_Market__c = 'UK';
        opp.AccountId = acc.Id;
        opp.LeadSource = 'Test';
        opp.Probability = 34;
        opp.Potential_CV_USD__c = 23;
        opp.CurrencyIsoCode = 'USD';
        opp.Commodity__c = 'Test';
       
        Insert opp;
       
        EMEA_Implementation__c imp = new EMEA_Implementation__c();
        imp.Name = 'Test imp';
        imp.Opportunity__c = opp.Id;
       
        Insert imp;
        
        imp.Share_record__c = u.Id;
       
        Update imp;
       
        imp.Share_record__c = u1.Id;
       
        Update imp;
        Test.stoptest();
    }
 

Thursday, October 16, 2014

Custom ButtonFor Standard PageLayouts

Q:In Opportunity Records when open one Record and Click on Custom Button(ConRole),
    1.it will check the any contact Role records and check the Manda troy fields,if it is ok go to next page.
    2.if no records in contact role showing error message.
Procedure: 1.Go to customization> opportunity> buttons and links>click on
                  2.click on new button>button name>s--->>
                  3.Behavior = Execute Javascript and Content source=Onclick Javascript

               4.copy the below code and past  and save.
              5.Goto>opportunity page layouts>> click on buttons>> drog conrole button and past it in custom buttons and save 
==============================JavaScript====================
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/19.0/apex.js")}

var oppcontactrole = sforce.connection.query("SELECT Id, ContactId,Contact.Name,Contact.Title,Contact.MailingStreet,Contact.MailingCity,Contact.MailingState,Contact.MailingCountry,Contact.MailingPostalCode,Contact.Email FROM OpportunityContactRole where OpportunityId = '{!Opportunity.Id}'");

var contactRecord,flag=0; 
var nullCheck = 'Please enter mandatory fields Title,Complete Mailing Address and Email on following contact(s)\n';


for(i=0;i<oppcontactrole.size;i++)
{
contactRecord = oppcontactrole.getArray("records")[i];

if(contactRecord.Contact.Title == null || contactRecord.Contact.MailingStreet == null || contactRecord.Contact.MailingCity == null || contactRecord.Contact.MailingState == null || contactRecord.Contact.MailingCountry == null || contactRecord.Contact.MailingPostalCode == null || contactRecord.Contact.Email == null)
{
flag = 1;
nullCheck+= contactRecord.Contact.Name+'\n';
}
}

if ( oppcontactrole.size == 0)
{
alert("You don't have contact role for related opportunity");
}
else if(flag == 1)
{
alert(nullCheck);
}
else
{
navigateToUrl("/apex/contactspage?Id={!Opportunity.Id}");

}

Test Class for if and else conditions and fetching id from current VF page..

          =================CONTROLLER=======================
Public Class ifelsecondition {
// We can get the id from when click on Button
    public ID impId = ApexPages.currentPage().getParameters().get('id');
   
    public Id getImpId()
    {
        return impId;
    }
      
    public PageReference autoRun()
    {
   
       
        System.debug('    #### This is implementation ID' + impId );
        account tmpimp = [select name,phone from account where ID =: impId ];
              
   
               
        anotherclass  testimp = new WebServiceGCTImplementationclass();
        testimp.sfdcRequest();
        return postProcessing();
       
    }
   
    public PageReference postProcessing()
    {
        account imp = [select Name, phone,Rating from account where ID =:impId];
        if((imp.phone == null)|| (imp.phone != 'Success')){
            String errmsg = '';
            if (imp.phone == null)
            {
                errmsg = 'There was an error contacting GCT.  Please contact your administrator. (Implementation Name:'+imp.Name+')';
            }
            else
            {
                errmsg = 'There was an error: '+imp.phone+' : '+imp.GCT_Status__c ;
            }
            Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR,
                        errmsg ));
           
            return null;
        }       
        PageReference pageRef = new PageReference('/'+impId);
        pageRef.setRedirect(true);
        return pageRef;        
    }   
   
    
    public PageReference autoRun_EMEA()
    {
   
       
        System.debug('    #### This is implementation ID' + impId );
        opportunity tmpimp = [select Opportunity__c from opportunity where ID =: impId ];
              
   
               
        GCTWebserviceCallController populateService = new GCTWebserviceCallController();
        populateService.sendImpDetails();
        return postProcessing_EMEA();
       
    }
   
    public PageReference postProcessing_EMEA()
    {
        opportunity imp = [select Name, mobile,status from opportunity where ID =:impId];
        String errmsg = '';
        System.debug('***imp.phone '+imp.mobile);
        if((imp.mobile == null)
                || (imp.mobile != 'Success'))
        {
            //String errmsg = '';
            if (imp.mobile == null)
            {
                errmsg = 'There was an error contacting GCT.  Please contact your administrator. (Implementation Name:'+imp.Name+')';
            }
            else
            {
                errmsg = 'There was an error: '+imp.mobile+' : '+imp.status;
            }
            Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR,
                        errmsg ));
           
            return null;
        } 
           
        PageReference pageRef = new PageReference('/'+impId);
        pageRef.setRedirect(true);
        return pageRef;        
    }   
}
================Test Class===========================================
@isTest(SeeAllData=true)
Public Class TestclassForifelsecondition                   
{
     public static Id Imp1;
     public static  Id EMEA;
     public static string error='';
     public static testMethod void autorun(){
     // here we hard code one id from records and put in get('id') is same as in put('id')
   //                                                                                   
       ApexPages.currentPage().getParameters().put('id', 'a0NA0000001qKT9MAM');
       system.debug('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'+Imp1);
       ifelsecondition cond = new ifelsecondition ();
       cond .getImpId();
       cond .autorun();
     }
     public static testMethod void autoRun_EMEA(){
        EMEA= ApexPages.currentPage().getParameters().put('id', 'a3uK00000000ZxXIAU');
        system.debug('######################################################'+EMEA);
        ifelsecondition cond = new ifelsecondition ();
        cond .autoRun_EMEA();
     }
     public static testMethod void postProcessing(){
       
        ApexPages.currentPage().getParameters().put('id', 'a0NA0000001qKT9MAM');
        ifelsecondition cond = new ifelsecondition ();
        cond .postProcessing();
       
     }
     public static testMethod void postProcessing_EMEA(){
        ApexPages.currentPage().getParameters().put('id', 'a3uK00000000aGAIAY');
        ApexPages.currentPage().getParameters().put('id', 'a3uA0000000EJMQIA4');
        ifelsecondition cond = new ifelsecondition ();
        cond .postProcessing_EMEA();
     }
  
}

Friday, October 10, 2014

Trigger After Update

  when Opportunint changing  stage 5 to 6 it is check the status records if status is not have the record send error message to create a status record if record is available check the status1 is completed,if status is not completed give error message  

 

trigger Checkingfulfillmentobjectstatus on Opportunity (after update) {
      system.debug('9999999999999999999999999999999999999999999999999');
     List<Opportunity> Oppfulfillment= new List<Opportunity>();
     List<status__c> fulfillmentRecords=new List<status__c>();
     if(Trigger.Isupdate){
         for(opportunity newRecords:Trigger.new){
               for(Opportunity oldRecords:Trigger.old){
                      system.debug('###################################'+oldRecords);
                      fulfillmentRecords=[select id,name,Status1__c from status__c where Opportunity__r.id =:oldRecords.id];
                      system.debug('List of Records in fulfillment object associated with opportunity @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'+fulfillmentRecords);
                      if(fulfillmentRecords.size()>0){
                          if(oldRecords.stagename=='5' && newRecords.stagename=='6'){
                               for(status__c ffm:fulfillmentRecords){
                                      if(ffm.Status1__c=='Completed'){
                                      } else if(ffm.Status1__c=='In Progress'){
                                       trigger.new.addError('status in Progress');
                                      }
                                  
                                }// end of for loop checking the fulfilment object
                           } 
                      } else{
                          Trigger.new.addError('Create New Record for status object');
                        }
                  
                              
               }// End of Trigger.old
           
          } //End of Trigger.new for loop              
     }// End of If IsUpdate
}

Thursday, October 9, 2014

Validation Rules.............

1.email_format ::

                   AND(DM_EMAIL__c!=NULL,NOT(REGEX( DM_EMAIL__c , "([A-Za-z0-9_\\-\\.])+@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]){2,3}")))


2.Nocommainmailingaddressline::

            CONTAINS( Mailing_Address_Line1__c , ",")

3.No Special Character In Name ::

      CONTAINS(Name, ",") || CONTAINS(Name, "@") || CONTAINS(Name, "#") || CONTAINS(Name, "*") || CONTAINS(Name, "+") || CONTAINS(Name, "=") || CONTAINS(Name, "{") || CONTAINS(Name, "<") || CONTAINS(Name, ">") || CONTAINS(Name, ":") || CONTAINS(Name, ";") || CONTAINS(Name, "~") || CONTAINS(Name, "`") || CONTAINS(Name, "}") || CONTAINS(Name, "[") || CONTAINS(Name, "]") || CONTAINS(Name, "'")|| CONTAINS(Name, "'")