function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
prasanth kumar 21prasanth kumar 21 

I have requirement for Account,Contact,Oppurtunity Insertion - Rest Webservices

/**************************
* File Name     : CreateOpportunityService 
* Description   : Webservice class for creating opportunity. 
* =========================================================================== 
* Ver Date        Author                                     Modification 
* --- ---- ------ ---------------- --------------------------------------- 
* 1.0 27-Feb-2020  Kumar                              Created
*************************/ 

@RestResource(urlMapping='/opportunities')
global class CreateOpportunityService {
    public static string jsonString = '';
    @HttpPost
    global  static void Assignment(){
        RestRequest request = RestContext.request;  
        RestResponse response = RestContext.response;
        if( jsonString == '') 
        {
            Blob body = request.requestBody;
            jsonstring = body.toString();
            system.debug('.....jsonstring ...'+jsonstring);
        }
        List<JSON2Apex> recordList= (List<JSON2Apex>) System.JSON.deserialize(jsonstring, List<JSON2Apex>.class);
        system.debug('<<<apexRecords'+recordList); 
        
        
        Set<string> emailSet=new Set<String>();
        Set<String> phoneSet=new Set<String>();
        Set<String> accountIds=new Set<String>();
        Set<Integer> pids=new Set<Integer>();   
        Map<string,contact> conEmailMap=new Map<String,Contact>();
        Map<String,JSON2Apex> conJSON2ApexMap=new Map<String,JSON2Apex>();
        Map<String,list<contact>> AccountToContactMap = new Map<String,list<contact>>();
        Map<String,opportunity> OpportunityMap = new Map<String,opportunity>();
        
        Map<String,Opportunity> accOppMap=new Map<String,Opportunity>();
        List<contact> contacts=new List<contact>();
        List<Opportunity> opportunities=new List<Opportunity>();
        List<account> accounts=new List<account>();
        String result = 'Success';
        Date CloseDt = Date.today()+7;
        String Stage_Name ='Open';
        
        for(JSON2Apex js:recordList){
            if(js.email!=null){
                emailSet.add(js.email);
            }
            else if(js.phone!=null){
                phoneSet.add(js.phone);
            }
        }
        
        system.debug('<<<emailSet'+emailSet);
        system.debug('<<<phoneSet'+phoneSet);

        List<Contact> conList=[SELECT Id,firstName,lastName,Email,Phone,accountId from Contact where email IN :emailSet OR phone IN :phoneSet];
        System.debug('<<<conList'+conList);
        
        if(conList.size()>0){
            for(Contact con:conList){
                conEmailMap.put(con.email,con);
                if(con.email==null){
                    conEmailMap.put(con.phone,con);
                }
                accountIds.add(con.accountId);
            }
            List<Account> accList=[SELECT Id,name,(SELECT id,pid__c,accountId FROM opportunities) from account where id in :accountIds];
            for(account acc:accList){
                for(opportunity opp:acc.opportunities){
                    OpportunityMap.put(opp.accountId,opp);
                }
            }
        }
        
        for(JSON2Apex jsn : recordList){
            String accountId='';
            if(conEmailMap.get(jsn.email)!=null || conEmailMap.get(jsn.phone)!=null){
                if(conEmailMap.get(jsn.email)!=null){
                    accountId= conEmailMap.get(jsn.email).accountId;
                }else{
                    accountId= conEmailMap.get(jsn.phone).accountId;
                }
                if(accountId!=null){
                    if(OpportunityMap.get(accountId)!=null){
                        if(jsn.pid==OpportunityMap.get(accountId).pid__c){
                            //Update opportunity - Not Clear what to Update
                        }
                        else{
                            Opportunity opp=new opportunity();
                            opp.pid__c=jsn.pid;
                            opp.name=jsn.fname+jsn.lname+jsn.pid;
                            opp.accountId=conEmailMap.get(jsn.email).accountid;
                            opp.CloseDate = CloseDt;
                            opp.StageName =Stage_Name;
                            opportunities.add(opp);
                        }
                        
                    }
                }
                
            }
            else{
                Account acc=new Account();
                acc.name= jsn.fname+jsn.lname;
                accounts.add(acc);  
                
                Contact con=new Contact();
                con.Email = jsn.email;
                con.Phone = jsn.Phone;
                con.FirstName = jsn.fname;
                con.LastName = jsn.lname;
                contacts.add(con);
                
                opportunity opp= new opportunity();
                opp.Name = jsn.fname+jsn.lname + jsn.pid ;
                opp.pid__c=jsn.pid;
                opp.CloseDate = CloseDt;
                opp.StageName =Stage_Name;
                opportunities.add(opp);
            }
        }
        if(!accounts.isEmpty()){
            try{
                insert accounts;
            }catch(Exception e){
                result = e.getMessage();
            }
        }
        
        for(Account accTemp : accounts){
            for(contact con :contacts){
                con.accountid = accTemp.id;
            }
        }
        
        for(Account accTemp : accounts){
            for(opportunity opp :opportunities){
                opp.accountid = accTemp.id;
            }
        }
        if(!contacts.isEmpty()){
            try{
                insert contacts;
            }catch(exception e){
                result = e.getMessage();
            }
        }
        
        if(!opportunities.isEmpty()){
            try{
                insert opportunities;
            }catch(exception e){
                result = e.getMessage();
            }
        }
        
    }
    public class JSON2Apex{
        public String pid;
        public String email;
        public String phone;
        public String fname;
        public String lname;
    }
}

 
prasanth kumar 21prasanth kumar 21
Complete requirement is below - above code is working for single record and not  working for multiple records and needs code modularisation,Kindly help me

you may complete this assignment in your own developer sandbox using the standard account, contact and opportunity objects. 
create custom field pid in opportunity and make it searchable field. we will use this to match records later. 
Create a web service in salesforce that will accept a list of following data 

{pid:1, email:joe@roofstock.com, phone:510-366-2251,fname='joe',lname='bryant'}, {pid:2, email:raj@roofstock.com, phone:510-366-2252,fname='raj',lname='bryant'}, {pid:3, email:joe@roofstock.com, phone:510-366-2251,fname='joe',lname='bryant'}, {pid:null, email:sree@roofstock.com, phone:510-366-2253,fname='sree',lname='menon'}, {pid:null, email:null, phone:510-366-2253,fname='ana',lname='joshi'}, {pid:3, email:raj@roofstock.com, phone:510-366-2252,fname='raj',lname='bryant'}, 
] Web service should be able to handle multiple records and should do the following logic- 
For each message in the list - 1. if email is not empty in the message, search for an existing contact record with matching email address 2. if email is missing in the message, search for an existing contact in sfdc with matching phone number. 3. if a matching contact is found in sfdc- 
create a new opportunity in sfdc under that account , if there is no opportunity with a matching pid. if there is an opportunity in sfdc with matching pid under that account, update the existing opportunity 
4. Note you may get the same pid for other users as well. so update should be for the correct user. 5. if no matching email or phone in sfdc, create account/contact for this user and create a new opportunity record under that account for that message. 
For testing- web service should be callable from from postman or any rest client, Please include the instructions on how to call this web service and required credentials. 
Note - Code should be bulkified and should have test class with atleast 90%