global without sharing class Batch_FixAttachmentToFiles implements Database.Batchable<sObject>{
|
// Id batchJobId = Database.executeBatch(new Batch_FixAttachmentToFiles(Datetime.newInstance(2023, 5, 20, 8, 0, 0),'Consumable_order__c'),2000);
|
private Datetime endDate = null;
|
private String objectApiName = null;
|
public Batch_FixAttachmentToFiles(Datetime setTime,String objectType) {
|
endDate = setTime;
|
objectApiName = objectType;
|
}
|
|
global Database.QueryLocator start(Database.BatchableContext BC) {
|
String queryObject = 'SELECT Id FROM ' + objectApiName + ' WHERE CreatedDate >=:endDate' + ' order by CreatedDate desc';
|
System.debug('queryObject:' + queryObject);
|
return Database.getQueryLocator(queryObject);//取指定Object下面的Id或者处理全部
|
}
|
|
global void execute(Database.BatchableContext BC, List<sObject> scope) {
|
Set<Id> setId = new Set<Id>();
|
for(sObject sc: scope){
|
setId.add(sc.Id);
|
}
|
List<ContentVersion> insertContents = new List<ContentVersion>();
|
Map<string,id> nameParentMaps = new Map<string,id>();
|
for (Attachment att : [select Id,Name ,OwnerId,ParentId, Body, CreatedById from Attachment where ParentId in: setId Order by Name desc]) {
|
nameParentMaps.put(att.name, att.ParentId);
|
ContentVersion cVersion = new ContentVersion();
|
cVersion.ContentLocation = 'S'; //S-Document is in Salesforce. E-Document is outside of Salesforce. L-Document is on a Social Netork.
|
cVersion.PathOnClient = att.Name; //File name with extention
|
cVersion.Origin = 'C'; //C-Content Origin. H-Chatter Origin.
|
cVersion.Title = att.Name; //Name of the file
|
cVersion.VersionData = att.Body; //File content
|
insertContents.add(cVersion);
|
}
|
if(insertContents.isEmpty()){
|
return;
|
}
|
Insert insertContents;
|
set<Id> contentIds = new set<Id>();
|
for(ContentVersion cv : insertContents){
|
contentIds.add(cv.id);
|
}
|
List<ContentVersion> conDocuments = [SELECT ContentDocumentId, Title FROM ContentVersion WHERE Id in: contentIds];
|
List<ContentDocumentLink> insertDocLinks = new List<ContentDocumentLink>();
|
for(ContentVersion cv : conDocuments){
|
ContentDocumentLink cDocLink = new ContentDocumentLink();
|
cDocLink.ContentDocumentId = cv.ContentDocumentId; //Add ContentDocumentId
|
cDocLink.LinkedEntityId = nameParentMaps.get(cv.Title); //Add attachment parentId
|
cDocLink.ShareType = 'V'; //V - Viewer permission. C - Collaborator permission. I - Inferred permission.
|
cDocLink.Visibility = 'AllUsers';
|
insertDocLinks.add(cDocLink);
|
}
|
Insert insertDocLinks;
|
}
|
|
global void finish(Database.BatchableContext BC) {
|
|
}
|
}
|