Add Prescription Table in Customer Record

  • A prescription is a custom record available in the system we want to show all available prescriptions for that customer.
  • The following script creates a prescription HTML table in the customer record.
  • The Prescription Table shows all essential data like the quantity of prescription items used in Transactions, Auto-ships, Pet & Vet details, etc. Also link to the RX record
/**
 * 
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 * 
 */
define(['N/record', 'N/search', 'N/ui/serverWidget', 'N/log', './vv_new_lib_constants'],
    function (record, search, serverWidget, log, _lib_constants) {
        const GLOBAL_CONSTANTS = _lib_constants.getConstants()
        const PRESCRIPTION_URL = GLOBAL_CONSTANTS.URL.PRESCRIPTION

        const _AUTOSHIP_LINE_RECORD = "customrecord_vv_autoship_record";
        const _PRESCRIPTION_RECORD = "customrecord_vv_prescription";
        const _RX_SUBLIST_LINK = "recmachcustrecord_vv_customer";

        /* AUTOSHIP CUSTOM RECORD FIELDS */
        const _AS_ITEM = "custrecord_vv_autoship_item"
        const _AS_SO_REFERENCE = "custrecord_vv_autoship_soref"
        const _AS_PRESCRIPTION = "custrecord_vv_autoship_prescription"
        const _AS_CUSTOMER_SRC = "custrecord_vv_autoship_customer_src";
        /* AUTOSHIP CUSTOM RECORD FIELDS */

        /* PRESCRIPTION RECORD FIELDS AND PRESCRIPTION ITEM RECORD FIELDS OBJ */
        const _PRESCRIPTION = {
            rxItemName: "custrecord_vv_item_name",
            itemNumber: "custrecord_vv_item_number",
            itemDescription:"custrecord_vv_description",
            prId: "custrecord_vv_prescription_id",
            refillQty: "custrecord_vv_refill_quantity",
            autoshipQty: "custrecord_vv_autoship_quantity",
            rxPet: "custrecord_vv_pet",
            customer: "custrecord_vv_customer",
            rxNumber: "custrecord_vv_rx_number",
            rxExpDate: "custrecord_vv_expiration_date",
            clinicName: "custrecord_vv_clinic_name",
            altName: "custrecord_vet_altname",
            rxVet: "custrecord_vv_vet",
            rxSpecies: "custrecord_vv_species",
            rxStatus: "custrecord_vv_status",
            quantityOpen: "custrecord_vv_quantity_open",
            asWriitten: "custrecord_vv_as_written",
            rxOpen: "custrecord_vv_open_rx",
            rxDirections: "custrecord_vv_directions",
            rxComments: "custrecord_vv_comments"
        }
        
        /* PRESCRIPTION AND PRESCRIPTION ITEM RECORD FIELDS OBJ */

        /**
         * Function definition to be triggered before record is loaded.
         * @param {Object} context
         * @param {Record} context.newRecord - New record
         * @param {Record} context.oldRecord - Old record
         * @param {string} context.type - Trigger type
         * @Since 2015.2
         */

        function beforeLoad(context) {
            try {
                var recType = context.newRecord.type;
                var recId = context.newRecord.id
                var recCustomer = record.load({type: recType,id: recId});
                var form = context.form;

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

                    //Hide "Pharmacy Rx View" Sublist in view mode
                    var taxRate = form.getSublist({id: _RX_SUBLIST_LINK})
                    taxRate.displayType = serverWidget.SublistDisplayType.HIDDEN;
                }

                var arrRXData = getPresciptions(recId);
                createTableHTML(form, arrRXData, recId);
                
            } catch (err) {
                log.error('ERROR@BEFORELOAD', err);
            }
        }

        function createTableHTML(form, data, custId) {
            var LOGTITLE = "CREATE_TABLE";

            var TAB_TABLE = form.addTab({
                id: 'custpage_tab_table',
                label: 'Prescription HTML'
            });
            form.insertTab({
                tab: TAB_TABLE,
                nexttab: 'custom103'
            })
            form.addFieldGroup({
                id: 'custpage_grp_table',
                label: 'Prescriptions',
                tab: 'custpage_tab_table'
            }).isBorderHidden = true;
            var TBL_DATA = form.addField({
                id: 'custpage_table',
                type: 'label',
                label: 'Prescriptions',
                container: 'custpage_grp_table'
            });

            var table = "<table width='100%' style='border-collapse: collapse;font-size: 9pt'>"
            table += "<tr>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>VIEW LINK</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>PET</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>SPECIES</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>VET</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>ITEM #</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>ITEM DESCRIPTION</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>QTY</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>USED</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>REMAINING</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>EXPIRES</b></th>"
            table += "<th style='padding: 4px;border:.5px solid black'><b>RX #</b></th>"

            table += "</tr>"
            for (var i = 0; i < data.length; i++) {
                var qty = data[i].qty
                var lineQty = (qty === '') ? 0 : qty;
                var usedQty = getUsedQty(data[i].itemId, custId, data[i].rxId)
                var openQty = qty - usedQty < 0 ? "0" : qty - usedQty;
                openQty = (openQty.toString().indexOf('-') === -1) ? openQty : 0;

                var isOdd = i % 2 === 0 ? "background-color: #E5E5E5;" : "";
                table += "<tr style='" + isOdd + "'>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].viewLink + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].pet + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].species + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].vetNameValue + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].itemNum + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].desc + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + lineQty.toString() + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + usedQty.toString() + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + openQty.toString() + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].expDate + "</td>"
                table += "<td style='padding: 4px;border:.5px solid black'>" + data[i].rxId + "</td>"

                table += "</tr>"
            }
            table += "</table>"
            TBL_DATA.label = table;
        }

        function createTable(form, data, custId) {
            var LOGTITLE = "CREATE_TABLE";

            var rxSublist = form.addSublist({
                id: 'custpage_presc_table',
                type: serverWidget.SublistType.LIST,
                label: 'Prescriptions',
                tab: 'custom103'
            });

            var prescriptionLinkCol = rxSublist.addField({
                id: 'custpage_prescrptnlink',
                type: serverWidget.FieldType.TEXT,
                label: 'View Link'
            });

            var petCol = rxSublist.addField({
                id: 'custpage_petfield',
                type: serverWidget.FieldType.TEXT,
                label: 'Pet'
            });
            var speciesCol = rxSublist.addField({
                id: 'custpage_speciesfield',
                type: serverWidget.FieldType.TEXT,
                label: 'Species'
            });
            var vetClinicCol = rxSublist.addField({
                id: 'custpage_vetclinicnamefield',
                type: serverWidget.FieldType.TEXT,
                label: 'Vet'
            });

            var itemNumCol = rxSublist.addField({
                id: 'custpage_itemnum',
                type: serverWidget.FieldType.TEXT,
                label: 'Item #'
            });

            var itemNameCol = rxSublist.addField({
                id: 'custpage_itemname',
                type: serverWidget.FieldType.TEXT,
                label: 'Item Name'
            });
            itemNameCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            var itemDescCol = rxSublist.addField({
                id: 'custpage_itemdescription',
                type: serverWidget.FieldType.TEXT,
                label: 'Item Description'
            });

            var qtyCol = rxSublist.addField({
                id: 'custpage_quantity',
                type: serverWidget.FieldType.TEXT,
                label: 'QTY'
            });

            var qtyUsedCol = rxSublist.addField({
                id: 'custpage_qtyused',
                type: serverWidget.FieldType.TEXT,
                label: 'USED'
            });

            var qtyOpenCol = rxSublist.addField({
                id: 'custpage_qtyopen',
                type: serverWidget.FieldType.TEXT,
                label: 'REMAINING'
            });

            var expirationDateCol = rxSublist.addField({
                id: 'custpage_expirationdate',
                type: serverWidget.FieldType.DATE,
                label: 'Expires'
            })

            var rxCol = rxSublist.addField({
                id: 'custpage_rxnum',
                type: serverWidget.FieldType.TEXT,
                label: 'RX #'
            });

            var asWrittenCol = rxSublist.addField({
                id: 'custpage_aswritten',
                type: serverWidget.FieldType.TEXT,
                label: 'As Written'
            });
            asWrittenCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            var openRxCol = rxSublist.addField({
                id: 'custpage_openrx',
                type: serverWidget.FieldType.TEXT,
                label: 'Open RX'
            });
            openRxCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            var directionsCol = rxSublist.addField({
                id: 'custpage_directions',
                type: serverWidget.FieldType.TEXT,
                label: 'Directions'
            });
            directionsCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            var commentsCol = rxSublist.addField({
                id: 'custpage_comments',
                type: serverWidget.FieldType.TEXT,
                label: 'Comments'
            });
            commentsCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            var statusCol = rxSublist.addField({
                id: 'custpage_status',
                type: serverWidget.FieldType.TEXT,
                label: 'Status'
            });
            statusCol.updateDisplayType({displayType: serverWidget.FieldDisplayType.HIDDEN});

            for (var i = 0; i < data.length; i++) {
                log.debug("data[i]: " + i, data[i])
                if (data[i].itemId) {
                    log.debug("linecount: " + i, rxSublist.lineCount)
                    var qty = data[i].qty
                    var lineQty = (qty === '') ? 0 : qty;
                    var usedQty = getUsedQty(data[i].itemId, custId, data[i].rxId)
                    var openQty = qty - usedQty < 0 ? "0" : qty - usedQty;


                    if (data[i].rxNum) {
                        rxSublist.setSublistValue({
                            id: 'custpage_prescrptnlink',
                            line: i,
                            value: data[i].viewLink
                        });
                    }

                    if (data[i].expDate) {
                        rxSublist.setSublistValue({
                            id: 'custpage_expirationdate',
                            line: i,
                            value: data[i].expDate
                        });
                    }

                    if (data[i].pet) {
                        rxSublist.setSublistValue({
                            id: 'custpage_petfield',
                            line: i,
                            value: data[i].pet
                        });
                    }

                    if (data[i].species) {
                        rxSublist.setSublistValue({
                            id: 'custpage_speciesfield',
                            line: i,
                            value: data[i].species
                        });
                    }
                    if (data[i].vet) {
                        rxSublist.setSublistValue({
                            id: 'custpage_vetclinicnamefield',
                            line: i,
                            value: data[i].vet + ' ,</br>' + data[i].clinic
                        });
                    }

                    if (data[i].rxNum) {
                        rxSublist.setSublistValue({
                            id: 'custpage_rxnum',
                            line: i,
                            value: data[i].rxId
                        });
                    }

                    if (data[i].itemName) {
                        rxSublist.setSublistValue({
                            id: 'custpage_itemname',
                            line: i,
                            value: data[i].itemName
                        });
                    }

                    if (data[i].itemNum) {
                        rxSublist.setSublistValue({
                            id: 'custpage_itemnum',
                            line: i,
                            value: data[i].itemNum
                        });
                    }

                    if (data[i].desc) {
                        rxSublist.setSublistValue({
                            id: 'custpage_itemdescription',
                            line: i,
                            value: data[i].desc
                        });
                    }
                    
                    rxSublist.setSublistValue({
                        id: 'custpage_quantity',
                        line: i,
                        value: lineQty.toString()
                    });
                   
                    rxSublist.setSublistValue({
                        id: 'custpage_qtyused',
                        line: i,
                        value: usedQty.toString()
                    });
                    
                    openQty = (openQty.toString().indexOf('-') === -1) ? openQty : 0;

                    rxSublist.setSublistValue({
                        id: 'custpage_qtyopen',
                        line: i,
                        value: openQty.toString()
                    });
                    

                    if (data[i].asWritten) {
                        rxSublist.setSublistValue({
                            id: 'custpage_aswritten',
                            line: i,
                            value: 'True'
                        });
                    } else {
                        rxSublist.setSublistValue({
                            id: 'custpage_aswritten',
                            line: i,
                            value: 'False'
                        });
                    }

                    if (data[i].openRx) {
                        rxSublist.setSublistValue({
                            id: 'custpage_openrx',
                            line: i,
                            value: 'True'
                        });
                    } else {
                        rxSublist.setSublistValue({
                            id: 'custpage_openrx',
                            line: i,
                            value: 'False'
                        });
                    }

                    if (data[i].directions) {
                        rxSublist.setSublistValue({
                            id: 'custpage_directions',
                            line: i,
                            value: data[i].directions
                        });
                    }

                    if (data[i].comments) {
                        rxSublist.setSublistValue({
                            id: 'custpage_comments',
                            line: i,
                            value: data[i].comments
                        });
                    }

                    if (data[i].status) {
                        rxSublist.setSublistValue({
                            id: 'custpage_status',
                            line: i,
                            value: data[i].status
                        });
                    }
                }
            }


            try {
                form.insertSublist({
                    sublist: rxSublist,
                    nextsublist: _RX_SUBLIST_LINK
                });
            } catch (e) {
                log.error('WARNING', e.message);
            }
        }

        function getPresciptions(custId) {
            var returnValue = [];
            var customrecord_vv_prescriptionSearchObj = search.create({
                type: _PRESCRIPTION_RECORD,
                filters: [
                    [_PRESCRIPTION.customer, "anyof", custId]
                ],
                columns: [
                    "internalid",
                    "name",
                    search.createColumn({
                        name: _PRESCRIPTION.rxNumber,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.rxItemName,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.itemNumber,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.itemDescription,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.refillQty,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.quantityOpen,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.asWriitten,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.rxOpen,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.rxDirections,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.rxComments,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: _PRESCRIPTION.rxStatus,
                        join: _PRESCRIPTION.prId
                    }),
                    search.createColumn({
                        name: "formulatext",
                        formula: "'<a href= " + PRESCRIPTION_URL + "'|| {internalid} ||' target=_blank>View</a>'",
                        label: "Formula (Text)"
                    }),
                    search.createColumn({name: _PRESCRIPTION.rxPet, label: "Pet"}),
                    search.createColumn({name: _PRESCRIPTION.rxSpecies, label: "Species"}),
                    search.createColumn({name: _PRESCRIPTION.rxVet, label: "Vet"}),
                    search.createColumn({name: _PRESCRIPTION.altName, label: "Vet Name"}),
                    search.createColumn({name: _PRESCRIPTION.clinicName, label: "Clinic Name"}),
                    search.createColumn({name: _PRESCRIPTION.rxExpDate, label: "Expiration Date"}),
                    search.createColumn({
                        name: "altname",
                        join: _PRESCRIPTION.rxVet,
                        label: "Vet"
                    }),
                ]
            });

            var myPagedData = customrecord_vv_prescriptionSearchObj.runPaged();
            log.debug("count", myPagedData.count)

            myPagedData.pageRanges.forEach(function (pageRange) {
                var myPage = myPagedData.fetch({
                    index: pageRange.index
                });
                myPage.data.forEach(function (result) {
                    returnValue.push({
                        recId: result.getValue('internalid'),
                        rxId: result.getValue('name'),
                        rxNum: result.getValue({
                            name: _PRESCRIPTION.rxNumber,
                            join: _PRESCRIPTION.prId
                        }),
                        itemId: result.getValue({
                            name: _PRESCRIPTION.rxItemName,
                            join: _PRESCRIPTION.prId
                        }),
                        itemName: result.getText({
                            name: _PRESCRIPTION.rxItemName,
                            join: _PRESCRIPTION.prId
                        }),
                        itemNum: result.getValue({
                            name: _PRESCRIPTION.itemNumber,
                            join: _PRESCRIPTION.prId
                        }),
                        desc: result.getValue({
                            name: _PRESCRIPTION.itemDescription,
                            join: _PRESCRIPTION.prId
                        }),
                        qty: result.getValue({
                            name: _PRESCRIPTION.refillQty,
                            join: _PRESCRIPTION.prId
                        }),
                        qtyOpen: result.getValue({
                            name: _PRESCRIPTION.quantityOpen,
                            join: _PRESCRIPTION.prId
                        }),
                        asWritten: result.getValue({
                            name: _PRESCRIPTION.asWriitten,
                            join: _PRESCRIPTION.prId
                        }),
                        openRx: result.getValue({
                            name: _PRESCRIPTION.rxOpen,
                            join: _PRESCRIPTION.prId
                        }),
                        directions: result.getValue({
                            name: _PRESCRIPTION.rxDirections,
                            join: _PRESCRIPTION.prId
                        }),
                        comments: result.getValue({
                            name: _PRESCRIPTION.rxComments,
                            join: _PRESCRIPTION.prId
                        }),
                        status: result.getValue({
                            name: _PRESCRIPTION.rxStatus,
                            join: _PRESCRIPTION.prId
                        }),
                        viewLink: result.getValue({
                            name: "formulatext",
                            formula: "'<a href= " + PRESCRIPTION_URL + "'|| {internalid} ||' target=_blank>View</a>'",
                            label: "Formula (Text)"
                        }),
                        pet: result.getText({name: _PRESCRIPTION.rxPet, label: "Pet"}),
                        species: result.getValue({name: _PRESCRIPTION.rxSpecies, label: "Species"}),
                        vet: result.getText(customrecord_vv_prescriptionSearchObj.columns[16]),
                        clinic: result.getValue({name: _PRESCRIPTION.clinicName}),
                        expDate: result.getValue({name: _PRESCRIPTION.rxExpDate}),
                        vetNameValue: result.getValue(customrecord_vv_prescriptionSearchObj.columns[20]),
                    })
                });
            });

            log.debug("returnValue", returnValue)
            return returnValue;

        }

        function getUsedQty(itemId, custId, prescId) {
            var qty = 0;

            if (itemId !== "" && custId !== "" && prescId !== "") {
                var customrecord_vv_autoship_recordSearchObj = search.create({
                    type: _AUTOSHIP_LINE_RECORD,
                    filters: [
                        [_AS_ITEM, "anyof", itemId],
                        "AND",
                        [_AS_CUSTOMER_SRC, "anyof", custId],
                        "AND",
                        [_AS_PRESCRIPTION, "anyof", prescId],
                        "AND",
                        [_AS_SO_REFERENCE,"noneof","@NONE@"]
                    ],
                    columns: [
                        search.createColumn({
                            name: _PRESCRIPTION.autoshipQty,
                            summary: "SUM"
                        })
                    ]
                });

                var myPagedData = customrecord_vv_autoship_recordSearchObj.runPaged();

                myPagedData.pageRanges.forEach(function (pageRange) {
                    var myPage = myPagedData.fetch({
                        index: pageRange.index
                    });
                    myPage.data.forEach(function (result) {
                        qty = result.getValue({
                            name: _PRESCRIPTION.autoshipQty,
                            summary: 'SUM'
                        });
                    });
                });
            }
            qty = (qty === '') ? 0 : qty;
            return qty;
        }

        return {
            beforeLoad: beforeLoad,
        }
    }
);

Leave a comment

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