# Create a business rule

> For the complete machine-readable documentation index, see [llms.txt](https://apidocs.chargebee.com/llms.txt).


[Idempotency Supported](/docs/api/idempotency)

Creates a business rule and releases its first version, so the new rule has `latest_version` set to `1` and `released_at` set. The rule is created inactive: Chargebee does not evaluate it until you call [Activate a business rule](/docs/api/business_rules/activate-a-business-rule).

Use this operation to encode a decision that Chargebee should make repeatedly and consistently, such as the discount to offer on a qualifying quote or the constraint that a quote must satisfy before it is sent to a customer. The condition goes in `structured_expression`, and what should happen when the condition is met goes in `actions_on_success`.

### Prerequisites & Constraints

Business rules must be enabled for the site.

### Impacts

**

Business rule

**

A business rule is created with its first version released, so `latest_version` is `1` and `released_at` and `released_by` are set. The rule is created with `active` set to `false`, so Chargebee does not evaluate it yet.

### Implementation Notes

-   Call [Activate a business rule](/docs/api/business_rules/activate-a-business-rule) to put the new rule into effect. [Release a business rule](/docs/api/business_rules/release-a-business-rule) is only needed later, once you have edited the rule and want the resulting draft to take effect.
-   To check an expression against sample data before you store it as a rule, call [Apply business rules](/docs/api/business_rules/apply-business-rules) with `structured_expression` and a `context`, and with `evaluate` set to `true` so that no actions are executed.

## Sample Request

#### cURL

```bash
curl  https://{site}.chargebee.com/api/v2/business_rules \
     -u {site_api_key}:\
     -d id="custom-uuid-1" \
     -d name="Apply 12 percentage discount at invoice level" \
     -d description="Apply 12 percentage discount at invoice level" \
     -d structured_expression='{"type":"GROUP","operation":"AND","children":[{"type":"CONDITION","field":"customer.language","operator":"CONTAINS","value":"en"},{"type":"CONDITION","field":"quote.shipping_address_country","operator":"ANY_OF","values":["IN","US"]}]}' \
     -d actions_on_success='[{"input":{"apply_on":"invoice_amount","duration_type":"one_time","discount":12.0,"discount_type":"percentage"},"action_template_id":"action-apply-discount","type":"APPLY_DISCOUNT"}]'
```

#### .NET

```dotnet
using ChargeBee.Api;
using ChargeBee.Models;
using Newtonsoft.Json.Linq;

ApiConfig.Configure("{site}","{site_api_key}");
var structuredExpression = new JObject {
  ["type"] = "GROUP",
  ["operation"] = "AND",
  ["children"] = "[{\"type\":\"CONDITION\",\"field\":\"customer.language\",\"operator\":\"CONTAINS\",\"value\":\"en\"},{\"type\":\"CONDITION\",\"field\":\"quote.shipping_address_country\",\"operator\":\"ANY_OF\",\"values\":[\"IN\",\"US\"]}]"
};
EntityResult result = BusinessRule.Create()
		.Id("custom-uuid-1")
		.Name("Apply 12 percentage discount at invoice level")
		.Description("Apply 12 percentage discount at invoice level")
		.StructuredExpression(structuredExpression)
		.ActionsOnSuccess(new JArray { "{\"input\":{\"apply_on\":\"invoice_amount\",\"duration_type\":\"one_time\",\"discount\":12,\"discount_type\":\"percentage\"},\"action_template_id\":\"action-apply-discount\",\"type\":\"APPLY_DISCOUNT\"}" })
		.Request();

BusinessRule businessRule = result.BusinessRule;
```

#### Go

```go
package main
import (
    "fmt"
    "github.com/chargebee/chargebee-go/v3"
    businessruleAction "github.com/chargebee/chargebee-go/v3/actions/businessrule"
    "github.com/chargebee/chargebee-go/v3/models/businessrule"
)
func main() {
    chargebee.Configure("{site_api_key}","{site}");
    res,err := businessruleAction.Create(&businessrule.CreateRequestParams{
        Id : "custom-uuid-1",
        Name : "Apply 12 percentage discount at invoice level",
        Description : "Apply 12 percentage discount at invoice level",
        StructuredExpression : &businessrule.CreateStructuredExpressionParams{
            Type : "GROUP",
            Operation : "AND",
            Children : [
    map[string]interface{}{
        "type" : "CONDITION",
        "field" : "customer.language",
        "operator" : "CONTAINS",
        "value" : "en",
    },
    map[string]interface{}{
        "type" : "CONDITION",
        "field" : "quote.shipping_address_country",
        "operator" : "ANY_OF",
        "values" : []interface{}{
            "IN",
            "US",
        },
    }
],
        },
        ActionsOnSuccess : []*businessrule.CreateActionsOnSuccessParams{
            {
                Input : map[string]interface{}{
    "apply_on" : "invoice_amount",
    "duration_type" : "one_time",
    "discount" : 12,
    "discount_type" : "percentage",
},
                ActionTemplateId : "action-apply-discount",
                Type : "APPLY_DISCOUNT",
            },
        },
    }).Request()
    if err != nil {
        fmt.Println(err)
    } else {
        BusinessRule := res.BusinessRule
    }
}
```

#### Go

```go
package main

import (
  "fmt"
  "github.com/chargebee/chargebee-go/v4"
)

func main() {
  config := &chargebee.ClientConfig{
    SiteName: "{site}",
    ApiKey: "{site_api_key}",
  }    
  client := chargebee.NewClient(config)
  req := &chargebee.BusinessRuleCreateRequest{
    Id : "custom-uuid-1",
    Name : "Apply 12 percentage discount at invoice level",
    Description : "Apply 12 percentage discount at invoice level",
    StructuredExpression : &chargebee.BusinessRuleCreateStructuredExpression{
        Type : "GROUP",
        Operation : "AND",
        Children : [
map[string]interface{}{
    "type" : "CONDITION",
    "field" : "customer.language",
    "operator" : "CONTAINS",
    "value" : "en",
},
map[string]interface{}{
    "type" : "CONDITION",
    "field" : "quote.shipping_address_country",
    "operator" : "ANY_OF",
    "values" : []interface{}{
        "IN",
        "US",
    },
}
],
    },
    ActionsOnSuccess : []*chargebee.BusinessRuleCreateActionsOnSuccess{
        {
            Input : map[string]interface{}{
"apply_on" : "invoice_amount",
"duration_type" : "one_time",
"discount" : 12,
"discount_type" : "percentage",
},
            ActionTemplateId : "action-apply-discount",
            Type : "APPLY_DISCOUNT",
        },
    },
}
  res, err := client.BusinessRule.Create(req)
      if err != nil {
        fmt.Println(err)
    } else {
        BusinessRule := res.BusinessRule
    }
}
```

#### Java

```java
import com.chargebee.*;
import com.chargebee.ListResult;
import com.chargebee.models.*;
import com.chargebee.models.enums.*;
import java.io.IOException;
import java.util.List;
import com.chargebee.org.json.JSONArray;
import com.chargebee.org.json.JSONObject;

public class Sample {

    public static void main(String args[]) throws IOException, Exception {
        Environment.configure("{site}", "{site_api_key}");
        Result result = BusinessRule.create()
            .id("custom-uuid-1")
            .name("Apply 12 percentage discount at invoice level")
            .description("Apply 12 percentage discount at invoice level")
            .structuredExpression(new JSONObject("{\"type\":\"GROUP\",\"operation\":\"AND\",\"children\":[{\"type\":\"CONDITION\",\"field\":\"customer.language\",\"operator\":\"CONTAINS\",\"value\":\"en\"},{\"type\":\"CONDITION\",\"field\":\"quote.shipping_address_country\",\"operator\":\"ANY_OF\",\"values\":[\"IN\",\"US\"]}]}"))
            .actionsOnSuccess(new JSONArray("[{\"input\":{\"apply_on\":\"invoice_amount\",\"duration_type\":\"one_time\",\"discount\":12.0,\"discount_type\":\"percentage\"},\"action_template_id\":\"action-apply-discount\",\"type\":\"APPLY_DISCOUNT\"}]"))
            .request();

        BusinessRule businessRule = result.businessRule();
    }
}
```

#### Java

```java
import com.chargebee.v4.client.ChargebeeClient;
import com.chargebee.v4.models.businessRule.BusinessRule;
import com.chargebee.v4.models.businessRule.params.BusinessRuleCreateParams;
import com.chargebee.v4.models.businessRule.responses.BusinessRuleCreateResponse;
import java.util.List;
import java.util.Map;

public class BusinessRuleCreate {

    public static void main(String[] args) {
        ChargebeeClient client = ChargebeeClient.builder()
            .apiKey("{site_api_key}")
            .siteName("{site}")
            .build();

        BusinessRuleCreateParams params = BusinessRuleCreateParams.builder()
            .id("custom-uuid-1")
            .name("Apply 12 percentage discount at invoice level")
            .description("Apply 12 percentage discount at invoice level")
            .structuredExpression(Map.of("type", "GROUP", "operation", "AND", "children", List.of(Map.of("type", "CONDITION", "field", "customer.language", "operator", "CONTAINS", "value", "en"), Map.of("type", "CONDITION", "field", "quote.shipping_address_country", "operator", "ANY_OF", "values", List.of("IN", "US")))))
            .actionsOnSuccess(List.of("[{\"input\":{\"apply_on\":\"invoice_amount\",\"duration_type\":\"one_time\",\"discount\":12.0,\"discount_type\":\"percentage\"},\"action_template_id\":\"action-apply-discount\",\"type\":\"APPLY_DISCOUNT\"}]"))
            .build();

        BusinessRuleCreateResponse response = client.businessRules().create(params);

        BusinessRule businessRule = response.getBusinessRule();
    }
}
```

#### Node.js

```node
import Chargebee from "chargebee";

const chargebee = new Chargebee({
    site: "{site}",
    apiKey: "{site_api_key}",
});

try {
    const result = await chargebee.businessRule.create({
        id: "custom-uuid-1",
        name: "Apply 12 percentage discount at invoice level",
        description: "Apply 12 percentage discount at invoice level",
        structured_expression: {
            type: "GROUP",
            operation: "AND",
            children: [
                {
                    type: "CONDITION",
                    field: "customer.language",
                    operator: "CONTAINS",
                    value: "en"
                },
                {
                    type: "CONDITION",
                    field: "quote.shipping_address_country",
                    operator: "ANY_OF",
                    values: ["IN", "US"]
                }
            ]
        },
        actions_on_success: [
            {
                input: {
                    apply_on: "invoice_amount",
                    duration_type: "one_time",
                    discount: 12,
                    discount_type: "percentage"
                },
                action_template_id: "action-apply-discount",
                type: "APPLY_DISCOUNT"
            }
        ]
    });

    console.log(result);
    const businessRule = result.business_rule;
} catch (err) {
    console.log(err);
}
```

#### PHP

```php
<?php

require __DIR__ . '/vendor/autoload.php';

use Chargebee\ChargebeeClient;

$chargebee = new ChargebeeClient(options: [
    "site" => "{site}",
    "apiKey" => "{site_api_key}",
]);
$result = $chargebee->businessRule()->create([
    "id" => "custom-uuid-1",
    "name" => "Apply 12 percentage discount at invoice level",
    "description" => "Apply 12 percentage discount at invoice level",
    "structured_expression" => '{"type":"GROUP","operation":"AND","children":[{"type":"CONDITION","field":"customer.language","operator":"CONTAINS","value":"en"},{"type":"CONDITION","field":"quote.shipping_address_country","operator":"ANY_OF","values":["IN","US"]}]}',
    "actions_on_success" => [
        [
            "input" => [
                "apply_on" => "invoice_amount",
                "duration_type" => "one_time",
                "discount" => 12,
                "discount_type" => "percentage"
            ],
            "action_template_id" => "action-apply-discount",
            "type" => "APPLY_DISCOUNT"
        ]
    ]
]);
$businessRule = $result->business_rule;
```

#### Python

```python
from chargebee import Chargebee

cb_client = Chargebee(api_key="{site_api_key}", site="{site}")
response = cb_client.BusinessRule.create(
    cb_client.BusinessRule.CreateParams(
        id="custom-uuid-1",
        name="Apply 12 percentage discount at invoice level",
        description="Apply 12 percentage discount at invoice level",
        structured_expression={
            "type": "GROUP",
            "operation": "AND",
            "children": [
    {
        "type": "CONDITION",
        "field": "customer.language",
        "operator": "CONTAINS",
        "value": "en"
    },
    {
        "type": "CONDITION",
        "field": "quote.shipping_address_country",
        "operator": "ANY_OF",
        "values": ["IN", "US"]
    }
]
        },
        actions_on_success=[
            cb_client.BusinessRule.CreateActionsOnSuccessParams(
              input={
    "apply_on": "invoice_amount",
    "duration_type": "one_time",
    "discount": 12,
    "discount_type": "percentage"
},
              action_template_id="action-apply-discount",
              type="APPLY_DISCOUNT"
            )
        ]
    )
)
business_rule = response.business_rule
```

#### Ruby

```ruby
require 'chargebee'

ChargeBee.configure(:site => "{site}",
  :api_key => "{site_api_key}")

result = ChargeBee::BusinessRule.create({
  :id => "custom-uuid-1",
  :name => "Apply 12 percentage discount at invoice level",
  :description => "Apply 12 percentage discount at invoice level",
  :structured_expression => {:type => "GROUP",:operation => "AND",:children => [{:type => "CONDITION",:field => "customer.language",:operator => "CONTAINS",:value => "en"},{:type => "CONDITION",:field => "quote.shipping_address_country",:operator => "ANY_OF",:values => ["IN","US"]}]},
  :actions_on_success => "[{\"input\":{\"apply_on\":\"invoice_amount\",\"duration_type\":\"one_time\",\"discount\":12.0,\"discount_type\":\"percentage\"},\"action_template_id\":\"action-apply-discount\",\"type\":\"APPLY_DISCOUNT\"}]"
})

business_rule = result.business_rule
```

## Sample Response

```json
{
  "business_rule": {
    "id": "custom-uuid-1",
    "name": "Apply 12 percentage discount at invoice level",
    "description": "Apply 12 percentage discount at invoice level",
    "latest_version": 1,
    "active": false,
    "released_at": 1788510782,
    "released_by": "full_access_key_v1",
    "updated_at": 1788510782,
    "updated_by": "full_access_key_v1",
    "created_by": "full_access_key_v1",
    "created_at": 1788510782,
    "tags": [
      "CPQ",
      {..}
    ],
    "structured_expression": {
      "type": "GROUP",
      "operation": "AND",
      "children": [
        {
          "type": "CONDITION",
          "field": "customer.language",
          "operator": "CONTAINS",
          "value": "en"
        },
        {..}
      ]
    },
    "actions_on_success": [
      {
        "input": {
          "apply_on": "invoice_amount",
          "duration_type": "one_time",
          "discount": 12,
          "discount_type": "percentage"
        },
        "action_template_id": "action-apply-discount",
        "type": "APPLY_DISCOUNT"
      },
      {..}
    ],
    "resource_version": 1788510782918,
    "object": "business_rule"
  }
}
```

## URL Format

**POST** https://[site].chargebee.com/api/v2/business_rules

## Input Parameters

- `id` (optional, string, max chars=100)
  Unique identifier for the business rule. If not provided, Chargebee generates one.
  
  **Constraints**
  
  -   The identifier of a deleted rule cannot be reused.

- `name` (required, string, max chars=500)
  Display name of the business rule.

- `description` (optional, string, max chars=1000)
  Description of what the business rule does.

- `structured_expression` (required, jsonobject)
  A structured JSON representation of the rule logic, designed for visual editors and dynamic builders. Chargebee validates and compiles it when the rule is created. Pass it as a JSON object.
  
  See [Expressions](/docs/api/business_rules#expressions) for the node types and the operators each field type supports, and [Context](/docs/api/business_rules#context) for the fields a condition can reference.
  
  **Impacts**
  
  -   A condition whose `field` is absent from the context passed to [Apply business rules](/docs/api/business_rules/apply-business-rules) evaluates to `false`, so the rule never matches and no error is returned.
  
  **Example →** `structured_expression = {"type":"GROUP","operation":"AND","children":[{"type":"CONDITION","field":"customer.language","operator":"CONTAINS","value":"en"},{"type":"CONDITION","field":"quote.shipping_address_country","operator":"ANY_OF","values":["IN","US"]}]}`

- `actions_on_success` (optional)
  The actions to execute when the rule expression evaluates to `true`, passed as a JSON array. Each action takes the `action_template_id` of the template it is built from and that template's parameters in `input`.
  
  See [Actions](/docs/api/business_rules#actions) for the templates available, the parameters each one takes, and the optional action-level `structured_expression` that narrows the items an action applies to.
  
  **Example →** `actions_on_success = [{"action_template_id":"action-apply-discount","input":{"apply_on":"invoice_amount","duration_type":"one_time","discount":12.0,"discount_type":"percentage"}}]`

## Returns

- `business_rule` (Business rule object)
  The newly created business rule, with its first version released so `latest_version` is `1`, and with `active` set to `false`.
