• Lavanya Ponniah 3
  • NEWBIE
  • 45 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 43
    Questions
  • 22
    Replies
trigger Leaves on Staff_Leaves__c(before insert, before update) {
integer noofdays;
string half;
string full;
integer k = 0;

List < Event > listevent = new list < event > ();
map < Date, date > listholy = new map < date, date > ();
map < date, date > liststart = new map < date, date > ();
list < user > listuserupdate = new list < user > ();

if ((trigger.isbefore && trigger.isinsert) || (trigger.isbefore && trigger.isupdate)) {
  for (Staff_Leaves__c sl: trigger.new) {
   user u = [select Medical_Leave_Half__c, Hospitalisation_Half__c, Dependant_care_Half__c, Compassionate_leave_Half__c, Child_care_Half__c, Annual_Leave_Half__c, Annual_Leave__c, Child_care__c, Compassionate_leave__c, Dependant_care__c, Hospitalisation__c, Medical_Leave__c from user where id = : sl.Staff__c];

   list < event > le = [select startdatetime from event where Leave_Type__c = 'Leave'];
   for (event elist: le) {
    date da = elist.StartDateTime.date();
    liststart.put(da, da);
   }

   if (sl.Status1__c == 'Submited') {
    for (integer j = 0; j < sl.Between_Days__c; j++) {
     date date1 = sl.from__c + j;
     date date3 = sl.to__c + j;
     date date2 = date.ValueOf('2015-11-1');
     integer numberDaysDue = date2.daysBetween(date1);

     if ((listholy.containsKey(date1)) || (math.MOD(numberDaysDue, 7) == 0) || (math.MOD(numberDaysDue, 7) == 6)) {

     } else {
      k += 1;
     }
     sl.No_of_business_days1__c = k;
    }

    full = 'true';
    half = 'false';
   }
   if (sl.half_day1__C == true) {
    if ((sl.from__C.daysBetween(sl.To__c)) == 0) {
     if (liststart.containsKey(sl.From__c)) {
      sl.adderror('Leave already apply one of selected day(s)');
     } else {
      if (sl.Leave_Type__c == 'Annual Leave') {
       if (u.Annual_Leave_Half__c == 1) {
        if (u.Annual_Leave__c - sl.No_of_business_days1__c < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       } else if (u.Annual_Leave_Half__c == 0) {
        if (u.Annual_Leave__c - (sl.No_of_business_days1__c + 1) < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      } else if (sl.Leave_Type__c == 'Child care') {
       if (u.Child_care_Half__c == 1) {
        if (u.Child_care__c - sl.No_of_business_days1__c < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       } else if (u.Child_care_Half__c == 0) {
        if (u.Child_care__c - (sl.No_of_business_days1__c + 1) < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      } else if (sl.Leave_Type__c == 'Compassionate leave') {
       if (u.Compassionate_leave_Half__c == 1) {
        if (u.Compassionate_leave__c - sl.No_of_business_days1__c < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       } else if (u.Compassionate_leave_Half__c == 0) {
        if (u.Compassionate_leave__c - (sl.No_of_business_days1__c + 1) < 0) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      } else if (sl.Leave_Type__c == 'Dependant care') {
       if (u.Dependant_care_Half__c == 1) {
        if (u.Dependant_care__c < sl.No_of_business_days1__c) {
         sl.addError('You do not have enough leaves to apply');
        }
       } else if (u.Dependant_care_Half__c == 0) {
        if (u.Dependant_care__c < (sl.No_of_business_days1__c + 1)) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      } else if (sl.Leave_Type__c == 'Hospitalisation') {
       if (u.Hospitalisation_Half__c == 1) {
        if (u.Hospitalisation__c < sl.No_of_business_days1__c) {
         sl.addError('You do not have enough leaves to apply');
        }
       } else if (u.Hospitalisation_Half__c == 0) {
        if (u.Hospitalisation__c < (sl.No_of_business_days1__c + 1)) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      } else if (sl.Leave_Type__c == 'Medical Leave') {
       if (u.Medical_Leave_Half__c == 1) {
        if (u.Medical_Leave__c < sl.No_of_business_days1__c) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
       if (u.Medical_Leave_Half__c == 0) {
        if (u.Medical_Leave__c < (sl.No_of_business_days1__c + 1)) {
         sl.addError('You do not have enough leaves to apply');
        }
       }
      }
     }

     half = 'true';
     full = 'false';
     sl.Half_day__c = 1;
     sl.No_of_business_days1__c = 0;
    } else sl.adderror('Please check the dates, between days more then 1');
   } else if (sl.Half_day1__c == false) {
    if (liststart.containsKey(sl.From__c)) {
     sl.adderror('Leave already apply one of selected day(s)');
    } else {
     if (u.id == sl.Staff__c) {
      system.debug('------------------------=' + u.Annual_Leave__c);
      if (sl.Leave_Type__c == 'Annual Leave') {
       //integer in1=u.Annual_Leave__c-sl.No_of_business_days1__c;
       system.debug('...............................=' + u.Annual_Leave__c);
       system.debug('...............................=' + sl.No_of_business_days1__c);
       //system.debug('...............................=' + in1);
       if (u.Annual_Leave__c - sl.No_of_business_days1__c < 0) {
        system.debug(',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,');
        sl.addError('You do not have enough leaves to apply');
       }
      } else if (sl.Leave_Type__c == 'Child care') {
       if (u.Child_care__c < sl.No_of_business_days1__c) {
        sl.addError('You do not have enough leaves to apply');
       }
      } else if (sl.Leave_Type__c == 'Compassionate leave') {
       if (u.Compassionate_leave__c < sl.No_of_business_days1__c) {
        sl.addError('You do not have enough leaves to apply');
       }
      } else if (sl.Leave_Type__c == 'Dependant care') {
       if (u.Dependant_care__c < sl.No_of_business_days1__c) {
        sl.addError('You do not have enough leaves to apply');
       }
      } else if (sl.Leave_Type__c == 'Hospitalisation') {
       if (u.Hospitalisation__c < sl.No_of_business_days1__c) {
        sl.addError('You do not have enough leaves to apply');
       }
      } else if (sl.Leave_Type__c == 'Medical Leave') {
       if (u.Medical_Leave__c < sl.No_of_business_days1__c) {
        sl.addError('You do not have enough leaves to apply');
       }
      }
     }
    }
    list < Holiday > holy = [select ActivityDate from Holiday];
    for (Holiday h: holy) {
     date d = h.ActivityDate;
     listholy.put(d, d);
    }


   }


   if (sl.Status1__c == 'Approved') {
    if (sl.Half_day1__c == true) {
     if (sl.Leave_Type__c == 'Annual Leave') {
      if (u.Annual_Leave_Half__c == 1) {
       u.Annual_Leave__c -= sl.No_of_business_days1__c;
       u.Annual_Leave_Half__c = 0;
       update u;
      } else if (u.Annual_Leave_Half__c == 0) {
       u.Annual_Leave__c -= (sl.No_of_business_days1__c + 1);
       u.Annual_Leave_Half__c = 1;
       update u;
      }
     } else if (sl.Leave_Type__c == 'Child care') {
      if (u.Child_care_Half__c == 1) {
       u.Child_care__c -= sl.No_of_business_days1__c;
       u.Child_care_Half__c = 0;
       update u;
      } else if (u.Child_care_Half__c == 0) {
       u.Child_care__c -= (sl.No_of_business_days1__c + 1);
       u.Child_care_Half__c = 1;
       update u;
      }
     } else if (sl.Leave_Type__c == 'Compassionate leave') {
      if (u.Compassionate_leave_Half__c == 1) {
       u.Compassionate_leave__c -= sl.No_of_business_days1__c;
       u.Compassionate_leave_Half__c = 0;
       update u;
      } else if (u.Compassionate_leave_Half__c == 0) {
       u.Compassionate_leave__c -= (sl.No_of_business_days1__c + 1);
       u.Compassionate_leave_Half__c = 1;
       update u;
      }
     } else if (sl.Leave_Type__c == 'Dependant care') {
      if (u.Dependant_care_Half__c == 1) {
       u.Dependant_care__c -= sl.No_of_business_days1__c;
       u.Dependant_care_Half__c = 0;
       update u;
      } else if (u.Dependant_care_Half__c == 0) {
       u.Dependant_care__c -= (sl.No_of_business_days1__c + 1);
       u.Dependant_care_Half__c = 1;
       update u;
      }
     } else if (sl.Leave_Type__c == 'Hospitalisation') {
      if (u.Hospitalisation_Half__c == 1) {
       u.Hospitalisation__c -= sl.No_of_business_days1__c;
       u.Hospitalisation_Half__c = 0;
       update u;
      } else if (u.Hospitalisation_Half__c == 0) {
       u.Hospitalisation__c -= (sl.No_of_business_days1__c + 1);
       u.Hospitalisation_Half__c = 1;
       update u;
      }
     } else if (sl.Leave_Type__c == 'Medical Leave') {
      if (u.Medical_Leave_Half__c == 1) {
       u.Medical_Leave__c -= sl.No_of_business_days1__c;
       u.Medical_Leave_Half__c = 0;
       update u;
      }
      if (u.Medical_Leave_Half__c == 0) {
       u.Medical_Leave__c -= (sl.No_of_business_days1__c + 1);
       u.Medical_Leave_Half__c = 1;
       update u;
      }
     }

     event eve = new event();
     eve.Subject = sl.Leave_Type__c;
     eve.StartDateTime = datetime.newInstance((sl.To__c).year(), (sl.To__c).month(), (sl.To__c).day()).addhours(8);
     eve.endDateTime = datetime.newInstance((sl.from__c).year(), (sl.from__c).month(), (sl.from__c).day()).addhours(17);
     eve.DurationInMinutes = null;
     eve.Leave_Type__c = 'Leave';
     insert eve;
    }


    if (sl.Half_day1__c == false) {
     if ((sl.Leave_Type__c == 'Annual Leave') && (u.Annual_Leave__c > 0)) {
      u.Annual_Leave__c -= sl.No_of_business_days1__c;
      update u;
     } else if ((sl.Leave_Type__c == 'Child care') && (u.Child_care__c > 0)) {
      u.Child_care__c -= sl.No_of_business_days1__c;
      update u;
     } else if ((sl.Leave_Type__c == 'Compassionate leave') && (u.Compassionate_leave__c > 0)) {
      u.Compassionate_leave__c -= sl.No_of_business_days1__c;
      update u;
     } else if ((sl.Leave_Type__c == 'Dependant care') && (u.Dependant_care__c > 0)) {
      u.Dependant_care__c -= sl.No_of_business_days1__c;
      update u;
     } else if ((sl.Leave_Type__c == 'Hospitalisation') && (u.Hospitalisation__c > 0)) {
      u.Hospitalisation__c -= sl.No_of_business_days1__c;
      update u;
     } else if ((sl.Leave_Type__c == 'Medical Leave') && (u.Medical_Leave__c > 0)) {
      u.Medical_Leave__c -= sl.No_of_business_days1__c;
      update u;
     }

     integer q = -1;
     for (integer a = 0; a < sl.Between_Days__c / 14; a++) {
      integer b = 0;
      system.debug('-------------integer =' + b);
      for (b = 0; b < 14; b++) {
       q += 1;
       if (q < sl.Between_Days__c) {
        event eve = new event();
        eve.Subject = sl.Leave_Type__c;
        eve.StartDateTime = datetime.newInstance((sl.To__c).year(), (sl.To__c).month(), (sl.To__c).day() + q).addhours(8);
        eve.endDateTime = datetime.newInstance((sl.to__c).year(), (sl.to__c).month(), (sl.to__c).day() + q).addhours(17);
        eve.DurationInMinutes = null;
        eve.Leave_Type__c = 'Leave';
        listevent.add(eve);
       }
       system.debug('------------- b=' + b);
      }
     }
     if (listevent.size() > 0) {
      insert listevent;
     }
     listevent.clear();
    }
   }
  }
}
}


Test Class:
@istest
public class TestLeaves
{
static testmethod void  testLeaves1()
    {
        map<Date,date> listholy=new map<date,date>();
          Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
       
        User u = new User(
            Alias = 'Anusiah',
         Email='swarna@ideallsf.com',
            EmailEncodingKey='General US & Western Europe (ISO-8859-1, ISO-LATIN-1)',
            LastName='Anusiah',
         LanguageLocaleKey='English',
            LocaleSidKey='en_US',
         ProfileId = p.Id ,
            TimeZoneSidKey='English (Singapore)',
         UserName='admin@dpa.org.sg.dpa',
         Medical_Leave_Half__c=2,
         Hospitalisation_Half__c=1,
         Dependant_care_Half__c=1,
         Compassionate_leave_Half__c=1,
         Child_care_Half__c=1,
         Annual_Leave_Half__c=1,
         Annual_Leave__c=1,
         Child_care__c=1,
         Compassionate_leave__c=1,
         Dependant_care__c=1,
         Hospitalisation__c=1,
         Medical_Leave__c=1);
       
       
        Staff_Leaves__c  sl=new Staff_Leaves__c ();
         sl.Leave_Type__c='Medical Leave';
         sl.to__c=date.today();
         sl.from__c=date.today();
         sl.Staff__c=u.id;
         sl.Half_day1__c=true;
         sl.Test__c='Approved';
         sl.Staff__c='005200000010IK0AAM';
        insert sl;
       
       
       event eee=new event();
         eee.Subject=sl.Leave_Type__c;
            eee.StartDateTime=date.today();
            eee.endDateTime=date.today();
            eee.DurationInMinutes= null;
            eee.Leave_Type__c='Leave';
        insert eee;
       
        Holiday h1=new Holiday(ActivityDate=date.today()+5, Name='test');
        
   
       
        list<Holiday> holy=[select ActivityDate from Holiday where ActivityDate=:date.today()+5];
        for(Holiday h:holy)
        {
            date d=h.ActivityDate;
          listholy.put(d,d); 
        }
       
       test.startTest();
        
         for(integer j=0;j<sl.Between_Days__c;j++)
         {
              date date1=sl.Start__c.date()+j;
              date date3=sl.end__c.date()+j;
              date date2= date.ValueOf('2015-11-1');
              integer numberDaysDue = date2.daysBetween(date1);
                integer k=0;
              
             if((listholy.containsKey(date1)) || (math.MOD( numberDaysDue,7)==0 ) ||(math.MOD( numberDaysDue,7)==6 ))
             {
                      
             }
                else
              {
                  k+=1;
              }
                sl.No_of_business_days1__c=k;
            }
            
              
        
         user u1=[select Medical_Leave_Half__c,Hospitalisation_Half__c,Dependant_care_Half__c,Compassionate_leave_Half__c,Child_care_Half__c,Annual_Leave_Half__c,Annual_Leave__c,Child_care__c,Compassionate_leave__c,Dependant_care__c,Hospitalisation__c,Medical_Leave__c from user where id =:'005200000010IK0AAM'];           
         system.assertEquals(u1.id, sl.Staff__c);
         event le=[select startdatetime from event where Leave_Type__c='Leave'];
          
       test.stopTest();
    }
   
It is covering only 19% 40 lines.
}
trigger trgCreateExpenseOnEventCompletion on Event (before insert, before update)
{
    Set<Id> setOwnerId = new Set<Id>();
    Set<Date> setNewDates = new Set<Date>();
    Set<Date> setExistingDates = new Set<Date>();
    
    List<Expense__c> lstExpense = new List<Expense__c>();
    
    if(Trigger.isBefore && Trigger.isInsert)
    {
        for(Event objEvent : Trigger.New)
        {
            if(objEvent.StartDateTime != Null)
            {
                setNewDates.add(objEvent.StartDateTime.Date());
                setOwnerId.add(objEvent.OwnerId);
            }
        }
        
        if(setNewDates != Null && setNewDates.size() > 0)
        {
            List<Event> lstTempEvent = [select Id, ActivityDate from Event where IsAllDayEvent = true AND ActivityDate IN : setNewDates AND OwnerId IN : setOwnerId AND Subject = 'Out Of Office' AND Status__c != 'Deferred' LIMIT 1];
            
            system.debug('test' + lstTempEvent);
            
            if(lstTempEvent != Null && lstTempEvent.size() > 0)
            {
                for(Event objEvent : lstTempEvent)
                {
                    setExistingDates.add(objEvent.ActivityDate);
                }
            }
        }
    }

    for(Event objEvent : Trigger.New)
    {
        if(setExistingDates.size() > 0 && setExistingDates.contains(objEvent.StartDateTime.Date()))
        {
            objEvent.addError('Sorry! You cant create an event for this date as you are on leave...');
        }
        else
        {
            String AccountId = '';
            
            if(objEvent.WhatId != Null)
            {
                AccountId = objEvent.WhatId;
            }
            
            if( objEvent.Status__c == 'Completed' && objEvent.Expense_Created__c != true && objEvent.Subject != 'Phone Call' && objEvent.Total_Expense__c > 0)
            {
                List<Sales_Representative__c> lstSalesRep = [select Id from Sales_Representative__c where Representative_Name__c =: objEvent.OwnerId];
                
                if(lstSalesRep.size() > 0)
                {
                    objEvent.Expense_Created__c = true;
                    
                    RecordType objRT = [select Id from RecordType where Name = 'Auto Created'];
                    
                    Expense__c objExpense = new Expense__c();
                    
                    objExpense.Activity_Performed__c = objEvent.Subject;
                    objExpense.Activity_Status__c = objEvent.Status__c;
                    objExpense.Entertainment_Expense__c = objEvent.Entertainment_Expense__c;
                    if(objEvent.End_DateTime__c != Null)
                    {
                        objExpense.Expense_Date__c = objEvent.End_DateTime__c.Date();
                    }
                    else
                    {
                        objExpense.Expense_Date__c = objEvent.EndDateTime.Date();
                    }
                    objExpense.Expense_Status__c = 'Created';
                    objExpense.Other_Expense__c = objEvent.Other_Expense__c;
                    objExpense.Parking_Expense__c = objEvent.Parking_Expense__c;
                    
                    objExpense.Sales_Representative__c = lstSalesRep[0].Id;
                    objExpense.Toll_Expense__c = objEvent.Toll_Expense__c;
                    objExpense.Total_Travel_Expense__c = objEvent.Total_Travel_Expense__c;
                    objExpense.RecordTypeId = objRT.Id;
                    
                    lstExpense.add(objExpense);
                }
            }
        }
    }
    
    if(lstExpense.size() > 0)
    {
        insert lstExpense;
    }
    
    if(Trigger.isBefore && Trigger.isUpdate)
    {
        for(Event objEvent : Trigger.New)
        {
            String AccountId = '';
        
            if(objEvent.WhatId != Null)
            {
                AccountId = objEvent.WhatId;
            }
            
            if(AccountId != '' &&  AccountId.substring(0,3) == '001' &&  objEvent.Status__c == 'Deferred' && Trigger.oldMap.get(objEvent.Id).Status__c != 'Deferred')
            {
                if(objEvent.Owner_Manager_Email__c != Null)
                {
                    try
                    {
                        Account objAccount = [select Id, Name from Account where Id =: AccountId];
                                         
                        List<String> toAddress = new List<String>();
                        List<String> bccAddress = new List<String>();
                                        
                        toAddress.add(objEvent.Owner_Manager_Email__c);   
                        //toAddress.add('ashish.jain@saasfocus.com');  
                        bccAddress.add('ashish.jain@saasfocus.com');
                            
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(toAddress);
                        mail.setBccAddresses(bccAddress);
                        
                        mail.setSubject('Activity Deferred');
                            
                        string strBody = '<br/><font style=\"font-family:arial; font-size:16px;\"> <br/><br/><br/>An activity has been deferred by ' + objEvent.Owner_Name__c + '.<br/><br>Following are the details of the activity : </font><br/><br/><br/>';
                        
                        strBody += '<b>Dealer Name - </b>' + objAccount.Name + '<br/><br/><b>Start DateTime - </b>' + objEvent.StartDateTime + '<br/><br/><b>End DateTime - </b>' + objEvent.EndDateTime + '<br/><br/>';
                        
                        strBody +=  '<br/><br/><b>Start DateTime - </b>' + objEvent.StartDateTime + '<br/><br/><b>End DateTime - </b>' + objEvent.EndDateTime + '<br/><br/>';
                        
                        strBody += '<a href=\"https://cs6.salesforce.com/' + objEvent.Id + '\" >Click to open the activity</a>';
                        strBody += '<br/><br/><br/>Thanks<br/><br/>Falken Tyres';
                        
                        mail.setHtmlBody(strBody);
                            
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                        
                    }
                    catch(Exception e)
                    {
                    }
                }
            }
            else if(AccountId != '' && AccountId.substring(0,3) != '001' && objEvent.Status__c == 'Deferred' && Trigger.oldMap.get(objEvent.Id).Status__c != 'Deferred')
            {
                if(objEvent.Owner_Manager_Email__c != Null)
                {
                    try
                    {
                        List<String> toAddress = new List<String>();
                        List<String> bccAddress = new List<String>();
                                        
                        toAddress.add(objEvent.Owner_Manager_Email__c);   
                        //toAddress.add('ashish.jain@saasfocus.com');  
                        bccAddress.add('ashish.jain@saasfocus.com');
                            
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(toAddress);
                        mail.setBccAddresses(bccAddress);
                        
                        mail.setSubject('Activity Deferred');
                            
                        string strBody = '<br/><font style=\"font-family:arial; font-size:16px;\"> <br/><br/><br/>An activity has been deferred by ' + objEvent.Owner_Name__c + '.<br/><br>Following are the details of the activity : </font><br/><br/><br/>';
                        
                        strBody +=  '<br/><br/><b>Start DateTime - </b>' + objEvent.StartDateTime + '<br/><br/><b>End DateTime - </b>' + objEvent.EndDateTime + '<br/><br/>';
                        strBody += '<a href=\"https://cs6.salesforce.com/' + objEvent.Id + '\" >Click to open the activity</a>';
                        strBody += '<br/><br/><br/>Thanks<br/><br/>Falken Tyres';
                        
                        mail.setHtmlBody(strBody);
                            
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
                        
                    }
                    catch(Exception e)
                    {
                    }
                }
           }
       }
    }
}
I need assistance with the below trigger, the line which i bold and underlined.When i insert bulk record using dataloader.io for all records v.Pending_Hardware_Installations_Order__c = ordr.Left_Hardware__c; is to reflect the updated ordr.Left_Hardware__c ,but for all records its not reflecting the updated ordr.Left_Hardware__c to the v.Pending_Hardware_Installations_Order__c .
trigger InstalledHardware on Vehicle_Details__c (before insert)
{
    Set<Id> setOrderIds = new Set<Id>();
    Map<Id,Order> mapIdWithOrder = new Map<Id,Order>();
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null){
           setOrderIds.add(v.Order__c); 
        }
    }
    if(!setOrderIds.isEmpty()){
        for(Order ordr :[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id IN :setOrderIds]){
            mapIdWithOrder.put(ordr.Id,ordr);    
        }
    }
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null && mapIdWithOrder != null && mapIdWithOrder.get(v.Order__c) != null){
           Order ordr = mapIdWithOrder.get(v.Order__c);
           v.Pending_Hardware_Installations_Order__c = ordr.Left_Hardware__c;
           v.Total_Hardware_Quantity_for_Order__c = ordr.Total_Hardware_Type_Ordered_Products__c; 
           ordr.Finished_HardWare__c = ordr.Finished_HardWare__c + V.Total_Hardware_Installed__c;
           mapIdWithOrder.put(v.Order__c,ordr)
        }
    }
    if(mapIdWithOrder.values().size() > 0)
    {
        update mapIdWithOrder.values();
    }
}
I am getting error ERROR: InstalledHardware: execution of BeforeInsertcaused by: System.ListException: Duplicate id in list: 801O00000003HOIIA2Trigger.InstalledHardware: line 32, column 1

trigger InstalledHardware on Vehicle_Details__c (before insert)
{
    list<Order> listup=new list<Order>();
    Set<Id> setOrderIds = new Set<Id>();
    Map<Id,Order> mapIdWithOrder = new Map<Id,Order>();
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null){
           setOrderIds.add(v.Order__c); 
        }
    }
    if(!setOrderIds.isEmpty()){
        for(Order ordr :[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id IN :setOrderIds]){
            mapIdWithOrder.put(ordr.Id,ordr);    
        }
    }
    for(Vehicle_Details__c V:trigger.new){
        if(v.Order__c != null && mapIdWithOrder != null && mapIdWithOrder.get(v.Order__c) != null){
           Order ordr = mapIdWithOrder.get(v.Order__c);
           v.Pending_Hardware_Installations_Order__c = ordr.Left_Hardware__c;
           v.Total_Hardware_Quantity_for_Order__c = ordr.Total_Hardware_Type_Ordered_Products__c; 
           ordr.Finished_HardWare__c = ordr.Finished_HardWare__c + V.Total_Hardware_Installed__c;
           listup.add(ordr);
        }
    }
    
    if(listup.size() > 0)
    {
        update listup;
    }
}
I have  objects Application_Members__c and Contact.If the contact Name = App.SurName + App.FirstName,in the contact con.FirstName=App.FirstName and con.LastName=App.SurName.
How to update using developer console by code. I tried below code but i get error.

List<Contact> c = new List<Contact>();
List<contact> con = [select Name, FirstName, LastName, RecordType.name from Contact];
List<Application_Members__c> ap = [select First_name__c, Surname__c,RecordType.name from  Application_Members__c];     
    
    if(ap.size() > 0)
    {
        if(con.size() > 0)
        {
            for(Contact c2:con)
            {
                    if(c2.Name == (ap.Surname__c + ' ' +  ap.First_name__c))
                    {
                        c2.FirstName = ap.First_name__c;
                        c2.LastName = ap.Surname__c;
                        c.add(c2);
                        update c;
                    }
                }
            }
        }
    }
This trigger works perfect for the single record insert and update.But how to do for the bulk records.Its Urgent

trigger InstalledHardware on Vehicle_Details__c (before insert, before update)
{
    list<Order> listup=new list<Order>();
    list<i
    for(Vehicle_Details__c V:trigger.new)
    {
        
        Order o=[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id=:v.Order__c];
        if(o.id!=null)
        {
            o.Finished_HardWare__c=o.Finished_HardWare__c+V.Total_Hardware_Installed__c;
            listup.add(o);
        }
        v.Pending_Hardware_Installations_Order__c=o.Left_Hardware__c;
        v.Total_Hardware_Quantity_for_Order__c=o.Total_Hardware_Type_Ordered_Products__c;
    }
    if(listup.size()>0)
    {
        update listup;
    }
}
I have Service Order as custom object.In this i have start date as date field,service start time as date time field, and Attended by as Lookup of Technician object Name.Now my question is if start date,service start time and Attended by are same for the other record it have show error  message as duplication
In the order i have a custom field as order no, if i create a first record i enter the order no.
For the next time when i create record for the same contract number, the order no have to insert.How can i do that

Can anyone provide code please.
At one shot how to update the contract owner as same as account owner
Whenever we select product in the opportunity line item the product should be unique.How to do that?
 
I have custom field in a products ,how to add that custom field to the opportunity line item multiline page layout.
public class sendquoteemail{
  


    public String getBcc() {
        return null;
    }


  public String emailSubject { get; set; }

  
 public quote getQ() {
        return q;
    }

    public sendquoteemail(ApexPages.StandardController controller) {}
    public String emailVal{get;set;}
    public String cc{get;set;}
    public String subject{ get; set; }
    public String body { get; set; }
    public Account accname{get;set;}  
    Public string aname; 
    private List<String> ccEmailIds;
    public  quote q;
    public Attachment att{get;set;}
    public List<Attachment> attList{get;set;}
  
    public sendquoteemail()
    {
        q= [SELECT email,contactid,cc__c,sbject__c,body__c,accountid,id from quote WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        system.debug('============================================='+q.email);
        accname=[select name from Account where id=:q.accountid];
        aname=accname.name;
        //body="abc" & BR() & "xyz";
        attList = new List<Attachment>();
        att = new Attachment();
    }
   
    public void upload()
    {
        if(att.name == null)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please Select File Path First.'));
        }
        else
        {
            att.OwnerId = UserInfo.getUserId();
            attList.add(att);

            att = new Attachment();
                        att.body=null;
        }
    }
   
    public PageReference send()
    {
         List<Messaging.EmailFileAttachment> mailAttList = new List<Messaging.EmailFileAttachment>();
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
       
        PageReference pdf =  Page.ProageQuoteTemplate;
        pdf.getParameters().put('id',(String)ApexPages.currentPage().getParameters().get('id'));
        pdf.setRedirect(true);
       
        Blob b = pdf.getContent();
         Messaging.EmailFileAttachment efa1 = new Messaging.EmailFileAttachment();
        efa1.setFileName('attachment.pdf');
        efa1.setBody(b);
        mailAttList.add(efa1);  
       
       
        QuoteDocument doc = new QuoteDocument(Document = b, QuoteId = q.id);
        insert doc;
     

       
        for(Attachment att1 : attList)
        {
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setBody(att1.body);
            efa.setFileName(att1.name);
            mailAttList.add(efa);
        }
       
        string[] ToAddresses=new string[] {q.email};
        email.setSubject( q.sbject__c );
        email.setToAddresses(ToAddresses);
        email.setPlainTextBody( q.body__c );
        if( q.cc__c !='' && q.cc__c.length() > 0 )
            ccEmailIds = q.cc__c.split(';');
        if(ccEmailIds != null && ccEmailIds.size()>0)
        {
            ccEmailIds = q.cc__c.split(';');
            email.setCcAddresses(ccEmailIds);
        }
        //email.setFileAttachments(new Messaging.EmailFileAttachment[] {mailAttList});      
          email.setFileAttachments(mailAttList);
        Messaging.SendEmailResult[] sendResult;

          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email }); 
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '));
       
      
      
        PageReference pageRef = new ApexPages.StandardController(q).view();
        return pageRef;
    }  
 } 
trigger CompanynameforClientprofile on Client_Profile__c (before insert, before update) 
{
  for(Client_Profile__c c:trigger.new)
    {
        Account a=[select id from Account where name=:c.Name];
        if(a.id!=null)
        {
          c.Company_name__c=a.id;
        }
        else if(a.id==null)
        {
            c.Company_name__c='001N000000LobTJ';
        }
    }
public class ClientProfile 
{
    public Boolean bool {get;set;}
    public Boolean bool1 {get;set;}
     private final  Client_Profile__c order;
     public Client_Profile__c getorder()
     {
         return order;
     }
     public ClientProfile(ApexPages.StandardController stdController) 
     {
        order = (Client_Profile__c)stdController.getRecord();
           
           
     }
     public PageReference next() 
     {
                
       PageReference np = new PageReference('/apex/ClientProfile1');
        np.setRedirect(false);
         return np;                 
    }
    public PageReference Continue1() 
     {
       PageReference np1 = new PageReference('/apex/ClientProfile2');
       np1.setRedirect(false);
       return np1;   
    }
     public PageReference Continue2() 
     {
     
      
       PageReference np2 = new PageReference('/apex/ClientProfile3');
        np2.setRedirect(false);
        return np2;   
    }
    public PageReference back() 
     {
       PageReference np3 = new PageReference('/apex/ClientProfile');
       np3.setRedirect(false);
       return np3;   
    }
     public PageReference back2() 
     {
       PageReference np4 = new PageReference('/apex/ClientProfile1');
       np4.setRedirect(false);
       return np4;   
    }
     public PageReference back3() 
     {
       PageReference np5 = new PageReference('/apex/ClientProfile2');
       np5.setRedirect(false);
       return np5;   
    }
    public PageReference save() 
    {
        insert order;
        PageReference np6 = new PageReference('/apex/Thankuform');
        np6.setRedirect(true);
        return np6;
    }
  /* public List<SelectOption> getTypes()
    {
       Schema.sObjectType sobject_type = Client_Profile__c.getSObjectType();
       Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe();
       Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap();          
       List<Schema.PicklistEntry> pick_list_values = field_map.get('Type_of_Company__c').getDescribe().getPickListValues();
       List<selectOption> options = new List<selectOption>();
       for (Schema.PicklistEntry a : pick_list_values) 
       {
          options.add(new selectOption(a.getLabel(), a.getValue()));
       }
      return options;
   }*/
}
For example I have Order object and vehicle Installation__c  ,i am adding product to that that order using order item.Now my question is the sumof the quantity of ordered  product has to copied to total product field in the vehicle_Installation__c whenever i create new Vehicle installation under the Order related list page.Then i need to input Installed_quantity__c in one field for that day.This value has to subtracted from the Total product field value and stored it in Pending_Installation__c field .Then record is saved,after that I want to create new Vehicle_Installation here I input Installed_quantity__c and it have to subtract the previous record value of Pending_Installation__c
trigger OrderInclusiveorWaive on OrderItem (before insert,before update) 
{
    List<Product2> pt = new List<Product2>();
      
    for(OrderItem op : Trigger.new)
    {
        for(PricebookEntry pbe : [Select Id, pricebook2id, product2id, unitprice From PricebookEntry Where Id=:op.PricebookEntryId])
        {
            for(Pricebook2 pb2 : [Select Id From Pricebook2 Where Id=:pbe.Pricebook2Id])
            {
                for(Product2 p : [Select Name From Product2 Where Id =: pbe.product2id])
                {
                       if(p.id == pbe.product2id)
                    {
                        if( op.Inclusive_or_Waive__c ==  TRUE )
                        {
                            if((op.Total_Hardware_Type_Ordered_Products__c) >= (op.Total_Package_Ordered_Products__c))
                              {
                                op.addError(' No Quantity is Matched,Please match it');
                            }
                        }
                        else if( op.Inclusive_or_Waive__c ==  FALSE )
                        {
                            if(p.id!=null || (op.Total_Hardware_Type_Ordered_Products__c) >= (op.Total_Package_Ordered_Products__c))
                            {
                                pt.add(p);
                            }
                        }
                    }
                    update p;
                }
            }
        }       
    }
}
I am using professional edition.So,I want to know whenever i choose account name in lookup field in contact object the related custom fields in accounts have to copied to the contact custom fields using custom button.
Can we skip auto number when creating a records  on a record if it has specific picklist values? 

Suppose i have 5 picklist values...I need to generate autonumber for only some records which have 3 picklist values. For remaining 2 picklist values it should not generate autonumbers on it.

 
This trigger works perfect for the single record insert and update.But how to do for the bulk records.Its Urgent

trigger InstalledHardware on Vehicle_Details__c (before insert, before update)
{
    list<Order> listup=new list<Order>();
    list<i
    for(Vehicle_Details__c V:trigger.new)
    {
        
        Order o=[select Order_Number__c,Finished_HardWare__c,Left_Hardware__c,Total_Hardware_Type_Ordered_Products__c from Order where id=:v.Order__c];
        if(o.id!=null)
        {
            o.Finished_HardWare__c=o.Finished_HardWare__c+V.Total_Hardware_Installed__c;
            listup.add(o);
        }
        v.Pending_Hardware_Installations_Order__c=o.Left_Hardware__c;
        v.Total_Hardware_Quantity_for_Order__c=o.Total_Hardware_Type_Ordered_Products__c;
    }
    if(listup.size()>0)
    {
        update listup;
    }
}
In the order i have a custom field as order no, if i create a first record i enter the order no.
For the next time when i create record for the same contract number, the order no have to insert.How can i do that

Can anyone provide code please.
trigger OrderInclusiveorWaive on OrderItem (before insert,before update) 
{
    List<Product2> pt = new List<Product2>();
      
    for(OrderItem op : Trigger.new)
    {
        for(PricebookEntry pbe : [Select Id, pricebook2id, product2id, unitprice From PricebookEntry Where Id=:op.PricebookEntryId])
        {
            for(Pricebook2 pb2 : [Select Id From Pricebook2 Where Id=:pbe.Pricebook2Id])
            {
                for(Product2 p : [Select Name From Product2 Where Id =: pbe.product2id])
                {
                       if(p.id == pbe.product2id)
                    {
                        if( op.Inclusive_or_Waive__c ==  TRUE )
                        {
                            if((op.Total_Hardware_Type_Ordered_Products__c) >= (op.Total_Package_Ordered_Products__c))
                              {
                                op.addError(' No Quantity is Matched,Please match it');
                            }
                        }
                        else if( op.Inclusive_or_Waive__c ==  FALSE )
                        {
                            if(p.id!=null || (op.Total_Hardware_Type_Ordered_Products__c) >= (op.Total_Package_Ordered_Products__c))
                            {
                                pt.add(p);
                            }
                        }
                    }
                    update p;
                }
            }
        }       
    }
}
I am using professional edition.So,I want to know whenever i choose account name in lookup field in contact object the related custom fields in accounts have to copied to the contact custom fields using custom button.
Details: Average test coverage across all Apex Classes and Triggers is 63%, at least 75% test coverage is required.
public class sendEmail5{ 

    public quote getQ() {
        return q;
    }

    public sendEmail5(ApexPages.StandardController controller) {}
    public String emailVal{get;set;}
    public String cc{get;set;}
    public String subject{ get; set; }
    public String body { get; set; }
 
    private List<String> ccEmailIds;
    public  quote q;

  
    public sendEmail5() {
        q= [SELECT email,contactid,cc__c,sbject__c from quote WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
        system.debug('============================================='+q.email);
       

    }

    public PageReference send() {
       
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
       
        PageReference pdf =  Page.QuoteTemplate;
        pdf.getParameters().put('id',(String)ApexPages.currentPage().getParameters().get('id'));
        pdf.setRedirect(true);
       
        //Blob b = pdf.getContent();
        Blob b = !Test.isRunningTest() ? pdf.getContent() : Blob.valueOf('This is the test');

       
        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
        efa.setFileName('attachment.pdf');
        efa.setBody(b);       
       
        string[] ToAddresses=new string[] {q.email};
        email.setSubject( q.sbject__c );
        email.setToAddresses(ToAddresses);
        email.setPlainTextBody( body );
        if( q.cc__c !='' && q.cc__c.length() > 0 )
         ccEmailIds = q.cc__c.split(';');
        if(ccEmailIds != null && ccEmailIds.size()>0)
        {
          ccEmailIds = q.cc__c.split(';');
         email.setCcAddresses(ccEmailIds);
        }
        email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});      
         
          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email }); 
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '));
      
        PageReference pageRef = new ApexPages.StandardController(q).view();
return pageRef;
    }
}
trigger LeadConvert on Lead (before update) 
{
    List<Account> acc = new List<Account>();
    Integer listint = 5;
   
    List<Opportunity> op = new List<Opportunity>();
    List<Contact> con = new List<Contact>();
   
    for(Lead l : Trigger.New)
    {     
       Lead oldl = Trigger.oldMap.get(l.Id);
        if (oldl.IsConverted == false && l.isConverted == true) 
        {     
            if (l.ConvertedContactId != null) 
            {
                List<Contact> contCk = [Select Id, LastName From Contact Where Id =: l.ConvertedContactId]; 
                   conCk.LastName = l.lastName;
                    con1.add(conCk); 
                    con2.add(conCk);
                    System.debug('After insert con2'+con2);
                    con3.add(conCk);
                    System.debug('After insert con3'+con3);

                }
                
            }
            if (l.ConvertedAccountId != null)
            {
                Account accCk = [Select Id, Name From Account Where Id =: l.ConvertedAccountId];
                accCk.Name = l.lastName;             
                acc.add(accCk);
            }
            if (l.ConvertedOpportunityId != null)
            {
                Opportunity oppCk = [Select Id, Name From Opportunity Where Id =: l.ConvertedOpportunityId];
                oppCk.Name = l.lastName;
                op.add(oppCk);
            }
        }
    }
This is my trigger in this it only creates one Contact but, i need to create multiple contacts when we convert lead.