简体   繁体   English

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

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

We need to get the field from the NetSuite Record page, ie workOrder.我们需要从 NetSuite Record 页面中获取字段,即 workOrder。 I've created a single JS file that defines the pageInit function and where I'm getting the xyz field value.我创建了一个定义 pageInit function 以及我获取 xyz 字段值的 JS 文件。

I'd like to have the NetSuite xyz field locally in the console so I can use it in my Java-script code to make it dynamic.我想在控制台中本地设置 NetSuite xyz 字段,这样我就可以在我的 Java 脚本代码中使用它来使其动态化。

But here, I am unable to get an exact solution for it.但是在这里,我无法得到确切的解决方案。 How can we get the value of a.netsuite (work-order page) form field using lambda and Node.js?我们如何使用 lambda 和 Node.js 获取 a.netsuite(工单页面)表单字段的值?

I don't see anything in your question that requires node so far.到目前为止,我在您的问题中没有看到任何需要节点的内容。 If you really need to use node you should look at the RESTlet/SuiteTalk options mentioned in the comments.如果你真的需要使用节点,你应该看看评论中提到的 RESTlet/SuiteTalk 选项。

If you are wanting to run a script in the console the code below shows how to do that.如果您想在控制台中运行脚本,下面的代码显示了如何执行此操作。

I keep a folder of these for various admin tasks.我为各种管理任务保留了一个文件夹。 Just open a console and run when needed.只需打开控制台并在需要时运行即可。 The code below is fairly complex for one of these scripts (though not the most complex by far).下面的代码对于这些脚本之一来说相当复杂(尽管目前还不是最复杂的)。 It is used while editing a role.它在编辑角色时使用。 It presents a list of roles that have been set up with minimal permissions for a particular job function. The roles that are selected have their permissions applied to the currently being edited role.它显示了已为特定作业 function 设置了最小权限的角色列表。所选角色将其权限应用于当前正在编辑的角色。

N/currentRecord is the API that loads the current record's data. 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.

相关问题 我们可以使用 Firebase 身份验证并符合 GDPR 吗? - Can we use Firebase Authentication and be GDPR compliant? 如何将 Google Pub/Sub Lite 与 Node.js 一起使用? - How do I use Google Pub/Sub Lite with Node.js? 如何在 AWS lambda 中使用 HTML 模板引擎和 Node.js function? - How to use an HTML templating engine with a Node.js function in an AWS lambda? "errorMessage": "require is not defined in ES module scope, you can use import instead" 使用 Node.js 18.x 时 - "errorMessage": "require is not defined in ES module scope, you can use import instead" When using Node.js 18.x 如何使用 node.js 将信息从 mongodb 数据库传输到 dialogflow? - How can I transfer the information from mongodb database to dialogflow with node.js? 在 Node JS 中使用 url 链接而不是文件路径 - Use url link instead of path to file in Node JS 如何将 Firebase 连接到 Node.JS 项目? - How to connect Firebase to a Node.JS project? 我们可以使用 Application Client ID + Client Secret 而不是 Tokens - Can we use Application Client ID + Client Secret instead of Tokens 无法在 Node.js 中导入 firebase-admin - Can't import firebase-admin in Node.js 我们如何为 appscript 驱动插件自定义 LoadIndicator? - How can we customize LoadIndicator for appscript drive addon?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM