• Akash A
  • NEWBIE
  • 0 Points
  • Member since 2023

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 2
    Replies
public class AttendanceEmailBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Calculate start date for querying attendance records
        Date startDate = Date.today().addDays(3);
        Date endDate = startDate.addDays(3);

/*
 // Calculate start date for querying attendance records
    Datetime startDate = Datetime.now().addMinutes(1);
    Datetime endDate = startDate.addMinutes(1);
*/
        String query = 'SELECT Id, Name, Employee__c, Employee__r.Manager__r.Email__c, Statuss__c, Date__c ' +
                       'FROM Attendance__c ' +
                       'WHERE (Statuss__c = \'Present\' OR Statuss__c = \'Less than 9.15\' OR Statuss__c = \'Status Unknown\' OR Statuss__c = \'Shortfall\') ' +
                       'AND Date__c >= :startDate AND Date__c <= :endDate';

        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Attendance__c> scope) {
        List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();

        for (Attendance__c att : scope) {
            if (att.Employee__r != null && att.Employee__r.Manager__r != null && att.Employee__r.Manager__r.Email__c != null) {
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(new List<String>{att.Employee__r.Employee_Email__c});
                email.setCcAddresses(new List<String>{att.Employee__r.Manager__r.Email__c});
                email.setSubject('Attendance Status Notification');
                email.setPlainTextBody('Dear ' + att.Employee__r.Name + ',\n\n' +
                                       'Your attendance on ' + att.Date__c + ' has a status of "' + att.Statuss__c + '".\n\n' +
                                       'Please review your attendance record.\n\n' +
                                       'Sincerely,\nYour Company');
                emailsToSend.add(email);
            }
        }

        // Send the emails
        Messaging.SendEmailResult[] results = Messaging.sendEmail(emailsToSend);
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Email sent successfully.');
            } else {
                System.debug('Failed to send email. Error: ' + result.getErrors()[0].getMessage());
            }
        }
    }

    public void finish(Database.BatchableContext context) {
        // Perform any post-processing or cleanup if needed
    }
}

Used This one Batch class but it is not sending emails plz anone provide solution plz.

Full question Link:- https://developer.salesforce.com/forums/ForumsMain?id=9065d0000007BDKAA2

I have two objects 1. Employee 2. Attendance 

Employee, Attendance has master detail relation.

Actually i already implemented everything getting attendance creating attendance using Aura Component. For the below requirement solution needed in asynchronous apex.

Requirement:- Create an automated process which runs every 3 days starting from 3rd day of the month to determine if the employee has any days where the attendance Status (Field) is –

1.Present, 
2.Less than 9.15
3.Status Unknown
4.Shortfall

Once the above is determined an email should trigger to the employee with manager in CC informing about the same 


Manager Field has self look up with employee object.

I need the above requirement solution implementation using asynchronous apex.

Below is the apex code for previos all requirements.

Apex Class:-

public class Employee_Attendance_Apex 
{
    @AuraEnabled
    public static ContactDataTableWrapper getAttendance( Integer pageNumber, Integer pageSize, String recordId, String eNumber, String sDate, String eDate, String empName) 
    {
        System.debug('getContactData '+empName);
        if(eNumber !=null && sDate != null && eDate != null || empName != null)
        {
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            //Offset for SOQL
            Integer offset = (pageNumber - 1) * pageSize;
            
              // Get the total number of records that match the criteria
        Integer totalRecords = [SELECT COUNT() FROM Attendance__c
                                WHERE (Date__c >= :startDate AND Date__c <= :endDate)
                                AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c = :empName)];
            
            //Total Records
           // Integer totalRecords = [SELECT COUNT() FROM Attendance__c];
           // Integer recordEnd = pageSize * pageNumber;
            
            //Instance of Contact DataTable Wrapper Class
            ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
            objDT.pageSize = pageSize;
            objDT.pageNumber = pageNumber;
            objDT.recordStart = offset + 1;
           // objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
           System.debug('eNumber '+eNumber);
            objDT.recordEnd = Math.min(offset + pageSize, totalRecords);

            objDT.totalRecords = totalRecords;
            objDT.AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee_Name__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                                 WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c =:empName) ORDER BY CreatedDate DESC LIMIT :pageSize OFFSET :offset];
            return objDT;
        }
        return null;
    } 
    
    @AuraEnabled
    public static ContactDataTableWrapper getAttendanceDownload(String recordId, String eNumber, String sDate, String eDate, String empName) 
    {
        System.debug('getContactData '+empName);
        if(eNumber !=null && sDate != null && eDate != null || empName != null)
        {
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            //Offset for SOQL
            //Integer offset = (pageNumber - 1) * pageSize;
            
            //Total Records
            Integer totalRecords = [SELECT COUNT() FROM Attendance__c];
            //Integer recordEnd = pageSize * pageNumber;
            
            //Instance of Contact DataTable Wrapper Class
            ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
            //objDT.pageSize = pageSize;
            //objDT.pageNumber = pageNumber;
            //objDT.recordStart = offset + 1;
            //objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
            //objDT.totalRecords = totalRecords;
            objDT.AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee_Name__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                                 WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c =:empName) ORDER BY CreatedDate DESC];
            return objDT;
        }
        return null;
    } 
    
    @AuraEnabled
    public static List<Employee__c> getAttendanceByName(String empName) 
    {
        System.debug('getContactData '+empName);
        List<Employee__c> empRec = new List<Employee__c>();
        if(empName != '')
        {
            String empNameVal = '%'+empName+'%';
            empRec = [Select Id, Name from Employee__c Where Name Like:empNameVal Order By CreatedDate DESC];
        }
        return empRec;
    } 
    
    public class ContactDataTableWrapper {
        @AuraEnabled
        public Integer pageSize {get;set;}
        @AuraEnabled
        public Integer pageNumber {get;set;}
        @AuraEnabled
        public Integer totalRecords {get;set;}
        @AuraEnabled
        public Integer recordStart {get;set;}
        @AuraEnabled
        public Integer recordEnd {get;set;}
        @AuraEnabled
        public List<Attendance__c> AttendanceList {get;set;}
    }
    /*@AuraEnabled
    public static List<Attendance__c> getAttendance(String recordId, String eNumber, String sDate, String eDate, String empName){
        
        List<Attendance__c> AttendanceList = new List<Attendance__c>();
        if(eNumber !=null && sDate != null && eDate != null || empName != null){
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            
            AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                              WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee_Name__c =:empName) ORDER BY CreatedDate DESC];  
        }
        return AttendanceList;
    }*/
   
    @AuraEnabled
    public static String createAttendance(String recordId, String dateInput, String inTime, String outTime) {
        Attendance__c attendance = new Attendance__c();
        String result = '';
        Date dateValue;
        Time inTimeChange;
        Time outTimeChange;
        
        if (recordId != null) {
            try {
                Employee__c empRec = [SELECT Id, Name, OwnerId, Manager__c, Manager__r.Email__c
                                      FROM Employee__c
                                      WHERE Id = :recordId LIMIT 1];
                
                if (empRec != null) {
                    // Setting Attendance fields based on input parameters
                    attendance.Name = empRec.Name + ' 1';
                    attendance.Employee__c = empRec.Id;
                    
                    if (dateInput != null) {
                        dateValue = Date.valueOf(dateInput);
                        Date date1 = System.today();
                        Date date2 = dateValue;
                        Integer dateDifference = date2.daysBetween(date1);
                        
                        if (dateDifference >= 7) {
                            return 'dateDifference';
                        } else {
                            attendance.Date__c = dateValue;
                        }
                    }
                    
                    if (inTime != null) {
                        List<String> strTimeSplit = inTime.split(':');
                        inTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
                        attendance.From_Time__c = inTimeChange;
                    }
                    
                    if (outTime != null) {
                        List<String> strTimeSplit = outTime.split(':');
                        outTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
                        attendance.To_Time__c = outTimeChange;
                    }
                    
                    // Insert the Attendance record
                    insert attendance;
                    
                    // Get Manager's email
                    String managerEmail = empRec.Manager__r.Email__c;
                    
                    // Send email to Manager
                    if (managerEmail != null) {
                        String emailSubject = 'Attendance Record Approval';
                        String emailBody = 'A new attendance record requires your approval.' +
                            '\n\nRecord Link: ' + getRecordLink(attendance.Id);
                        
                        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                        email.setToAddresses(new List<String>{managerEmail});
                        email.setSubject(emailSubject);
                        email.setPlainTextBody(emailBody);
                        
                        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
                        if (results[0].isSuccess()) {
                            System.debug('Email sent successfully.');
                        } else {
                            System.debug('Failed to send email. Error: ' + results[0].getErrors()[0].getMessage());
                        }
                    }
                    
                    
                    // Submit the record for approval using the Approval.ProcessSubmitRequest class
                    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
                    req.setComments('Submitting record for approval.');
                    req.setObjectId(Attendance.Id);
                    
                    // Make sure to use the correct Approval process name (replace 'Attendance_Approval' with your actual process name)
                    req.setProcessDefinitionNameOrId('Attendance_Approval');
                    
                    Approval.ProcessResult result2 = Approval.process(req);
                    
                    if (result2.isSuccess()) {
                        System.debug('Record submitted for approval successfully.');
                        // If the record is submitted for approval successfully, update the Status__c field to "Pending Approval"
                        update Attendance;
                    } else {
                        System.debug('Failed to submit record for approval. Error: ' + result2.getErrors());
                    }
                    result = 'true';
                }
            } catch (Exception ex) {
                System.debug('Ex: ' + ex.getMessage());
                result = 'false';
            }
        }
        return result;
    }
    // Helper method to get the Salesforce record link
    private static String getRecordLink(Id recordId) {
        String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
        return baseURL + '/' + recordId;
    }
    @AuraEnabled 
    public static String updateAttendance(String row){
        
        System.debug('row '+row);  
        Map<String, Object> dataMap = (Map<String, Object>)JSON.deserializeUntyped(row);
        
        System.debug('Converted Map: ' + dataMap);
        System.debug('Key '+dataMap.get('Date'));
        
        String attId = (String)dataMap.get('Id');
        String dateInput = (String)dataMap.get('Date');
        String inTime = (String)dataMap.get('InTime');
        String outTime = (String)dataMap.get('OutTime');
        String result = '';
        
        Attendance__c att = [Select Id, Date__c, From_Time__c, To_Time__c from Attendance__c Where Id =:attId];
        
        if(dateInput!=null)
        {
            Date Datevalue = Date.valueOf(dateInput);
            Date date1 = att.Date__c;
            Date date2 = Datevalue;
            Integer dateDifference = date2.daysBetween(date1);
            
            if (dateDifference >= 7) {
                result = 'dateDifference';
            } else {
                att.Date__c = Datevalue;
            }
        }
        if (inTime != null) {
            String[] strTimeSplit = inTime.split(':');
            Time inTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
            att.From_Time__c = inTimeChange;
        }
        if (outTime != null) {
            String[] strTimeSplit = outTime.split(':');
            Time outTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
            att.To_Time__c = outTimeChange;
        }
        
        try{
            Update att; 
            result = 'true';
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
            result = 'false';
        }
        return result;
    }
    @AuraEnabled
    public static String getManagerEmail(Id employeeId) {
        try {
            if (employeeId != null) {
                Employee__c empRec = [SELECT Id, Manager__c, Manager__r.Email__c 
                                      FROM Employee__c 
                                      WHERE Id = :employeeId LIMIT 1];
                
                // Check if the employee record has a manager and the manager has an email
                if (empRec != null && empRec.Manager__c != null && empRec.Manager__r != null && empRec.Manager__r.Email__c != null) {
                    return empRec.Manager__r.Email__c;
                }
            }
        } catch (Exception ex) {
            // Handle exceptions here, such as logging or returning an error message.
            System.debug('Error occurred while fetching Manager\'s Email: ' + ex.getMessage());
        }
        return null;
    }
   

}
public class AttendanceEmailBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
    public Database.QueryLocator start(Database.BatchableContext context) {
        // Calculate start date for querying attendance records
        Date startDate = Date.today().addDays(3);
        Date endDate = startDate.addDays(3);

/*
 // Calculate start date for querying attendance records
    Datetime startDate = Datetime.now().addMinutes(1);
    Datetime endDate = startDate.addMinutes(1);
*/
        String query = 'SELECT Id, Name, Employee__c, Employee__r.Manager__r.Email__c, Statuss__c, Date__c ' +
                       'FROM Attendance__c ' +
                       'WHERE (Statuss__c = \'Present\' OR Statuss__c = \'Less than 9.15\' OR Statuss__c = \'Status Unknown\' OR Statuss__c = \'Shortfall\') ' +
                       'AND Date__c >= :startDate AND Date__c <= :endDate';

        return Database.getQueryLocator(query);
    }

    public void execute(Database.BatchableContext context, List<Attendance__c> scope) {
        List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();

        for (Attendance__c att : scope) {
            if (att.Employee__r != null && att.Employee__r.Manager__r != null && att.Employee__r.Manager__r.Email__c != null) {
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(new List<String>{att.Employee__r.Employee_Email__c});
                email.setCcAddresses(new List<String>{att.Employee__r.Manager__r.Email__c});
                email.setSubject('Attendance Status Notification');
                email.setPlainTextBody('Dear ' + att.Employee__r.Name + ',\n\n' +
                                       'Your attendance on ' + att.Date__c + ' has a status of "' + att.Statuss__c + '".\n\n' +
                                       'Please review your attendance record.\n\n' +
                                       'Sincerely,\nYour Company');
                emailsToSend.add(email);
            }
        }

        // Send the emails
        Messaging.SendEmailResult[] results = Messaging.sendEmail(emailsToSend);
        for (Messaging.SendEmailResult result : results) {
            if (result.isSuccess()) {
                System.debug('Email sent successfully.');
            } else {
                System.debug('Failed to send email. Error: ' + result.getErrors()[0].getMessage());
            }
        }
    }

    public void finish(Database.BatchableContext context) {
        // Perform any post-processing or cleanup if needed
    }
}

Used This one Batch class but it is not sending emails plz anone provide solution plz.

Full question Link:- https://developer.salesforce.com/forums/ForumsMain?id=9065d0000007BDKAA2

I have two objects 1. Employee 2. Attendance 

Employee, Attendance has master detail relation.

Actually i already implemented everything getting attendance creating attendance using Aura Component. For the below requirement solution needed in asynchronous apex.

Requirement:- Create an automated process which runs every 3 days starting from 3rd day of the month to determine if the employee has any days where the attendance Status (Field) is –

1.Present, 
2.Less than 9.15
3.Status Unknown
4.Shortfall

Once the above is determined an email should trigger to the employee with manager in CC informing about the same 


Manager Field has self look up with employee object.

I need the above requirement solution implementation using asynchronous apex.

Below is the apex code for previos all requirements.

Apex Class:-

public class Employee_Attendance_Apex 
{
    @AuraEnabled
    public static ContactDataTableWrapper getAttendance( Integer pageNumber, Integer pageSize, String recordId, String eNumber, String sDate, String eDate, String empName) 
    {
        System.debug('getContactData '+empName);
        if(eNumber !=null && sDate != null && eDate != null || empName != null)
        {
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            //Offset for SOQL
            Integer offset = (pageNumber - 1) * pageSize;
            
              // Get the total number of records that match the criteria
        Integer totalRecords = [SELECT COUNT() FROM Attendance__c
                                WHERE (Date__c >= :startDate AND Date__c <= :endDate)
                                AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c = :empName)];
            
            //Total Records
           // Integer totalRecords = [SELECT COUNT() FROM Attendance__c];
           // Integer recordEnd = pageSize * pageNumber;
            
            //Instance of Contact DataTable Wrapper Class
            ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
            objDT.pageSize = pageSize;
            objDT.pageNumber = pageNumber;
            objDT.recordStart = offset + 1;
           // objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
           System.debug('eNumber '+eNumber);
            objDT.recordEnd = Math.min(offset + pageSize, totalRecords);

            objDT.totalRecords = totalRecords;
            objDT.AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee_Name__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                                 WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c =:empName) ORDER BY CreatedDate DESC LIMIT :pageSize OFFSET :offset];
            return objDT;
        }
        return null;
    } 
    
    @AuraEnabled
    public static ContactDataTableWrapper getAttendanceDownload(String recordId, String eNumber, String sDate, String eDate, String empName) 
    {
        System.debug('getContactData '+empName);
        if(eNumber !=null && sDate != null && eDate != null || empName != null)
        {
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            //Offset for SOQL
            //Integer offset = (pageNumber - 1) * pageSize;
            
            //Total Records
            Integer totalRecords = [SELECT COUNT() FROM Attendance__c];
            //Integer recordEnd = pageSize * pageNumber;
            
            //Instance of Contact DataTable Wrapper Class
            ContactDataTableWrapper objDT =  new ContactDataTableWrapper();  
            //objDT.pageSize = pageSize;
            //objDT.pageNumber = pageNumber;
            //objDT.recordStart = offset + 1;
            //objDT.recordEnd = totalRecords >= recordEnd ? recordEnd : totalRecords;
            //objDT.totalRecords = totalRecords;
            objDT.AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee_Name__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                                 WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee__c =:empName) ORDER BY CreatedDate DESC];
            return objDT;
        }
        return null;
    } 
    
    @AuraEnabled
    public static List<Employee__c> getAttendanceByName(String empName) 
    {
        System.debug('getContactData '+empName);
        List<Employee__c> empRec = new List<Employee__c>();
        if(empName != '')
        {
            String empNameVal = '%'+empName+'%';
            empRec = [Select Id, Name from Employee__c Where Name Like:empNameVal Order By CreatedDate DESC];
        }
        return empRec;
    } 
    
    public class ContactDataTableWrapper {
        @AuraEnabled
        public Integer pageSize {get;set;}
        @AuraEnabled
        public Integer pageNumber {get;set;}
        @AuraEnabled
        public Integer totalRecords {get;set;}
        @AuraEnabled
        public Integer recordStart {get;set;}
        @AuraEnabled
        public Integer recordEnd {get;set;}
        @AuraEnabled
        public List<Attendance__c> AttendanceList {get;set;}
    }
    /*@AuraEnabled
    public static List<Attendance__c> getAttendance(String recordId, String eNumber, String sDate, String eDate, String empName){
        
        List<Attendance__c> AttendanceList = new List<Attendance__c>();
        if(eNumber !=null && sDate != null && eDate != null || empName != null){
            
            Date startDate = Date.valueOf(sDate);
            Date endDate   = Date.valueOf(eDate);
            
            AttendanceList = [Select Id, Name, Employee__r.Name, Employee__c, Employee__r.Employee_Name__c, Employee__r.Employee_ID__c, Date__c, Day__c, From_Time__c, To_Time__c, Total_Hours__c, Statuss__c from Attendance__c 
                              WHERE (Date__c >= :startDate AND Date__c <= :endDate) AND (Employee__r.Employee_ID__c = :eNumber OR Employee_Name__c =:empName) ORDER BY CreatedDate DESC];  
        }
        return AttendanceList;
    }*/
   
    @AuraEnabled
    public static String createAttendance(String recordId, String dateInput, String inTime, String outTime) {
        Attendance__c attendance = new Attendance__c();
        String result = '';
        Date dateValue;
        Time inTimeChange;
        Time outTimeChange;
        
        if (recordId != null) {
            try {
                Employee__c empRec = [SELECT Id, Name, OwnerId, Manager__c, Manager__r.Email__c
                                      FROM Employee__c
                                      WHERE Id = :recordId LIMIT 1];
                
                if (empRec != null) {
                    // Setting Attendance fields based on input parameters
                    attendance.Name = empRec.Name + ' 1';
                    attendance.Employee__c = empRec.Id;
                    
                    if (dateInput != null) {
                        dateValue = Date.valueOf(dateInput);
                        Date date1 = System.today();
                        Date date2 = dateValue;
                        Integer dateDifference = date2.daysBetween(date1);
                        
                        if (dateDifference >= 7) {
                            return 'dateDifference';
                        } else {
                            attendance.Date__c = dateValue;
                        }
                    }
                    
                    if (inTime != null) {
                        List<String> strTimeSplit = inTime.split(':');
                        inTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
                        attendance.From_Time__c = inTimeChange;
                    }
                    
                    if (outTime != null) {
                        List<String> strTimeSplit = outTime.split(':');
                        outTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
                        attendance.To_Time__c = outTimeChange;
                    }
                    
                    // Insert the Attendance record
                    insert attendance;
                    
                    // Get Manager's email
                    String managerEmail = empRec.Manager__r.Email__c;
                    
                    // Send email to Manager
                    if (managerEmail != null) {
                        String emailSubject = 'Attendance Record Approval';
                        String emailBody = 'A new attendance record requires your approval.' +
                            '\n\nRecord Link: ' + getRecordLink(attendance.Id);
                        
                        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                        email.setToAddresses(new List<String>{managerEmail});
                        email.setSubject(emailSubject);
                        email.setPlainTextBody(emailBody);
                        
                        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
                        if (results[0].isSuccess()) {
                            System.debug('Email sent successfully.');
                        } else {
                            System.debug('Failed to send email. Error: ' + results[0].getErrors()[0].getMessage());
                        }
                    }
                    
                    
                    // Submit the record for approval using the Approval.ProcessSubmitRequest class
                    Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
                    req.setComments('Submitting record for approval.');
                    req.setObjectId(Attendance.Id);
                    
                    // Make sure to use the correct Approval process name (replace 'Attendance_Approval' with your actual process name)
                    req.setProcessDefinitionNameOrId('Attendance_Approval');
                    
                    Approval.ProcessResult result2 = Approval.process(req);
                    
                    if (result2.isSuccess()) {
                        System.debug('Record submitted for approval successfully.');
                        // If the record is submitted for approval successfully, update the Status__c field to "Pending Approval"
                        update Attendance;
                    } else {
                        System.debug('Failed to submit record for approval. Error: ' + result2.getErrors());
                    }
                    result = 'true';
                }
            } catch (Exception ex) {
                System.debug('Ex: ' + ex.getMessage());
                result = 'false';
            }
        }
        return result;
    }
    // Helper method to get the Salesforce record link
    private static String getRecordLink(Id recordId) {
        String baseURL = URL.getSalesforceBaseUrl().toExternalForm();
        return baseURL + '/' + recordId;
    }
    @AuraEnabled 
    public static String updateAttendance(String row){
        
        System.debug('row '+row);  
        Map<String, Object> dataMap = (Map<String, Object>)JSON.deserializeUntyped(row);
        
        System.debug('Converted Map: ' + dataMap);
        System.debug('Key '+dataMap.get('Date'));
        
        String attId = (String)dataMap.get('Id');
        String dateInput = (String)dataMap.get('Date');
        String inTime = (String)dataMap.get('InTime');
        String outTime = (String)dataMap.get('OutTime');
        String result = '';
        
        Attendance__c att = [Select Id, Date__c, From_Time__c, To_Time__c from Attendance__c Where Id =:attId];
        
        if(dateInput!=null)
        {
            Date Datevalue = Date.valueOf(dateInput);
            Date date1 = att.Date__c;
            Date date2 = Datevalue;
            Integer dateDifference = date2.daysBetween(date1);
            
            if (dateDifference >= 7) {
                result = 'dateDifference';
            } else {
                att.Date__c = Datevalue;
            }
        }
        if (inTime != null) {
            String[] strTimeSplit = inTime.split(':');
            Time inTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
            att.From_Time__c = inTimeChange;
        }
        if (outTime != null) {
            String[] strTimeSplit = outTime.split(':');
            Time outTimeChange = Time.newInstance(Integer.valueOf(strTimeSplit[0]), Integer.valueOf(strTimeSplit[1]), 0, 0);
            att.To_Time__c = outTimeChange;
        }
        
        try{
            Update att; 
            result = 'true';
        }
        catch(Exception ex){
            System.debug(ex.getMessage());
            result = 'false';
        }
        return result;
    }
    @AuraEnabled
    public static String getManagerEmail(Id employeeId) {
        try {
            if (employeeId != null) {
                Employee__c empRec = [SELECT Id, Manager__c, Manager__r.Email__c 
                                      FROM Employee__c 
                                      WHERE Id = :employeeId LIMIT 1];
                
                // Check if the employee record has a manager and the manager has an email
                if (empRec != null && empRec.Manager__c != null && empRec.Manager__r != null && empRec.Manager__r.Email__c != null) {
                    return empRec.Manager__r.Email__c;
                }
            }
        } catch (Exception ex) {
            // Handle exceptions here, such as logging or returning an error message.
            System.debug('Error occurred while fetching Manager\'s Email: ' + ex.getMessage());
        }
        return null;
    }
   

}