• sravan kumar 95
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 5
    Replies
global class Batch_SMSInjection implements Database.Batchable<sObject>, Database.AllowsCallouts{    
    
    // Start method of batch class
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        String str_CommunicationType = 'SMS';
        String query = 'SELECT Id, Activate__c, Business_Rule__c, Comminication_Template__c, Communication_Type__c, Comminication_Template__r.Template_Name__c,Patient__r.Person__r.Contact__r.MobilePhone,'+
                        +' Day__c, Frequency__c, Hours__c, Patient__c, Patient__r.Person__c, Patient__r.Person__r.Contact__c, Patient__r.Person__r.Current_Timezone__c, Scheduled_Date__c, Time__c'+
                        +' FROM Communication_Scheduled__c'+
                        +' WHERE Activate__c = true AND Communication_Type__c =:str_CommunicationType AND Patient__r.SMS_Opt__c = true';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Communication_Scheduled__c> scope) {
        
        Map<Id, Communication_History__c> mapIdToSMSHistory = new Map<Id, Communication_History__c>();
        
        // creating map for all the communication history
        for(Communication_History__c history: [SELECT Id, CreatedDate, Patient__c, Communication__c, Communication_Template__c 
                                                    FROM Communication_History__c 
                                                    WHERE Communication__c IN :scope 
                                                    ORDER BY CreatedDate ASC]){
            
            if(!mapIdToSMSHistory.containsKey(history.Communication__c)){
                mapIdToSMSHistory.put(history.Communication__c,history);
            }
        }
        
        List<Communication_History__c> lstSMSHistoryInsert = new List<Communication_History__c>();
        Map<String, List<String>> map_TemplateNameSetOfContactId = new Map<String, List<String>>(); 
        Set<Id> set_ContactId = new Set<Id>();
        Map<Id, Contact> map_ContactIdAndRecord;
        List<Communication_Scheduled__c> list_CommScheduleToUpdate = new List<Communication_Scheduled__c>();
        
        // Iterating all the communication scheduled
        for(Communication_Scheduled__c smsSchedule : scope){
                    
            DateTime datetime_Accr_UserTimezone;
            if(!String.isEmpty(smsSchedule.Patient__r.Person__r.Current_Timezone__c)){
                datetime_Accr_UserTimezone = Utility.convertTimeAccrTimeZone(smsSchedule.Patient__r.Person__r.Current_Timezone__c);
            }else{
                datetime_Accr_UserTimezone = System.now();
            }
            
             // calculating the weekday of the current date And current time for a patient respective to timezone.    
            String currentTime = String.valueOf(datetime_Accr_UserTimezone.hour());          
           
            System.debug('------currentTime--------'+currentTime);
            System.debug('--------smsSchedule---------'+smsSchedule);
            
            
            String communicationTime = '12';
            if(smsSchedule.Time__c.indexOf(':') != -1){
                communicationTime = smsSchedule.Time__c.subString(0, smsSchedule.Time__c.indexOf(':'));
            }else if(smsSchedule.Time__c != '') {
                communicationTime =  smsSchedule.Time__c;
            }
            
            // checking for the communication matching criteria
            Boolean isCommSend = false;
            if(smsSchedule.Frequency__c == 'Daily'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime)
                        ||( mapIdToSMSHistory.containsKey(smsSchedule.Id) && datetime_Accr_UserTimezone.dateGmt() != mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.date())) {
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                }
            }
            else if(smsSchedule.Frequency__c == 'Monthly'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime && Integer.valueOf(smsSchedule.Day__c) == datetime_Accr_UserTimezone.dayGmt())
                            || mapIdToSMSHistory.containsKey(smsSchedule.Id) && mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.Day() != datetime_Accr_UserTimezone.dayGmt()){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                }
            }
            else if(smsSchedule.Frequency__c == 'Other' || String.isEmpty(smsSchedule.Frequency__c)){
                if(smsSchedule.Scheduled_Date__c == datetime_Accr_UserTimezone.dateGmt() && communicationTime == currentTime){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                    smsSchedule.Activate__c = false;
                    list_CommScheduleToUpdate.add(smsSchedule);
                }
            }
            
            // creating map of sms template and list of Person id
            if(isCommSend && !String.isEmpty(smsSchedule.Comminication_Template__r.Template_Name__c)){
                if(map_TemplateNameSetOfContactId.containsKey(smsSchedule.Comminication_Template__r.Template_Name__c)){
                    map_TemplateNameSetOfContactId.put(smsSchedule.Comminication_Template__r.Template_Name__c, new List<String>());
                }
                map_TemplateNameSetOfContactId.get(smsSchedule.Comminication_Template__r.Template_Name__c).add(smsSchedule.Patient__r.Person__r.Mobile_Phone__c);
                set_ContactId.add(smsSchedule.Patient__r.Person__c);
            }
        }
        
        if(set_ContactId.size() > 0){
             // This list is having all email instances which will be send out
            List<smagicinteract__smsMagic__c> list_SMSToBeSend = new List<smagicinteract__smsMagic__c>();
            
            // SMS instances are created for a respective sms template
            for(smagicinteract__SMS_Template__c smsTemplate : [SELECT Id, smagicinteract__Text__c FROM smagicinteract__SMS_Template__c WHERE smagicinteract__Name__c IN :map_TemplateNameSetOfContactId.keySet()]){
                //smagicinteract.TemplateResolver temp = new smagicinteract.TemplateResolver();
                String  templateText = smsTemplate.smagicinteract__Text__c;             
                String senderId = 'smsMagic';
                for(String personMob : map_TemplateNameSetOfContactId.get(smsTemplate.smagicinteract__Name__c)){  
                    smagicinteract__smsMagic__c smsObject = new smagicinteract__smsMagic__c();
                    smsObject.smagicinteract__SenderId__c = senderId;
                    smsObject.smagicinteract__PhoneNumber__c = personMob ;
                    smsObject.smagicinteract__ObjectType__c = 'Person__c';
                    smsObject.smagicinteract__disableSMSOnTrigger__c = 1;
                    smsObject.smagicinteract__external_field__c = smagicinteract.ApexAPI.generateUniqueKey();
                    smsObject.smagicinteract__SMSText__c = templateText;
                    list_SMSToBeSend.add(smsObject);
                }               
            }
            
            // Communications are send out and history created for each communication,.
            if(list_SMSToBeSend.size() > 0){
                String response = smagicinteract.ApexAPI.pushSMSCallout(list_SMSToBeSend);
                system.debug('@@@response  <> :' + response );
                Database.insert (list_SMSToBeSend, false);      
                insert lstSMSHistoryInsert;
            }
            
            if(list_CommScheduleToUpdate.size() > 0){
                Database.update(list_CommScheduleToUpdate, false);
            }
        }
        
    }
    
    
    global void finish(Database.BatchableContext BC) {
        // Do nothing
    }
    
    // this method is used to create communication history.
    public Communication_History__c createCommHistory(String patientId, String commScheduleId){
        Communication_History__c commHistory = new Communication_History__c();
        commHistory.Patient__c = patientId;
        commHistory.Communication__c = commScheduleId;
        return commHistory;
    }
}
how to track the email by using google analytics
global class Batch_SMSInjection implements Database.Batchable<sObject>, Database.AllowsCallouts{    
    
    // Start method of batch class
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        String str_CommunicationType = 'SMS';
        String query = 'SELECT Id, Activate__c, Business_Rule__c, Comminication_Template__c, Communication_Type__c, Comminication_Template__r.Template_Name__c,Patient__r.Person__r.Contact__r.MobilePhone,'+
                        +' Day__c, Frequency__c, Hours__c, Patient__c, Patient__r.Person__c, Patient__r.Person__r.Contact__c, Patient__r.Person__r.Current_Timezone__c, Scheduled_Date__c, Time__c'+
                        +' FROM Communication_Scheduled__c'+
                        +' WHERE Activate__c = true AND Communication_Type__c =:str_CommunicationType AND Patient__r.SMS_Opt__c = true';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Communication_Scheduled__c> scope) {
        
        Map<Id, Communication_History__c> mapIdToSMSHistory = new Map<Id, Communication_History__c>();
        
        // creating map for all the communication history
        for(Communication_History__c history: [SELECT Id, CreatedDate, Patient__c, Communication__c, Communication_Template__c 
                                                    FROM Communication_History__c 
                                                    WHERE Communication__c IN :scope 
                                                    ORDER BY CreatedDate ASC]){
            
            if(!mapIdToSMSHistory.containsKey(history.Communication__c)){
                mapIdToSMSHistory.put(history.Communication__c,history);
            }
        }
        
        List<Communication_History__c> lstSMSHistoryInsert = new List<Communication_History__c>();
        Map<String, List<String>> map_TemplateNameSetOfContactId = new Map<String, List<String>>(); 
        Set<Id> set_ContactId = new Set<Id>();
        Map<Id, Contact> map_ContactIdAndRecord;
        List<Communication_Scheduled__c> list_CommScheduleToUpdate = new List<Communication_Scheduled__c>();
        
        // Iterating all the communication scheduled
        for(Communication_Scheduled__c smsSchedule : scope){
                    
            DateTime datetime_Accr_UserTimezone;
            if(!String.isEmpty(smsSchedule.Patient__r.Person__r.Current_Timezone__c)){
                datetime_Accr_UserTimezone = Utility.convertTimeAccrTimeZone(smsSchedule.Patient__r.Person__r.Current_Timezone__c);
            }else{
                datetime_Accr_UserTimezone = System.now();
            }
            
             // calculating the weekday of the current date And current time for a patient respective to timezone.    
            String currentTime = String.valueOf(datetime_Accr_UserTimezone.hour());          
           
            System.debug('------currentTime--------'+currentTime);
            System.debug('--------smsSchedule---------'+smsSchedule);
            
            
            String communicationTime = '12';
            if(smsSchedule.Time__c.indexOf(':') != -1){
                communicationTime = smsSchedule.Time__c.subString(0, smsSchedule.Time__c.indexOf(':'));
            }else if(smsSchedule.Time__c != '') {
                communicationTime =  smsSchedule.Time__c;
            }
            
            // checking for the communication matching criteria
            Boolean isCommSend = false;
            if(smsSchedule.Frequency__c == 'Daily'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime)
                        ||( mapIdToSMSHistory.containsKey(smsSchedule.Id) && datetime_Accr_UserTimezone.dateGmt() != mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.date())) {
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                }
            }
            else if(smsSchedule.Frequency__c == 'Monthly'){
                if((!mapIdToSMSHistory.containsKey(smsSchedule.Id) && communicationTime == currentTime && Integer.valueOf(smsSchedule.Day__c) == datetime_Accr_UserTimezone.dayGmt())
                            || mapIdToSMSHistory.containsKey(smsSchedule.Id) && mapIdToSMSHistory.get(smsSchedule.Id).CreatedDate.Day() != datetime_Accr_UserTimezone.dayGmt()){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                }
            }
            else if(smsSchedule.Frequency__c == 'Other' || String.isEmpty(smsSchedule.Frequency__c)){
                if(smsSchedule.Scheduled_Date__c == datetime_Accr_UserTimezone.dateGmt() && communicationTime == currentTime){
                    lstSMSHistoryInsert.add(createCommHistory(smsSchedule.Patient__c, smsSchedule.Id));
                    smsSchedule.Activate__c = false;
                    list_CommScheduleToUpdate.add(smsSchedule);
                }
            }
            
            // creating map of sms template and list of Person id
            if(isCommSend && !String.isEmpty(smsSchedule.Comminication_Template__r.Template_Name__c)){
                if(map_TemplateNameSetOfContactId.containsKey(smsSchedule.Comminication_Template__r.Template_Name__c)){
                    map_TemplateNameSetOfContactId.put(smsSchedule.Comminication_Template__r.Template_Name__c, new List<String>());
                }
                map_TemplateNameSetOfContactId.get(smsSchedule.Comminication_Template__r.Template_Name__c).add(smsSchedule.Patient__r.Person__r.Mobile_Phone__c);
                set_ContactId.add(smsSchedule.Patient__r.Person__c);
            }
        }
        
        if(set_ContactId.size() > 0){
             // This list is having all email instances which will be send out
            List<smagicinteract__smsMagic__c> list_SMSToBeSend = new List<smagicinteract__smsMagic__c>();
            
            // SMS instances are created for a respective sms template
            for(smagicinteract__SMS_Template__c smsTemplate : [SELECT Id, smagicinteract__Text__c FROM smagicinteract__SMS_Template__c WHERE smagicinteract__Name__c IN :map_TemplateNameSetOfContactId.keySet()]){
                //smagicinteract.TemplateResolver temp = new smagicinteract.TemplateResolver();
                String  templateText = smsTemplate.smagicinteract__Text__c;             
                String senderId = 'smsMagic';
                for(String personMob : map_TemplateNameSetOfContactId.get(smsTemplate.smagicinteract__Name__c)){  
                    smagicinteract__smsMagic__c smsObject = new smagicinteract__smsMagic__c();
                    smsObject.smagicinteract__SenderId__c = senderId;
                    smsObject.smagicinteract__PhoneNumber__c = personMob ;
                    smsObject.smagicinteract__ObjectType__c = 'Person__c';
                    smsObject.smagicinteract__disableSMSOnTrigger__c = 1;
                    smsObject.smagicinteract__external_field__c = smagicinteract.ApexAPI.generateUniqueKey();
                    smsObject.smagicinteract__SMSText__c = templateText;
                    list_SMSToBeSend.add(smsObject);
                }               
            }
            
            // Communications are send out and history created for each communication,.
            if(list_SMSToBeSend.size() > 0){
                String response = smagicinteract.ApexAPI.pushSMSCallout(list_SMSToBeSend);
                system.debug('@@@response  <> :' + response );
                Database.insert (list_SMSToBeSend, false);      
                insert lstSMSHistoryInsert;
            }
            
            if(list_CommScheduleToUpdate.size() > 0){
                Database.update(list_CommScheduleToUpdate, false);
            }
        }
        
    }
    
    
    global void finish(Database.BatchableContext BC) {
        // Do nothing
    }
    
    // this method is used to create communication history.
    public Communication_History__c createCommHistory(String patientId, String commScheduleId){
        Communication_History__c commHistory = new Communication_History__c();
        commHistory.Patient__c = patientId;
        commHistory.Communication__c = commScheduleId;
        return commHistory;
    }
}