Risk Assessment

Goal: This example illustrates how to leverage Eventing Service in the Banking and Financial domain. When a credit card transaction exceeds the user’s available credit limit, to indicate a high-risk transaction, an alert can be generated.

Implementation: Create a JavaScript Function that contains an OnUpdate handler. The handler listens to data-changes within a specified, transactions source bucket. When a document within the source bucket is created or mutated, the handler executes a user-defined routine. In this example, if the created or mutated document contains a high-risk transaction, a new document gets created in a specified, flagged_transactions bucket.

Preparations:

For this example, four buckets 'flagged_transactions', 'users', 'transactions', and 'metadata', are required (note the metadata bucket for Eventing can be shared with other Eventing functions). Make all three buckets with minimum size of 100MB.

For steps to create buckets, see Create a Bucket.

Procedure:

  1. From the Couchbase Web Console > Eventing page, click ADD FUNCTION, to add a new Function. The ADD FUNCTION dialog appears.

  2. In the ADD FUNCTION dialog, for individual Function elements provide the below information:

    • For the Source Bucket drop-down, select transactions.

    • For the Metadata Bucket drop-down, select metadata.

    • Enter high_risks_transactions as the name of the Function you are creating in the Function Name text-box.

    • [Optional Step] Enter text Functions that computes risky transaction and flags them, in the Description text-box.

    • Expand the Settings option

      • Change only the Language compatibility which should be 6.0.0.

      • Unexpand the setting control

    • For the Bindings option, add two bindings.

      • For the first binding, select "bucket alias", specify users as the "alias name" of the bucket, and select users as the associated bucket, and select "read only".

      • For the second binding, select "bucket alias", specify high_risk as the "alias name" of the bucket, and select flagged_transactions as the associated bucket, and select "read only".

    • After configuring your settings your screen should look like:

      highrisk 01 settings
  3. After providing all the required information in the ADD FUNCTION dialog, click Next: Add Code. The high_risks_transactions dialog appears.

    • The high_risks_transactions dialog initially contains a placeholder code block. You will substitute your actual high_risks_transactions code in this block.

      highrisk 02 editor with default
    • Copy the following Function, and paste it in the placeholder code block of high_risks_transactions dialog.

      function OnUpdate(doc, meta) {
        try {
          //log('txn id:', meta.id, '; user_id:', doc.user_id , ', doc.amount:', doc.amount);
          var this_user = getUser(doc.user_id);
          if (this_user) {
            if (this_user['creditlimit'] < doc.amount) {
              log('Txn[' + String(meta.id) + ']*****High Risk Transaction as Txn Amount:' + String(doc.amount) + ' exceeds Credit Limit:', this_user['creditlimit']);
              doc["comments"] = "High Risk Transaction as Txn Amount exceeds Credit Limit " + String(this_user['creditlimit']);
              doc["reason_code"] = "X-CREDIT";
              high_risk[meta.id] = doc;
              return;
            } else {
              if (doc.txn_currency != this_user['currency']) {
                log('Txn[' + String(meta.id) + ']*****High Risk Transaction - Currency Mismatch:' + this_user['currency']);
                doc["comments"] = "High Risk Transaction - Currency Mismatch:" + this_user['currency'];
                doc["reason_code"] = "XE-MISMATCH";
                high_risk[meta.id] = doc;
                return;
              }
            }
            //log('Acceptable Transaction:',doc.amount, ' for Credit Limit:', this_user['creditlimit']);
          } else {
            log('Txn[' + String(meta.id) + "] User Does not Exist:" + String(doc.user_id));
          }
        } catch (e) {
          log('Error OnUpdate :', String(meta.id), e);
        }
      }
      
      function OnDelete(meta) {
        log('Document OnDelete:', meta.id);
      }
      
      function getUser(userId) {
        try {
          if (userId != null) {
            return user[userId];
          }
        } catch (e) {
          log('Error getUser :', userId, '; Exception:', e);
        }
        return null;
      }

      After pasting, the screen appears as displayed below:

      highrisk 03 editor with code
    • Click Save.

    • To return to the Eventing screen, click the '< back to Eventing' link (below the editor) or click Eventing tab.

  4. The OnUpdate handler is triggered for every transaction. The handler checks if the transaction amount is less than the user’s available credit limit. When this condition is breached, then this transaction is flagged as a high-risk transaction. The Function high_risks_transactions then moves this transaction to a different bucket, flagged_transactions bucket. When the transaction is moved to a new bucket, the handler enriches the document with predefined comments and also provides a reason code*.* In the last part, the handler performs a currency validation step. If the transaction currency is other than the preconfigured home currency of the user, then the handler flags the transactions and moves it to a different bucket.

  5. From the Eventing screen, click Deploy.

    • In the Confirm Deploy Function dialog, select Everything from the Feed boundary option.

    • Click Deploy Function.

  6. The Eventing function is deployed and starts running within a few seconds. From this point, the defined Function is executed on all existing documents and on subsequent mutations.

  7. To check the results of the deployed Function, after a sufficient time elapse, access the Couchbase Web Console > Buckets page

  8. Click flagged_transactions bucket. All documents available in this bucket are transactions that are flagged as high-risk transactions.

    highrisk 04 buckets

    This indicates that transactions which were flagged as high risk gets moved to the flagged_transactions bucket.

  9. From the Couchbase Web Console > Query page, execute the below N1QL query:

    SELECT reason_code, COUNT(1), num_txns, SUM(amount) amount
    FROM `flagged_transactions`
    GROUP BY reason_code;
    highrisk 05 n1ql query