Question

I recently encountered below scenario in drools. I want to know how to proceed with the rule design for this.

Class Emp{
 beingDate:Date
 endDate:Date
}

Rule to determine annual income for the employee based on the given dates:

  • For dates before 3/5/2003 the hourly rate is $3.5 and annual multiplier is 2100
  • For dates after 3/5/2003 the hourly rate changes every year (given data) and annual multiplier is 2092.

There might be scenarios where begin date is before 3/5/2003 and end date is after 3/5/2003.

What is the best way to design rules for this scenario.

Update: added an e.g. for more clarity If the object is

empObj={
  beginDate=10/8/2001, 
  endDate=5/10/2005
}

The rule should give the sum of below:

  1. 3.5 * (no. of days in 2001 starting 10/8/2001) / (total no. of days in 2001) * 2100
  2. 3.5 * 2100 ==> This is for year 2002
  3. 3.5 * (no. of days in 2003 before 3/5/2003) / (total no. of days in 2003) * 2100
  4. (2003 hourly rate) * (no. of days in 2003 after 3/5/2003) / (total no. of days in 2003) * 2092 ==> note the change in yearly multiplier..
  5. (2004 hourly rate) * 2092
  6. (2005 hourly rate) * (no. of days in 2005 before 5/10/2005) / (total no. of days in 2005) * 2092
Was it helpful?

Solution

One way to do this is to have one rule per year. So it would look something like this

rule "2001"
when:
   e : Emp( beginDate < "01-Jan-2002" )
then:
   // 1. Get the number of days worked in 2001, probably easiest to do with some Java helper method
   // 2. Calculate the sum
   // 3. Add the sum to some Fact, could be the same Emp fact even
 end

 rule "2002"
 when:
   e : Emp( beginDate < "01-Jan-2003" )
 then:
    // As with 2001
 end

The rest of the rules are very similar, just change the yearly multiplier accordingly. If you decide to use the Emp object to hold the sum, add method like

class Emp {
  long sum = 0
  void addToSum( long value ) { sum += value }
}

And in your RHS side call the method and update the object on each rule.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top