global class SelectRepairPDFDeleteBatch implements Database.Batchable<sObject> {
|
public String query;
|
public List<Repair__c> reList=new List<Repair__c>();
|
public List<Id> Ids=new List<String>();
|
global SelectRepairPDFDeleteBatch(list<Repair__c> scope) {
|
this.reList = scope;
|
for(Repair__c re:reList){
|
Ids.add(re.Id);
|
}
|
}
|
|
global Database.QueryLocator start(Database.BatchableContext bc) {
|
query='SELECT Id,Name from Repair__c where Id in:Ids';
|
return Database.getQueryLocator(query);
|
}
|
|
global void execute(Database.BatchableContext BC, list<Repair__c> repList) {
|
List<String> attachmentNameList = new List<String>();
|
List<Id> parentIdList = new List<Id>();
|
List<ContentDocumentLink> isGeneratedPDFLinkList = new List<ContentDocumentLink>();
|
List<ContentDocument> isGeneratedPDFList = new List<ContentDocument>();
|
for(Repair__c re : repList){
|
attachmentNameList.add(re.name + '_' + 'MaintenanceCommission.pdf');
|
parentIdList.add(re.Id);
|
}
|
isGeneratedPDFLinkList = [select ContentDocumentId from ContentDocumentLink where LinkedEntityId in: parentIdList];
|
List<Id> attachmentIdList = new List<Id>();
|
for (ContentDocumentLink PDFLink : isGeneratedPDFLinkList) {
|
attachmentIdList.add(PDFLink.ContentDocumentId);
|
}
|
isGeneratedPDFList = [select Id from ContentDocument where Id in: attachmentIdList and Title in: attachmentNameList];
|
if(isGeneratedPDFList.size() > 0){
|
delete isGeneratedPDFList;
|
}
|
|
PageReference pdfPage;
|
List<ContentVersion> versions = new List<ContentVersion>();
|
for(Repair__c re : repList){
|
pdfPage = new PageReference('/apex/MaintenanceCommissionPDF?id=' + re.Id);
|
Blob pdfBody;
|
if(System.Test.isRunningTest()) {
|
pdfBody = blob.valueOf('Unit.Test');
|
} else {
|
pdfBody = pdfPage.getContentAsPDF();
|
}
|
ContentVersion version = new ContentVersion();
|
version.VersionData = pdfBody;
|
version.Title = re.name + '_' + 'MaintenanceCommission.pdf';
|
version.ContentLocation = 's';
|
version.PathOnClient = re.name + '_' + 'MaintenanceCommission.pdf';
|
versions.add(version);
|
}
|
|
if (versions.size() > 0) {
|
insert versions;
|
}
|
List<Id> idList = new List<Id>();
|
for (ContentVersion newVersion : versions) {
|
idList.add(newVersion.Id);
|
}
|
versions = [select ContentDocumentId from ContentVersion where Id in: idList];
|
List<ContentDocumentLink> links = new List<ContentDocumentLink>();
|
Integer i = 0;
|
for (ContentVersion newVersion : versions) {
|
ContentDocumentLink link = new ContentDocumentLink();
|
link.ContentDocumentId = newVersion.ContentDocumentId;
|
link.LinkedEntityId = repList[i].Id;
|
link.ShareType = 'I';
|
link.Visibility = 'AllUsers';
|
links.add(link);
|
i++;
|
}
|
|
if (links.size() > 0) {
|
insert links;
|
}
|
}
|
|
global void finish(Database.BatchableContext BC) {
|
|
}
|
}
|