Package: business-rules-reloaded
business-rulesBased onvenmo/business-rules.As a software system grows in complexity and usage, it can become burdensome if
every change to the logic/behavior of the system also requires you to write and
deploy new code. The goal of this business rules engine is to provide a simple
interface allowing anyone to capture new rules and logic defining the behavior
of a system, and a way to then process those rules on the backend.You might, for example, find this is a useful way for analysts to define
marketing logic around when certain customers or items are eligible for a
discount or to automate emails after users enter a certain state or go through
a particular sequence of events.Usage1. Define Your set of variablesVariables represent values in your system, usually the value of some particular object.  You create rules by setting threshold conditions such that when a variable is computed that triggers the condition some action is taken.You define all the available variables for a certain kind of object in your code, and then later dynamically set the conditions and thresholds for those.For example:importdatetimefrombusiness_rules.variablesimport(BaseVariables,numeric_rule_variable,select_rule_variable,string_rule_variable)classProductVariables(BaseVariables):def__init__(self,product):self.product=product@numeric_rule_variabledefcurrent_inventory(self):returnself.product.current_inventory@numeric_rule_variable(label='Days until expiration')defexpiration_days(self):last_order=self.product.orders[-1]return(last_order.expiration_date-datetime.date.today()).days@string_rule_variable()defcurrent_month(self):returndatetime.datetime.now().strftime("%B")@select_rule_variable(options=Products.top_holiday_items())defgoes_well_with(self):returnproducts.related_products2. Define your set of actionsThese are the actions that are available to be taken when a condition is triggered.For example:frombusiness_rules.actionsimport(BaseActions,rule_action)frombusiness_rules.operatorsimportFIELD_NUMERICclassProductActions(BaseActions):def__init__(self,product):self.product=product@rule_action(params={"sale_percentage":FIELD_NUMERIC})defput_on_sale(self,sale_percentage):self.product.price=(1.0-sale_percentage)*self.product.priceself.product.save()@rule_action(params={"number_to_order":FIELD_NUMERIC})deforder_more(self,number_to_order):ProductOrder.objects.create(product_id=self.product.id,quantity=number_to_order)If you need a select field for an action parameter, another -more verbose- syntax is available:frombusiness_rules.actionsimport(BaseActions,rule_action)frombusiness_rules.operatorsimportFIELD_SELECTclassProductActions(BaseActions):def__init__(self,product):self.product=product@rule_action(params=[{'fieldType':FIELD_SELECT,'name':'stock_state','label':'Stock state','options':[{'label':'Available','name':'available'},{'label':'Last items','name':'last_items'},{'label':'Out of stock','name':'out_of_stock'}]}])defchange_stock_state(self,stock_state):self.product.stock_state=stock_stateself.product.save()3. Build the rulesA rule is just a JSON object that gets interpreted by the business-rules engine.Note that the JSON is expected to be auto-generated by a UI, which makes it simple for anyone to set and tweak business rules without knowing anything about the code.  The javascript library used for generating these on the web can be foundhere.An example of the resulting python lists/dicts is:rules=[# expiration_days < 5 AND current_inventory > 20{"conditions":{"all":[{"name":"expiration_days","operator":"less_than","value":5,},{"name":"current_inventory","operator":"greater_than","value":20,},]},"actions":[{"name":"put_on_sale","params":{"sale_percentage":0.25},},],},# current_inventory < 5 OR (current_month = "December" AND current_inventory < 20){"conditions":{"any":[{"name":"current_inventory","operator":"less_than","value":5,},]},{"all":[{"name":"current_month","operator":"equal_to","value":"December",},{"name":"current_inventory","operator":"less_than","value":20,}]},},"actions":[{"name":"order_more","params":{"number_to_order":40},},],}]Export the available variables, operators and actionsTo e.g. send to your client so it knows how to build rulesfrombusiness_rulesimportexport_rule_dataexport_rule_data(ProductVariables,ProductActions)that returns{"variables":[{"name":"expiration_days","label":"Days until expiration","field_type":"numeric","options":[]},{"name":"current_month","label":"Current Month","field_type":"string","options":[]},{"name":"goes_well_with","label":"Goes Well With","field_type":"select","options":["Eggnog","Cookies","Beef Jerkey"]}],"actions":[{"name":"put_on_sale","label":"Put On Sale","params":{"sale_percentage":"numeric"}},{"name":"order_more","label":"Order More","params":{"number_to_order":"numeric"}}],"variable_type_operators":{"numeric":[{"name":"equal_to","label":"Equal To","input_type":"numeric"},{"name":"less_than","label":"Less Than","input_type":"numeric"},{"name":"greater_than","label":"Greater Than","input_type":"numeric"}],"string":[{"name":"equal_to","label":"Equal To","input_type":"text"},{"name":"non_empty","label":"Non Empty","input_type":"none"}]}}Run your rulesfrombusiness_rulesimportrun_allrules=_some_function_to_receive_from_client()forproductinProducts.objects.all():run_all(rule_list=rules,defined_variables=ProductVariables(product),defined_actions=ProductActions(product),stop_on_first_trigger=True)APIVariable Types and Decorators:The type represents the type of the value that will be returned for the variable and is necessary since there are different available comparison operators for different types, and the front-end that's generating the rules needs to know which operators are available.All decorators can optionally take a label:label- A human-readable label to show on the frontend. By default we just split the variable name on underscores and capitalize the words.The available types and decorators are:numeric- an integer, float, or python Decimal.@numeric_rule_variableoperators:equal_togreater_thanless_thangreater_than_or_equal_toless_than_or_equal_toNote: to compare floating point equality we just check that the difference is less than some small epsilonstring- a python bytestring or unicode string.@string_rule_variableoperators:equal_tostarts_withends_withcontainsmatches_regexnon_emptyboolean- a True or False value.@boolean_rule_variableoperators:is_trueis_falseselect- a set of values, where the threshold will be a single item.@select_rule_variableoperators:containsdoes_not_containselect_multiple- a set of values, where the threshold will be a set of items.@select_multiple_rule_variableoperators:contains_allis_contained_byshares_at_least_one_element_withshares_exactly_one_element_withshares_no_elements_with