Scenario: Am having Invoice__c Object. On the list view I have download button to download the selected invoices PDF's. What my below code is doing is it is after fetching the selected records id's of the PDF it is saving to notes and attachments and then downloading from there. Now I don't want to save to notes and attachments before downloading. I want to save in the program itself using some variables or anything. How can I do this.
My code is below
global class DownloadInvoice
{
// Receive Attachments info from Attachment ParentId
private static String API_STATUS_NORMAL = '200';
webService static string getAttachmentByParentId(string sfdcId)
{
List<id> ids = new List<id>();
if(string.isempty(sfdcId)) {
return DownloadInvoiceResponse.errorJson('Parameter sfdcId is required.');
}
system.debug('SFDCid'+sfdcId);
string[] idsArray = sfdcId.split(',');
for(integer i=0; i<idsArray.size();i++)
{
ids.add(idsArray[i]);
}
// Added this code to restrict batch download for some of the accounts who all are having uncheck for this field Print_Invoice__c
List<Invoice__c> invList = New List<Invoice__c>();
invList = [Select id, name, Print_Invoice__c, Account__r.name from Invoice__c where ID IN: ids];
List<Attachment> attInsert = new List<Attachment>();
if(invList.size() > 0){
System.debug(' ====> invList size <==== ');
for(Invoice__c invc : invList){
System.debug(' ====> Invoice is : <==== ' + invc);
String msg = 'Selected invoices are not eligible for Invoice Printing, please check the Account '+invc.Account__r.name;
if(invc.Print_Invoice__c == false){
System.debug(' ====> invc.Print_Invoice__c value false <==== ');
return DownloadInvoiceResponse.errorJson( msg );
}
PageReference pdf = new PageReference('/apex/InvoicePDF?id='+invc.id);
//Attachment attach = new Attachment();
Attachment attach = new Attachment();
if (attach == null) attach = new Attachment();
Blob body;
try {
if(Test.IsRunningTest()){
System.debug(' ==> as Test Class <== ');
body = Blob.valueOf('Some Text');
}
else{
System.debug(' ==> as Apex normal Class <== ');
body = pdf.getContentAsPDF();
}
}
catch (VisualforceException e) {
String msg2 = e.getMessage();
return DownloadInvoiceResponse.errorJson( msg2 );
}
*******HERE AM SAVING TO ATTACHMENT********
*******I DONT WANT TO SAVE TO NOTES AND ATTACHMENTS********
attach.Body = body;
attach.name= invc.name +'_Invoice_'+ Datetime.Now() +'.PDF';
attach.IsPrivate = false;
attach.ParentId = invc.id;
attach.contentType = 'application/pdf';
attInsert.add(attach);
}
}
******Inserting to Attachments********
Insert attInsert;
integer totalSizeOfFiles=0;
integer totalSizeAnInvoice=0;
String invoiceId='';
set<String> remainingsIdsSet=new set<String>();
List<attachment> attachmentList = new List<attachment>();
//for(attachment att:[select ParentId,id,Name,Body,contenttype from attachment where ParentId IN:ids]) {
for(attachment att: attInsert) {
integer eachFileSize=att.Body.size();
String parentId=att.ParentId;
att.contenttype='application/pdf';
if(!invoiceId.equals(parentId)){
invoiceId=parentId;
totalSizeAnInvoice=eachFileSize;
System.debug('--ID: '+att.id+'. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalInvoiceSize: '+totalSizeAnInvoice);
}else if(invoiceId.equals(parentId)){
totalSizeAnInvoice=totalSizeAnInvoice+eachFileSize;
System.debug('--ID: '+att.id+'. ParentId: '+parentId+'. FileSize: '+eachFileSize+'. TotalInvoiceSize: '+totalSizeAnInvoice);
}
if(eachFileSize<4500000 && totalSizeAnInvoice<4500000){
totalSizeOfFiles=totalSizeOfFiles+eachFileSize;
System.debug('--ID: '+parentId+'. FileSize: '+eachFileSize+'. TotalFileSize: '+totalSizeOfFiles+'. HeapSize: '+Limits.getHeapSize());
if(totalSizeOfFiles>= 4500000){
System.debug('--Adding to RemIDs ID: '+parentId+'. FileSize: '+eachFileSize);
remainingsIdsSet.add(parentId);
}else{
attachmentList.add(att);
}
}
}
String remainingIds=null;
List<String> remainingIdList=new List<String>(remainingsIdsSet);
for(integer i=0;i<remainingIdList.size();i++){
if(i==0){
remainingIds=remainingIdList.get(i);
}else{
remainingIds=remainingIds+','+remainingIdList.get(i);
}
}
List<Object> dataList = new List<Object>();
for(Attachment at :attachmentList)
{
Map<String, String> atMap = new Map<String, String>();
atMap.put( 'Name', at.Name );
atMap.put( 'Body', EncodingUtil.base64Encode( at.body ));
datalist.add( atMap );
}
Map<String, Object> response = new Map<String, Object>();
response.put('status', API_STATUS_NORMAL);
if( datalist != null ){
response.put('data',datalist);
response.put('id', remainingIds);
}
return json.serialize( response );
}
// Save Zip file to Document
webService static String saveToDocument( String zipFileData, String fileName ){
try{
String userId = UserInfo.getUserId();
List<Document> docList = [SELECT Id, Name, FolderId, Body FROM Document WHERE Name = :fileName AND FolderId = :userId];
Document doc = new Document();
if( docList == null || docList.size() == 0 ) {
doc.Name = fileName;
doc.FolderId = UserInfo.getUserId();
doc.Body = EncodingUtil.base64Decode( zipFileData );
System.debug(' Insert Doc @@@@ ' + doc);
insert doc;
}
else {
doc = docList.get(0);
doc.Body = EncodingUtil.base64Decode( zipFileData );
update doc;
}
System.debug('--ZipFileName: '+fileName+'. DocId: '+doc.Id);
return DownloadInvoiceResponse.normalJson( doc.Id );
} catch ( Exception ex ) {
return DownloadInvoiceResponse.errorJson( ex.getMessage() );
}
}
}
Onclick Javascript of Download Button on List view
{!REQUIRESCRIPT("/resource/jqueryInvoice")}
{!REQUIRESCRIPT("/resource/JSzipfileInvoice")}
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}
var records = {!GetRecordIds($ObjectType.Invoice__c)};
var newRecords = [];
var SelectedIds='';
var fileDatafinal;
for(var i=0;i < records.length; i++)
{
SelectedIds+=records[i]+",";
}
SelectedIds=SelectedIds.substring(0,SelectedIds.length - 1);
//alert(SelectedIds);
if(SelectedIds.length > 0){
//while(SelectedIds!=null && SelectedIds.length > 0){
//alert('Selected Ids: ' + SelectedIds);
alert(' Please wait until end of the process ');
var response = sforce.apex.execute("DownloadInvoice","getAttachmentByParentId",{sfdcId:SelectedIds});
var respObj = JSON.parse(response);
if( respObj['status'] != '200' )
{
alert( respObj['error'] );
}
else
{
var fileData = respObj['data'];
SelectedIds=respObj['id'];
//alert('RemainingIds Added to DownloadList: '+SelectedIds);
downloadZip(fileData);
}
//}
}
else
{
alert('Please select atleast one record');
}
function downloadZip( fileData) {
var fileName = 'Attachments.zip';
var zip = new JSZip();
for( var k in fileData ) {
zip.file(fileData[k]['Name'], fileData[k]['Body'].toString(),{base64: true});
}
content = zip.generate();
response = sforce.apex.execute("DownloadInvoice","saveToDocument",{zipFileData:content, fileName:fileName});
var fileObj = JSON.parse(response);
if( fileObj['status'] != '200' ) {
alert( fileObj['error'] );
return;
}
var docId = fileObj['data'];
//alert('Starting download of: '+docId);
alert('Please confirm to download Zip file');
/*setTimeout(function(){document.location.href = '/servlet/servlet.FileDownload?file=' + docId;},500);*/
window.location = '/servlet/servlet.FileDownload?file=' + docId;
try {
for (var n=0; n<records.length; n++){
//alert('==>1');
var sv = new sforce.SObject("Invoice__c");
//alert('==>2');
sv.id = records[n];
//alert('==>3');
sv.Is_Printed__c = true;
//alert('==>4');
newRecords.push(sv);
//alert('==>5');
}
result = sforce.connection.update(newRecords);
//alert('alert for update'+result);
//window.location.reload();
}
catch (e) {
alert(e);
}
}
thanks!