function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
WarjieWarjie 

Recalculate button not working

hi, I have a VF page that shows all the data per month. When you click the button, the page will load and will display no data (rarely). i think its some SF or internet issue. Here's the code

 

 

public with sharing class ReportPartnerTrialistController {
public List<Analytic_Report__c> PartnerReports {get; set;}
public boolean showSendEmailButton {get; set;}
public boolean showRecalculateButton {get; set;}
public boolean ArReportEmailSent {get; set;}
public integer previousMonths {get; set;}
public String monthReport {get; set;}
public String yearReport {get; set;}
public date firstDayMonthReport {get; set;}

public ReportPartnerTrialistController() {
  // set month with previousMonths number
  if (previousMonths == null) previousMonths = 0;
  // recalculate button to true
  // showRecalculateButton = true;
}

public List<Analytic_Report__c> getReports() {
 
  firstDayMonthReport = date.today().addMonths(-(1 + previousMonths)).toStartOfMonth();
  // add test flag as no old data can be created from test
  if(Test.isRunningTest() == true){
   firstDayMonthReport = date.today().toStartOfMonth();
  }
  String monthAR = String.Valueof(firstDayMonthReport.month());
     yearReport = String.Valueof(firstDayMonthReport.year());
    
     if (monthAR == '1') monthAR = 'January';
     if (monthAR == '2') monthAR = 'February';
     if (monthAR == '3') monthAR = 'March';
     if (monthAR == '4') monthAR = 'April';
     if (monthAR == '5') monthAR = 'May';
     if (monthAR == '6') monthAR = 'June';
     if (monthAR == '7') monthAR = 'July';
     if (monthAR == '8') monthAR = 'August';
     if (monthAR == '9') monthAR = 'September';
     if (monthAR == '10') monthAR = 'October';
     if (monthAR == '11') monthAR = 'November';
     if (monthAR == '12') monthAR = 'December';
     monthReport = monthAR;
    
  // set display for send email button
  List<Report_Email__c> ReportEmails = new List<Report_Email__c>([Select Id, Name, Analytic_Report__c, Contact__c, Email_status__c, type__c from Report_Email__c where Email_status__c = 'Waiting' and Analytic_Report__r.Month__c = :monthReport and Analytic_Report__r.year__c = :yearReport ]);
       if(ReportEmails.size() > 0){
        showSendEmailButton = true;
        showRecalculateButton = true;
       }else{
        showSendEmailButton = false;
        showRecalculateButton = false;
       }

  PartnerReports = new List<Analytic_Report__c>([Select Referring_Partner__c,Referring_Partner__r.Name, Partner_City__c, Month__c, Year__c, Type__c, Patients_who_completed_trial__c,Patients_who_have_not_purchased_products__c,Patients_who_purchased_products__c,Patients_who_started_trial__c,Emails__c, Financial_situation_constraints__c,Non_Compliant__c,Not_an_immediate_priority__c,Other__c,Average_Trial_Time__c, Number_of_Patients_not_contactable__c, Purchased_from_partner__c, Purchased_from_an_other_partner__c,Purchased_from_internet__c, Patients_who_discontinued__c, Purchased_from_government__c, Purchased_from_second_hand__c   
   from Analytic_Report__c
   where  Type__c = 'Partner Trialist Report' and Month__c =: monthReport and Year__c = :yearReport
   order by Referring_Partner__r.Name asc ]);
  return PartnerReports;
}

public PageReference sendEmails(){
       List<Report_Email__c> ReportEmails = new List<Report_Email__c>([Select Id, Name, Analytic_Report__c, Contact__c, Email_status__c, type__c from Report_Email__c where Email_status__c = 'Waiting' and Analytic_Report__r.Month__c = :monthReport and Analytic_Report__r.year__c = :yearReport ]);
       List<Note> emailSentNotes = new List<Note>();
       for (Report_Email__c re :ReportEmails ){
        // set the status for the workflow rule to send email using template - the status will be change to sent by the workflow rule
        re.Email_status__c = 'To be sent';
        Note tempNote = new Note();
        tempNote.Title = 'Partner Trialist HTML Email sent - ' + monthReport + ' ' + yearReport;
        tempNote.ParentId = re.Contact__c;
        tempNote.Body = 'Trialist Partner Report \n \n Sent from the Analytic Report record: ' + URL.getSalesforceBaseUrl().toExternalForm() + '/' + re.Analytic_Report__c;
        emailSentNotes.add(tempNote);
       
       }
       // add notes to all contact who email was sent to
       insert emailSentNotes;
      
       update ReportEmails;
       PageReference newpage = new PageReference(System.currentPageReference().getURL());
     newpage.setRedirect(true);
     return newpage;
    }
   
    public PageReference movePreviousMonth(){
       previousMonths++;
     return null;
    }
   
    public PageReference lastMonth(){
       // set previousMonths to 0
       previousMonths = 0;
       return null;
    }
   

WarjieWarjie

    public PageReference reCalculate(){
       // Delete and recalculate data
       List<Analytic_Report__c> ArToDelete = new List<Analytic_Report__c>([Select Id, Status__c from Analytic_Report__c where Year__c =:yearReport and Month__c = :monthReport and type__c = 'Partner Trialist Report' ]);
       for (Analytic_Report__c ArSent : ArToDelete){
        if(ArSent.Status__c == 'Emails sent'){
         ArReportEmailSent = true;
        }
       }
       delete ArToDelete;
      
       // recalculate script
       date firstDayLastMonth = date.today().addMonths(-(1 + previousMonths)).toStartOfMonth();
  date firstDayThisMonth = firstDayLastMonth.addDays(date.daysInMonth(firstDayLastMonth.year(),firstDayLastMonth.month()));
 
  // add test flag as no old data can be created from test
  if(Test.isRunningTest() == true){
   firstDayLastMonth = date.today().toStartOfMonth();
   firstDayThisMonth = firstDayLastMonth.addDays(date.daysInMonth(firstDayLastMonth.year(),firstDayLastMonth.month()));
  }
 
       List<Case> cases = new List<Case>([Select Account.Trialist_Partner__c, Account.Trialist_Partner__r.ShippingCity, Id, Reason_for_not_purchasing__c, Trial_Purchase_made__c, Purchase_Partner__c, type, Trial_Start_Date_previous__c, Trial_End_Date_previous__c, Case_Trial_Start_Date__c, Case_Trial_End_Date__c   FROM Case WHERE Trialist_Partner__c != null AND RecordType.DeveloperName = 'Trialist' AND ( (Case_Trial_Start_Date__c >= :firstDayLastMonth AND Case_Trial_Start_Date__c < :firstDayThisMonth ) OR (Case_Trial_End_Date__c >= :firstDayLastMonth AND Case_Trial_End_Date__c < :firstDayThisMonth ) )]);
      
       // copy from batch
       List<Analytic_Report__c> AnalyticReports = new List<Analytic_Report__c>();
         
     // month & year
     String monthAR = String.Valueof(firstDayLastMonth.month());
     if (monthAR == '1') monthAR = 'January';
     if (monthAR == '2') monthAR = 'February';
     if (monthAR == '3') monthAR = 'March';
     if (monthAR == '4') monthAR = 'April';
     if (monthAR == '5') monthAR = 'May';
     if (monthAR == '6') monthAR = 'June';
     if (monthAR == '7') monthAR = 'July';
     if (monthAR == '8') monthAR = 'August';
     if (monthAR == '9') monthAR = 'September';
     if (monthAR == '10') monthAR = 'October';
     if (monthAR == '11') monthAR = 'November';
     if (monthAR == '12') monthAR = 'December';
     String yearAR = String.valueof(firstDayLastMonth.year());
     //integer numberDaysInLastMonth = date.daysInMonth(firstDayLastMonth.year(),firstDayLastMonth.month());
     //Date lastDayOfLastMonth = firstDayLastMonth.addDays(numberDaysInLastMonth);
    
     // get set partner Ids
     Set<ID> partnerIds = new Set<ID>();
     for (Case c : cases) {     
       partnerIds.add(c.Account.Trialist_Partner__c);
     }
 
  // preparing email report list for each partner/analytic report
     Map<Id,List<Report_Email__c>> PiDReportEmails = new Map<Id,List<Report_Email__c>>();
     List<Contact> listContactEmails = new List<Contact>([Select Type__c, Name, Email, AccountId From Contact  where Email != null AND (Type__c = 'Decision Maker' OR Type__c = 'Sleep Lab Manager') AND AccountId IN :partnerIds  ]);
     for(Id PiD : partnerIds ){  
      List<Report_Email__c> TempListReportEmails = new List<Report_Email__c>();
      Set<String> uniqueEmail = new Set<String>();
      for(Contact cont :listContactEmails){   
       if(cont.AccountId == PiD){
        if(!uniqueEmail.contains(cont.Email)){
         Report_Email__c tempReportEmail = new Report_Email__c();
         tempReportEmail.Name = cont.Name;
         tempReportEmail.Contact__c = cont.Id;
         tempReportEmail.Email__c = cont.Email;
         if (ArReportEmailSent != true){
          tempReportEmail.Email_status__c = 'Waiting';
         }else{
          tempReportEmail.Email_status__c = 'Sent';
         }
         tempListReportEmails.add(tempReportEmail);
         uniqueEmail.add(cont.Email);
        }
       }
      }
      PiDReportEmails.put(PiD,tempListReportEmails);
     }
    
     // going through all partner and calculate values
     for(Id PiD : partnerIds ){
      integer UnableToContact = 0;
      integer AverageTrialTime =0;
      integer FinancialSituationConstraints =0;
      integer NonCompliant = 0;
      integer NotAnImmediatePriority = 0;
      integer NumberOfPatientsNotContactable =0;
      integer Other = 0;
      integer PatientsWhoDiscontinuedTrial = 0; // v7
      integer PatientsWhoHaveNotPurchasedProducts = 0;
      integer PatientsWhoPurchasedProducts = 0;
      integer PatientsWhoStartedTrial = 0;
      integer PurchasedFromAnOtherPartner = 0;
      integer PurchasedFromInternet = 0;
      integer PurchasedFromSecondHand = 0;
      integer PurchasedFromGovernement = 0;
      integer PurchasedFromPartner = 0;
      integer PatientStarted = 0;
      integer PatientCompleted = 0;
      integer AverageTotal = 0;
   String partnerCity = '';
     
      for (Case c : cases){
       if(c.Account.Trialist_Partner__c == PiD){
        partnerCity = c.Account.Trialist_Partner__r.ShippingCity;
       
        // counter+ for each report field if exist
       
        // purchased or not
        if ( c.Type == 'Trialist - End of Trial' && c.Case_Trial_End_Date__c >= firstDayLastMonth && c.Case_Trial_End_Date__c  < firstDayThisMonth ){
         if (c.Reason_for_not_purchasing__c == 'Non-compliant' ) NonCompliant++;
         if (c.Reason_for_not_purchasing__c == 'Not an immediate priority' ) NotAnImmediatePriority++;
         if (c.Reason_for_not_purchasing__c == 'Financial situation constraints' ) FinancialSituationConstraints++;
         if (c.Reason_for_not_purchasing__c == 'Other' ) Other++;
         if (c.Trial_Purchase_made__c == true ) PatientsWhoPurchasedProducts++;
         if (c.Trial_Purchase_made__c == false ) PatientsWhoHaveNotPurchasedProducts++;
         if (c.Purchase_Partner__c == 'Trialist referring partner') PurchasedFromPartner++;
         // update march 13 - if (c.Purchase_Partner__c == 'Non-listed referring partner') PurchasedFromInternet++;
         if (c.Purchase_Partner__c == 'Other listed referring partner') PurchasedFromAnOtherPartner++;
         if (c.Purchase_Partner__c == 'Second hand device') PurchasedFromSecondHand++;
         if (c.Purchase_Partner__c == 'Government issued') PurchasedFromGovernement++;
         if (c.Purchase_Partner__c == 'Internet purchase') PurchasedFromInternet++;
        }

        if (c.Type == 'Trialist - Unable to contact') UnableToContact++;
        if (c.Type == 'Trialist – Discontinued') PatientsWhoDiscontinuedTrial++; // v7
        if (c.Case_Trial_Start_Date__c != null && c.Case_Trial_Start_Date__c >= firstDayLastMonth && c.Case_Trial_Start_Date__c < firstDayThisMonth && c.Type != 'Trialist - Unable to contact' ) PatientStarted++;
        if ( c.Case_Trial_End_Date__c != null && c.Case_Trial_End_Date__c >= firstDayLastMonth && c.Case_Trial_End_Date__c  < firstDayThisMonth && c.Type == 'Trialist - End of Trial'  ){
          PatientCompleted++;
          if (c.Case_Trial_Start_Date__c != null && c.Case_Trial_End_Date__c != null ){
           AverageTotal = AverageTotal + c.Case_Trial_Start_Date__c.daysBetween(c.Case_Trial_End_Date__c);
          }
        }
       }
      }
     
      // add a new report record
      if(PatientsWhoPurchasedProducts + PatientsWhoHaveNotPurchasedProducts + PatientStarted + PatientCompleted > 0 ){
     
       Analytic_Report__c ARtoAdd = new Analytic_Report__c();
       // ARtoAdd.Average_Trial_Time__c
       ARtoAdd.Referring_Partner__c = PiD;
       ARtoAdd.Partner_City__c = partnerCity;
       ARtoAdd.Non_Compliant__c = NonCompliant;
       ARtoAdd.Not_an_immediate_priority__c = NotAnImmediatePriority;
       ARtoAdd.Financial_situation_constraints__c = FinancialSituationConstraints;
       ARtoAdd.Other__c = Other;
       ARtoAdd.Patients_who_purchased_products__c = PatientsWhoPurchasedProducts;
       ARtoAdd.Patients_who_have_not_purchased_products__c = PatientsWhoHaveNotPurchasedProducts;
       ARtoAdd.Purchased_from_partner__c = PurchasedFromPartner;
       ARtoAdd.Purchased_from_an_other_partner__c = PurchasedFromAnOtherPartner;
       ARtoAdd.Purchased_from_internet__c = PurchasedFromInternet;
       // new from march 13
       ARtoAdd.Purchased_from_second_hand__c = PurchasedFromSecondHand;
       ARtoAdd.Purchased_from_government__c = PurchasedFromGovernement;
       ARtoAdd.Number_of_Patients_not_contactable__c = UnableToContact;
       ARtoAdd.Patients_who_started_trial__c = PatientStarted;
       ARtoAdd.Patients_who_discontinued__c = PatientsWhoDiscontinuedTrial; //v7
       ARtoAdd.Patients_who_completed_trial__c = PatientCompleted;
       if (PatientCompleted > 0 && AverageTotal > 0 ){
        ARtoAdd.Average_Trial_Time__c = AverageTotal / PatientCompleted;
       }else{
        ARtoAdd.Average_Trial_Time__c = 0;
       }
       ARtoAdd.Month__c = monthAR;
       ARtoAdd.Year__c = yearAR;
       ARtoAdd.Type__c = 'Partner Trialist Report'; 
      
       ARtoAdd.Report_Ref__c = PiD + monthAR + yearAR; // external Id for upsert
   
    if (PiDReportEmails.get(PiD) != null){
     List<Report_Email__c> REList = PiDReportEmails.get(PiD);
     for ( Report_Email__c r : REList ){
      if (ARtoAdd.Emails__c == null){
       ARtoAdd.Emails__c = r.Email__c;
      }else{
       ARtoAdd.Emails__c = ARtoAdd.Emails__c + '<br>' + r.Email__c;
      }
     }
    }
    // to avoid sending again when recalculate month report sent
    if (ArReportEmailSent == true){
        ARtoAdd.Status__c = 'Emails sent';
       }else{
        ARtoAdd.Status__c = 'Email to be sent';
       }
       AnalyticReports.add(ARtoAdd);
      }
     }
    
     try {
    upsert AnalyticReports Report_Ref__c ;
   } catch (DmlException e) {
    System.debug(e.getMessage());
  }

     // add list of report email for each upserted ar record
     List<Report_Email__c> REtoUpsert = new List<Report_Email__c>();
     for (Analytic_Report__c ar :AnalyticReports){
      for(Id PiD : partnerIds ){
       if(ar.Referring_Partner__c == PiD){
        List<Report_Email__c> tempRE = PiDReportEmails.get(PiD);
        for(Report_Email__c re : tempRE){
         re.Analytic_Report__c = ar.Id;
         re.RE_Ref__c = PiD + ar.Month__c + re.Email__c;
         REtoUpsert.add(re);
        }
       }
      }
     }
    
     try {
    upsert REtoUpsert RE_Ref__c ;
   } catch (DmlException e) {
    System.debug(e.getMessage());
  }
       return null;
    } 
}