1

I'm trying to amend my code to change one of the fields that appears in an email. I no longer wish for the BMCServiceDesk__IncidentResolution__c field to appear in an email.

I understand how I could easily change the name in three parts of the code if the desired field was on the incident object (and i've tested that to confirm it works, but unfortunately the field is on another object. It's stored in the IncidentHistory object. How should I go about changing my code so that it pulls through the field BMCServiceDesk__note__c from the IncidentHistory object.

public with sharing class COL_JIS_EmailConversationController {



     BMCServiceDesk__Incident__c incident = null;
    //List<BMCServiceDesk__CustomAttachment__c> incidentAttachments = null;
    //Map<String,String> incidentAttachments = null;

     transient String bodyText = null;
     transient String lastEmailBody = null;
     String subject = null;
    //Attachment attachment = null;
    //String attID = null;
    String toAddresses = '';
    String ccAddresses = '';

        public COL_JIS_EmailConversationController(){
      incident =  [select id, name, COL_JIS_Caller_Email__c, COL_JIS_Caller_Name__c, COL_JIS_Subject__c,
                        BMCServiceDesk__openDateTime__c,BMCServiceDesk__IncidentResolution__c,
                        COL_JIS_Service_Desk_Signature__c,COL_JIS_Incident_History_last_entry__c,
                        COL_JIS_Category_Type__c
                               from BMCServiceDesk__Incident__c
                where id = :ApexPages.currentPage().getParameters().get('id') limit 1];

            List<BMCServiceDesk__IncidentHistory__c> inboundEmails = [select Id, BMCServiceDesk__note__c, BMCServiceDesk__EmailConversationData__c,
                                                                                    COL_JIS_CCEmailAddresses__c
                                                                                    from BMCServiceDesk__IncidentHistory__c 
                                                                                    where BMCServiceDesk__actionId__c = 'Email Received'
                                                                                    and BMCServiceDesk__FKIncident__c = :ApexPages.currentPage().getParameters().get('id')
                                                                                    order by Name DESC Limit 1]; 

            if(inboundEmails != null && inboundEmails.size() > 0){
                lastEmailBody = inboundEmails[0].BMCServiceDesk__note__c;
                if(inboundEmails[0].BMCServiceDesk__EmailConversationData__c != null){toAddresses = inboundEmails[0].BMCServiceDesk__EmailConversationData__c;}
                if(inboundEmails[0].COL_JIS_CCEmailAddresses__c != null){ccAddresses = inboundEmails[0].COL_JIS_CCEmailAddresses__c;}
            }
        if(incident != null){
            toAddresses += incident.COL_JIS_Caller_Email__c;
            subject = incident.COL_JIS_Subject__c;   
        }

    }

    public PageReference sendEmail() {
        system.debug('enter sendEmail');

        // attach files
        attachFile();
        // create a mail incident history record 

        BMCServiceDesk__Action__c action = null;
        List<BMCServiceDesk__Action__c> actions = [select Id from BMCServiceDesk__Action__c where BMCServiceDesk__Abbreviation__c = 'EMAILOUT' Limit 1];
        if(actions != null && actions.size()>0){
            system.debug('action found');
          action = actions[0];
        }

        String emailBody = bodyText;




        system.debug('************************* To: ' + toAddresses);
        COL_JIS_SingleEmailMessage mail = new COL_JIS_SingleEmailMessage();

        // get the org address to send the email from
        if(incident.COL_JIS_Category_Type__c != ''){
            List<OrgWideEmailAddress> orgWideAddresses = [SELECT Id, Address FROM OrgWideEmailAddress WHERE DisplayName = :incident.COL_JIS_Category_Type__c limit 1 ];
            if(orgWideAddresses != null && orgWideAddresses.size() > 0){
                mail.setReplyTo(orgWideAddresses[0].Address);
                mail.setOrgWideEmailAddressId(orgWideAddresses[0].Id);
            }

        }

        // set the from address as the default no reply
        /*List<OrgWideEmailAddress> replyTo = [SELECT Id, Address FROM OrgWideEmailAddress WHERE DisplayName = 'Jisc Remedyforce' limit 1 ];
            if(replyTo != null && replyTo.size() > 0){
                mail.setOrgWideEmailAddressId(replyTo[0].Id);

            }*/

        mail.setToAddress(toAddresses);
        mail.setSubject(subject + '(Ref:IN:' + incident.Name + ')');
        if(ccAddresses != null && ccAddresses != ''){
            mail.setCcAddresses(ccAddresses);
        }
        mail.setPlainTextBody(buildPlaintextBody());
        mail.setHtmlBody(buildHTMLBody());
        mail.setSaveAsActivity(false);
        Messaging.EmailFileAttachment[] attachArray = new Messaging.EmailFileAttachment[]{};
        String attachmentText = '';
        Integer noOfAttachments = selectedFoos.size();

        if(selectedFoos.size() > 0){
            //noOfAttachments ++;
            attachmentText = 'Attachments sent with this email(' + noOfAttachments + ')';
        }

        //List<Attachment> attachmentsToInsert = new List<Attachment>();
        Integer i = 1;
        for(Attachment a : selectedFoos){

            attachmentText += '\n' + i + '. ' + a.Name;
            i++;
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            Attachment at = [select body from Attachment where Id = :a.Id limit 1];
            attach.setFileName(a.Name);
            attach.setBody(at.body);
            //a.parentId = incident.Id;
            attachArray.add(attach);

            //if(a.Id == null){
                //attachmentsToInsert.add(a);
            //}
        }
        //insert attachmentsToInsert;

        if(attachmentText != ''){
            attachmentText += '\n***********************';
        }
        mail.setFileAttachments(attachArray);

        if(incident != null && action != null){
            system.debug('incident and action exist');
            Integer actionCount = [select count() from BMCServiceDesk__IncidentHistory__c where BMCServiceDesk__FKIncident__c = :incident.Id];
            actionCount++;
            String actionName = incident.Name + '_' + string.valueOf(actionCount);
            // add a note to the incident

            emailBody = bodyText + '\n\n' + attachmentText ;

            BMCServiceDesk__IncidentHistory__c note = new BMCServiceDesk__IncidentHistory__c(BMCServiceDesk__FKIncident__c = incident.Id,
                                                        BMCServiceDesk__note__c = emailBody,
                                                        BMCServiceDesk__description__c = 'Email sent to ' + toAddresses,
                                                        BMCServiceDesk__FKAction__c = action.Id,
                                                        Name =  actionName,COL_JIS_Caller_Email__c = incident.COL_JIS_Caller_Email__c );
            if(note != null){
                system.debug('insert the note');
                insert note;
            }
        }

    try{
        mail.send();
    }catch(Exception e){
        ApexPages.addMessages(e);
        return null;
    }

    //return null; // stay on the same page 
    return new PageReference('javascript:window.close()');
}

    String[] getAddressArray(String addresses){
        if(addresses == null){addresses = '';}
        String[] addressList = addresses.split(';',0);
        return addressList;

    }

    public BMCServiceDesk__Incident__c getIncident() {

        return incident;
    }

    public String getToAddresses() {
        if(toAddresses == null){
            toAddresses = getIncident().COL_JIS_Caller_Email__c;
        }
        return toAddresses;
    }

    public void setToAddresses(String s){
        toAddresses = s;
    }

    public String getCcAddresses() {

        return ccAddresses;
    }

    public void setCcAddresses(String s){
        ccAddresses = s;
    }

    public String getAdditionalText() {
        return bodyText;
    }

    public void setAdditionalText(String s) {
        bodyText = s;
    }

    public String getLastEmailText() {


        return lastEmailBody;
    }

    public void setLastEmailText(String s) {
        lastEmailBody = s;
    }

    public String getSubject() {


        return subject;
    }

    public void setSubject(String s) {
        subject = s;
    }

     public String getAttachFiles() {

        String attachmentList = '';

        for(Attachment a : attachments){
            attachmentList += a.name + '\n';
        }   
        return attachmentList;
    }



    // =====================================================================================
    // Private helper methods
    // =====================================================================================

    private String buildHTMLBody(){
        // we cannot use templates as this would require a contact or user and would 
        // result in a double count of the email limit.


        String body = bodyText;
        if(incident.COL_JIS_Service_Desk_Signature__c != null){body += incident.COL_JIS_Service_Desk_Signature__c;}
        body += '<p><hr/><p>';
        body = body.replaceAll('\n','<br>');
        body += '<p>Enquiry Number: '  + incident.Name;
        body += '<br>Subject: ';
        if(incident.COL_JIS_Subject__c != null){body += incident.COL_JIS_Subject__c;}
        body += '<br>Open Date: ';
        if(incident.BMCServiceDesk__openDateTime__c != null){body += incident.BMCServiceDesk__openDateTime__c;}
        body += '<br>Caller Name: ';
        if(incident.COL_JIS_Caller_Name__c != null){body += incident.COL_JIS_Caller_Name__c;}
        body += '<br>Enquiry: <p>';
        if(incident.BMCServiceDesk__incidentResolution__c != null){body += incident.BMCServiceDesk__incidentResolution__c.replaceAll('\n', '<br>');}
        body += '<p>Please reply to this email with any updates on this issue.<p>';

        if(lastEmailBody != null){body += lastEmailBody.replaceAll('\n', '<br>');}

        return body;

    }

    private String buildPlaintextBody(){
        // we cannot use templates as this would require a contact or user and would 
        // result in a double count of the email limit.

        String body = bodyText;
        if(incident.COL_JIS_Service_Desk_Signature__c != null){body += incident.COL_JIS_Service_Desk_Signature__c;}
        body += '\n----------------------------------------------------------------\n\n';
        body += '\n\nEnquiry Number: '  + incident.Name;
        body += '\nSubject: ';
        if(incident.COL_JIS_Subject__c != null){body += incident.COL_JIS_Subject__c;}
        body += '\nOpen Date: ';
        if(incident.BMCServiceDesk__openDateTime__c != null){body += incident.BMCServiceDesk__openDateTime__c;}
        body += '\nCaller Name: ';
        if(incident.COL_JIS_Caller_Name__c != null){body += incident.COL_JIS_Caller_Name__c;}
        body += '\nEnquiry: \n';
        if(incident.BMCServiceDesk__incidentResolution__c != null){body += incident.BMCServiceDesk__incidentResolution__c;}
        body += '\nPlease reply to this email with any updates on this issue.\n\n';

        if(lastEmailBody != null){body += lastEmailBody;}

        return body;

    }

    // =====================================================================================
    // attachments
    // =====================================================================================





    public void setAttachment(Attachment att) {
        if(att != null){this.attachment = att;}
    }



    // attachments
    transient public Attachment attachment;

    public Attachment getAttachment() {
      if (attachment == null)
          attachment = new Attachment();
        return attachment;
      }



    List<Attachment> attachments = new List<Attachment>();
    public String filesize { get; set; }


    public PageReference attachFile() {
        try{
        system.debug('************** attachFile: '+ attachment);
        if(attachment != null && attachment.Name != null && attachment.Name != ''){
            attachment.parentId = incident.Id;

            insert attachment;
            attachment.body = null;
            wFoo f = new wFoo(attachment);
            f.selected = true;
            fooList.add(f);
            //attachments.add(attachment);
            attachment = null;
        }

        selectedFoos = new List<Attachment>();
        for (wFoo foo : getFoos()) {
            if (foo.selected == true) {
                system.debug('********************************** Selected Foo: ' + foo.foo.Name);
                selectedFoos.add(foo.foo); 
                //attachments.add(foo.foo);
            }
        }
        Set<Attachment> uniqueAttachments = new Set<Attachment>(selectedFoos);
        attachments = new List<Attachment>(uniqueAttachments);
        }catch(Exception e){

        }
        return null;
    }

    public List<Attachment> getAttachments(){

        return attachments;
    }



    public class wFoo {
        public Attachment foo {get; set;}
        public boolean selected {get; set;}

        public wFoo(Attachment foo) {
            this.foo = foo;
            selected = false; //If you want all checkboxes initially selected, set this to true
        }
    }

    public List<wFoo> fooList {get;set;}
    public List<Attachment> selectedFoos {get; set;}

    public List<wFoo> getFoos() {
        system.debug('*************************** Get Foos: ');
        if (fooList == null) {
            fooList = new List<wFoo>();
            for (Attachment foo : [select id, Name, Body from Attachment where ParentId = :incident.Id]) {
                system.debug('*************************** Custom Attachment: ' + foo.Name);
                fooList.add(new wFoo(foo));
            }
        }
        return fooList;
    }


}

1 Answer 1

1

This appears to me to be fairly straightforward. To preserve the attachment and pull through the BMCServiceDesk__note__c, the below section of code remains unchanged:

    if(incident != null && action != null){
        system.debug('incident and action exist');
        Integer actionCount = [select count() from BMCServiceDesk__IncidentHistory__c where BMCServiceDesk__FKIncident__c = :incident.Id];
        actionCount++;
        String actionName = incident.Name + '_' + string.valueOf(actionCount);
        // add a note to the incident

        emailBody = bodyText + '\n\n' + attachmentText ;

        BMCServiceDesk__IncidentHistory__c note = new BMCServiceDesk__IncidentHistory__c(BMCServiceDesk__FKIncident__c = incident.Id,
                                                    BMCServiceDesk__note__c = emailBody,
                                                    BMCServiceDesk__description__c = 'Email sent to ' + toAddresses,
                                                    BMCServiceDesk__FKAction__c = action.Id,
                                                    Name =  actionName,COL_JIS_Caller_Email__c = incident.COL_JIS_Caller_Email__c );
        if(note != null){
            system.debug('insert the note');
            insert note;
        }
    }

What does get changed is the way you compose your email. In your helper method:

// =====================================================================================
// Private helper methods
// =====================================================================================

private String buildHTMLBody(){
    // we cannot use templates as this would require a contact or user and would 
    // result in a double count of the email limit.

Remove the following line:

if(incident.BMCServiceDesk__incidentResolution__c != null){body += incident.BMCServiceDesk__incidentResolution__c.replaceAll('\n', '<br>');}

And in a different section under:

private String buildPlaintextBody(){
    // we cannot use templates as this would require a contact or user and would 
    // result in a double count of the email limit.

Remove this line:

if(incident.BMCServiceDesk__incidentResolution__c != null){body += incident.BMCServiceDesk__incidentResolution__c;}

That will remove references to BMCServiceDesk__incidentResolution__c from within your email bodies (both plain text and html) without disturbing the BMCServiceDesk__IncidentHistory__c note which appears to consist of the email body you're generating based on what I can gather from reading your code.

9
  • Thanks for your help, I've tried this before and I find that it doesn't pull through any of the incident history notes. FYI they're stored on a seperate object and one is created after every customer interaction. Can you suggest anything else that I could change?
    – Glenn Daly
    May 12, 2016 at 15:28
  • I suggest you add debug statements to your wFoo class and to your other attachment code as well to see why it's not selecting the email bodies to attach and push them thru. That's the only thing I can see from just reading your code. If the debugs don't detect something, I'd need to see your schema to advise you further. I suspect that because you removed the Incident_Resolution__c field, either it's not being written to the history notes or it's no longer something is missing for it to be returned by the query.
    – crmprogdev
    May 12, 2016 at 16:01
  • @crmprogev I have noticed that is pulling through the note (apologies for the confusion), but it only pulls through 1 of the notes into the email. How can I ensure that it pulls through all notes from the incident history, and not just the first?
    – Glenn Daly
    May 16, 2016 at 9:00
  • I think i've solved it! There is limitation of 1 record to be pulled through on the Incident History SOQL query. Increasing that pulls through the other records.
    – Glenn Daly
    May 16, 2016 at 10:45
  • Oh, so you removed the limit 1 on your query? That would seem to make sense to me as I think about it since you want multiple history records. It also would imply that your previous code was "broken" and you weren't returning all of those records. If you were, then that shouldn't have solved your issue. In any case, am glad to hear you got it sorted.
    – crmprogdev
    May 16, 2016 at 12:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .