0

I am trying to look at all tasks for a specific time frame, then create a note and set the LinkedEntityId to the whatid or whoid. This code creates the content note, 1 for each task. But then created a contentdocumentlink for each whatid or whoid for every note.

For instance, the query returns 8 tasks, 8 contentnotes are created and then each note is associated to each whatid(opps). So every opp has 8 notes. I have reworked this a million times and I am just not sure how to get it to know that I just want each contentnote associated to the task it "copied".

At this point I think I am over complicating it and the answer is so easy that I am not seeing it. How can I get this to create one note per task, and then associate it to the opp that the task is related? (whatid)

global class archiveTasksBatch implements Database.Batchable<SObject>, Schedulable{

public final string query;
date mydate = date.today().addDays(-369);

public archiveTasksBatch() {
    query = 'Select WhoId, WhatId, Subject, Status, OwnerId, Id, Description, CreatedDate, ActivityDate From Task where ActivityDate = :mydate' ;
}
public void execute(SchedulableContext sc){
    Database.executeBatch(this, 100);
}
public Database.QueryLocator start(Database.BatchableContext bc){
    return Database.getQueryLocator(query);
}

public void execute(Database.BatchableContext bc, List<sObject> scope){

    list<ContentNote > newObjects = new list<ContentNote >();
    list<ContentDocumentLink  > newCDL = new list<ContentDocumentLink  >();
    Map<ID, String> taskIdMap = new Map<ID, String>();





    for(Sobject s : scope){
        Task obj = (Task) s;
        String myString = obj.Description + obj.ActivityDate;
        Blob myBlob = Blob.valueof(myString.escapeHtml4());
        newObjects.add(new ContentNote (
        Title = obj.Subject,
        Content = myBlob
        ));

   }

        system.debug('*********************************newObjects' +newObjects.size());
        system.debug('*********************************scope' +scope.size());

        if(!newObjects.isEmpty()){
            Database.SaveResult[] srList = Database.insert(newObjects, false);
            for (Database.SaveResult sr : srList) {
                        for (Sobject sc : scope){
                        Task t = (Task) sc;
                        string tid = t.WhatId;
                        if(tid == null) {
                            tid = t.WhoId;}
                        taskIdMap.put(sr.Id, tid);
                if(sr.isSuccess()) {
                    ContentDocumentLink cdl = new ContentDocumentLink();
                    cdl.ContentDocumentId = sr.getId();
                    cdl.LinkedEntityId = taskIdMap.get(sr.id);
                    cdl.Visibility = 'AllUsers';
                    cdl.ShareType = 'I';
                    newCDL.add(cdl);
        system.debug('*********************************srList' +srList.size());
        system.debug('*********************************newCDL' +newCDL.size());
        system.debug('*********************************LinkedEntityId' +cdl.LinkedEntityId);
        system.debug('*********************************ContentDocumentId' +cdl.ContentDocumentId);

                }
            }
        }
     }
    insert newCDL;
}


public void finish(Database.BatchableContext bc){
    system.debug('JOB IS FINISHED');
}

}

1 Answer 1

0

I finally figured this out - with some help from Zuinglio Lopes Ribeiro Júnior on the Salesforce dev forum.

global class archiveTasksBatch implements Database.Batchable<SObject>, Schedulable{

public final string query;
Date mydate = Date.newInstance(2017, 11, 30);
private Integer count = -1;

public archiveTasksBatch() {
    query = 'Select WhoId, WhatId, Subject, Status, OwnerId, Id, Owner.Name, Description, CreatedDate, ActivityDate From Task where IsClosed=True AND ActivityDate >= :mydate' ;
}
public void execute(SchedulableContext sc) {
    Database.executeBatch(this, 100);
}
public Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator(query);
}

public void execute(Database.BatchableContext bc, List<sObject> scope) { //scope is the list of Tasks returned from the query
    Map<Id,ContentNote> contentsByTask  = new Map<Id,ContentNote>(); //Map of content for the Note by task
    List<ContentDocumentLink>   newCDL  = new List<ContentDocumentLink>(); //list to add the new Notes to be created
    for (Task task : (List<Task>)scope){
        if(!string.isBlank(task.Description)){ //if the description field is not blank
            string comment = task.Description; //add it to the string comment
            comment = comment.replaceAll('<[/a-zAZ0-9]*>',' '); // replace all HTML tags in comment
            string myString = 'Owner: ' +task.owner.name +'\n Due Date: ' +task.ActivityDate +'\n Comments: '+comment ; //string of notes to dd to blob
            Blob myBlob = Blob.valueOf(myString.escapeHtml4().escapeXml().replace('\r\n', '<br>').replace('\n', '<br>').replace('\r', '<br>')); //blob to add task comments to Note comments replacing HTML, XML and adding line breaks
            Id tid = task.WhatId; //set tid to the Whatid - account or opp
            if(tid == null){ // if the whatid is null
                tid = task.WhoId; //set the whoid - contacts
            }
            contentsByTask.put(tid, new ContentNote ( //put the new note in the list
                                        Title = task.Subject,
                                        Content = myBlob
                                        ));
        }
        if(string.isBlank(task.Description)){ //if the description field is  blank
            string myString = 'Owner: ' +task.owner.name +'\n Due Date: ' +task.ActivityDate +'\n Comments: None' ; //string of notes to dd to blob
            myString = myString.replaceAll('<[^>]+>',' '); // replace all HTML tags in comment
            Blob myBlob = Blob.valueof(myString.escapeHtml4().replace('\r\n', '<br>').replace('\n', '<br>').replace('\r', '<br>')); //blob to add task comments to Note comments replacing HTML, XML and adding line breaks
            Id tid = task.WhatId;//set tid to the Whatid - account or opp
            if(tid == null){ // if the whatid is null
                tid = task.WhoId; //set the whoid - contacts
            }
            contentsByTask.put(tid, New ContentNote ( //put the new note in the list
                                    Title = task.Subject,
                                    Content = myBlob
                                    ));
        }
    }
    if (!contentsByTask.isEmpty()) { //if the list of notes is not blank
        Database.insert(contentsByTask.values(), false); //insert the notes into the database
        for (Id taskId : contentsByTask.keySet()) {
            Contentnote cont = contentsByTask.get(taskId); //get the task id associated in the map to the note
            if (cont.Id != null){ //if it is not null
                ContentDocumentLink cdl = new ContentDocumentLink(); //create the ContentDocumentLink and associate it to the note
                cdl.ContentDocumentId   = cont.Id;
                cdl.LinkedEntityId      = taskId;
                cdl.Visibility          = 'AllUsers';
                cdl.ShareType           = 'I';
                newCDL.add(cdl);

                system.debug('*********************************newCDL' +newCDL.size());
                system.debug('*********************************LinkedEntityId' +cdl.LinkedEntityId);
            }
        }
        if (!newCDL.isEmpty())
            try{
               insert newCDL; 
            }
        catch(Exception e){
            system.debug(e.getMessage());                
        }
        count += scope.size();
        system.debug('*********************************count' +count);

    }
    delete scope; //deletes all of the tasks
}

public void finish(Database.BatchableContext bc){
    system.debug('JOB IS FINISHED');
}

}

You must log in to answer this question.

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