FactoryFour Learn Center Index

Last updated September 15, 2019


Add Workflow Based on Task Form Entry

Add workflow to an order when a particular task form field is entered


Description:

In certain process flows, the full workflow cannot be known at order creation. Oftentimes next steps are decided due to inputs occuring mid-process. This results in a decision fork, where different inputs can result in different downstream processes. By pre-building workflows as segments and leveraging task forms to add a new segment based on an entry, users can add to their workflow as their workflow progresses.

How to Use:

  1. Create a Custom Task Form Rule where the Scope specifies relevant the task form(s)
  2. For the rule action, use the below snippet
  3. Make sure you have loaded axios

  4. In the below snippet, enter the key of the ‘metric code’ associated to the form field which will dictate the workflow addition. Additionally, modify the ‘VALUE_TO_WORKFLOW_MAP’ array to specify which workflow will be generated from which form entry.
  5. Make sure you save the code in the editor, and turn the rule on

Snippet:


const axios = require('axios');

/*
 * Specify metric code here
 */
const METRIC_CODE = 'metric_code';

/*
 * Modify the below mapping for {Form Field Value}: {workflow_code}
 */
const VALUE_TO_WORKFLOW_MAP = {
    'Value_1': 'workflow_code_1',
    'Value_2': 'workflow_code_2',
};

/*
 * Retrieve a valid FactoryFour token from the headers in the context
 */
const getToken = (ctx) => {
    const token = ctx.headers['x-factoryfour-token'];
    if (!token) {
        throw new Error('Unable to find token in context');
    }
    return token;
};

/*
 * Retrieve the designated error code from the metrics calculated from the submitted form.
 */ 
const getErrorCode = (ctx) => {
    const errorMetric = ctx.body.formData.metrics
/*
* Modify the below key of the metric code associated to the form field
*/
        .filter((m) => (m.code === METRIC_CODE))[0];
    if (!errorMetric) {
        throw new Error('Could not find a metric with the matching code');
    }
    return errorMetric.value;
};

/*
 * Fetch the order this form was submitted on from the context
 */
const getOrderId = (ctx) => {
    const orderId = ctx.body.orders[0].id;
    if (!orderId) {
        throw new Error('Could not find an order for this form');
    }
    return orderId;
};

/*
 * Make calls to the FactoryFour API using the token passed to this rule and the workflowCode specified
 */
const addAndInitWorkflow = (orderId, workflowCode, token) => {
    // Format the headers for the request
    const headers = {
        Authorization: `Bearer ${token}`,
    };

    // Create a new workflow object
    return axios({
        method: 'POST',
        url: 'https://api.factoryfour.com/workflows/',
        headers,
        data: {
            format: 'order',
            parent: `f4::order::${orderId}`,
            code: workflowCode
        }
    })
        .then((res) => {
            const workflowId = res.data.data.workflow.id;

            // Initialize the newly created workflow to create tasks
            const optionsInit = {
                method: 'POST',
                url: `https://api.factoryfour.com/workflows/${workflowId}/initiate`,
                headers,
                json: true,
            };
            return axios(optionsInit);
        });
};

module.exports = (context, cb) => {
    const token = getToken(context);
    const errorCode = getErrorCode(context);
    const orderId = getOrderId(context);

    // Search the map for a workflow to add
    const workflowToAdd = VALUE_TO_WORKFLOW_MAP[errorCode];
    if (!workflowToAdd) {
        // if no workflow was found, exit with no further action
        return cb(null, {});
    }

    // add a workflow to the order, then initialize it
    return addAndInitWorkflow(orderId, workflowToAdd, token)
        .then(() => {
            return cb(null, {});
        })
        .catch((err) => {
            console.log(err);
            return cb('Could not add an initialize workflow');
        });
};

Search the FactoryFour Learn Center


FactoryFour Learn Center