Creating APIs‎ > ‎

Logic

The following video illustrates an overview of reactive logic, what it is, how to use it, and how you declare your logic by specifying your business rules as a series of spreadsheet-like expressions (rules):

You specify the logic as a series of constraint declarations, expressions that the runtime system guarantees to be true for a transaction to succeed. The logic you declare in Live API Creator is bound to your database tables and enforced on all updates against those tables. You can reuse this logic.

Logic ensures the integrity of your data when update requests are made. For example, business rules for the following constraints:

  • Derivations. Rules to derive or return a column value (for example, Sum, Count, Formula, Min/Max, and Parent Copy). Reactive programming expressions define the value of a column in a table. They range from simple formulas (product_price * qty_ordered) to multi-table (sum example). API Server watches for changes in referenced data; if detected, it recomputes the derivation in an optimal manner. This can become quite complex, since derivations can chain.

For more information about reactive programming, see the Reactive Programming wikipedia page.

  • Validations. Rules to ensure the integrity of the transaction. They are expressions that must be true for a transaction to commit (else an exception is raised). Validations are multi-field and can operate on derivation results (as in this credit_limit example). Each rule is defined on a business entity (Table) and perhaps an attribute (Column). The rule is triggered when a state change occurs (for example, PUT/POST/DELETE operations) on the entity and/or attribute.

In the context of Live API Creator, business logic refers to the PUT/POST/DELETE-transactional business logic that API Creator applies when committing a transaction. The rules (your logic) is comprised of multi-table derivation, constraint, and action rules that govern update processing, using expressions instead of code.

You specify business rules with a combination of JavaScript (logic) events and reactive logic. You associate the server-side JavaScript events with tables. Contextual information is passed to your code, in particular the row object. Extensibility is provided by way of loadable JavaScript librariesReactive logic enforces the bulk of your business rules.

Design Approach

Using Agile as an example:
  • Identify an epic. A system might have several epics, for example, sales entry, and HR management.
  • Identify a feature, such as Place Order.
  • Identify a user story. Within a Feature, identify multiple user stories, such as Check Credit, Explode Bill of Materials.  All User Stories should be testable.
  • Identify the behavior. Alternative to User Story in some methodologies.
  • Enter the user story/behavior as a topic. Define topics and associate rules to the topics. For each behavior (such as Check Credit), enter it as a topic. 
For more information about categorizing rules into topics and filtering rules by topics, see Topics.
  • Define the logic that solves the behavior. Define one or more rules that solve the identified behavior, for example, the Check Credit topic.

In many cases, such as the following example, this entails capturing a validation rule and then defining the multiple derivations that provide the data for the validation.

For more information about managing topics, including entering behaviors as topics and entering user stories/behavior as topics, see Manage Topics.

A First Look at Logic

The sample Business Logic demo illustrates the use and operation of business logic. Logic is expressed as a set of rules that define what your data meansLike a spreadsheet, Live API Creator invokes rules in response to changes in the data from PUT, POST, and DELETE requests on base tables.

For more information about the sample business logic demo, see Business Logic API Project Sample.

Your logic specifications are defined for base tables and are automatically applied to all resources defined over that table. Logic execution is a sophisticated process that automates complex multi-table dependencies with automatic re-use across use cases, while maintaining enterprise-class performance through SQL reduction/elimination. Logic plans reflect the latest deployed logic, so that compliance and performance are maintained while providing business agility.

Consider the Place Order user story, with the behavior customer's balance may not exceed their credit limit. The following logic, which looks rather like a requirements document, is executable:

Validation Logic

Validations are the most familiar form of business logic and are expressions that must be satisfied to commit transactions. Without the validations, an exception is thrown and the transaction is rolled back. Validations can be simple single-attribute or multi-attribute. For example, the following Customer Validation has a multi-attribute requirement:

balance < credit_limit

For more information about validations, see Validations.

Derivation Logic

API Creator applies derivation logic to individual column attributes. Derivations and events are more valuable than validations, per dependency/re-use automation. Derivations include multi-table derivation rules. For example, the following rule defines the balance as the sum of the unpaid order totals:

Customer.balance = sum(purchaseorder.amount_total where paid = false)

Alter, or derive, the value of a specific attribute using derivation rule types. Much like a spreadsheet cell, these derivations become part of a chain of events that are called during the processing of a data transaction. These derivations are applied to a specific attributes on a table.

In this exercise, uses the classic Customer/Order/Invoice to describe each of the derivation rules and how they are applied to an invoice. The following image shows an example invoice:

The typical invoice contains company information, customer billing and shipping information, order header (invoice specific) and line item details. Using this template as a guide, the invoice line item has an item#, quantity, details, unit price ($), and Total price ($).

The TotalPrice is derived using a formula (row.unitprice * row.quantity). You do not enter the unit price by hand. It is assigned to the Parts inventory system. The next rule to add is a parent copy of unitprice from the parts table when you enter the part item number. The parent copy makes a replication of the value at the time of entry (non-maintained) so future price changes do not impact existing orders. Not shown is the lineitem discount calculations for this customer using a formula which applies quantity discounts based on customer loyalty. You can also populate the details on the line item using the Parent Copy from part.

The Invoice SubTotal uses a sum on the invoice (order header) itself and Live API Creator uses a derivation called sum(lineitem.TotalPrice). The invoice discount is the sum(lineitem.discount). The Tax/VAT is another formula (row.subtotal * row.taxrate). Finally, Live API Creator calculates the grand total using a formula ((row.subtotal -row.discount) - (row.tax + row.shipping)). 

Notice that in the building of rules, you did not specify the order of operation or what events were needed. In other words, state change means inserting a new line item, deleting a line item, changing a quantity or even an item number triggers the recalculation of these rules.

Derivations are conceptually similar to spreadsheet cell formulas:

    • Derivations are multi-table, as in the previous example.
    • Derivations can chain, both to validations, and other derivations:
      • Purchaseorder.amount_total = sum(lineitem.amount)
      • Lineitem.amount = qty_ordered * product_price
      • Lineitem.product_price = copy(product.price)
    • Live API Creator handles chaining, ordering, and dependencies automatically.
    • Derivations can include if/else logic, state transition logic, and reference related data.
    • Derivations are optimized to eliminate/optimize SQLs. For example, changing an orders's date does not retrieve the customer, and paying an order adjusts the customer with a one-row update, not an aggregate query.

For more information:

Event Logic

API Creator creates JavaScript objects, or rows, for each base table. The rows provide accessors for attributes and related data, and automated persistence. API Creator supplies old/new versions of rows to your events and logic, with automatic resource/object mapping. Resource/object mapping means your rules apply to update requests for both custom and default resources.

Early events, row events, regular events, request, and response events are JavaScript entry points to perform user-defined actions. For example, auditing, copying (an order clone), sending mail, and messages. This is complementary to other forms of business logic such as process (workflow) logic, application integration, and decision logic.

You typically use both reactive logic and JavaScript events to meet requirements. They are integrated by virtue of a common underlying object model, created directly from your schema.

Logic is transparent documentation. As a business user and IT, you can partner and find missing/incorrect elements using the logic.

For more information:

Logic Re-use over Behaviors

Significant value is realized in the next user story/behavior, for example Change Order Item - Reassign Product. Related user stories typically do not require new logic. Reactive logic is defined on the tables and columns, and not on a specific service. Automatic invocation ensures it is re-used over all relevant User Stories/Behaviors. In the case of Live API Creator's  customer.balance rule, this means that this one statement obligates the system respond to all of the following:

  • Order inserted - balance increased
  • Order deleted - balance decreased (if not paid)
  • Order paid - balance decreased
  • Order unpaid - balance decreased
  • Order amountTotal changed - balance adjusted
  • Order reassigned to different customer - balance increased for new customer, decreased for old
Live API Creator's five rules fully dictate the following User Stories - the complete order entry system:
  • Place Order – the balance is increased, and checked against the credit limit
  • Change customer credit limit – but not fall below the current balance
  • Delete Order – the balance is reduced for unpaid orders
  • Pay Order – the balance is reduced
  • UnPay Order – the balance is increased
  • Reassign Order to a new customer – new customer balance increased, old balance decreased (for unpaid Orders).
  • Reassign a Line Item to a different Product (see above)
  • Add a Line Item – adjust order and customer, with credit limit check
  • Delete a Line Item – adjust order and (for unpaid orders) customer
  • Change Line Item Price – adjust order and customer, with credit limit check
  • Change Line Item Quantity – adjust order and customer, with credit limit check.
  • Combinations of these, such as altering the quantity and product.
There are implications of this declarative approach to logic using reactive logic.

Example: Change Item Quantity

Use this example to explore business logic. When you update the Line Item qtyOrdered, the resultant logic recomputes the Order.amountTotal and Customer.balance, and checks the credit. Live API Creator watch/react-processing is an optimized version of forward chaining. It:
  1. Watches. Live API Creator watches for changes in referenced data.
  2. Reacts. Determines the attributes dependent on what has changed, including across tables, and adjusts these, in an order that reflects their dependencies.
  3. Chains. If detected, Live API Creator optimally recomputes the derivation. This can become complex, since derivations can chain.
The Rules Animation Doc video illustrates the following:
  1. The amount derivation references qtyOrdered, so it is recomputed.
  2. The amountTotal references amount, so (per chaining), it is recomputed (SQL automated).
  3. The balance references the amountTotal, so it is recomputed.
  4. The validation references the balance, so it is re-evaluated (failure results in rollback and exception).

Iterations

Logic chaining execution order reflects dependencies between the rules. Iterating and altering the logic computes a new execution order. This eliminates the time-consuming study of existing code to determine where to introduce new code, which is the main hassle of maintenance.

Derived attributes are stored in the database. Performance optimizations presume the stored data is correct.

Important! When you introduce new columns (for example, the customer balance), bring the database into compliance with the rule.

For more information:

Manage Rules

Reactive logic is active as soon as you save and activate. The rules are maintained in the repository. Manage the rules by way of a RESTful API or by exporting the project. 

More Information

For more information: