• Hussein Azeez 2
  • NEWBIE
  • 35 Points
  • Member since 2017
  • Salesforce Developer

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 5
    Questions
  • 8
    Replies
here is the class:
 
global class Batch_EmailCheckLastModified implements Database.Batchable<sObject>{
    private String query;
    global Batch_EmailCheckLastModified(){
        System.debug('enter batch'); 
        this.query = 'SELECT Id,CreatedDate,LastModifiedDate,Expire_date__c,owner.name,owner.email,Quotation_Number__c, Inactive__c,PO_Approve_by_manager__c FROM Opportunity';
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('starting'); 
        return Database.getQueryLocator(this.query);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for(SObject s:scope){
            Opportunity opp=(Opportunity)s;
            Date created = date.newInstance(opp.CreatedDate.year(),opp.CreatedDate.month(),opp.CreatedDate.day());
            Date LastModify = date.newInstance(opp.LastModifiedDate.year(),opp.LastModifiedDate.month(),opp.LastModifiedDate.day());
            Date todayDate = date.today();
            Integer dayBetweenCreated=created.daysbetween(todayDate);
            if((dayBetweenCreated>3)&&(created.isSameDay(LastModify))){
                 mails.add(sendAlertEmail(opp)); 
            }
                
        }
        send(mails);
        
    }
    
    global void finish(Database.BatchableContext BC){
        
    }
   private Messaging.Singleemailmessage sendAlertEmail(Opportunity quot) {
        EmailTemplate emailTemplate = getEmailTemplate();
        String[] userEmails = new List<String>();
        String Body = emailTemplate.Body;
        String fullFileURL = URL.getSalesforceBaseUrl().toExternalForm() +
            '/' + quot.id; 
      
        Body = Body.replace('Dear User,', 'Dear User,<br/>');
        Body = Body.replace('Thank you,', '<br/><br/>Thank you,<br/>');
        Body = Body.replace('{!Opportunity.Link}', '<br/>'+fullFileURL);
        Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
        
        userEmails.add('warunya@crm-c.club');
        email.setHtmlBody(Body);
        email.setToAddresses(userEmails);
        email.setSubject(emailTemplate.Subject);
        
        //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        return email;
    }
    
    private void send(List<Messaging.SingleEmailMessage> mails){
        Messaging.sendEmail(mails);
    }
    
    private EmailTemplate getEmailTemplate() {
        EmailTemplate emailTemplate = [
            SELECT 
                Id, 
                HtmlValue,
                Subject,
                Body
            FROM EmailTemplate 
            Where Name = 'Update Opportunity Notification'
        ];
        return emailTemplate;
    }

}

And here is the test class:
 
@isTest (SeeAllData = true)
public class Test_Batch{
    static testMethod void Test_Batch_EmailCheckLastModifided_Method(){
        Test.startTest();
        
        Batch_EmailCheckLastModified batch = new Batch_EmailCheckLastModified();
        DataBase.executeBatch(batch);
        
        BatchOppProcuReserveExpiry batch2 = new BatchOppProcuReserveExpiry();
        Opportunity inputOpp=[select id,owner.name,Quotation_Number__c,owner.email from Opportunity limit 1];
        
        EmailTemplate newEmailTemplate = new EmailTemplate();
        newEmailTemplate.Name='Expired Opp';
        newEmailTemplate.DeveloperName='TestName';
        newEmailTemplate.TemplateType = 'Text';
		newEmailTemplate.FolderId = UserInfo.getUserId();
        newEmailTemplate.Body='{!Opportunity.OwnerFirstName} test {!Opportunity.Quotation_Number__c} test {!Opportunity.Link}';
        insert newEmailTemplate;
        batch2.sendAlertEmail(inputOpp);
        DataBase.executeBatch(batch2);

        Datetime dt = Datetime.now().addMinutes(1);
        String CRON_EXP = '0  00 1 3 * ?';
        
        System.schedule('Sample_Heading',CRON_EXP,new Schedule_EmailCheckLastModified()); 
        
        
        Test.stopTest();
        
    }
}

These two functions are not covered:
1- sendAlertEmail(Opportunity quot),
2- getEmailTemplate()

User-added image

I will appreciate any kind of help. Thank you
Here is the class that I want to create a test class for
@RestResource(urlMapping='/delivery_report')
global class SmsDeliveryReport {

	@HttpGet
    global static void receiveReport() {
    	RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;

        if(req.params.containsKey('Transaction') && req.params.containsKey('Status')) {
        	List<Task> updatedSms = updateDeliveryStatus(req.params.get('Transaction'), req.params.get('Status'));

        	if(!updatedSms.isEmpty()) {
        		res.statuscode = 200;
		        res.addHeader('Content-Type', 'text/html');
				res.responseBody = Blob.valueOf('REPORT_RECEIVED');

        	} else {
        		res.statuscode = 500;
		        res.addHeader('Content-Type', 'text/html');
				res.responseBody = Blob.valueOf('FAILED_TO_RECEIVE_REPORT');
        	}	        

        } else {
        	res.statuscode = 400;
	        res.addHeader('Content-Type', 'text/html');
			res.responseBody = Blob.valueOf('MISSING_REQUIRED_FIELD');
        }             
    }

    private static List<Task> updateDeliveryStatus(String transactionId, String newStatus) {
    	List<Task> sms = [
            SELECT SMS_Delivery_Status__c 
            FROM Task 
            WHERE SMS_Transaction_ID__c = :transactionId 
            ORDER BY CreatedDate DESC 
            LIMIT 1
        ];

    	if(!sms.isEmpty()) {
    		sms.get(0).SMS_Delivery_Status__c = newStatus;

    		update sms;
    	}

    	return sms;
    }
}

I've tried to test it with CalloutWithStaticResources but it turned out that the class method declared as a void type. Here is the test class that I've tried to use:
@IsTest
public class SmsDeliveryReportTest {

    @isTest static void receiveReportTest() {
        // Use StaticResourceCalloutMock built-in class to
        // specify fake response and include response body 
        // in a static resource.
        StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
        mock.setStaticResource('mockResponse');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'application/json');
        
        // Set the mock callout mode
        Test.setMock(HttpCalloutMock.class, mock);
        HTTPResponse res = new HTTPResponse();
        
        // Call the method that performs the callout
        SmsDeliveryReport.receiveReport();
        
        // Verify response received contains values returned by
        // the mock response.
        // This is the content of the static resource.
        System.assertEquals('{"hah":"fooled you"}', res.getBody());
        System.assertEquals(200,res.getStatusCode());
        System.assertEquals('application/json', res.getHeader('Content-Type'));   
    }
       
}

The test is failed and I only got 18% coverage.
I will appreciate any kind of help. Thank you.
Here is the code for the Batch class: 
global class SmsCounterBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator([
			SELECT 
				Id, Total_SMS_Delivered__c, Total_SMS_Failed__c, Total_SMS_Sent__c, 
				(
					SELECT Id, SMS_Delivery_Status__c 
					FROM ActivityHistories 
					WHERE (ActivityType = 'SMS') AND (Status = 'Completed')
				) 
			FROM Campaign 
			WHERE (IsActive = TRUE) AND (EndDate >= TODAY) 
			ORDER BY LastModifiedDate DESC
		]);
	}

   	global void execute(Database.BatchableContext BC, List<Campaign> scope) {
   		List<Campaign> campaignToUpdate = new List<Campaign>();

		for(Campaign campaign : scope) {
			if(!campaign.ActivityHistories.isEmpty()) {
				campaign.Total_SMS_Delivered__c = 0;
				campaign.Total_SMS_Failed__c = 0;
				campaign.Total_SMS_Sent__c = 0;

				for(ActivityHistory record : campaign.ActivityHistories) {
					if(record.SMS_Delivery_Status__c == 'Delivered') campaign.Total_SMS_Delivered__c++;
					else if(record.SMS_Delivery_Status__c == 'OK') campaign.Total_SMS_Sent__c++;
					else campaign.Total_SMS_Failed__c++;
				}

				campaignToUpdate.add(campaign);
			}
		}

		if(!campaignToUpdate.isEmpty()) update campaignToUpdate;
	}
	
	global void finish(Database.BatchableContext BC) {  }
}

And currently, I only figured out this testing class:
@isTest(SeeAllData=true) 
public class SmsCounterBatchTest {

    @IsTest public static void couterBatchTestMethod() {
    	
    	Campaign cam1 = new Campaign ();
        cam1.Name = 'Test Campaign 1';
        cam1.IsActive = True;
        cam1.Total_SMS_Delivered__c = 0;
        cam1.Total_SMS_Sent__c = 0;
        cam1.Total_SMS_Failed__c = 0;
        
    	Insert cam1;
    	
    	Campaign cam2 = new Campaign();
        cam2.Name = 'Test Campaign 2';
        cam2.IsActive = True;
        cam2.Total_SMS_Delivered__c = 0;
        cam2.Total_SMS_Sent__c = 0;
        cam2.Total_SMS_Failed__c = 0;
        
    	Insert cam2;
        Contact c = new Contact();
        c.LastName = 'Test Account';

        insert c;
        
        SMS__c sms = new SMS__C();
        sms.Campaign__c = cam1.Id;
        sms.Delivery_Status__c = 'Delivered';
        sms.Message__c = 'Test Message';
        sms.Recipient__c = c.Id;
        sms.Transaction_ID__c = '1b9f8ac8eb75494e80f1474aeb61d93d';
        
        insert sms;
        List<Campaign> campaignList = [SELECT Id, Total_SMS_Delivered__c, Total_SMS_Failed__c, Total_SMS_Sent__c, 
				(
					SELECT Id, SMS_Delivery_Status__c 
					FROM ActivityHistories 
					WHERE (ActivityType = 'SMS') AND (Status = 'Completed')
				) 
			FROM Campaign 
			WHERE (IsActive = TRUE)];
        if(!campaignList.isEmpty()) {

        cam1.Total_SMS_Delivered__c = 0;
        cam1.Total_SMS_Sent__c = 0;
        cam1.Total_SMS_Failed__c = 0;
        }
        update cam1;
        

        Test.StartTest();

        SmsCounterBatch counterBatch = new SmsCounterBatch();
     	
     	Database.executeBatch(counterBatch);
	    
	    Test.StopTest();   
        System.AssertEquals(database.countquery('SELECT COUNT()'+' FROM SMS__c'), 21);
    }
}

And here the uncovered part of the Batch class:

User-added image

I will appreciate any kind of help.
Thank you
Hi, everyone. I wrote a Trigger to assign the cases from Origin "Facebook" and "Web Live Chat" to different queues, but what is happening that the cases from the "Facebook" it assigns correctly but the case from "Web Live Chat" it goes to the user who created it. If someone creates it manually it works well but it doesn't when the case created automatically. Here is the code that used: 
trigger ChangetheCaseOwner on Case (before insert) {
    
    ID HQId = [SELECT Id 
               FROM Group 
               WHERE name=:'HQ'].Id;
    ID HKId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - HK'].Id;
    Id INId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - IN'].Id;
    Id MYId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - MY'].Id;
    Id PHId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - PH'].Id;
    Id SGId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - SG'].Id;
    Id THId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - TH'].Id;

    for(Case c : trigger.new)
    {
        if(c.Origin == 'Facebook') {
            c.OwnerId = HQId;
        } 
        else if (c.Origin =='Web Live Chat' && String.isEmpty(c.Description)) {
            c.OwnerId = HQId;
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: India')) {
            c.OwnerId = INId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Thailand')) {
            c.OwnerId = THId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Philippines')) {
            c.OwnerId = PHId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Singapore')) {
            c.OwnerId = SGId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Malaysia')) {
            c.OwnerId = MYId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Hong Kong')) {
            c.OwnerId = HKId;   
        }
        
    }  
}
User-added image
                                 <tbody>
                                    <apex:repeat value="{!SearchResult}" var="SearchProduct">
                                        <tr>
                                            <td><apex:inputCheckbox value="{!SearchProduct.Selected}"/></td>
                                            <td>{!SearchProduct.ArticleNumber}</td>
                                            <td>{!SearchProduct.ProductName}</td>
                                            <td>{!SearchProduct.PowerinKW}</td>
                                            <td>{!SearchProduct.Vacuuminmbar}</td>
                                            <td>{!SearchProduct.Airvolume}</td>
                                            <td>{!SearchProduct.FilterSize}</td>
                                            <td><button class="bsbtn bsbtn-xs" data-toggle="modal" data-
                                            target="#ProductInformation" data-dismiss="modal" type="button" 
                                   onclick="ProductInfoModal('{!SearchProduct.ProductDescription.Product2.Id}');">
                                           <span class="glyphicon glyphicon-question-sign"></span></button></td>
                                        </tr>
                                    </apex:repeat>
                                </tbody>

 
Here is the code for the Batch class: 
global class SmsCounterBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator([
			SELECT 
				Id, Total_SMS_Delivered__c, Total_SMS_Failed__c, Total_SMS_Sent__c, 
				(
					SELECT Id, SMS_Delivery_Status__c 
					FROM ActivityHistories 
					WHERE (ActivityType = 'SMS') AND (Status = 'Completed')
				) 
			FROM Campaign 
			WHERE (IsActive = TRUE) AND (EndDate >= TODAY) 
			ORDER BY LastModifiedDate DESC
		]);
	}

   	global void execute(Database.BatchableContext BC, List<Campaign> scope) {
   		List<Campaign> campaignToUpdate = new List<Campaign>();

		for(Campaign campaign : scope) {
			if(!campaign.ActivityHistories.isEmpty()) {
				campaign.Total_SMS_Delivered__c = 0;
				campaign.Total_SMS_Failed__c = 0;
				campaign.Total_SMS_Sent__c = 0;

				for(ActivityHistory record : campaign.ActivityHistories) {
					if(record.SMS_Delivery_Status__c == 'Delivered') campaign.Total_SMS_Delivered__c++;
					else if(record.SMS_Delivery_Status__c == 'OK') campaign.Total_SMS_Sent__c++;
					else campaign.Total_SMS_Failed__c++;
				}

				campaignToUpdate.add(campaign);
			}
		}

		if(!campaignToUpdate.isEmpty()) update campaignToUpdate;
	}
	
	global void finish(Database.BatchableContext BC) {  }
}

And currently, I only figured out this testing class:
@isTest(SeeAllData=true) 
public class SmsCounterBatchTest {

    @IsTest public static void couterBatchTestMethod() {
    	
    	Campaign cam1 = new Campaign ();
        cam1.Name = 'Test Campaign 1';
        cam1.IsActive = True;
        cam1.Total_SMS_Delivered__c = 0;
        cam1.Total_SMS_Sent__c = 0;
        cam1.Total_SMS_Failed__c = 0;
        
    	Insert cam1;
    	
    	Campaign cam2 = new Campaign();
        cam2.Name = 'Test Campaign 2';
        cam2.IsActive = True;
        cam2.Total_SMS_Delivered__c = 0;
        cam2.Total_SMS_Sent__c = 0;
        cam2.Total_SMS_Failed__c = 0;
        
    	Insert cam2;
        Contact c = new Contact();
        c.LastName = 'Test Account';

        insert c;
        
        SMS__c sms = new SMS__C();
        sms.Campaign__c = cam1.Id;
        sms.Delivery_Status__c = 'Delivered';
        sms.Message__c = 'Test Message';
        sms.Recipient__c = c.Id;
        sms.Transaction_ID__c = '1b9f8ac8eb75494e80f1474aeb61d93d';
        
        insert sms;
        List<Campaign> campaignList = [SELECT Id, Total_SMS_Delivered__c, Total_SMS_Failed__c, Total_SMS_Sent__c, 
				(
					SELECT Id, SMS_Delivery_Status__c 
					FROM ActivityHistories 
					WHERE (ActivityType = 'SMS') AND (Status = 'Completed')
				) 
			FROM Campaign 
			WHERE (IsActive = TRUE)];
        if(!campaignList.isEmpty()) {

        cam1.Total_SMS_Delivered__c = 0;
        cam1.Total_SMS_Sent__c = 0;
        cam1.Total_SMS_Failed__c = 0;
        }
        update cam1;
        

        Test.StartTest();

        SmsCounterBatch counterBatch = new SmsCounterBatch();
     	
     	Database.executeBatch(counterBatch);
	    
	    Test.StopTest();   
        System.AssertEquals(database.countquery('SELECT COUNT()'+' FROM SMS__c'), 21);
    }
}

And here the uncovered part of the Batch class:

User-added image

I will appreciate any kind of help.
Thank you
Hi, everyone. I wrote a Trigger to assign the cases from Origin "Facebook" and "Web Live Chat" to different queues, but what is happening that the cases from the "Facebook" it assigns correctly but the case from "Web Live Chat" it goes to the user who created it. If someone creates it manually it works well but it doesn't when the case created automatically. Here is the code that used: 
trigger ChangetheCaseOwner on Case (before insert) {
    
    ID HQId = [SELECT Id 
               FROM Group 
               WHERE name=:'HQ'].Id;
    ID HKId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - HK'].Id;
    Id INId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - IN'].Id;
    Id MYId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - MY'].Id;
    Id PHId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - PH'].Id;
    Id SGId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - SG'].Id;
    Id THId = [SELECT Id
               FROM Group
               WHERE name =:'B2C - TH'].Id;

    for(Case c : trigger.new)
    {
        if(c.Origin == 'Facebook') {
            c.OwnerId = HQId;
        } 
        else if (c.Origin =='Web Live Chat' && String.isEmpty(c.Description)) {
            c.OwnerId = HQId;
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: India')) {
            c.OwnerId = INId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Thailand')) {
            c.OwnerId = THId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Philippines')) {
            c.OwnerId = PHId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Singapore')) {
            c.OwnerId = SGId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Malaysia')) {
            c.OwnerId = MYId;   
        }
        else if (c.Origin =='Web Live Chat' && c.Description.contains('Country: Hong Kong')) {
            c.OwnerId = HKId;   
        }
        
    }  
}
User-added image
                                 <tbody>
                                    <apex:repeat value="{!SearchResult}" var="SearchProduct">
                                        <tr>
                                            <td><apex:inputCheckbox value="{!SearchProduct.Selected}"/></td>
                                            <td>{!SearchProduct.ArticleNumber}</td>
                                            <td>{!SearchProduct.ProductName}</td>
                                            <td>{!SearchProduct.PowerinKW}</td>
                                            <td>{!SearchProduct.Vacuuminmbar}</td>
                                            <td>{!SearchProduct.Airvolume}</td>
                                            <td>{!SearchProduct.FilterSize}</td>
                                            <td><button class="bsbtn bsbtn-xs" data-toggle="modal" data-
                                            target="#ProductInformation" data-dismiss="modal" type="button" 
                                   onclick="ProductInfoModal('{!SearchProduct.ProductDescription.Product2.Id}');">
                                           <span class="glyphicon glyphicon-question-sign"></span></button></td>
                                        </tr>
                                    </apex:repeat>
                                </tbody>