User Event Script dynamically adds action buttons at the body level

This User Event Script dynamically adds action buttons at the body level of the record form based on specific conditions. 

/**

 * @NApiVersion 2.1

 * @NScriptType UserEventScript

 */

/******************************************************************************************************************************

 * STERI – 991 Create the button for Send to SIDCO, Repack Complete, Verify Repack, Post Repack Complete, Post Verify Repack

 * ****************************************************************************************************************************

 *

 * Date: 29-01-2025

 *

 * Author:Jobin & Jismi IT Services LLP.

 *

 * Description: This script displays button named Send to SIDCO, Repack Complete, Verify Repack, Post Repack Complet and Post Verify Repack

 * based on conditions.

 *

 * Created By: JJ0281, Jobin & Jismi IT Services LLP.

 * 

 *Revision History:

 * Revision 1.0 ${29-01-2025} : created initial deployment by JJ0281.

 *

 * *************************************************************

 */

define([‘N/ui/serverWidget’, ‘N/url’, ‘N/search’, ‘N/record’, ‘N/runtime’], (serverWidget, url, search, record, runtime) => {

  let SUITELETSCRIPID = ‘customscript_jj_sl_updaterepack_steri991’;

  let SUITELETDEPLOYMENTID = ‘customdeploy_jj_sl_updaterepack_steri991’

  /**

   * Checks the number of protocols associated with a specific job record

   * that match the defined status criteria.

   *

   * @param {string} recId – The internal ID of the job record.

   * @returns {number} – The count of matching protocols.

   */

  function checkRepackProtocol(recId) {

    try {

      let customrecord_vr_job_protocolSearchObj = search.create({

        type: “customrecord_vr_job_protocol”,

        filters:

          [

            [“custrecord_vr_job_proto_status”, “anyof”, “41”, “12”, “47”, “42”],

            “AND”,

            [“custrecord_vr_job_proto_job”, “anyof”, recId]

          ],

        columns:

          [

            search.createColumn({ name: “custrecord_vr_job_proto_stage”, label: “Stage” })

          ]

      });

      let searchResultCount = customrecord_vr_job_protocolSearchObj.runPaged().count;

      return searchResultCount;

    } catch (err) {

      log.error(“err @ checkRepackProtocol”, err);

      return null;

    }

  }

  /**

 * This function adds a custom “Send SIDCO” button to the form, which sends a request to SIDCO using a Suitelet URL when clicked.

 * The function handles the click event, displays a confirmation prompt, and then sends a POST request with the record ID to a Suitelet for

 * further processing. The button is only displayed if a specific field is present in the form.

 *

 * @param {number} recId – The record ID that will be sent to the Suitelet for processing.

 * @param {Object} form – The form object where the button will be added. *

 * @returns {void} *

 * @throws {Error} – If an error occurs during the button creation or fetch request.

 */

  function buttonforSendSidco(recId, form) {

    try {

      const inlineHtmlDialog = form.addField({

        id: ‘custpage_dialog_sidco’,

        type: serverWidget.FieldType.INLINEHTML,

        label: ‘SIDCO Dialog HTML’

      });

      inlineHtmlDialog.updateDisplayType({

        displayType: serverWidget.FieldDisplayType.NORMAL

      });

      const suiteletUrlDialog = url.resolveScript({

        scriptId: SUITELETSCRIPID,

        deploymentId: SUITELETDEPLOYMENTID

      });

      inlineHtmlDialog.defaultValue = `

      <style>

        #sidco_dialog_overlay {

          display: none;

          position: fixed;

          top: 0;

          left: 0;

          width: 100%;

          height: 100%;

          background: rgba(0, 0, 0, 0.5);

          z-index: 999;

        }

        #sidco_custom_dialog {

          display: none;

          position: fixed;

          top: 50%;

          left: 50%;

          transform: translate(-50%, -50%);

          background: white;

          border: 1px solid #ccc;

          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

          padding: 20px;

          z-index: 1000;

          width: 300px;

          text-align: center;

        }

        .dialog-button {

          padding: 5px 15px;

          margin: 5px;

          background-color: #007bff;

          color: white;

          border: none;

          border-radius: 4px;

          cursor: pointer;

          font-size: 12px;

        }

        .dialog-button:hover {

          background-color: #0056b3;

        }

      </style>

      <div id=”sidco_dialog_overlay”></div>

      <div id=”sidco_custom_dialog”>

        <p>Are you sure you want to send a response to SIDCO?</p>

        <button id=”sidco_dialog_submit” class=”dialog-button”>Send</button>

        <button id=”sidco_dialog_cancel” class=”dialog-button”>Cancel</button>

      </div>

      <script>

        document.addEventListener(“DOMContentLoaded”, function() {

          const fieldLabel = document.getElementById(“custrecord_jj__sent_to_sidco_fs_lbl”);

          if (fieldLabel) {

            const button = document.createElement(“button”);

            button.id = “custpage_sidco_button”;

            button.textContent = “Send SIDCO”;

            button.className = “dialog-button”;

            fieldLabel.insertAdjacentElement(“afterend”, button);

    

            const overlay = document.getElementById(“sidco_dialog_overlay”);

            const dialog = document.getElementById(“sidco_custom_dialog”);

            const submitButton = document.getElementById(“sidco_dialog_submit”);

            const cancelButton = document.getElementById(“sidco_dialog_cancel”);

    

            button.addEventListener(“click”, function(event) {

              event.preventDefault();

              overlay.style.display = “block”;

              dialog.style.display = “block”;

            });

    

            cancelButton.addEventListener(“click”, function(event) {

              event.preventDefault();

              overlay.style.display = “none”;

              dialog.style.display = “none”;

            });

    

            submitButton.addEventListener(“click”, function(event) {

              event.preventDefault();

              fetch(“${suiteletUrlDialog}“, {

                method: “POST”,

                headers: {

                  “Content-Type”: “application/json”

                },

                body: JSON.stringify({

                  recordId: ${recId},

                  resposebutton: ‘SENTTOSIDCO’

                })

              })

              .then(response => response.json())

              .then(data => {

                if (data.success) {

                  alert(“You have sent the request to SIDCO successfully!”);

                  location.reload();

                } else {

                  alert(“Error: ” + data.message);

                }

              })

              .catch(error => {

                alert(“An error occurred: ” + error.message);

              });

            });

          }

        });

      </script>

      `;

    } catch (e) {

      log.debug(‘Error @ buttonforSendSidco’, e.message);

    }

  }

  /**

   * This function adds a custom “Repack Completed” button to the form, which triggers a dialog box

   * for the user to enter a quantity for repack. Once the user submits the quantity, a request is

   * sent to a Suitelet with the record ID and the entered quantity. The dialog box can be canceled

   * by the user. The button is displayed only if a specific field is present on the form.

   *

   * @param {number} recId – The record ID that will be sent to the Suitelet for processing.

   * @param {Object} form – The form object where the button will be added.  *

   * @returns {void}  

   * @throws {Error} – If an error occurs during button creation, dialog handling, or the fetch request.

   */

  function buttonforRepackCompleted(recId, form) {

    try {

      const inlineHtmlDialog = form.addField({

        id: ‘custpage_dialog_html’,

        type: serverWidget.FieldType.INLINEHTML,

        label: ‘Dialog Box HTML’

      });

      inlineHtmlDialog.updateDisplayType({

        displayType: serverWidget.FieldDisplayType.NORMAL

      });

      const suiteletUrlDialog = url.resolveScript({

        scriptId: SUITELETSCRIPID,

        deploymentId: SUITELETDEPLOYMENTID

      });

      inlineHtmlDialog.defaultValue = `

      <style>

        #dialog_overlay {

          display: none;

          position: fixed;

          top: 0;

          left: 0;

          width: 100%;

          height: 100%;

          background: rgba(0, 0, 0, 0.5);

          z-index: 999;

        }

        #custom_dialog {

          display: none;

          position: fixed;

          top: 50%;

          left: 50%;

          transform: translate(-50%, -50%);

          background: white;

          border: 1px solid #ccc;

          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

          padding: 20px;

          z-index: 1000;

          width: 300px;

          text-align: center;

        }

        #custom_dialog input {

          width: 100%;

          padding: 8px;

          margin-bottom: 10px;

        }

        .dialog-button {

          padding: 5px 15px;

          margin: 5px;

          background-color: #007bff;

          color: white;

          border: none;

          border-radius: 4px;

          cursor: pointer;

          font-size: 12px;

        }

        .dialog-button:hover {

          background-color: #0056b3;

        }

      </style>

      <div id=”dialog_overlay”></div>

      <div id=”custom_dialog”>

        <label for=”custom_quantity”>Enter Quantity in this Repack:</label>

        <input type=”number” id=”custom_quantity” min=”1? />

        <button id=”dialog_submit” class=”dialog-button”>Submit</button>

        <button id=”dialog_cancel” class=”dialog-button”>Cancel</button>

      </div>

      <script>

        document.addEventListener(“DOMContentLoaded”, function() {

          const fieldLabel = document.getElementById(“custrecord_jj_job_repack_complete_fs_lbl”);

          if (fieldLabel) {

            const button = document.createElement(“button”);

            button.id = “custpage_dialog_button”;

            button.textContent = “Repack Completed”;

            button.className = “dialog-button”;

            fieldLabel.insertAdjacentElement(“afterend”, button);

  

            const overlay = document.getElementById(“dialog_overlay”);

            const dialog = document.getElementById(“custom_dialog”);

            const inputField = document.getElementById(“custom_quantity”);

            const submitButton = document.getElementById(“dialog_submit”);

            const cancelButton = document.getElementById(“dialog_cancel”);

  

            button.addEventListener(“click”, function(event) {

              event.preventDefault();

              overlay.style.display = “block”;

              dialog.style.display = “block”;

            });

  

            cancelButton.addEventListener(“click”, function(event) {

              event.preventDefault();

              overlay.style.display = “none”;

              dialog.style.display = “none”;

            });

  

            submitButton.addEventListener(“click”, function(event) {

              event.preventDefault();

              const quantity = inputField.value.trim();

              if (!quantity || quantity <= 0) {

                alert(“Please enter a valid quantity.”);

                return;

              }

              console.log(‘quantity’, quantity);

              fetch(“${suiteletUrlDialog}“, {

                method: “POST”,

                headers: {

                  “Content-Type”: “application/json”

                },

                body: JSON.stringify({

                  recordId: ${recId},

                  quantity: quantity,

                  resposebutton: ‘REPACKCOMPLETED’

                })

              })

              .then(response => response.json())

              .then(data => {

                if (data.success) {

                  alert(“Repacked quantity updated successfully!”);

                  location.reload();

                } else {

                  alert(“Error: ” + data.message);

                }

              })

              .catch(error => {

                alert(“An error occurred: ” + error.message);

              });

            });

          }

        });

      </script>

    `;

    } catch (e) {

      log.debug(‘Error @ buttonforRepackCompleted’, e.message);

    }

  }

  /**

 * This function adds a custom “Verified Repack” button to the form, which, when clicked,

 * prompts the user with a confirmation dialog. If the user confirms, a request is sent to

 * a Suitelet to verify the repack for the specified record. After successful verification,

 * the page is reloaded. In case of errors, an alert with the error message is shown.

 *

 * @param {number} recId – The record ID that will be sent to the Suitelet for verification.

 * @param {Object} form – The form object where the “Verified Repack” button will be added.

 *

 * @returns {void}

 *

 * @throws {Error} – If an error occurs during button creation, event binding, or the fetch request.

 */

  function buttonforVerifyRepack(recId, form) {

    try {

      const inlineHtmlDialog = form.addField({

        id: ‘custpage_verified_repack_html’,

        type: serverWidget.FieldType.INLINEHTML,

        label: ‘Verified Repack HTML’

      });

      inlineHtmlDialog.updateDisplayType({

        displayType: serverWidget.FieldDisplayType.NORMAL

      });

      const suiteletUrl = url.resolveScript({

        scriptId: SUITELETSCRIPID,

        deploymentId: SUITELETDEPLOYMENTID

      });

      inlineHtmlDialog.defaultValue = `

        <style>

          #dialog_overlay {

            display: none;

            position: fixed;

            top: 0;

            left: 0;

            width: 100%;

            height: 100%;

            background: rgba(0, 0, 0, 0.5);

            z-index: 999;

          }

          #custom_dialog {

            display: none;

            position: fixed;

            top: 50%;

            left: 50%;

            transform: translate(-50%, -50%);

            background: white;

            border: 1px solid #ccc;

            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

            padding: 20px;

            z-index: 1000;

            width: 300px;

            text-align: center;

          }

          .dialog-button {

            padding: 5px 15px;

            margin: 5px;

            background-color: #007bff;

            color: white;

            border: none;

            border-radius: 4px;

            cursor: pointer;

            font-size: 12px;

          }

          .dialog-button:hover {

            background-color: #0056b3;

          }

        </style>

        <div id=”dialog_overlay”></div>

        <div id=”custom_dialog”>

          <p>Are you sure you want to verify the repack?</p>

          <button id=”dialog_confirm” class=”dialog-button”>Confirm</button>

          <button id=”dialog_cancel” class=”dialog-button”>Cancel</button>

        </div>

        <script>

          document.addEventListener(“DOMContentLoaded”, function() {

            const fieldLabel = document.getElementById(“custrecord_jj_job_verify_repack_fs_lbl”);

            if (fieldLabel) {

              const button = document.createElement(“button”);

              button.id = “custpage_verified_repack_button”;

              button.textContent = “Verified Repack”;

              button.className = “dialog-button”;

              fieldLabel.insertAdjacentElement(“afterend”, button);

  

              const overlay = document.getElementById(“dialog_overlay”);

              const dialog = document.getElementById(“custom_dialog”);

              const confirmButton = document.getElementById(“dialog_confirm”);

              const cancelButton = document.getElementById(“dialog_cancel”);

  

              button.addEventListener(“click”, function(event) {

                event.preventDefault();

                overlay.style.display = “block”;

                dialog.style.display = “block”;

              });

  

              cancelButton.addEventListener(“click”, function(event) {

                event.preventDefault();

                overlay.style.display = “none”;

                dialog.style.display = “none”;

              });

  

              confirmButton.addEventListener(“click”, function(event) {

                event.preventDefault();

                fetch(“${suiteletUrl}“, {

                  method: “POST”,

                  headers: {

                    “Content-Type”: “application/json”

                  },

                  body: JSON.stringify({

                    recordId: ${recId},

                    resposebutton: “VERIFYREPACK”

                  })

                })

                .then(response => response.json())

                .then(data => {

                  if (data.success) {

                    alert(“Repack verified successfully!”);

                    location.reload();

                  } else {

                    alert(“Error: ” + data.message);

                  }

                })

                .catch(error => {

                  alert(“An error occurred: ” + error.message);

                });

              });

            }

          });

        </script>

      `;

    } catch (e) {

      log.debug(“Error @ buttonforVerifyRepack”, e.message);

    }

  }

  /**

 * This function adds a custom “Post Repack Completed” button to the form, which opens a dialog

 * box when clicked. The dialog prompts the user to enter the quantity of repacked items. Upon

 * submitting, a request is sent to a Suitelet to update the record with the entered quantity.

 * If the action is successful, the page is reloaded, and if there is an error, an alert with

 * the error message is shown.

 *

 * @param {number} recId – The record ID to be sent to the Suitelet for post repack completion.

 * @param {Object} form – The form object where the “Post Repack Completed” button will be added.

 *

 * @returns {void}

 *

 * @throws {Error} – If an error occurs during button creation, dialog handling, or the fetch request.

 */

  function buttonforPostRepackCompleted(recId, form) {

    try {

      const postRepackHtmlField = form.addField({

        id: ‘custpage_post_repack_html’,

        type: serverWidget.FieldType.INLINEHTML,

        label: ‘Post Repack Completed Button and Dialog’

      });

      postRepackHtmlField.updateDisplayType({

        displayType: serverWidget.FieldDisplayType.NORMAL

      });

      let postRepackSuiteletUrl = url.resolveScript({

        scriptId: SUITELETSCRIPID,

        deploymentId: SUITELETDEPLOYMENTID

      });

      postRepackHtmlField.defaultValue = `

    <style>

      /* Style for the dialog box */

      #post_repack_dialog {

        display: none;

        position: fixed;

        top: 50%;

        left: 50%;

        transform: translate(-50%, -50%);

        background: white;

        border: 1px solid #ccc;

        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

        padding: 20px;

        z-index: 1000;

        width: 300px;

      }

      #post_repack_overlay {

        display: none;

        position: fixed;

        top: 0;

        left: 0;

        width: 100%;

        height: 100%;

        background: rgba(0, 0, 0, 0.5);

        z-index: 999;

      }

      #post_repack_dialog input {

        width: 100%;

        padding: 8px;

        margin-bottom: 10px;

      }

      #post_repack_dialog button {

        margin-left: 10px;

        padding: 5px 15px;

        background-color: #007bff;

        color: white;

        border: none;

        border-radius: 4px;

        cursor: pointer;

        font-size: 12px;

      }

      #post_repack_button {

        margin-left: 10px;

        padding: 5px 15px;

        background-color: #007bff;

        color: white;

        border: none;

        border-radius: 4px;

        cursor: pointer;

        font-size: 12px;

      }

      #post_repack_button:hover {

        background-color: #0056b3;

      }

    </style>

    <div id=”post_repack_overlay”></div>

    <div id=”post_repack_dialog”>

      <label for=”post_repack_input”>Enter Post Repack Completed Quantity:</label>

      <input type=”text” id=”post_repack_input” />

      <button id=”post_repack_submit”>Submit</button>

      <button id=”post_repack_cancel”>Cancel</button>

    </div>

    <script>

    console.log(“button triggered”)

    document.addEventListener(“DOMContentLoaded”, function () {

  const postRepackFieldLabel = document.getElementById(“custrecord_jj_job_post_repack_complete_fs_lbl”);

  if (postRepackFieldLabel) {

    const button = document.createElement(“button”);

    button.id = “post_repack_button”;

    button.textContent = “Post Repack Completed”;

    button.style.cssText = “margin-left: 10px; padding: 5px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 12px;”;

    postRepackFieldLabel.insertAdjacentElement(“afterend”, button);

    const overlay = document.getElementById(“post_repack_overlay”);

    const dialog = document.getElementById(“post_repack_dialog”);

    const inputField = document.getElementById(“post_repack_input”);

    const submitButton = document.getElementById(“post_repack_submit”);

    const cancelButton = document.getElementById(“post_repack_cancel”);

    button.addEventListener(“click”, function () {

     event.preventDefault();

      overlay.style.display = “block”;

      dialog.style.display = “block”;

    });

    cancelButton.addEventListener(“click”, function (event) {

      event.preventDefault(); // Prevent form submission

      overlay.style.display = “none”;

      dialog.style.display = “none”;

    });

    submitButton.addEventListener(“click”, function () {

    event.preventDefault();

      const quantity = inputField.value.trim();

      if (!quantity) {

        alert(“Enter quantity post repacked.”);

        return;

      }

      fetch(“${postRepackSuiteletUrl}“, {

        method: “POST”,

        headers: {

          “Content-Type”: “application/json”

        },

        body: JSON.stringify({

          recordId: ${recId},

          quantity: quantity,

           resposebutton: ‘POSTREPACKCOMPLETED’

        })

      })

      .then(response => response.json())

      .then(data => {

        if (data.success) {

          alert(“Post Repack Completed successfully!”);

          location.reload();

        } else {

          alert(“Error: ” + data.message);

        }

      })

      .catch(error => {

        alert(“An error occurred: ” + error.message);

      });

    });

  }

});

    </script>

  `;

    } catch (e) {

      log.debug(‘error @ buttonforPostRepackCompleted’, e.message);

    }

  }

  /**

   * Creates a button in the form to post the verified repack action.

   *

   * @param {number} recId – The record ID of the current record for which the post repack action is performed.

   * @param {Object} form – The form object to which the button will be added.

   */

  function buttonforPostVerifiedRepack(recId, form) {

    try {

      const inlineHtmlDialog = form.addField({

        id: ‘custpage_postverified_button_html’,

        type: serverWidget.FieldType.INLINEHTML,

        label: ‘Post Verified Repack Button’

      });

      inlineHtmlDialog.updateDisplayType({

        displayType: serverWidget.FieldDisplayType.NORMAL

      });

      const suiteletUrl = url.resolveScript({

        scriptId: SUITELETSCRIPID,

        deploymentId: SUITELETDEPLOYMENTID

      });

      inlineHtmlDialog.defaultValue = `

        <style>

          #dialog_overlay {

            display: none;

            position: fixed;

            top: 0;

            left: 0;

            width: 100%;

            height: 100%;

            background: rgba(0, 0, 0, 0.5);

            z-index: 999;

          }

          #custom_dialog {

            display: none;

            position: fixed;

            top: 50%;

            left: 50%;

            transform: translate(-50%, -50%);

            background: white;

            border: 1px solid #ccc;

            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);

            padding: 20px;

            z-index: 1000;

            width: 300px;

            text-align: center;

          }

          .dialog-button {

            padding: 5px 15px;

            margin: 5px;

            background-color: #007bff;

            color: white;

            border: none;

            border-radius: 4px;

            cursor: pointer;

            font-size: 12px;

          }

          .dialog-button:hover {

            background-color: #0056b3;

          }

        </style>

        <div id=”dialog_overlay”></div>

        <div id=”custom_dialog”>

          <p>Are you sure you want to post verify the repack?</p>

          <button id=”dialog_confirm” class=”dialog-button”>Confirm</button>

          <button id=”dialog_cancel” class=”dialog-button”>Cancel</button>

        </div>

        <script>

          document.addEventListener(“DOMContentLoaded”, function() {

            const fieldLabel = document.getElementById(“custrecord_jj_job_post_verify_repack_fs_lbl”);

            if (fieldLabel) {

              const button = document.createElement(“button”);

              button.id = “custpage_postverified_button”;

              button.textContent = “Post Verified Repack”;

              button.className = “dialog-button”;

              fieldLabel.insertAdjacentElement(“afterend”, button);

  

              const overlay = document.getElementById(“dialog_overlay”);

              const dialog = document.getElementById(“custom_dialog”);

              const confirmButton = document.getElementById(“dialog_confirm”);

              const cancelButton = document.getElementById(“dialog_cancel”);

  

              button.addEventListener(“click”, function(event) {

                event.preventDefault();

                overlay.style.display = “block”;

                dialog.style.display = “block”;

              });

  

              cancelButton.addEventListener(“click”, function(event) {

                event.preventDefault();

                overlay.style.display = “none”;

                dialog.style.display = “none”;

              });

  

              confirmButton.addEventListener(“click”, function(event) {

                event.preventDefault();

                fetch(“${suiteletUrl}“, {

                  method: “POST”,

                  headers: {

                    “Content-Type”: “application/json”

                  },

                  body: JSON.stringify({

                    recordId: ${recId},

                    resposebutton: “POSTVERIFYREPACK”

                  })

                })

                .then(response => response.json())

                .then(data => {

                  if (data.success) {

                    alert(“Post Verified Repack completed successfully!”);

                    location.reload();

                  } else {

                    alert(“Error: ” + data.message);

                  }

                })

                .catch(error => {

                  alert(“An error occurred: ” + error.message);

                });

              });

            }

          });

        </script>

      `;

    } catch (e) {

      log.debug(“Error @ buttonforPostVerifiedRepack”, e.message);

    }

  }

  function pnvl(value, number) {

    if (number) {

      if (isNaN(parseFloat(value))) return 0;

      return parseFloat(value);

    }

    if (value === null || value === undefined || value === ‘null’) return ”;

    return ” + value;

  }

  /**

   * Fetches sub-job data based on the provided filter.

   * @param {Array} filter – The filter criteria for sub-job search.

   * @returns {Object} An object containing sub-job record IDs and their corresponding data.

  */

  function fetchJobData(intakeId) {

    try {

      let customrecord_vr_jobSearchObj = search.create({

        type: “customrecord_vr_job”,

        filters:

          [

            [“custrecord_vr_job_inboundtran”, “anyof”, intakeId],

            “AND”,

            [“isinactive”, “is”, “F”],

            “AND”,

            [“custrecord_sub_jobs”, “anyof”, “@NONE@”]

          ],

        columns:

          [

            search.createColumn({ name: “custrecord_vr_jobstatus_i”, label: “Status” }),

            search.createColumn({ name: “custrecord_vr_jobstage”, label: “Stage” })

          ]

      }), jobStatusData = {};

      customrecord_vr_jobSearchObj.run().each(function (result) {

        jobStatusData = {

          status: {

            text: result.getText({ name: “custrecord_vr_jobstatus_i”, label: “Status” }),

            value: result.getValue({ name: “custrecord_vr_jobstatus_i”, label: “Status” })

          },

          stage: {

            text: result.getText({ name: “custrecord_vr_jobstage”, label: “Stage” }),

            value: result.getValue({ name: “custrecord_vr_jobstage”, label: “Stage” })

          },

          id: result.id

        }

      });

      return jobStatusData;

    } catch (err) {

      log.error(“err @ job search”, err)

    }

  }

  function fetchNextProtocol(jobId, statusId) {

    try {

      let customrecord_vr_job_protocolSearchObj = search.create({

        type: “customrecord_vr_job_protocol”,

        filters:

          [

            [“custrecord_vr_job_proto_job”, “anyof”, jobId],

            “AND”,

            [“isinactive”, “is”, “F”]

          ],

        columns:

          [

            search.createColumn({ name: “custrecord_vr_job_proto_stage”, label: “Stage” }),

            search.createColumn({ name: “custrecord_vr_job_proto_status”, label: “Status” }),

            search.createColumn({ name: “custrecord_vr_job_proto_num”, label: “Step Number” })

          ]

      }), finalJobProtocolList = {};

      customrecord_vr_job_protocolSearchObj.run().each(function (result) {

        finalJobProtocolList[result.getValue({ name: “custrecord_vr_job_proto_num”, label: “Step Number” })] = result.getValue({ name: “custrecord_vr_job_proto_status”, label: “Status” });

        return true;

      });

      log.debug(“finalJobProtocolList”, finalJobProtocolList)

      let currentStepNumberObj;

      for (let key in finalJobProtocolList) {

        finalJobProtocolList[key] == statusId ? currentStepNumberObj = key : “”;

      }

      log.debug(“currentStepNumberObj”, currentStepNumberObj)

      return currentStepNumberObj ? finalJobProtocolList[Number(currentStepNumberObj) + 1] : “”;

    } catch (err) {

      log.error(“error @ fetch protocol”, err)

    }

  }

  function jobChildStage(jobId, stage) {

    try {

      let results = search.create({

        type: ‘customrecord_vr_jobstage’,

        filters: [

          [‘custrecord_vr_jobstage_job’, ‘anyof’, jobId], ‘and’,

          [‘isinactive’, ‘is’, ‘F’], ‘and’,

          [‘custrecord_vr_jobstage_stage’, ‘anyof’, stage]

        ]

      }), jobChildRecId;

      results.run().each(function (result) {

        jobChildRecId = result.id

      });

      log.debug(“jobChildRecId”, jobChildRecId)

      return jobChildRecId;

    } catch (err) {

      log.error(“err @ job child stage fetch function”, err);

    }

  }

  /**

   * Defines the function definition that is executed before record is loaded.

   * @param {Object} context

   * @param {Record} context.newRecord – New record

   * @param {string} context.type – Trigger type; use values from the context.UserEventType enum

   * @param {Form} context.form – Current form

   * @param {ServletRequest} context.request – HTTP request information sent from the browser for a client action only.

   * @since 2015.2

   */

  const beforeLoad = (context) => {

    try {

      if (context.type === context.UserEventType.VIEW || context.type === context.UserEventType.EDIT) {

        // log.debug(‘edit’);

        let newRec = context.newRecord;

        let form = context.form;

        let recId = newRec.id;

        let status = newRec.getValue({ fieldId: “custrecord_vr_jobstatus_i” })

        let sendToSidco = form.getField({ id: ‘custrecord_jj__sent_to_sidco’ });

        let sendToSidcoValue = newRec.getValue({ fieldId: ‘custrecord_jj__sent_to_sidco’ });

        let repackCheck = checkRepackProtocol(recId);

        log.debug(“full data”, { status: status, sendToSidco: sendToSidco, sendToSidcoValue: sendToSidcoValue, repackCheck: repackCheck });

        if (!sendToSidcoValue && status == 43)

          buttonforSendSidco(recId, form);

        if (status == 41 && repackCheck > 0)

          buttonforRepackCompleted(recId, form);

        if (status == 42 && repackCheck > 0)

          buttonforVerifyRepack(recId, form);

        if (status == 12 && repackCheck > 0)

          buttonforPostRepackCompleted(recId, form);

        if (status == 47 && repackCheck > 0)

          buttonforPostVerifiedRepack(recId, form);

      }

    } catch (er) {

      log.debug(‘error @ beforeLoad’, er);

    }

  }

  /**

    * Defines the function definition that is executed before record is submitted.

    * @param {Object} context

    * @param {Record} context.newRecord – New record

    * @param {Record} context.oldRecord – Old record

    * @param {string} context.type – Trigger type; use values from the context.UserEventType enum

    * @since 2015.2

    */

  const beforeSubmit = (context) => {

    try {

      let newRec = context.newRecord, finalSubmitObj = {};

      let recId = pnvl(newRec.id);

      log.debug(‘beforeSubmit recId’, recId);

      let svoInternalId = pnvl(newRec.getValue({ fieldId: ‘custrecord_vr_job_svcord’ }));

      if ([‘edit’, ‘create’].indexOf(context.type) !== –1) {

        let customerId = pnvl(newRec.getValue({ fieldId: ‘custrecord_vr_customer’ }));

        let intakeId = newRec.getValue({ fieldId: ‘custrecord_vr_job_inboundtran’ });

        let sidcoLabelCheckOld = context.oldRecord.getValue({ fieldId: “custrecord_jj__sent_to_sidco” });

        let sidcoLabelCheckNew = context.newRecord.getValue({ fieldId: “custrecord_jj__sent_to_sidco” });

        let sidcoLabelCompletedCheckOld = context.oldRecord.getValue({ fieldId: “custrecord_jj_sidco_labeling_complete” });

        let sidcoLabelCompletedCheckNew = context.newRecord.getValue({ fieldId: “custrecord_jj_sidco_labeling_complete” });

        let repackComplete = context.newRecord.getValue({ fieldId: “custrecord_jj_job_repack_complete” });

        let status = context.newRecord.getValue({ fieldId: “custrecord_vr_jobstatus_i” });

        let postRepackComplete = context.newRecord.getValue({ fieldId: “custrecord_jj_job_post_repack_complete” });

        let postVerifyRepack = context.newRecord.getValue({ fieldId: “custrecord_jj_job_post_verify_repack” });

        let verifyRepack = context.newRecord.getValue({ fieldId: “custrecord_jj_job_verify_repack” });

        log.debug(“data”, {

          intakeId: intakeId,

          sidcoLabelCheckOld: sidcoLabelCheckOld,

          sidcoLabelCheckNew: sidcoLabelCheckNew,

          sidcoLabelCompletedCheckNew: sidcoLabelCompletedCheckNew,

          sidcoLabelCompletedCheckOld, sidcoLabelCompletedCheckOld

        });

        intakeId && (sidcoLabelCheckNew != sidcoLabelCheckOld) ?

          finalSubmitObj = {

            “custbody_vr_sent_to_sidco”: sidcoLabelCheckNew ? true : false

          } : {};

        log.debug(“finalSubmitObj”, finalSubmitObj)

        Object.entries(finalSubmitObj).length != 0 ? record.submitFields({

          type: ‘returnauthorization’,

          id: intakeId,

          values: finalSubmitObj,

          options: { ignoreMandatoryFields: true }

        }) : “”;

        let repackCheck = checkRepackProtocol(recId);

        if ((repackComplete && status == 41 && repackCheck > 0) || (verifyRepack && status == 42 && repackCheck > 0) ||

          (postRepackComplete && status == 12 && repackCheck > 0) || (postVerifyRepack && status == 47 && repackCheck > 0)) {

          let jobSearch = fetchJobData(intakeId), finalStatus = “”;

          log.debug(“jobSearch”, jobSearch);

          Object.entries(jobSearch).length != 0 ?

            jobSearch.status.value == 43 ? finalStatus = 1 :

              jobSearch.status.value == 41 ? finalStatus = fetchNextProtocol(jobSearch.id, jobSearch.status.value) :

                jobSearch.status.value == 42 ? finalStatus = fetchNextProtocol(jobSearch.id, jobSearch.status.value) :

                  jobSearch.status.value == 12 ? finalStatus = fetchNextProtocol(jobSearch.id, jobSearch.status.value) :

                    jobSearch.status.value == 47 ? finalStatus = fetchNextProtocol(jobSearch.id, jobSearch.status.value)

                      : log.debug(“status is not pending labelling”) : “”;

          let idNum = jobChildStage(jobSearch.id, jobSearch.stage.value);

          context.newRecord.setValue({ fieldId: ‘custrecord_vr_jobstatus_i’, value: finalStatus });

        }

      }

    } catch (er) {

      log.error(‘error @ beforeSubmit’, er.message);

    }

  }

  return { beforeLoad, beforeSubmit };

});

Leave a comment

Your email address will not be published. Required fields are marked *