I am trying to create a contentworkspaceDoc , contentWorkspaceDoc allows a document to be shared with multiple libraries. I am have a query where I pull all the existing contentworkspaceDoc from the existing documents. , I have a query where I pull the workspaces which I have want to check against.
I am trying to find for each contentworkspace , if there is a corresponding ContentworkspaceDoc with that contentworkspaceId and contentdocumentId. If Yes , do nothing , If no then create a new content workspace Doc , which allows me to share the content document Id with that contentworkspace. Below is the piece of code , I am trying to do this logic. But I am not sure , it works in some scenarios but in some scenarios it picks up the content document Id which is already shared and gives me an error. Any help or advise would be really great. Many Thanks.
//get contentworkspace
Map<Id, ContentWorkspace> contentWorkspaceMap = new Map<Id, ContentWorkspace>([select Id, Name from ContentWorkspace Where Name IN: UserNames ORDER BY Id DESC]);
//Get documents from contentversions
Map<Id, ContentVersion> contentVersionMap = new Map<Id, ContentVersion>([Select Id, ContentDocumentId, ContentDocument.ParentId from ContentVersion where IsLatest = true AND (record__c IN: dealRecordMap.keySet() OR agreement__c IN: agreementMap.keySet())]);
set<Id> documentIds = new set<Id>();
for(contentVersion cvValue : contentVersionMap.values()){
documentIds.add(cvValue.contentDocumentId);
}
//get all documents
Map<Id, ContentDocument> cDocumentsMap = new Map<Id, ContentDocument>([Select Id from ContentDocument where Id IN: documentIds]);
// get all contentworkspacedoc for which have contentdocumentId in those documentIds set.
Map<Id, ContentworkspaceDoc> cwSpaceDocMap = new Map<Id, ContentWorkspaceDoc>();
Map<Id, Id> bigMap;
for(contentWorkspaceDoc cwSpaceDoc : [select Id , contentDocumentId, contentWorkspaceId from ContentWorkspaceDoc where contentDocumentId IN: documentIds and isOwner = false ORDER BY contentWorkspaceId ASC])
{
cwSpaceDocMap.put(cwSpaceDoc.Id, cwSpaceDoc);
bigMap = new Map<Id,Id>{cwSpaceDoc.ContentWorkspaceId => cwSpaceDoc.ContentDocumentId};
}
Map<Id, contentworkspaceDoc> cwDocNewMap = new Map<Id, contentWorkspaceDoc>();
for(Id cwId1 : contentWorkspaceMap.keySet()){
system.debug('entered 1st loop');
for(contentWorkspaceDoc spaceDoc1 : cwSpaceDocMap.values()){
system.debug('cwSpaceDocMap '+ cwSpaceDocMap.size());
system.debug('spaceDoc1'+ spaceDoc1.contentWorkspaceId);
system.debug('cwId1'+ cwId1);
system.debug('content document Id' + spaceDoc1.ContentDocumentId);
if(spaceDoc1.contentWorkspaceId == cwId1){
cwSpaceDocMap.remove(spaceDoc1.Id);
break;
}
else{
ContentWorkspaceDoc cwdoc = new ContentWorkspaceDoc();
system.debug('entered');
cwDoc.ContentDocumentId = spaceDoc1.contentDocumentId;
cwDoc.ContentWorkspaceId = cwId1;
cwTocwDocMap.put(cwId1, cwDoc);
// break;
//
}
Thank You