My_Test_Repo/force-app/main/default/classes/AddAttachementToProjectHand...

62 lines
2.9 KiB
OpenEdge ABL

/**
* This class handles the addition of attachments to projects.
*/
public with sharing class AddAttachementToProjectHandler {
//Method to add attachments to a list of projects.
public static void AddAttachments(List<ProjectDemo__c> newProject) {
// Collect the Opportunity IDs associated with the new projects
try{
Set<Id> oppIds = new Set<Id>();
for (ProjectDemo__c pro : newProject) {
oppIds.add(pro.Opportunity_Name__c);
}
// Retrieve ContentDocumentLink records for the collected Opportunity IDs
List<ContentDocumentLink> contentDocumentLinks = [
SELECT ContentDocumentId, LinkedEntityId, ShareType, Visibility
FROM ContentDocumentLink
WHERE LinkedEntityId IN :oppIds
];
// Organize ContentDocumentLinks by Opportunity ID
Map<Id, List<ContentDocumentLink>> projectIdToContentDocumentLinks = new Map<Id, List<ContentDocumentLink>>();
for (ContentDocumentLink cdl : contentDocumentLinks) {
List<ContentDocumentLink> cdlList = projectIdToContentDocumentLinks.containsKey(cdl.LinkedEntityId) ?
projectIdToContentDocumentLinks.get(cdl.LinkedEntityId) :
new List<ContentDocumentLink>();
cdlList.add(cdl);
projectIdToContentDocumentLinks.put(cdl.LinkedEntityId, cdlList);
}
// Prepare a list of ContentDocumentLinks to be inserted
List<ContentDocumentLink> insertCdlList = new List<ContentDocumentLink>();
for (ProjectDemo__c proj : newProject) {
system.debug('@@@@@@ proid:'+proj.Id);
if (projectIdToContentDocumentLinks.containsKey(proj.Opportunity_Name__c)) {
List<ContentDocumentLink> contentDocumentLinksToCopy = projectIdToContentDocumentLinks.get(proj.Opportunity_Name__c);
for (ContentDocumentLink cdl : contentDocumentLinksToCopy) {
// Create new ContentDocumentLink records with relevant data
ContentDocumentLink newCdl = new ContentDocumentLink(
ContentDocumentId = cdl.ContentDocumentId,
LinkedEntityId = proj.Id,
ShareType = cdl.ShareType,
Visibility = cdl.Visibility
);
insertCdlList.add(newCdl);
}
}
}
// Insert the new ContentDocumentLink records if the list is not empty
if (!insertCdlList.isEmpty()) {
database.insert(insertCdlList);
}
}
catch(exception ex){
system.debug('Error Occur ==' +ex.getMessage());
}
}
}