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
prasanth kumar 31prasanth kumar 31 

how to write discount apex class

HI I'm New to Developing Can you please let me Know how to write Applying Discount on Record using trigger and apex Class. please send me code i'm able to understand or below is my apex class code, please Modify it.
Public Class PenClassdemonstration {

Public Static Void applyDiscountPen (list<pen__c> varpenslistNew) {

for (pen__c varp : varpenslistNew) {

if(varp.penamount__C >= 100) {

varp.penamount__C = varp.penamount__C - 20;

   }
  }
 }
}
ANUTEJANUTEJ (Salesforce Developers) 
Hi Prasanth,

I would suggest you check the formula field as you can simply use a formula field that is of type number that automatically calculates this value, you can see these implementations in the below links:

>> https://salesforce.stackexchange.com/questions/47248/formula-to-calculate-discounts

>> https://developer.salesforce.com/docs/atlas.en-us.usefulFormulaFields.meta/usefulFormulaFields/useful_advanced_formulas_discounting.htm

If you want to use trigger you use the below snippet and modify as per the usecase:
 
trigger PenTrigger on pen__c (after insert)
{
PenTriggerHandler objHandler = new PenTriggerHandler();
if(trigger.isAfter && trigger.isInsert)
{
list<pen__c> lpen = new list<pen__c>
for (pen__c varp : varpenslistNew) {

if(varp.penamount__C >= 100) {

lpen.add(varp);
   }

objHandler.OnAfterInsert(lpen);
}

}
 
public class PenTriggerHandler
{
public void OnAfterInsert(list<pen__c> penList)
{
list<pen__c> toupdatepen= new list<pen__c>();
for(pen__c p: penList){
Pen__c temporaryPen= new Pen__c();
temporaryPen.id= p.id;
temporaryPen.penamount__C = p.penamount__C - (p.penamount__C*0.2);
toupdatepen.add(temporaryPen);
}
if(toupdatepen.size()>0)
{update toupdatepen;}
}
}

Please do note that this is a sample snippet and you need to modify it accordingly.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
leonardokipperleonardokipper
What are the requirements/criteria to apply the discout (maybe it can be accomplished with a point & click solution instead of using code.: using a process, workflow or formula fields...). 

To help, we need to know the data model. What are the objects and fields to be used.