Skip to content

Instantly share code, notes, and snippets.

@Sunil02kumar
Created November 19, 2019 10:16
Show Gist options
  • Save Sunil02kumar/5b2a95a27354e76e07a7e47878ee2440 to your computer and use it in GitHub Desktop.
Save Sunil02kumar/5b2a95a27354e76e07a7e47878ee2440 to your computer and use it in GitHub Desktop.
How to Convert Salesforce Classic Notes into Lightning Notes
public class SK_ConvertNotesForLightningBatch implements Database.Batchable<sObject>,Database.Stateful{
public string qString;
string errorDetailsString = 'Parent Record Id ,Note Id, Error deatils \n';
string successRecordString='Parent Record Id ,Note Id,ContentNote Id \n';
long jobStartTime= 0;
long jobEndTime= 0;
public SK_ConvertNotesForLightningBatch(string qStr){
qString = qStr;
}
public Database.QueryLocator start(Database.BatchableContext BC) {
jobStartTime = system.now().getTime();
return Database.getQueryLocator(qstring);
}
public void execute(Database.batchableContext BC, List<sObject> scope){
List<string> parentRecordIds= new List<string>();
for(sObject sb:scope){
parentRecordIds.add(string.valueof(sb.get('Id')));
}
if(parentRecordIds.size()>0){
List<ContentNote> cnForInsertList = new List<ContentNote>();
List<ContentNote> contentNoteList = new List<ContentNote>();
List<Note> existingNoteList = new List<Note>();
for(Note nt:[select id,Title,parentId,body from Note where parentId IN:parentRecordIds]){
if(nt.body!=null && nt.body.length()>0){
ContentNote cn = new ContentNote();
cn.Title = nt.Title;
cn.Content = Blob.valueOf(nt.Body.escapeHTML4());
//no need to store note body in heap memory so initailizing new note with id
contentNoteList.add(cn);
existingNoteList.add(new Note(id=nt.Id,parentId=nt.parentId));
}
}
integer recordIndex = 0;
if(contentNoteList.size()>0){
List<Database.SaveResult> srlist= database.insert(contentNoteList,false);
recordIndex = 0;
List<ContentDocumentLink> conlinkList = new List<ContentDocumentLink>();
List<Note> successNoteList = new List<Note>();
for(Database.SaveResult sr:srlist){
if(sr.isSuccess()){
System.debug('ContentNote got inserted with id:'+sr.getId());
ContentDocumentLink recLink = new ContentDocumentLink();
recLink.ContentDocumentId = sr.getId();
recLink.LinkedEntityId = existingNoteList[recordIndex].parentId;
recLink.ShareType = 'I';
conLinkList.add(recLink);
successNoteList.add(existingNoteList[recordIndex]);
}else{
string errorString='';
for(Database.Error err : sr.getErrors()) {
errorString = err.getStatusCode() + ': ' + err.getMessage()+ ': ' +err.getFields();
System.debug('The following error has occurred.'+errorString);
}
errorDetailsString = errorDetailsString + existingNoteList[recordIndex].parentId +','+existingNoteList[recordIndex].Id+','+errorString.escapeCsv()+' \n';
}
recordIndex = recordIndex+1;
}
system.debug('**successNoteList.size()-'+successNoteList.size());
system.debug('**conLinkList.size()-'+conLinkList.size());
if(conLinkList.size()>0){
srlist= new List<Database.SaveResult>();
srlist = database.insert(conLinkList,false);
recordIndex = 0;
for(Database.SaveResult sr:srlist){
if(sr.isSuccess()){
System.debug('ContentDocumentLink Note got inserted with id:'+sr.getId());
successRecordString = successRecordString+ conLinkList[recordIndex].LinkedEntityId+','+successNoteList[recordIndex].Id+','+conLinkList[recordIndex].ContentDocumentId+'\n';
}else{
string errorString='';
for(Database.Error err : sr.getErrors()) {
errorString = err.getStatusCode() + ': ' + err.getMessage()+ ': ' +err.getFields();
System.debug('The following error has occurred.'+errorString);
}
errorDetailsString = errorDetailsString + conLinkList[recordIndex].LinkedEntityId +','+successNoteList[recordIndex].Id+','+errorString.escapeCsv()+' \n';
}
recordIndex = recordIndex+1;
}
}
}
}
}
public void finish(Database.batchableContext BC){
jobEndTime = system.now().getTime();
long batchJobExecutionTimeInSeconds= (jobEndTime - jobStartTime)/1000;
long batchJobExecutionTimeInMins= batchJobExecutionTimeInSeconds/60;
long batchJobExecutionTimeInHours= batchJobExecutionTimeInMins/60;
AsyncApexJob a = [SELECT id, ApexClassId, JobItemsProcessed, TotalJobItems, NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :BC.getJobId()];
string jobConclusion='Your SK_ConvertNotesForLightningBatch batch job with id-'+BC.getJobId()+' to convert Notes to Lightning notes is completed';
jobConclusion = jobConclusion + ' This job took '+ string.valueof(batchJobExecutionTimeInMins)+' minutes to complete';
jobConclusion =jobConclusion +' It executed ' + a.totalJobItems + ' batches. Of which, ' + a.jobitemsprocessed + ' processed without any exceptions thrown and ' + a.numberOfErrors + ' batches threw unhandled exceptions.';
system.debug('*******SK_ConvertNotesForLightningBatch jobConclusion:'+jobConclusion);
string instanceURL= URL.getSalesforceBaseUrl().gethost();
Messaging.EmailFileAttachment csvAttcError = new Messaging.EmailFileAttachment();
blob errorcsvBlob = Blob.valueOf(errorDetailsString);
string errorcsvname= instanceURL+'-Error deatils for Notes not being processed.csv';
csvAttcError.setFileName(errorcsvname);
csvAttcError.setBody(errorcsvBlob);
Messaging.EmailFileAttachment csvAttcSuccess = new Messaging.EmailFileAttachment();
blob successcsvBlob = Blob.valueOf(successRecordString);
string successcsvname= instanceURL+'-Successfully processed notes.csv';
csvAttcSuccess.setFileName(successcsvname);
csvAttcSuccess.setBody(successcsvBlob);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject(instanceURL+'-SK_ConvertNotesForLightningBatch job is completed.');
mail.setPlainTextBody(jobConclusion);
mail.setHtmlBody(jobConclusion);
mail.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttcError,csvAttcSuccess});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment