繁体   English   中英

我们如何在 Node JS 中使用 suiteScript.netsuite 2.0)?

[英]How can we use suiteScript(netsuite 2.0) in Node JS?

我们需要从 NetSuite Record 页面中获取字段,即 workOrder。 我创建了一个定义 pageInit function 以及我获取 xyz 字段值的 JS 文件。

我想在控制台中本地设置 NetSuite xyz 字段,这样我就可以在我的 Java 脚本代码中使用它来使其动态化。

但是在这里,我无法得到确切的解决方案。 我们如何使用 lambda 和 Node.js 获取 a.netsuite(工单页面)表单字段的值?

到目前为止,我在您的问题中没有看到任何需要节点的内容。 如果你真的需要使用节点,你应该看看评论中提到的 RESTlet/SuiteTalk 选项。

如果您想在控制台中运行脚本,下面的代码显示了如何执行此操作。

我为各种管理任务保留了一个文件夹。 只需打开控制台并在需要时运行即可。 下面的代码对于这些脚本之一来说相当复杂(尽管目前还不是最复杂的)。 它在编辑角色时使用。 它显示了已为特定作业 function 设置了最小权限的角色列表。所选角色将其权限应用于当前正在编辑的角色。

N/currentRecord是加载当前记录数据的 API。

require(['N/search', 'N/currentRecord', 'N/xml'], function(search, currentRecord, xml) {

    const roleList = search.create({
        type:'role',
        filters:[
            ['custrecord_kotn_is_role_capabilities', 'is', 'T'], 'AND',
            ['isinactive', 'is', 'F']
        ],
        columns:['name']
    }).run().getRange({start:0, end:1000}).map(ref=>{
        return {
            id:ref.id,
            name:ref.getValue({name:'name'})
        };
    }).map(r=>(`<option value=${r.id}>${r.name}</option>`)).join('\n');

    console.log(roleList);

    const body = document.querySelector('body');

    

    const form=`
        <div id="kotn-choose-roles" style="position:fixed;width:320px;left:50%;transform:translateX(-50%);top:30vh;background-color:white;border:1px solid #ccc;padding:10px;">
        <form onSubmit="return false;">
        <table><tr>
            <td>Roles</td>
            <td><select multiple id="kotn-roles-chosen">${roleList}</select>
            </td>
        </tr>
        <tr><td colspan="2" align="center"><button id="kotn-apply-roles" type="button">Apply</button><button id="kotn-cancel-roles" type="button">Cancel</button>
        </table>
        </form>
        </div>
    `;

    const frag = document.createElement('div');
    frag.setAttribute('id', 'kotn-role-chooser');
    frag.innerHTML = form;

    body.appendChild(frag);

    jQuery('#kotn-apply-roles').bind('click', function(){
        const roleIds = jQuery('#kotn-roles-chosen').val();
        console.log(roleIds);
        applyRoles(roleIds);
        alert('done');

        frag.parentNode.removeChild(frag);
    });

    jQuery('#kotn-cancel-roles').bind('click', function(){
        frag.parentNode.removeChild(frag);
    });


    function applyRoles(permSources){

        const roleRec = currentRecord.get();

        const machineNames = [
            {
                name:'custrecordmach',
                permRef:'custrecord',
                permLevelField:'permittedlevel',
                restricted:'restriction'
            },

            {
                name:'tranmach',
                permRef: 'permkey1',
                permLevelField:'permlevel1'
            },
            {
                name:'listsmach',
                permRef:'permkey3',
                permLevelField:'permlevel3'
            },
            {
                name:'setupmach',
                permRef:'permkey4',
                permLevelField:'permlevel4'
            }

        ];

        function doPerms(){
            if(!permSources.length) return;
            processPerm(permSources.shift()).then(doPerms);
        }

        function processPerm(id){
            return fetchWithRetry(`/app/setup/role.nl?id=${id}&xml=T`,{
                credentials: 'same-origin'
            }).
                then(resp =>{
                    console.log(id, resp.status);
                    return resp.text();
                }).
                then(data=>{


                    const roleDoc = xml.Parser.fromString({
                        text: data
                    });

                    console.log('role: ',selectValue(roleDoc, '/nsResponse/record/name'));

                    machineNames.forEach(m=>{
                        console.log('process machine', `//machine[@name="${m.name}"]/line`);
                        const docLines = xml.XPath.select({
                            node: roleDoc,
                            xpath: `//machine[@name="${m.name}"]/line`
                        });

                        console.log('machine lines', m.name, docLines.length);

                        const lines = docLines.map(line=>{

                            const perm = {
                                perm: selectValue(line, m.permRef),
                                level:parseInt(selectValue(line, m.permLevelField),10),
                                restricted:null
                            };
                            if(m.restricted){
                                perm.restricted = parseInt(selectValue(line, m.restricted), 10);
                            }
                            return perm;
                        });

                        console.log('lines for', m.name, lines);

                        const findPermIndex = perm =>{
                            for(var i = 0; i< lines.length; i++){
                                if(lines[i].perm == perm) return i;
                            }
                            return -1;
                        };

                        iter(roleRec, m.name, (idx, getV) =>{
                            const perm = getV(m.permRef);
                            const applyingIndex = findPermIndex(perm);
                            if(applyingIndex == -1) return;

                            const applyingPerm = lines.splice(applyingIndex, 1)[0];

                            console.log('have current perm', JSON.stringify(applyingPerm));

                            const permVal = getV(m.permLevelField);
                            const applyingLevel = (permVal >= applyingPerm.level) ? permVal : applyingPerm.level;

                            let applyingRestriction = null;

                            if(m.restricted){
                                let restrictionVal = parseInt(getV(m.restricted), 10) || null;
                                applyingRestriction = (!restrictionVal) ? null : applyingPerm.restricted;

                                if(restrictionVal && applyingRestriction){
                                    if(applyingRestriction <restrictionVal){
                                        applyingRestriction = restrictionVal;
                                    }
                                } 
                            }

                            setTimeout(()=>{

                                roleRec.selectLine({sublistId:m.name, line:idx});
                                roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permLevelField, value:applyingLevel, forceSyncSourcing:true});
                                if(applyingRestriction){
                                    roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.restricted, value:applyingRestriction, forceSyncSourcing:true});
                                }
                                roleRec.commitLine({sublistId:m.name});
                            }, idx *20);

                            
                        });
                        lines.forEach((line, idx)=>{
                            console.log('adding ', m.name, JSON.stringify(line));
                            setTimeout(()=>{
                                roleRec.selectNewLine({sublistId:m.name});
                                roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permRef, value:line.perm, forceSyncSourcing:true});
                                roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.permLevelField, value:line.level, forceSyncSourcing:true});
                                if(m.restricted){
                                    roleRec.setCurrentSublistValue({sublistId:m.name, fieldId:m.restricted, value:line.restricted, forceSyncSourcing:true });
                                }
                                roleRec.commitLine({sublistId:m.name, ignoreRecalc:true});
                            }, idx*100);
                        });
                    });
                    return id;
                }).catch(e=>{
                    console.error(e.message);
                    return null;
                });
        }

        doPerms();
    }



    //load role
    //for each machine
    //  transfer perms
    //  check current level - use highest



    function selectValue(node, path) {
        const targets = xml.XPath.select({
            node: node,
            xpath: path
        });

        if (!targets || !targets.length) return null;
        return targets[0].firstChild.nodeValue;
    }

    // function selectAttribute(node, path, attr) {
    //  const targets = xml.XPath.select({
    //      node: node,
    //      xpath: path
    //  });

    //  if (!targets || !targets.length) return null;
    //  return targets[0].getAttribute(attr);
    // }

    function iter(rec, listName, cb){
        var lim = rec.getLineCount({sublistId:listName});
        var i = 0;
        var getV = function (fld){
            return rec.getSublistValue({sublistId:listName, fieldId:fld, line:i});
        };
        for(; i< lim; i++){
            cb(i, getV);
        }
    }



    async function fetchWithRetry(url, opts, tries = 3) {
        const errs = [];

        const waiter = async (pause) => {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(null);
                }, pause);
            });
        };


        for (let i = 0; i < tries; i++) {
            // log for illustration
            if(i != 0) console.error(`trying GET '${url}' [${i + 1} of ${tries}]`);

            try {
                const resp = await fetch(url, opts);
                return resp;
            } catch (err) {
                errs.push(err);
                await waiter(800 * i + 1);
            }
        }

        throw errs;
    }


});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM