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
rohitash yadavrohitash yadav 

Optimize apex class

Hi

I write a apex class to insert objects/child objects. This class is called through rest api in php.
 
@RestResource(urlMapping='/FieldCase/*')
global with sharing class RESTCaseController {
    @HttpPost
    global static string updateCase() {
        String requestBody = RestContext.request.requestBody.toString();

        Map<String, Object> root = (Map<String, Object>)JSON.deserializeUntyped(requestBody);
        List<Object> records = (List<Object>)root.get('records');
        List<Lead> totLeads = new List<Lead>();
        List<Opportunity> totOppor = new List<Opportunity>();
		for (Object record : records) {
            Map<String, Object> i = (Map<String, Object>)record;
            Map<String, Object> item = (Map<String, Object>)i.get('quote');
			Quote__c[] exQuote = [Select ID, Quote_no__c from Quote__c where Site_Quote_Id__c =:Integer.valueof(item.get('id')) LIMIT 1];
            if(exQuote.size() == 0){
                // check account and create if not exists
                Map<String, Object> accountData = (Map<String, Object>)i.get('accountData');
                Id quoteAccountId = null;
				quoteAccountId = createAccount(accountData);
                system.debug('quoteAccountId=='+quoteAccountId);

                Map<String, Object> contactData = (Map<String, Object>)i.get('contactData');
                ID quoteContactId = null;
				quoteContactId = createContact(contactData,quoteAccountId);
                system.debug('quoteContactId=='+quoteContactId);

                // insert quote
                Map<String, Object> quoteData = (Map<String, Object>)i.get('quote');
                //Object quoteData = (Object)i.get('quote');
                Quote__c qut = new Quote__c();
                Id quoteId = NULL;
                qut.Account__c = quoteAccountId;
                qut.Contact__c = quoteContactId;
                qut.Created_Date__c = DateTime.Valueof((String)quoteData.get('created_date')); // (Datetime)quoteData.get('created_date');
                if(Integer.valueof(quoteData.get('quote_print')) == 1)
                	qut.Printed__c = true;

                if(Integer.valueof(quoteData.get('quote_emb')) == 1)
                	qut.Embr__c = true;

                if(Integer.valueof(quoteData.get('quote_digi')) == 1)
                	qut.digi__c = true;

                if(Integer.valueof(quoteData.get('quote_trans')) == 1)
                	qut.Transfer__c = true;

                if(Integer.valueof(quoteData.get('quote_names')) == 1)
                	qut.Names__c = true;

                if(Integer.valueof(quoteData.get('user_exists')) == 1)
                	qut.Existing_user__c = true;
                else
                    qut.New_User__c = true;

				qut.Name = (String)quoteData.get('quote_no');
                qut.Quote_no__c = Integer.valueof(quoteData.get('quote_no'));

                Contact[] salespr = [Select ID, Name from Contact where Site_User_Id__c =:Integer.valueof(quoteData.get('assigned_staff_id')) LIMIT 1];
                if(salespr.size() >= 0)
					qut.Sales_person__c = salespr[0].ID;

				qut.Shirts__c = Integer.valueof(quoteData.get('tot_qty'));
                qut.Site_Quote_Id__c = Integer.valueof(quoteData.get('id'));
                qut.Site_Quote_Parent_Id__c = Integer.valueof(quoteData.get('parent_quote_id'));
                qut.Value__c = Integer.valueof(quoteData.get('value'));
                insert qut;
				quoteId = qut.Id;

                if( Integer.valueof(quoteData.get('user_orderd_before')) == 0 ){
                    // check or create leads
                    Lead[] exLeads = [Select ID, Site_Quote_Id__c from Lead where Site_Quote_Id__c =:Integer.valueof(item.get('id')) LIMIT 1];
					if(exLeads.size() == 0){
                        Lead ld = new Lead();
                        ld.Email = (String)quoteData.get('email');
                        ld.First_Name__c = (String)quoteData.get('first_name');
                        ld.Last_Name__c = (String)quoteData.get('family_name');
                        ld.Status = 'Open - Not Contacted';
                        ld.Phone = (String)quoteData.get('telephone');
                        ld.LeadSource = 'Web';
                        ld.Opportunity_Amount__c = Integer.valueof(quoteData.get('value'));
                        ld.Account__c = quoteAccountId;
                        if(salespr.size() >= 0)
							ld.Sales_person__c = salespr[0].ID;
                        
                        ld.Site_Quote_Id__c = Integer.valueof(quoteData.get('id'));
                        ld.Site_quote_no__c = Integer.valueof(quoteData.get('quote_no'));
                        ld.Site_User_Id__c = Integer.valueof(quoteData.get('user_id'));
                        ld.Quantity__c = Integer.valueof(quoteData.get('tot_qty'));
                        if(Integer.valueof(quoteData.get('quote_print')) == 1)
                            ld.Printed__c = true;
        
                        if(Integer.valueof(quoteData.get('quote_emb')) == 1)
                            ld.Embroidery__c = true;
        
                        if(Integer.valueof(quoteData.get('quote_digi')) == 1)
                            ld.Digital__c = true;
        
                        if(Integer.valueof(quoteData.get('quote_trans')) == 1)
                            ld.Transfer__c = true;
        
                        if(Integer.valueof(quoteData.get('quote_names')) == 1)
                            ld.Names__c = true;
        
                        if(Integer.valueof(quoteData.get('user_exists')) == 1)
                            ld.Existing_user__c = true;
                        else
                            ld.New_User__c = true;
                        
                        //ld.User_Activated__c
                        ld.Is_Ordered__c = false;
                        if(Integer.valueof(quoteData.get('is_ordered')) == 1)
                            ld.Is_Ordered__c = true;
                        totLeads.add(ld);
						//insert ld;
                    }
                } else {
                    // check or create opportunity
                    Opportunity[] exOppor = [Select ID, Site_Quote_Id__c from Opportunity where Site_Quote_Id__c =:Integer.valueof(item.get('id')) LIMIT 1];
            		if(exOppor.size() == 0){
                        Opportunity oppor = new Opportunity();
                        oppor.Name = 'Quote no. '+(String)quoteData.get('quote_no');
                        oppor.AccountId = quoteAccountId;
                        oppor.Contact__c = quoteContactId;
                        oppor.CloseDate = Date.Valueof((String)quoteData.get('created_date')).addDays(30);
                        oppor.LeadSource = 'Web';
                        oppor.TotalOpportunityQuantity = Integer.valueof(quoteData.get('tot_qty'));
                        oppor.Site_Quote_Id__c = Integer.valueof(quoteData.get('id'));
                        oppor.Site_Salesperson_Id__c = Integer.valueof(quoteData.get('assigned_staff_id'));
                        oppor.StageName = 'Proposal/Price Quote';
                        oppor.Amount = Integer.valueof(quoteData.get('value'));
                        if(salespr.size() >= 0)
							oppor.Sales_person__c = salespr[0].ID;
                        totOppor.add(oppor);
                        //insert oppor;
                    }
                }

                // inserting quote products
                List<Object> quoteProducts = (List<Object>)quoteData.get('quoteProducts');

                for (Object quoteProduct : quoteProducts) {
                    Map<String, Object> p = (Map<String, Object>) quoteProduct;
                    // insert quote products
                    saveQuoteProduct(p,quoteId);
                }
            }
        }
        insert totLeads;
        insert totOppor;
        return 'data';
    }

    private static Void saveQuoteProduct(Map<String, Object> quoteProductData,Id quoteId){
        Id quoteProductId = null;
        Quote_Products__c qp = new Quote_Products__c();
        if(Integer.valueof(quoteProductData.get('brand_id')) != 0){
            Brand__c[] brand = [Select Id from Brand__c where Brand_Site_Id__c =:Integer.valueof(quoteProductData.get('brand_id')) LIMIT 1];
            if(brand.size() > 0)
                qp.Brand__c = brand[0].Id;
        }
        qp.Customised_Colour_hex_value__c = (String)quoteProductData.get('customised_colour_hex');
        qp.Customised_Colour_name__c = (String)quoteProductData.get('customised_colour_name');
        qp.Plain_Item__c = false;
        if(Integer.valueof(quoteProductData.get('plain_item')) == 1)
            qp.Plain_Item__c = true;
        
        if(Integer.valueof(quoteProductData.get('product_category_id')) != 0){
            qp.Site_Category_Id__c = Integer.valueof(quoteProductData.get('product_category_id'));
            Product_Category__c[] prdcat = [Select Id from Product_Category__c where Site_Category_Id__c =:Integer.valueof(quoteProductData.get('product_category_id')) LIMIT 1];
            if(prdcat.size() > 0)
                qp.Product_Category__c = prdcat[0].Id;
        }
        
        qp.Product_Code__c = (String)quoteProductData.get('pencarrie_lnLine');
        qp.Name = qp.Product_Name__c = (String)quoteProductData.get('name');
        if(Integer.valueof(quoteProductData.get('root_category_id')) != 0){
            qp.Site_Root_Category_Id__c = Integer.valueof(quoteProductData.get('root_category_id'));
            Product_Category__c[] prdrootcat = [Select Id from Product_Category__c where Site_Category_Id__c =:Integer.valueof(quoteProductData.get('root_category_id')) LIMIT 1];
            if(prdrootcat.size() > 0)
                qp.Product_Root_Category__c = prdrootcat[0].Id;
        }
        
        qp.Quote__c = quoteId;
        qp.Site_Brand_Id__c = Integer.valueof(quoteProductData.get('brand_id'));
        qp.Site_Customised_Colour__c = Integer.valueof(quoteProductData.get('customised_colour'));
        qp.site_quote_id__c = Integer.valueof(quoteProductData.get('quote_id'));
        qp.Site_Quote_Product_Id__c = Integer.valueof(quoteProductData.get('product_id'));
        qp.Site_SessionKey__c = Integer.valueof(quoteProductData.get('sessionKey'));
        qp.tot_qty__c = Integer.valueof(quoteProductData.get('total_qty'));

        insert qp;
        quoteProductId = qp.Id;
		// insert quote product sizes

        List<Object> quoteProductSizesNew = (List<Object>)quoteProductData.get('productSizes');
        List<Quote_Product_Size__c> totqps = new List<Quote_Product_Size__c>();
        for (Object quoteProductSize : quoteProductSizesNew) {
            Map<String, Object> quotePrdSizeData = (Map<String, Object>) quoteProductSize;
            // insert quote products
            Quote_Product_Size__c qps = new Quote_Product_Size__c();
            qps = saveQuoteProductSize(quotePrdSizeData,quoteId,quoteProductId);
            totqps.add(qps);
        }
        insert totqps;

        if( !qp.Plain_Item__c ){
            Map<String, Object> data = (Map<String, Object>) quoteProductData.get('data');
            List<Object> quoteProductPositions = (List<Object>)data.get('positions');
            List<Quote_Product_Positions__c> totqpp = new List<Quote_Product_Positions__c>();
            for (Object quoteProductPosition : quoteProductPositions) {
                Map<String, Object> quoteProductPositionData = (Map<String, Object>) quoteProductPosition;
                // insert quote products positions
                Quote_Product_Positions__c qpp = new Quote_Product_Positions__c();
                qpp = saveQuoteProductPosition(quoteProductPositionData,quoteId,quoteProductId);
                totqpp.add(qpp);
            }
            insert totqpp;
        }
        //return qp.Id;
    }

    private static Quote_Product_Size__c saveQuoteProductSize(Map<String, Object> quoteProductSizeData,Id quoteId,Id quoteProductId){
        Quote_Product_Size__c qps = new Quote_Product_Size__c();
        qps.Quantity__c = Integer.valueof(quoteProductSizeData.get('qty'));
        qps.Quote_Id__c = quoteId;
        qps.Name = (String)quoteProductSizeData.get('description');
        qps.Quote_Products__c = quoteProductId ; //Integer.valueof(quoteProductSizeData.get('quoteProductId'));
        qps.Site_Quote_Id__c = Integer.valueof(quoteProductSizeData.get('quote_id'));
        qps.Quote_Products__c = quoteProductId;
        qps.Site_Quote_Product_Id__c = Integer.valueof(quoteProductSizeData.get('product_id'));
        qps.Site_Quote_Id__c = Integer.valueof(quoteProductSizeData.get('quote_id'));
        qps.Site_SessionKey__c = Integer.valueof(quoteProductSizeData.get('sessionKey'));
        qps.Site_Size_Id__c = Integer.valueof(quoteProductSizeData.get('size_id'));
        qps.Size_Name__c = (String)quoteProductSizeData.get('description');
        //insert qps;
        return qps;
    }
    
    private static Quote_Product_Positions__c saveQuoteProductPosition(Map<String, Object> quoteProductSizeData,Id quoteId,Id quoteProductId){
        Quote_Product_Positions__c qpp = new Quote_Product_Positions__c();
        
        qpp.Customised_Position__c = (String)quoteProductSizeData.get('customised_position_name');
        qpp.Name = (String)quoteProductSizeData.get('customised_position_name');
        qpp.Quote__c = quoteId;
        qpp.Quote_Products__c = quoteProductId;

        String customType = (String)quoteProductSizeData.get('custom_type');
        qpp.Custom_Type__c = customType;
        if( customType == 'artwork' ){
			qpp.Site_Artwork__c = (String)quoteProductSizeData.get('artwork');
            qpp.Site_ColorName__c = (String)quoteProductSizeData.get('colorName');
            qpp.Site_ColorOpt__c = (String)quoteProductSizeData.get('colorOpt');
            qpp.Site_Colorvalues__c = (String)quoteProductSizeData.get('colorValues');
        } else {
            qpp.Site_printname__c = (String)quoteProductSizeData.get('printname');
            qpp.Site_printNameOpt__c = (String)quoteProductSizeData.get('printNameOpt');
            qpp.Site_printnameQty__c = Integer.valueof(quoteProductSizeData.get('printnameQty'));
        }
        qpp.Site_Customised_Position__c = Integer.valueof(quoteProductSizeData.get('customised_position'));
        //qpp.Site_Num_Colour__c
        qpp.Site_positionQty__c = Integer.valueof(quoteProductSizeData.get('positionQty'));
        String print_type = (String)quoteProductSizeData.get('print_type');
        qpp.Print_Type__c = print_type;
        qpp.Site_Print_type_Option__c = print_type;
        qpp.Site_Quote_Id__c = Integer.valueof(quoteProductSizeData.get('quote_id'));
        qpp.Site_Quote_Product_Id__c = Integer.valueof(quoteProductSizeData.get('product_id'));
        qpp.Site_SessionKey__c = Integer.valueof(quoteProductSizeData.get('sessionKey'));
        //insert qpp;
        return qpp;
    }

    private static ID createAccount(Map<String, Object> accountData){
        Id quoteAccountId = null;
        if(Integer.valueof(accountData.get('Site_Company_Id__c')) != 0){
            Account[] account = [Select ID, Name from Account where Site_Company_Id__c =:Integer.valueof(accountData.get('Site_Company_Id__c')) LIMIT 1];
            if(account.size() == 0){
                Account acc = new Account();
                acc.Name = (String)accountData.get('Name');
                acc.Site_Company_Id__c = Integer.valueof(accountData.get('Site_Company_Id__c'));
                acc.Site_User_Id__c = 0;
                insert acc;
                quoteAccountId = acc.Id;
            }else{
                quoteAccountId = account[0].ID;
            }
        } else {
            Account[] account = [Select ID, Name from Account where Site_User_Id__c =:Integer.valueof(accountData.get('Site_User_Id__c')) LIMIT 1];
            if(account.size() == 0){
                Account acc = new Account();
                acc.Name = (String)accountData.get('Name');
                acc.Site_Company_Id__c = 0;
                acc.Site_User_Id__c = Integer.valueof(accountData.get('Site_User_Id__c'));
                insert acc;
                quoteAccountId = acc.Id;
            }else{
                quoteAccountId = account[0].ID;
            }
        }
    	return quoteAccountId;
    }

    private static ID createContact(Map<String, Object> contactData,Id quoteAccountId){
        ID quoteContactId = null;
        if(Integer.valueof(contactData.get('Site_User_Id__c')) != 0){
            Contact[] contact = [Select ID, Name from Contact where Site_User_Id__c =:Integer.valueof(contactData.get('Site_User_Id__c')) LIMIT 1];
            if(contact.size() == 0){
                Contact con = new Contact();
                con.Firstname = (String)contactData.get('Firstname');
                con.Lastname = (String)contactData.get('Lastname');
                con.Email = (String)contactData.get('Email');
                con.Phone = (String)contactData.get('Phone');
                con.Site_User_Id__c = Integer.valueof(contactData.get('Site_User_Id__c'));
                
                if(quoteAccountId != null)
                    con.AccountId = quoteAccountId;

                if(Integer.valueof(contactData.get('sales_person__c')) != 0 ){
                    Contact[] salcon = [Select ID, Name from Contact where Site_User_Id__c =:Integer.valueof(contactData.get('sales_person__c')) LIMIT 1];
                    if(salcon.size()>0){
                        con.sales_person__c = salcon[0].ID;
                    }
                }
                insert con;
                quoteContactId = con.Id;
            }else{
                quoteContactId = contact[0].ID;
            }
        }
        return quoteContactId;
    }
}


What I need to do optimize this class,reduce DML operations and SOQL statements? 

Thanks,
Rohitash Yadav