Restrict Service Resources from Modifying Shifts for Two Weeks with an Apex Trigger

Restrict Service Resources from Modifying Shifts for Two Weeks with an Apex Trigger

Service territory managers work with their service resources to plan shifts in advance. For example, you want to make an appointment booking available for two weeks starting from the current day. As a result, you want to prevent service resources from modifying their shifts during that period. To restrict a service resource from making any updates to shifts for two weeks, create an Apex trigger.

//Because the next two weeks of time slots are visible to customers and are bookable,
//we want to prevent any updates to those shifts.
//This trigger doesn't allow to create a shift
//where either start time or end time falls under
// 1. Older than today's date
// 2. Two weeks after today's date
 
trigger TwoWeeksLimitTrigger on Shift (before insert,before update) {
    if(trigger.isInsert || trigger.isUpdate){
        if (Trigger.isBefore) {
            for(Shift shift : Trigger.New) {
                Date todayDate = date.today();
                Date twoWeekDate = todayDate.addDays(14);
                if(shift.StartTime < todayDate || shift.StartTime > twoWeekDate){
                    trigger.new[0].StartTime.addError('Customers are already booking slots for this time period and so changing Shifts is not allowed.');
                }
                else if(shift.EndTime < todayDate || shift.EndTime > twoWeekDate){
                    trigger.new[0].EndTime.addError('Customers are already booking slots for this time period and so changing Shifts is not allowed.');
                }
            }
        }
    }
}