Logic

Logic
lac52
You express your logic as a set of rules in API Creator. The rules define what your data means. Like a spreadsheet, 
CA Live API Creator
 invokes these rules in response to changes in the data from PUT, POST, and DELETE requests on base tables. It applies transaction business logic when committing a transaction.
Your API's logic are composed of derivation, constraint, and event rules. The rules govern update processing, using expressions instead of code.
For more information about business logic, see Interface Logic Versus Business Logic.
In this article:
2
Specify Business Logic
You specify your business logic in the following ways:
  • By filling out a form.
     You use forms for parent copy rules, sum rules, count rules, minimum rules, and maximum rules.
  • By providing server-side JavaScript.
     For formula and validation rules, you provide an expression or, more generally, a JavaScript function.
You specify business rules with a combination of event rules and reactive logic. You associate the event rules with tables. 
CA Live API Creator
 passes contextual information to your code, in particular the 
row
 object. Reactive logic enforces the bulk of your business rules.
The following image shows the process of specifying business logic:
 
You specify business logic as a series of constraint declarations. Declarations are expressions that the runtime system ensures to be true for a transaction to succeed. 
CA Live API Creator
 applies the table-based logic that you declare to updates on the table and to updates to the resources that you explicitly define over the table. 
CA Live API Creator
 automatically reuses the logic across the verbs (insert, update, delete) and the resources that you create over the table.
Logic ensures the integrity of your data when update requests are made. For example, business rules for the following constraints:
  • Derivation rules. 
    These rules derive or return a column value. 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 optimally. Derivations can chain.
    Rule types:
     Sum rules, count rules, formula rules, minimum rules, maximum rules, and parent copy rules.
    For more information about reactive programming, see Reactive Programming on the Wikipedia website.
  • Validation rules. 
    These rules ensure the integrity of a transaction. They are expressions that must be true for a transaction to commit (else an exception is raised). Validation rules are multi-field and can operate on derivation results (as in this 
    credit_limit
     example). You define these rules on a business entity (table or view) and perhaps an attribute (column). 
    CA Live API Creator
     triggers this rule when a state change occurs (for example, PUT/POST/DELETE operations) on the entity or attribute.
    Rule types:
     Validation rule and commit validation rule.
Design Approach
Using Agile as an example:
  1. Identify an epic.
     A system might have several epics, for example, sales entry, and HR management.
  2. Identify a feature,
     such as Place Order.
  3. Identify a user story. 
    Within a Feature, identify multiple user stories, such as Check Credit, Explode Bill of Materials. Your User Stories should be testable.
  4. Identify the behavior.
     Alternative to User Story in some methodologies.
  5. Enter the user story/behavior as a topic.
     Define topics and associate rules to the topics. For each behavior (such as Check Credit), categorize the rules into a topic.
    For more information about topics, see Manage Topics.
  6. Define the logic that solves the behavior.
     Define one or more rules that solve the identified behavior, for example, the Check Credit topic.
Often, such as the following example, specifying business logic entails capturing a validation rule and then defining the multiple derivations that provide the data for the validation rule.
A First Look at Logic
The 
Demo
 API sample illustrates the use and operation of business logic.
For more information about the Demo API sample, see Demo API 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. It automates complex multi-table dependencies with automatic reuse 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 cannot exceed their credit limit. The following logic, which looks rather like a requirements document, is executable:
Validation Rules
Validation rules 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. Validation rules 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 validation rules, see Validation Rule Type.
Derivation Rules
 
CA Live API Creator
 applies derivation rules to individual column attributes. Derivation and event rules are more valuable than validation rules, per dependency/re-use automation. Derivation rules include multi-table derivation rules. For example, the following derivation 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 rules. Much like a spreadsheet cell, these derivation rules become part of a chain of events. 
CA Live API Creator
 calls event rules during the processing of a data transaction. It applies derivation rules to a specific attribute on a table.
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 information, customer 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 
SubTotal
 invoice uses a sum on the invoice (order header) itself and 
CA Live API Creator
 uses the 
sum(lineitem.TotalPrice)
 derivation.
 
The invoice discount
 
is the 
sum(lineitem.discount)
 .
 
The Tax/VAT is another formula: 
row.subtotal * row.taxrate
 . Finally, 
CA Live API Creator
 calculates the grand total using the following formula:
((row.subtotal -row.discount) - (row.tax + row.shipping))
State change means that inserting a new line item, deleting a line item, changing a quantity, or even an item number triggers 
CA Live API Creator
 to recalculate these rules.
Derivation rules are conceptually similar to spreadsheet cell formulas. They:
  • Are multi-table, as in the previous example.
  • Can chain, both to validation rules and other derivation rules:
    •  
      Purchaseorder.amount_total = sum(lineitem.amount)
       
    •  
      Lineitem.amount = qty_ordered * product_price
       
    •  
      Lineitem.product_price = copy(product.price
       
  •  
    CA Live API Creator
     handles chaining, ordering, and dependencies automatically.
  • Can include if/else logic, state transition logic, and reference related data.
  •  
    CA Live API Creator
     optimizes derivation rules 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 Rules
 
CA Live API Creator
 creates JavaScript objects, or rows, for each base table. The rows provide accessors for attributes and related data, and automated persistence. 
CA Live API Creator
 supplies old/new versions of rows to your event rules, with automatic resource/object mapping. Resource/object mapping means your rules apply to update requests for default resources and the resource that you define explicitly in API Creator.
Event rules, early event rules, resource GET events, request event handlers, and response event handlers are JavaScript entry points to perform user-defined actions. For example, auditing, copying (an order clone), sending mail, and messages. These entry points are complementary to other forms of business logic such as process (workflow) logic, application integration, and decision logic.
You typically use both event rules and event handlers to meet requirements. 
CA Live API Creator
 integrates the event rules and event handlers by virtue of a common underlying JavaScript object model that it creates 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
The following user story/behavior provides significant value. For example, the Change Order Item - Reassign Product user story. Related user stories typically do not require new logic. This user story defines reactive logic on the tables and columns, and not on a specific service. Automatic invocation ensures that 
CA Live API Creator
 reuses the logic over all relevant user stories/behaviors. In the case of the 
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
The rules dictate the following user stories, which are 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. The following image shows the logic reuse over behaviors:
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. 
CA Live API Creator
 watch/react-processing is an optimized version of forward chaining. It:
  1. Watches.
     
    CA 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, 
    CA Live API Creator
     optimally recomputes the derivation. This can become complex, because derivations can chain.
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.
 
CA Live API Creator
 stores derived attributes in the database. Performance optimizations presume the stored data is correct.
When you introduce new columns (for example, the 
customer balance
), bring the database into compliance with the rule.
For more information about how to do bring the database in compliance with the rule, using SQL, see Database Connectivity.
For more information about performance, see Performance.