首页 > 解决方案 > Drools:在多次执行后阻止规则触发

问题描述

我试图弄清楚如何在多次执行后阻止规则触发。假设您购买商品 X(当前价格 10 美元)给予折扣,但每位客户只能给予 2 次折扣。

所以我的规则如下:

 rule "Fixed Price Promotion Item X"

 when
     $o : Order( )
     $ol1 : OrderLine( item.code == "X" )
 then
    FixedPrice fixedPrice = new FixedPrice(8.80, $ol1.getItem().getPrice().doubleValue(), $ol1.getItem().getBarcode(), 1, "e78fbca5ed014f49806ad667aea80965" , "Happy Mother's day!! This is a fixed price promotion" );
    insertLogical (fixedPrice); //here I grant a promotion

最初,我想有另一个规则在满足我的条件时插入一个事实,这样它就会阻止我的提升规则被触发。

我会有这样的事情:

declare LimitReachedOut
   promotionId : String
end

rule "stop Promotion"
when
     Number($numOfGrantedProm : intValue) from accumulate ( 
                                FixedPrice(promotionId == "123",
                                        $count: quantity),
                                sum($count)
            )
then
    if( $numOfGrantedProm == 2  ){ //this cause an issue, even > 1 or >=2 will keep inserting new LimitReachedOut("123") recursively.
        insertLogical (new LimitReachedOut("123"));
     }
end  


rule "Fixed Price Promotion Item X"
 when
     not( LimitReachedOut( promotionId == "123" ) )
     $o : Order( )
     $ol1 : OrderLine( item.code == "X" ) 
 then
    FixedPrice fixedPrice = new FixedPrice(8.80, $ol1.getItem().getPrice().doubleValue(), $ol1.getItem().getBarcode(), 1, "123" , "Happy Mother's day!! This is a fixed price promotion" );
    insertLogical (fixedPrice);

 end

还有另一种方法吗?

我将非常感谢您的意见。

标签: drools

解决方案


我找到了一种方法来完成我想要的,如果有人也想使用它,我将它发布在这里。我基本上没有执行将条件子句放在那里的规则的 RHS。

首先,我正在使用累积函数计算插入到工作内存中的 Facts 的数量(FixedPrice 的 id 称为 ruleId 以将事实链接到这个特定的规则) 。其次,RHS if( $numOfGrantedProm < 2 ) 中的条件意味着我将执行条件 if (create & insert fixedPrice fact) 内的块最多两次。无论如何都会触发该规则,但if条件将避免执行代码块。

rule "Fixed Price Promotion Item X"

when
   $o : Order( )
   $ol1 : OrderLine( item.code == "X" )
   Number($numOfGrantedProm : intValue) from accumulate ( 
                                           FixedPrice(ruleId == 
                           "e78fbca5ed014f49806ad667aea80965",$count:quantity),
                           sum($count)
                      )
then
   if( $numOfGrantedProm < 2  ){ 
       FixedPrice fixedPrice = new FixedPrice(8.80,
                                   $ol1.getItem().getPrice().doubleValue(),
                                   $ol1.getItem().getBarcode(), 
                                   1, 
                                   "e78fbca5ed014f49806ad667aea80965" , 
                                   "Happy Mother's day!! This is a fixed price 
                                    promotion" );
       insertLogical (fixedPrice); //here I grant a promotion enter code here
    }
end

推荐阅读