I have made a little trigger that updates record owner based on a parent(and another parent) record owner.
The data model is: HR_Data__c < Clock_in_out_user__c < Clock_in_out_Date__c.
The problem is that when user is not in the office, the colleague will clock him in with record type Unplanned Outage. However, the record owner will be of colleague and that screws up the reports a bit.
Here's the code:
trigger changeUnauthorizedClockinOwner on Clock_in_out_Date__c (before insert, before update) {
// Get the record type id based on name Unplanned Outage
RecordType unplannedOutage = [select Id from RecordType where Name = 'Unplanned Outage' and SobjectType = 'Clock_in_out_Date__c' limit 1];
// Get the owner id from the related clock out user and hr data objects
Clock_in_out_Date__c newOwner = [
Select id, Clock_in_out_User__r.HR_Data_User__r.OwnerId
From Clock_in_out_Date__c
where id in : trigger.new];
// Update the owner when it matches the Unplanned Outage ID
for(Clock_in_out_Date__c newRecord: trigger.new) {
if (newRecord.RecordTypeId==unplannedOutage.id){
newRecord.OwnerId=newOwner.Clock_in_out_User__r.HR_Data_User__r.OwnerId;
}
}}
And the test class (a bit long winded):
@isTest(SeeAllData=true)
private class TestChangeUnauthorizedClockinOwner{
Static testMethod void TESTOwnerChange(){
// Insert test user
Profile p = [select id from profile where name='Standard User'];
User testUser = new User(alias = 'test123', email='[email protected]',
emailencodingkey='UTF-8', firstname = 'Wesley', lastname='Testing', languagelocalekey='en_US',
localesidkey='en_US', profileid = p.Id, country='United States',
timezonesidkey='America/Los_Angeles', username='[email protected]');
insert testUser;
// Insert HR Data test record
HR_Data__c TestHRData = new HR_Data__c(
name = 'Test HR Data User',
ownerId = testUser.id);
insert TestHRData;
// Insert linked HR Data User
Clock_in_out_User__c TestClockInOutUser = new Clock_in_out_User__c(
Name = 'Test Clock User',
Hidden_Check_last_enter_Date_not_same__c = System.Today()+410,
HR_Data_User__c = TestHRData.Id);
insert TestClockInOutUser;
// Recordtype Unplanned Outage SOQL
RecordType TestUnplannedOutage = [
select Id from RecordType
where Name = 'Unplanned Outage'
and SobjectType = 'Clock_in_out_Date__c'
limit 1];
// Clockin Time Date insert Test record
Clock_in_out_Date__c TestClockDate = new Clock_in_out_Date__c(
RecordTypeId=TestUnplannedOutage.id,
Clock_in_out_User__c = TestClockInOutUser.Id,
Clocking_in_date__c = system.Today()+3);
insert TestClockDate; }}
The full test result is:
Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, changeUnauthorizedClockinOwner: execution of BeforeInsert
caused by: System.QueryException: List has no rows for assignment to SObject
Trigger.changeUnauthorizedClockinOwner: line 10, column 1: []
Stack Trace Class.TestChangeUnauthorizedClockinOwner.TESTOwnerChange: line 39, column 1