Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
492
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 12.67 KB | None | 0 0
  1. public with sharing class EmailPDFController {
  2.    
  3.     public Travel_Service__c opp { get; set; }
  4.    
  5.     public String selected { get; set; }
  6.    
  7.     public String emailCC {get; set;}
  8.    
  9.     public String emailBCC {get; set;}
  10.    
  11.     public Contact_lookup_for_API__c tempAccount {get; set;}
  12.    
  13.     public String htmlBodyStr {get; set;}
  14.    
  15.     public Account emailTo {get; set;}
  16.    
  17.     public Boolean failed = false;
  18.    
  19.     public String  errMsg;
  20.     public User activeUser {get; set;}
  21.    
  22.     public EmailPDFController(){
  23.       errMsg='';
  24.    
  25.       if(ApexPages.currentPage().getParameters().get('Id') == ''){
  26.        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No Id Specified'));
  27.        opp =  new Travel_Service__c();
  28.        errMsg='No Id Specified';
  29.        failed = true;
  30.       }
  31.       else{
  32.        Id oppId=ApexPages.currentPage().getParameters().get('Id');
  33.        try{
  34.         opp = [select Id, Name, Main_passenger_name__c from Travel_Service__c where Id = :oppId];
  35.         tempAccount = new Contact_lookup_for_API__c();
  36.        
  37.        }
  38.        catch(Exception e){
  39.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Invalid Travel Services Id'));
  40.         opp =  new Travel_Service__c();
  41.         errMsg='Invalid Travel Services Id';
  42.         failed = true;
  43.        }
  44.       }
  45.       if(ApexPages.currentPage().getParameters().get('success') == 'true'){
  46.        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'The invoice was sent.'));
  47.       }
  48.      
  49.      
  50.       try{
  51.        EmailTo=[select Id, PersonEmail from Account where Id=:opp.Main_Passenger__c];
  52.        tempAccount.Account__c=emailTo.Id;
  53.      
  54.       }
  55.       catch(Exception e){
  56.        emailTo=new Account();
  57.       // tempAccount.Account__c=new Id();
  58.       }
  59.      
  60.       activeUser = [Select Email, Phone, Mobilephone, Title From User where Id = : UserInfo.getUserId() limit 1];
  61.       emailBCC=activeUser.Email;
  62.      
  63.       htmlBodyStr = '<p>Dear '+opp.Main_Passenger_Name__c+',</p><p>Please find attached your invoice.</p><p>Kind regards,<br /><br />'+
  64.          UserInfo.getName()+' | '+ activeUser.Title+' | Stratix Corp. | '+ activeUser.Email +' | Direct Line '+activeUser.Phone +' | Mobile '+activeUser.Mobilephone;
  65.          
  66.          
  67.          //UserInfo.getName()+'<br />'+activeUser.Title+'<br />GSMA Ltd.';
  68.          /*
  69.          if(activeUser.Phone!=null){
  70.           htmlBodyStr=htmlBodyStr +'<br />Office: '+activeUser.Phone+'<br />';      
  71.          }
  72.          if(activeUser.Mobilephone!=null){
  73.           htmlBodyStr=htmlBodyStr +'<br />Mobile: '+activeUser.Mobilephone+'<br />';      
  74.          }*/
  75.      
  76.     }
  77.    
  78.     /*public PageReference checkApproved(){
  79.      if(!salesQuotes.approved(quote.id)){
  80.          pagereference pr = new pagereference('/apex/proposalError?error=approvals&id='+quote.id);
  81.          pr.setredirect(false);
  82.          return pr;
  83.      }
  84.      else{
  85.       return null;
  86.      }
  87.     }*/
  88.  
  89.     public PageReference sendReport() {
  90.        if(!failed){
  91.    
  92.         System.Debug('In sendreport');
  93.         System.Debug('body is'+htmlBodyStr);
  94.         //System.debug(ApexPages.currentPage().getParameters());
  95.         //return null;
  96.         Messaging.SingleEmailMessage emailMsg = new Messaging.SingleEmailMessage();
  97.         emailMsg.setSaveAsActivity(false);
  98.         //emailMsg.setTargetObjectId(UserInfo.getUserId());
  99.        
  100.        
  101.         System.Debug('Created email object');
  102.         //emailMsg.setWhatId(quote.Id);
  103.         System.Debug('Associated invoice');
  104.         //emailMsg.setTemplateId([select Id from EmailTemplate where DeveloperName = 'quoteEmail'].Id);
  105.         System.Debug('Set template');
  106.         //System.Debug('Template Id is: ' + [select Id from EmailTemplate where DeveloperName = 'quoteEmail'].Id);
  107.         System.Debug('Id is: ' + tempAccount.Account__c);
  108.         emailMsg.setSubject('Your requested invoice from Costamar');
  109.        
  110.          
  111.          if(tempAccount.Account__c == null){
  112.           failed=true;
  113.           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Invalid Contact'));
  114.           return null;
  115.          }
  116.          
  117.          
  118.          
  119.          EmailTo= [select Id, PersonEmail, Name from Account where Id= :tempAccount.Account__c];
  120.          
  121.          
  122.          
  123.          System.Debug('Email is' + EmailTo.PersonEmail);
  124.          if(EmailTo.PersonEmail == null || !EmailTo.PersonEmail.contains('@')){
  125.           System.Debug('No valid email for Contact');
  126.           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Contact does not have a valid Email address'));
  127.            failed=true;
  128.           return null;
  129.          }
  130.          
  131.          
  132.          System.Debug('Email is: ' + EmailTo.PersonEmail);
  133.        
  134.          String[] toAddresses = new String[] {EmailTo.PersonEmail};
  135.          
  136.          String userEmail = activeUser.Email;
  137.          
  138.          String txtBodyStr='Dear '+EmailTo.Name+',\nPlease find attached your order form and terms and conditions.  When you have reviewed both documents, please return the signed order form by fax to + 44 (0)207 356 0691.\nRegards,\n\n'+
  139.          UserInfo.getName()+'\n';
  140.          if(activeUser.Phone!=null){
  141.           txtBodyStr=txtBodyStr+'\nOffice: '+activeUser.Phone+'\n';      
  142.          }
  143.          if(activeUser.Mobilephone!=null){
  144.           txtBodyStr=txtBodyStr +'\nMobile: '+activeUser.Mobilephone+'\n';      
  145.          }
  146.          
  147.          emailMsg.setPlainTextBody(txtBodyStr);
  148.        
  149.          emailMsg.setHtmlBody(htmlBodyStr);
  150.        
  151.         emailMsg.setToAddresses(toAddresses);
  152.         System.Debug('Set to addresses');
  153.        
  154.         String[] emailAddresses;
  155.        
  156.         try{
  157.         emailAddresses = emailCC.split(';');
  158.         emailMsg.setCcAddresses(removeBlanks(emailAddresses));
  159.         System.Debug('Set CC addresses to :' + emailAddresses);
  160.         emailAddresses = emailBCC.split(';');
  161.         emailMsg.setBccAddresses(removeBlanks(emailAddresses));
  162.         System.Debug('Set BCC addresses to :' + emailAddresses);
  163.         }
  164.         catch(Exception e){
  165.          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Invalid CC or BCC Address. Addresses must be separated by a semicolon (;)'));
  166.          failed=true;
  167.          return null;
  168.         }
  169.        
  170.         //Prepare URL for PDF page
  171.         String profileURL = Page.CostPDF.getURL() + '?Id=' + opp.Id;
  172.        
  173.    
  174.                    
  175.         //Add title query parm and file name
  176.         String fileName = opp.Name + '.pdf';
  177.        
  178.         //Instantitiate PDF page
  179.         PageReference profilePage = new PageReference(profileURL);
  180.        
  181.         //Prepare attachment
  182.         Attachment profileAttachment = new Attachment();
  183.         profileAttachment.Body = profilePage.getContent();
  184.         profileAttachment.Name = fileName;
  185.         profileAttachment.ParentId = opp.Id;
  186.              
  187.         //Insert attachment to email
  188.         Messaging.EmailFileAttachment emailAttachment = new Messaging.EmailFileAttachment();
  189.         emailAttachment.setFileName(fileName);
  190.         emailAttachment.setBody(profilePage.getContent());
  191.         emailMsg.setFileAttachments(new Messaging.EmailFileAttachment[] {emailAttachment});
  192.        
  193.        
  194.        
  195.         emailMsg.setFileAttachments(new Messaging.EmailFileAttachment[] {emailAttachment});
  196.  
  197.  
  198.         Messaging.SendEmailResult[] sers;
  199.         //Insert PDF as quote attachment & send email
  200.         try
  201.         {
  202.             //insert profileAttachment;
  203.             sers = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {emailMsg});
  204.            
  205.             Task task = new Task();
  206.              task.WhatId = opp.Id;
  207.             task.WhoId = EmailTo.Id;
  208.             task.Subject = 'Sent Email with invoice';
  209.             task.Type='Email';
  210.            //task.priority= Object.Priority__c;
  211.            
  212.             task.ActivityDate = date.today();
  213.             task.status = 'Completed';
  214.             task.description = 'Emailed invoice ' + opp.Name;
  215.             insert task;
  216.            
  217.            
  218.         }
  219.         catch(Exception e)
  220.         {
  221.             ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage()));
  222.              failed=true;
  223.             return null;
  224.         }
  225.        
  226.         Boolean allSuccessful = true;
  227.         for(Messaging.SendEmailResult ser : sers)
  228.         {
  229.             if(!ser.isSuccess())
  230.             {
  231.                 allSuccessful = false;
  232.                 break;
  233.             }
  234.         }
  235.         if(allSuccessful){
  236.            
  237.             PageReference newPage = new PageReference(Page.emailInvoice.getURL()+ '?Id='+ opp.Id + '&success=true');
  238.             failed=true;
  239.             newPage.setRedirect(true);
  240.             return newPage;
  241.         }
  242.         else
  243.         {
  244.             for(Messaging.SendEmailResult ser : sers)
  245.             {
  246.                 for(Database.Error de : ser.getErrors())
  247.                     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, de.getMessage()));
  248.             }
  249.              failed=true;
  250.             return null;
  251.         }
  252.        }
  253.        else{
  254.         ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, errMsg));
  255.        }
  256.         return null;
  257.     }
  258.  
  259. private String[] removeBlanks(String[] emailAddresses)
  260.     {
  261.         String[] returnAddresses = new String[0];
  262.         for(Integer i=0; i < emailAddresses.size(); i++)
  263.         {
  264.             emailAddresses[i] = emailAddresses[i].trim();
  265.             if(emailAddresses[i].length() > 0) returnAddresses.add(emailAddresses[i]);
  266.         }
  267.         return returnAddresses;
  268.     }
  269.    
  270.    
  271.     public PageReference goBack(){
  272.       String newPageUrl = '/'+ opp.Id;
  273.       PageReference newPage = new PageReference(newPageUrl);
  274.       newPage.setRedirect(true);
  275.      
  276.       return newPage;
  277.     }
  278.  
  279.  
  280.  
  281.    /*** test methods ***/
  282.     public static testmethod void testConstructor()
  283.     {
  284.              
  285.         Test.startTest();
  286.        
  287.         /** test no id in url */
  288.          System.Debug(' test no id in url');
  289.         Test.setCurrentPageReference(new PageReference(Page.EmailInvoice.getURL()));
  290.         EmailPDFController ssc = new EmailPDFController();
  291.         System.assertEquals(true, ssc.failed);
  292.        
  293.         /** test empty id in url */
  294.            System.Debug('  test empty id in url ');
  295.         Test.setCurrentPageReference(new PageReference(Page.emailInvoice.getURL()+ '?Id='));
  296.         ssc = new EmailPDFController();
  297.         System.assertEquals(true, ssc.failed);
  298.        
  299.         /** test garbage id **/
  300.        //    System.Debug('  test garbage id ');
  301.        // Test.setCurrentPageReference(new PageReference(Page.emailQuote.getURL()+ '?Id=asas'));
  302.        // ssc = new emailQuoteController();
  303.        // System.assertEquals(true, ssc.failed);
  304.        
  305.         /** test good random id **/
  306.            System.Debug(' test good random id');
  307.         Travel_Service__c testAccount= [select Id from Travel_Service__c limit 1];
  308.              
  309.         Test.setCurrentPageReference(new PageReference(Page.emailInvoice.getURL()+ '?id='+ testAccount.Id));
  310.         ssc = new EmailPDFController();
  311.         System.assertEquals(false, ssc.failed);
  312.        
  313.         /** test no contact selected **/
  314.            System.Debug(' test no contact selected ');
  315.         ssc.sendReport();
  316.         System.assertEquals(true, ssc.failed);
  317.        
  318.         /* load a contact with no email */
  319.            System.Debug('load a contact with no email');
  320.         ssc = new EmailPDFController();
  321.         ssc.tempAccount.Account__c=[select Id, Email from Contact  where Email = '' limit 1].Id;
  322.         ssc.emailCC='';
  323.         ssc.emailBCC='';
  324.         ssc.sendReport();
  325.         System.assertEquals(true, ssc.failed);
  326.        
  327.         /* load a random contact with  email */
  328.            System.Debug('load a random contact with  email');
  329.         ssc = new EmailPDFController();
  330.         ssc.tempAccount.Account__c=[select Id, Email from Contact  where Email <> '' limit 1].Id;
  331.         ssc.emailCC='';
  332.         ssc.emailBCC='';
  333.         ssc.sendReport();
  334.         System.assertEquals(true, ssc.failed);
  335.        
  336.        
  337.         /* add some CCs and BCCs */
  338.            System.Debug('  add some CCs and BCCs');
  339.         ssc = new EmailPDFController();
  340.         ssc.tempAccount.Account__c=[select Id, Email from Contact  where Email <> '' limit 1].Id;
  341.         ssc.emailCC='test@email.com';
  342.         ssc.emailBCC='test@email.com; test@email.com;test@email.com ; test@email.com';
  343.         ssc.sendReport();
  344.         System.assertEquals(true, ssc.failed);
  345.        
  346.         ssc.goBack();
  347.        
  348.        
  349.         Test.stopTest();
  350.     }
  351.  
  352. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement