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
HaralambyHaralamby 

Simple APEX CLASS code.....please help!!!

Hello!
I am new at writing APEX code and I need some help.   I want to write the following Excel logic in APEX CODE:

My organization has three products.let's call them "Product 1" , "Product 2", and "Product 3"

For Each Product I have a field called "Product 1 Rate", "Product 2 Rate" and "Product 3 Rate"

I want to declare a variable called "PriceDaily" and have it equal one of the product rates.

So I want to say:  If Product name is  "Product 1" than "Price Daily" is "Product 1 Rate",
                                    If Product name is  "Product 2" than "Price Daily" is "Product 2 Rate",
                                    If Product name is  "Product 3" than "Price Daily" is "Product 3 Rate"

How is this written in an APEX Class? 

Thank you for you help!!!!!!!!!

Best Answer chosen by Admin (Salesforce Developers) 
CaptainObviousCaptainObvious

Ok, it's making more sense...
Daily_Revenue_Rate__c is a field on the Opportunity object.
You already added it to the OpportunityList- Make sure you add it to both the 'Batch' and 'Single' lists.
Here are the next steps:
Find the ReEstablish method: public void ReEstablish()

Edit this section of code as follows:

else{ double ProductAmount; double PriceWeekly=myOpp.Daily_Revenue_Rate__c; //if (myOpp.QUAL__c>0){ ProductAmount=myOpp.Qual__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUAL',myOpp.Estimated_Start_Date__c, myOpp.Name,PriceWeekly); //} //if (myOpp.QUANT__c>0){ ProductAmount=myOpp.QUANT__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUANT', myOpp.Quant_Start_Date__c, myOpp.Name,PriceWeekly); //} //if (myOpp.ARM__c>0){ ProductAmount=myOpp.ARM__c; ReEstablishProduct(myOpp.Id, ProductAmount,'HIT', myOpp.Hit_Start_Date__c, myOpp.Name,PriceWeekly); //} }

 

Now find and edit the ReEstablishProduct method:

 

public void ReEstablishProduct(string OppId, double ProductAmount, string ProductName, date StartDate, string OppName, double PriceWeekly)

That you should allow you to reference the Daily Revenue Rate.

Make sure to comment out (or delete) the old calculation:

 

//double PriceWeekly=(newUnitPrice * myOppItem.Quantity)/52;

Hope that helps!

All Answers

MVJMVJ

You should be able to do this with a formula field.  Based upon what I see it does not look like you need to create an APEX code.

 

 

HaralambyHaralamby
The code was already written for us but we want to edit it.  The field that I was referring to is already a formula field and these products are associated with an opportunity that has dynamic revenue schedules which need to be updated...hence the code....but can you help me with the declaration and if statement that I psoted earlier?
CaptainObviousCaptainObvious

Not sure if this is what you're looking for:

//declare a variable Double PriceDaily; //assign a value to the variable depending on the Product Name: if (Product_Name__c=='Product 1') { PriceDaily=Product_1_Rate__c; } else if (Product_Name__c=='Product 2') { PriceDaily=Product_2_Rate__c; } else if (Product_Name__c=='Product 3') { PriceDaily=Product_3_Rate__c; } //now do something with the variable...

 

HaralambyHaralamby
              double PriceWeekly;      

           // PriceWeekly=myOpp.Daily_Revenue_Rate__c;

 

 

I declared the above variable but it's returning Null even though the field is showing $2,000

 

Any ideas why?

CaptainObviousCaptainObvious

It could be a number of things... Did your SOQL query return any results? Is this the only field that comes back null? Would it be possible for you to post a snippet of the code?

 

HaralambyHaralamby

I don't mind sharing the code:  

 

This code updates open opportunities....it updates the product schedules as each day passes......I only wanted to edit the formula for the revenue field of the schedule.....if you notice right now it simply takes the product amount and devides it by 52 weeks and gives the weekly revenue schedule......

 

I want to change it to a daily schedule with a "daily_revenue_rate__c"   field that is a custom formula field.  I thought I would only need to change a few fields....but when you don't speak the language it is very difficult....If you can do anything with this I would GREATLY Appreciate it if not no worries I know it's a big task.

 

 

Thanks anyway for your help!!!!!!!!!!

public class OpportunityNEWReEstablish_controller { public integer OpenOpportunities {get; set;} public Integer countProgress {get; set;} public boolean DisableReEstablish {get;set;} string[] BatchMessages = new string[]{}; public Integer StartBatch {get; set;} public string BatchStatus {get; set;} public boolean PollerEnabled {get; set;} public string stopText {get; set;} public List<Opportunity> OpportunityList=new List<Opportunity>(); public List<Opportunity> getOpportunityList() { if (OpportunityList.isEmpty()){ //Max number of open opportunities is projected to 200 (can go up to 1000 before hit Governor Limit) if (System.currentPageReference().getParameters().get('id')==null){ //Batch OpportunityList= [Select o.ARM__c, o.QUANT__c, o.QUAL__c, o.Expected_Revenue_Quant__c, o.Expected_Revenue_Qual__c, o.Expected_Revenue_ARM__c, o.HIT_Start_Date__c, o.Estimated_Start_Date__c, o.Quant_Start_Date__c, o.AccountId,o.IsDeleted, o.IsClosed, o.Id, o.Name From Opportunity o where o.IsClosed=false AND o.IsDeleted=false ]; } else { //Single OpportunityList= [Select o.ARM__c, o.QUANT__c, o.QUAL__c, o.Expected_Revenue_Quant__c, o.Expected_Revenue_Qual__c, o.Expected_Revenue_ARM__c, o.HIT_Start_Date__c, o.Estimated_Start_Date__c, o.Quant_Start_Date__c, o.AccountId, o.IsDeleted, o.IsClosed, o.Id, o.Name From Opportunity o where o.Id=:System.currentPageReference().getParameters().get('id') ]; } OpenOpportunities=OpportunityList.size(); } if (OpportunityList.size()>0){ DisableReEstablish=false; } return OpportunityList; } public OpportunityNEWReEstablish_controller (){ DisableReEstablish=false; countProgress=0; StartBatch=0; stopText='Batch not started'; PollerEnabled=false; OpenOpportunities=0; getOpportunityList(); } public void ReEstablish() { ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Re-establish Opportunity started:') ; //ApexPages.addMessage(msg); try { for (Opportunity myOpp: OpportunityList) { countProgress++; if (myOpp.IsClosed){ msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Re-establish Opportunity is not allowed: Closed Opportunity. ') ; ApexPages.addMessage(msg); } else{ double ProductAmount; //if (myOpp.QUAL__c>0){ ProductAmount=myOpp.Qual__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUAL',myOpp.Estimated_Start_Date__c, myOpp.Name); //} //if (myOpp.QUANT__c>0){ ProductAmount=myOpp.QUANT__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUANT', myOpp.Quant_Start_Date__c, myOpp.Name); //} //if (myOpp.ARM__c>0){ ProductAmount=myOpp.ARM__c; ReEstablishProduct(myOpp.Id, ProductAmount,'HIT', myOpp.Hit_Start_Date__c, myOpp.Name); //} } } } catch (DmlException e) { ApexPages.addMessages(e); } return; } public void ReEstablishProduct(string OppId, double ProductAmount, string ProductName, date StartDate, string OppName) { try { if (ProductAmount==null){ ProductAmount=0; } ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Re-establish Product: ' + ProductName ) ; ApexPages.addMessage(msg); msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Amount: ' + decimal.valueOf(ProductAmount).setScale(2).round().format() ) ; ApexPages.addMessage(msg); msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Start Date: ' + string.valueOf(StartDate) ) ; ApexPages.addMessage(msg); //find Opp product line item and update prace and reestablish schedule //if it is more than one opportunity line item per opportunity=>sum quantity and recalculate all List<OpportunityLineItem> OpportunityLineItemList=new List<OpportunityLineItem>(); OpportunityLineItemList=[Select o.UnitPrice, o.ServiceDate, o.Quantity, o.PricebookEntryId, o.OpportunityId, o.ListPrice, o.IsDeleted, o.Id, o.HasSchedule, o.HasRevenueSchedule, o.HasQuantitySchedule, o.Description, o.PricebookEntry.Name, o.PricebookEntry.Pricebook2Id, o.PricebookEntry.Product2Id, o.PricebookEntry.ProductCode, (Select Id From OpportunityLineItemSchedules) From OpportunityLineItem o where o.OpportunityId=:OppId AND o.PricebookEntry.ProductCode=:ProductName]; if (ProductAmount!=0.0 && OpportunityLineItemList.size()==0){ msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have product item: ' + ProductName + ' for amount: ' + ProductAmount +'.') ; ApexPages.addMessage(msg); msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please add the product.') ; ApexPages.addMessage(msg); //if (System.currentPageReference().getParameters().get('id')==null){ if (this.OpportunityList.size()>1){ BatchMessages.add('Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have product item: ' + ProductName + ' for amount: ' + ProductAmount); } return; } if (ProductAmount==0.0 && OpportunityLineItemList.size()>0){ msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have allocated an amount to the Product: ' + ProductName + '.' ) ; ApexPages.addMessage(msg); msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please update amount.' ) ; ApexPages.addMessage(msg); //if (System.currentPageReference().getParameters().get('id')==null){ if (this.OpportunityList.size()>1){ BatchMessages.add('Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have allocated an amount to the Product: ' + ProductName); } return; } //calculate quantity for multiply opportunity Items double Qty=0; for (OpportunityLineItem myOppItem: OpportunityLineItemList) { Qty+=myOppItem.Quantity; } if (Qty==0){ msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have Qty defined for product item: ' + ProductName + ' for amount: ' + ProductAmount +'.') ; ApexPages.addMessage(msg); msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Please add the product.') ; ApexPages.addMessage(msg); //if (System.currentPageReference().getParameters().get('id')==null){ if (this.OpportunityList.size()>1){ BatchMessages.add('Opportunity: ' + OppName + ' ('+OppId+')' + ' do not have Qty defined for product item: ' + ProductName + ' for amount: ' + ProductAmount +'. Please add the product.'); } return; } double newUnitPrice=ProductAmount/Qty; msg = new ApexPages.Message(ApexPages.Severity.INFO, 'New Price is: ' + string.valueOf(decimal.valueOf(newUnitPrice).setScale(2)) + ' for Qty:' + Qty) ; ApexPages.addMessage(msg); //update LineItem with new price and recalculate schedule OpportunityLineItem[] Update_OpportunityLineItemList=new OpportunityLineItem[]{};//Bulk array for (OpportunityLineItem myOppItem: OpportunityLineItemList) { //ReEstablish every time because start date can be updated too if (myOppItem.HasSchedule){ //delete schedule first then update price and recalculate schedule OpportunityLineItemSchedule[] Delete_OpportunityLineItemSchedule=new OpportunityLineItemSchedule[]{};//Bulk array for (OpportunityLineItemSchedule mySchedules: myOppItem.OpportunityLineItemSchedules){ Delete_OpportunityLineItemSchedule.add(mySchedules); } delete (Delete_OpportunityLineItemSchedule); } myOppItem.UnitPrice=newUnitPrice; update myOppItem; //generate new schedule OpportunityLineItemSchedule[] Insert_OpportunityLineItemSchedule=new OpportunityLineItemSchedule[]{};//Bulk array double TotalCheck=0; double PriceWeekly=(newUnitPrice * myOppItem.Quantity)/52; date myScheduleDate=StartDate ;//myOppItem.ServiceDate; msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Weekly price is: ' + string.valueOf(decimal.valueOf(PriceWeekly).setScale(2))) ; ApexPages.addMessage(msg); for (Integer j = 0; j < 52 ; j++){ OpportunityLineItemSchedule mySchedule=new OpportunityLineItemSchedule(); mySchedule.OpportunityLineItemId=myOppItem.Id; mySchedule.Type='Revenue'; mySchedule.Revenue=PriceWeekly; mySchedule.ScheduleDate=myScheduleDate; if (j==51){ //last iteration iron price total mySchedule.Revenue=(myOppItem.Quantity * newUnitPrice)- TotalCheck; } Insert_OpportunityLineItemSchedule.add(mySchedule); //insert (mySchedule); //DML exception go to bulk approach TotalCheck+=PriceWeekly; myScheduleDate=myScheduleDate.addDays(7); } insert (Insert_OpportunityLineItemSchedule); } } //end of try catch (DmlException e) { ApexPages.addMessages(e); } //end of catch return; } public PageReference ProcessBatch(){ countProgress++; integer WorkBatch=1; double PercentDone = (CountProgress*100) / this.OpportunityList.size(); BatchStatus='Processed %'+PercentDone.format(); /* if (this.OpportunityList.size()-StartBatch < WorkBatch){ WorkBatch=this.OpportunityList.size()-StartBatch; } */ integer EndBatch=StartBatch + WorkBatch; for (Integer j = StartBatch; j < EndBatch; j++){ Opportunity myOpp=new Opportunity(); StartBatch++; myOpp=OpportunityList[j]; ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO, 'Re-established Opportunity:' + myOpp.Name ) ; ApexPages.addMessage(msg); double ProductAMount; //if (myOpp.QUAL__c>0){ ProductAmount=myOpp.Qual__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUAL',myOpp.Estimated_Start_Date__c, myOpp.Name); // } //if (myOpp.QUANT__c>0){ ProductAmount=myOpp.QUANT__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUANT', myOpp.Quant_Start_Date__c, myOpp.Name); // } //if (myOpp.ARM__c>0){ ProductAmount=myOpp.ARM__c; ReEstablishProduct(myOpp.Id, ProductAmount,'HIT', myOpp.Hit_Start_Date__c, myOpp.Name); // } } if (this.OpportunityList.size()==EndBatch){ PollerEnabled=false; BatchStatus='Processed %100'; stopText='Batch proces is finished'; //Send Email with errors to user Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); //find user email String CurrentUserId=system.Userinfo.getUserId(); User CurrentUser=[Select u.Email From User u Where u.Id=:CurrentUserId]; String[] toAddresses = new String[] {CurrentUser.Email}; mail.setToAddresses(toAddresses); mail.setSubject('Batch Opportunity Re-Establish Ravenue Result (Errors)'); string mailBody=''; mailBody+='The Batch Opportunity Re-Establish Ravenue Procedure Result: \r\n'; mailBody+='User: ' + system.Userinfo.getName() + '\r\n'; mailBody+='\r\n'; mailBody+='Open Opportunities: ' + this.OpportunityList.size() + '\r\n'; if (BatchMessages.size()>0){ mailBody+='Errors: \r\n'; for (string myMessage : BatchMessages){ mailBody+=myMessage + ' \r\n'; } } mail.setPlainTextBody( mailBody); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } return null; } public PageReference StartBatch(){ PollerEnabled=true; stopText='Batch is started (Idle period)...'; return null; } public PageReference StopBatch(){ PollerEnabled=false; stopText='Batch is stoped'; return null; } } //End of Class

 

 

CaptainObviousCaptainObvious

So much for the Simple Apex Class!!!

There's a lot of code here, but the first thing that comes to mind is this Daily_Revenue_Rate__c field you want to reference...

As you mentioned, PriceWeekly is currently calculated as follows:

double PriceWeekly=(newUnitPrice * myOppItem.Quantity)/52;

If you want to use your custom formula field instead of the calculation:

 

double PriceWeekly=myOppItem.Daily_Revenue_Rate__c;

You will have to include Daily_Revenue_Rate__c when you build the OpportunityLineItemList:

 

List<OpportunityLineItem> OpportunityLineItemList=new List<OpportunityLineItem>(); OpportunityLineItemList=[Select o.UnitPrice, o.ServiceDate, o.Quantity, o.PricebookEntryId, o.OpportunityId, o.ListPrice, o.IsDeleted, o.Id, o.HasSchedule, o.HasRevenueSchedule, o.HasQuantitySchedule, o.Description, o.PricebookEntry.Name, o.PricebookEntry.Pricebook2Id, o.PricebookEntry.Product2Id, o.PricebookEntry.ProductCode, o.Daily_Revenue_Rate__c, (Select Id From OpportunityLineItemSchedules) From OpportunityLineItem o where o.OpportunityId=:OppId AND o.PricebookEntry.ProductCode=:ProductName];

Note that I assumed the field is in the OpportunityLineItemList because of the following line of code:

 

for (OpportunityLineItem myOppItem: OpportunityLineItemList) {

It would be quite a challenge to fully debug the code without actually replicating the fields in my developer instance, but I hope that gives you some direction. Feel free to post any errors you may receive.

HaralambyHaralamby

LOL!!!

 

I am new at this but all I want to do is declare a variable; which is "Price Weekly"  and set it to equal my custom field so I am typing in the code:


double PriceWeekly=myOpp.Daily_Revenue_Rate__c;

but when I run the code I get the following error:   Variable does not exist: myOpp.Daily_Revenue_Rate__c

 

I don't know what it could be.....isn't that the right delcaration?

 

I even added the field in: 

 

 

OpportunityList= [Select o.ARM__c, o.QUANT__c, o.QUAL__c, o.Expected_Revenue_Quant__c, o.Expected_Revenue_Qual__c, o.Expected_Revenue_ARM__c, o.HIT_Start_Date__c, o.Estimated_Start_Date__c, o.Quant_Start_Date__c, o.Daily_Revenue_Rate__c, o.AccountId,o.IsDeleted, o.IsClosed, o.Id, o.Name From Opportunity o where o.IsClosed=false AND o.IsDeleted=false

 I can not put in OppItem list because "Daily_Revenue_Rate__c" is not part of that Subject...

 

 

HaralambyHaralamby

Hold on I added the field in the sObject and then included it in the list and it worked...now I just have to to minor changes (I hope) and it should be done but I still don't understand why it wasn't not recognizing the myopp.daily_revenue_rate__c and it recognizes myoppitem.daily_revenue_rate__C when they are both in the their respective list......

 

 

Thanks again for your help will keep you posted !!!!!!!

CaptainObviousCaptainObvious

Ok, it's making more sense...
Daily_Revenue_Rate__c is a field on the Opportunity object.
You already added it to the OpportunityList- Make sure you add it to both the 'Batch' and 'Single' lists.
Here are the next steps:
Find the ReEstablish method: public void ReEstablish()

Edit this section of code as follows:

else{ double ProductAmount; double PriceWeekly=myOpp.Daily_Revenue_Rate__c; //if (myOpp.QUAL__c>0){ ProductAmount=myOpp.Qual__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUAL',myOpp.Estimated_Start_Date__c, myOpp.Name,PriceWeekly); //} //if (myOpp.QUANT__c>0){ ProductAmount=myOpp.QUANT__c; ReEstablishProduct(myOpp.Id, ProductAmount,'QUANT', myOpp.Quant_Start_Date__c, myOpp.Name,PriceWeekly); //} //if (myOpp.ARM__c>0){ ProductAmount=myOpp.ARM__c; ReEstablishProduct(myOpp.Id, ProductAmount,'HIT', myOpp.Hit_Start_Date__c, myOpp.Name,PriceWeekly); //} }

 

Now find and edit the ReEstablishProduct method:

 

public void ReEstablishProduct(string OppId, double ProductAmount, string ProductName, date StartDate, string OppName, double PriceWeekly)

That you should allow you to reference the Daily Revenue Rate.

Make sure to comment out (or delete) the old calculation:

 

//double PriceWeekly=(newUnitPrice * myOppItem.Quantity)/52;

Hope that helps!

This was selected as the best answer
HaralambyHaralamby

Awsome it worked and using the same logic I changed the number of installments to be dynamic as well based on other formula fields......Thanks for everything!!!!!!!!!!!!!!!!!!

 

Now all I need to do is to pass it on from sandbox to our actual platform (deploy it)....Does that require code as well or can just I click away????

 

Thanks again!!!!!