Suitelet for approve transaction page.

Jira Code: SMT-27

Description:

Create a suitelet page which shows the list of transactions: Credit memo, Invoice, Bill, Journal Entry & Expense report which is ready to approve based on certain conditions. The conditions are given below:

  • The Team lead(role) can view the approval page with the transactions: Credit memo, Invoice, Vendor bill, Journal entry & Expense report created by the roles: Team lead, Approve User, Manager User & SS_Super User, but can’t approve.
  • The Approve User (role) can view the approval page with the transactions: Credit memo, Invoice, Vendor bill, Journal entry & Expense report created by the roles: Team Lead and other Approve users and can approve them.
  • The Manager User (role) can view the approval page with the transactions: Credit memo, Invoice, Vendor bill, Journal entry & Expense report created by the roles: Team Lead, Approve Users, and other Manager User & can approve them.
  • The SS_Super User (role) can view the approval page with the transactions: Credit memo, Invoice, Vendor bill, Journal entry & Expense report created by the roles: Team Lead, Approve Users, Manager User & SS_Super user & can approve them.

Suitelet:

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
define(['N/ui/serverWidget', 'N/search', 'N/record', 'N/runtime', 'N/http', 'N/https', 'N/url'],

    function(serverWidget, search, record, runtime, http, https, url) {

        /**
         * Definition of the Suitelet script trigger point.
         *
         * @param {Object} context
         * @param {ServerRequest} context.request - Encapsulation of the incoming request
         * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
         * @Since 2015.2
         */
        function onRequest(context) {



            try {
                var userObj = runtime.getCurrentUser();
                log.debug("userObj.role", userObj.role);
                log.debug("userObj.id", userObj.id);


                if (context.request.method == 'GET') {

                    var getData = getDataRecord(userObj);
                    log.debug("getDataRecord", getData);


                    // To create Form and add button

                    var form = serverWidget.createForm({
                        title: 'Approve Transactions Page'
                    });
                    if (userObj.role != 1036) { //the button can be viewed only if the user role is not 'Team Lead'.
                        form.addSubmitButton({
                            label: 'Submit'
                        });

                        form.addResetButton({
                            label: 'Reset'
                        });
                    }

                    //To create sublist and fields

                    var sublist = form.addSublist({
                        id: 'custpage_sublistid',
                        type: serverWidget.SublistType.LIST,
                        label: 'Transactions to Approve'
                    });

                    if (userObj.role != 1036) { //the button can be viewed only if the user role is not 'Team Lead'.
                        var checkbox = sublist.addField({
                            id: 'custpage_checkbox',
                            label: 'SELECT',
                            type: serverWidget.FieldType.CHECKBOX
                        });
                    }
                    if (userObj.role != 1036) {
                        sublist.addMarkAllButtons();
                    }
                    var field1 = sublist.addField({
                        id: 'custpage_dateid',
                        label: 'DATE',
                        type: serverWidget.FieldType.DATE
                    });
                    field1.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });


                    var field2 = sublist.addField({
                        id: 'custpage_type',
                        label: 'Type',
                        type: serverWidget.FieldType.TEXT
                    });

                    field2.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });

                    var field3 = sublist.addField({
                        id: 'custpage_documentno',
                        label: 'Document No. ',
                        type: serverWidget.FieldType.TEXT
                    });
                    field3.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                    var field4 = sublist.addField({
                        id: 'custpage_status',
                        label: 'Status',
                        type: serverWidget.FieldType.TEXT
                    });
                    field4.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                    var field5 = sublist.addField({
                        id: 'custpage_amount',
                        label: 'Amount',
                        type: serverWidget.FieldType.TEXT
                    });
                    field5.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                    var field6 = sublist.addField({
                        id: 'custpage_createduserrole',
                        label: 'Created User Role',
                        type: serverWidget.FieldType.TEXT
                    });
                    field6.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                    var field7 = sublist.addField({
                        id: 'custpage_createduser',
                        label: 'Created User',
                        type: serverWidget.FieldType.TEXT
                    });
                    field7.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });


                    var field8 = sublist.addField({
                        id: 'custpage_internalid',
                        label: 'Internal ID',
                        type: serverWidget.FieldType.TEXT
                    });
                    field8.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.HIDDEN
                    });

                    //Set values from the saved search to the sublist on the suitelet page
                    if (getData) {
                        log.debug("getData.length", getData.length)

                        if (getData.length > 0) {
                            for (var i = 0; i < getData.length; i++) {

                                sublist.setSublistValue({
                                    id: 'custpage_internalid',
                                    line: i,
                                    value: getData[i].internalid || 'null'
                                });


                                sublist.setSublistValue({
                                    id: 'custpage_dateid',
                                    line: i,
                                    value: getData[i].date || 'null'
                                });

                                sublist.setSublistValue({
                                    id: 'custpage_documentno',
                                    line: i,
                                    value: getData[i].docuno || 'null'
                                });

                                sublist.setSublistValue({
                                    id: 'custpage_type',
                                    line: i,
                                    value: getData[i].type || 'null'
                                });

                                sublist.setSublistValue({
                                    id: 'custpage_status',
                                    line: i,
                                    value: getData[i].status || 'null'
                                });
                                sublist.setSublistValue({
                                    id: 'custpage_amount',
                                    line: i,
                                    value: getData[i].amount || 'null'
                                });
                                sublist.setSublistValue({
                                    id: 'custpage_createduserrole',
                                    line: i,
                                    value: getData[i].createduserrole || 'null'
                                });
                                sublist.setSublistValue({
                                    id: 'custpage_createduser',
                                    line: i,
                                    value: getData[i].createduser || 'null'
                                });
                            }
                        }
                    }
                    context.response.writePage(form);

                }

                //action on click of the submit button
                if (context.request.method == 'POST') {


                    var list = context.request.getLineCount({
                        group: "custpage_sublistid"
                    });

                    var approveList = [];
                    var typelist = {}
                    var count = 0;
                    for (var i = 0; i < list; i++) {
                        var chkboxvalue = context.request.getSublistValue({
                            group: 'custpage_sublistid',
                            name: 'custpage_checkbox',
                            line: i
                        });
                        var ApproveINternalId = context.request.getSublistValue({
                            group: 'custpage_sublistid',
                            name: 'custpage_internalid',
                            line: i
                        });
                        var type = context.request.getSublistValue({
                            group: 'custpage_sublistid',
                            name: 'custpage_type',
                            line: i
                        });
                        if (chkboxvalue == 'T') {
                            count++
                            typelist[ApproveINternalId] = {
                                'id': ApproveINternalId,
                                'type': type
                            };

                        }
                    }
                    log.debug('approveList', typelist)
                    for (var key in typelist) {
                        log.debug('typelist[key].type', typelist[key].type)

                        if (typelist[key].type == 'Journal') {
                            var tempId = typelist[key].id;
                            var journalEdit = record.load({
                                type: "journalentry",
                                id: tempId,
                                isDynamic: false
                            });
                            journalEdit.setValue({
                                fieldId: 'approved',
                                value: true
                            });
                            journalEdit.save();


                            log.debug("tempId", typelist[key].type);
                        } else if (typelist[key].type == 'Credit Memo') {
                            var tempId = typelist[key].id;
                            var creditmemoEdit = record.load({
                                type: "creditmemo",
                                id: tempId,
                                isDynamic: false
                            });
                            creditmemoEdit.setValue({
                                fieldId: 'custbody_pi_ss_approved_checkbox',
                                value: true
                            });
                            creditmemoEdit.save();

                        } else if (typelist[key].type == 'Bill') {
                            var tempId = typelist[key].id;
                            var billEdit = record.load({
                                type: "vendorbill",
                                id: tempId,
                                isDynamic: false
                            });
                            billEdit.setValue({
                                fieldId: 'approvalstatus',
                                value: 2
                            });
                            billEdit.save();

                        } else if (typelist[key].type == 'Invoice') {
                            var tempId = typelist[key].id;
                            var invoiceEdit = record.load({
                                type: "invoice",
                                id: tempId,
                                isDynamic: false
                            });
                            invoiceEdit.setValue({
                                fieldId: 'approvalstatus',
                                value: 2
                            });
                            invoiceEdit.save();

                        } else if (typelist[key].type == "Expense Report") {

                            var tempId = typelist[key].id;
                            var expenseEdit = record.load({
                                type: "expensereport",
                                id: tempId,
                                isDynamic: false
                            });

                            expenseEdit.setValue({
                                fieldId: 'accountingapproval',
                                value: true
                            });
                            expenseEdit.save();
                        }


                    }
                    var redirectViewURL = url.resolveScript({
                        scriptId: 'customscript_jj_smt_26_approve_page',
                        deploymentId: 'customdeploy_jj_smt_26_approve_page',
                        returnExternalUrl: false
                    });
                    if (count > 0)
                        var htmlCode = '<html><head></head><body><script>confirm("Successfully Approved the transactions");window.location.href ="' + redirectViewURL + '";</script></body></html>';
                    else
                        var htmlCode = '<html><head></head><body><script>confirm("No transactions selected for approval");window.location.href ="' + redirectViewURL + '";</script></body></html>';

                    context.response.write(htmlCode);
                }
            } catch (e) {
                log.debug("Error @ onRequest FN ", e);
            }

        }



        function getDataRecord(userObj) {
            try {

                var array = [];
                var recObj = {};
                var searchDate, searchDocuno, searchType, searchStatus, searchAmount;
                var role = [];
                var user_id = userObj.id;
                var filters_all = [];

                filters_all.push(["type", "anyof", "VendBill", "CustCred", "CustInvc", "ExpRept", "Journal"]);
                filters_all.push("AND");
                filters_all.push(["status", "anyof", "VendBill:D", "CustCred:A", "ExpRept:B", "ExpRept:C", "CustInvc:D", "Journal:A"]);
                filters_all.push("AND");
                filters_all.push(["mainline", "is", "T"]);
                filters_all.push("AND");
                filters_all.push(["custbody_pi_ss_approved_checkbox", "is", "F"]);
                filters_all.push("AND");


                if (userObj.role == 3) {

                    role = ["3"];
                    filters_all.push(["custbody_jj_smt_11_role", "anyof", role]);

                } else if (userObj.role == 1036) {

                    role = ["1036", "1049", "1048", "1037"];
                    filters_all.push(["custbody_jj_smt_11_role", "anyof", role]);

                } else if (userObj.role == 1049) {

                    role = ["1036"];
                    role1 = ["1049"];
                    filters_all.push([
                        [
                            ["custbody_jj_smt_11_role", "anyof", role], "AND", ["user.role", "anyof", role1]
                        ], "OR", [
                            ["custbody_jj_smt_11_role", "anyof", role1], "AND", ["custbody_jj_smt_11_user", "noneof", "@CURRENT@"]
                        ]
                    ]);


                } else if (userObj.role == 1048) {
                    role = ["1049", "1036"];
                    role1 = ["1048"];
                    filters_all.push([
                        [
                            ["custbody_jj_smt_11_role", "anyof", role], "AND", ["user.role", "anyof", role1]
                        ], "OR", [
                            ["custbody_jj_smt_11_role", "anyof", role1], "AND", ["custbody_jj_smt_11_user", "noneof", "@CURRENT@"]
                        ]
                    ]);


                } else if (userObj.role == 1037) {

                    role = ["1036", "1049", "1048", "1037"];
                    filters_all.push(["custbody_jj_smt_11_role", "anyof", role]);
                }


                var transactionSearchObj = search.create({
                    type: "transaction",
                    filters: filters_all,
                    columns: [
                        search.createColumn({ name: "trandate", summary: "GROUP", label: "Date" }),
                        search.createColumn({ name: "tranid", summary: "GROUP", label: "Document Number" }),
                        search.createColumn({ name: "type", summary: "GROUP", label: "Type" }),
                        search.createColumn({ name: "statusref", summary: "GROUP", label: "Status" }),
                        search.createColumn({ name: "amount", summary: "MAX", label: "Amount" }),
                        search.createColumn({ name: "internalid", summary: "GROUP", label: "Internal ID" }),
                        search.createColumn({ name: "custbody_jj_smt_11_role", summary: "GROUP", label: "Created User Role" }),
                        search.createColumn({ name: "custbody_jj_smt_11_user", summary: "GROUP", label: "Created User" })
                    ]
                });
                var searchResultCount = transactionSearchObj.runPaged().count;
                log.debug("transactionSearchObj result count", searchResultCount);
                transactionSearchObj.run().each(function(result) {

                    //get each value from search
                    searchDate = result.getValue(transactionSearchObj.columns[0]);
                    recObj.date = searchDate;

                    searchDocuno = result.getValue(transactionSearchObj.columns[1]);
                    recObj.docuno = searchDocuno;

                    searchType = result.getText(transactionSearchObj.columns[2]);
                    recObj.type = searchType;


                    searchStatus = result.getText(transactionSearchObj.columns[3]);
                    recObj.status = searchStatus;

                    searchAmount = result.getValue(transactionSearchObj.columns[4]);
                    recObj.amount = searchAmount;

                    searchInternalid = result.getValue(transactionSearchObj.columns[5]);
                    recObj.internalid = searchInternalid;

                    searchCreateduserrole = result.getText(transactionSearchObj.columns[6]);
                    recObj.createduserrole = searchCreateduserrole;

                    searchCreateduser = result.getText(transactionSearchObj.columns[7]);
                    recObj.createduser = searchCreateduser;


                    log.debug("recObj", recObj);
                    array.push(recObj);
                    recObj = {} //for clearing each line after it is pushed otherwise it will overwrite
                    // .run().each has a limit of 4,000 results
                    return true;
                });



                return array;

            } catch (e) {
                log.error("Error", e);
            }
        }


        return {
            onRequest: onRequest
        };


    });

Leave a comment

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