繁体   English   中英

Netsuite:Suitescript 2.X:我需要帮助使用搜索/getValue 来自动填充自定义 CPN。 交叉引用项目和客户以查找 CPN

[英]Netsuite: Suitescript 2.X: I need help using searches/getValue to populate custom CPN automatically. Cross referencing item and customer to find CPN

因为 Netsuite 的原生 CPN 不允许人们使用 CPN 中的空间,所以我的公司制作了一个自定义套件脚本来为 CPN 使用自定义记录类型。 下面的脚本用于交叉引用客户和项目以生成可能的 CPN 列表,然后它选择该列表中的第一个也是唯一的选项。 起初我们将其路由到子公司,但现在我们认为将它们连接到母公司可能会更好。这样,如果一家公司有 12 个子公司,我们只需上传一次 CPN。 有人会查看下面的代码并让我知道为什么我不能让代码使用父客户而不是孩子吗? 或者更确切地说,它根本不会填充。

define(["N/search", "N/log"], function(Search, _Log) {
    var TAG = "pi_cs_so_v2";

    function Log() {};
    Log.log = function (tag, msg) {
        console.log(tag + " : " + msg);
    };
    Log.debug = function(tag, msg) {
        _Log.debug(tag, msg);
        Log.log(tag, msg);
    };
    Log.error = function(tag, msg) {
        _Log.error(tag, msg);
        Log.log(tag, msg);
    };

    function fieldChanged(context) {
        PartNumber.fieldChanged(context);
    }

    /**
     * Static object, contains customizations relevant to EURO-3
     * @constructor
     */
    function PartNumber () {}
    function cusParent (){}
    /**
     * Handle the native field changed NetSuite call
     * @param context
     * @returns {boolean} True if CPN is updated, else false
     */
    PartNumber.fieldChanged = function(context) {
        var nr = context.currentRecord;
        if (context.sublistId !== "item" || context.fieldId !== "item") return false;
        Log.debug(TAG, "fieldChanged, executing CPN extension");

        var item = nr.getCurrentSublistValue({sublistId: context.sublistId, fieldId: "item"});
        var customer = nr.getValue("entity");
        var parent = nr.getValue({
                        join: "entity",
                        fieldId: "parent",
                        name: "name"
                    });

        Log.debug(TAG, "Item, customer: " + JSON.stringify([item, parent]));
        if (!parent || parent === "" || !item || item === "") return false;
        var cpn = PartNumber.find(parent, item);
        if (!cpn) return false;

        nr.setCurrentSublistValue({sublistId: context.sublistId, fieldId: "custcol_cpn_transaction", value: cpn});
      nr.setCurrentSublistValue({sublistId: context.sublistId, fieldId: "custcol24", value: parent});
        Log.debug(TAG, "Found CPN: " + cpn);
        return true;
    };
    /**
     * Search for the customer part number, assumes there is only ever a single result
     * @param customer
     * @param item
     * @returns {number | undefined} InternalID of the True Customer Part Number record
     */

  PartNumber.find = function(customer, item) {
        var searchObj = Search.create({
            type: "customrecord_true_cpn",
            filters:
                [
                    ["custrecord_cpn_customer","anyof",customer],
                    "AND",
                    ["custrecord_cpn_item","anyof",item]
                ],
            columns: []
        });
        var ans = -1;
        searchObj.run().each(function(result){
            // .run().each has a limit of 4,000 results
            ans = result.id;
            return false;
        });
        return ans !== -1 ? ans : undefined;
    };
 

    return {
        postSourcing: fieldChanged,
    };
});

假设具有层次结构的公司可能有一个树而不仅仅是一条直线,您需要一种方法来有效地查询从顶层到当前客户的层次结构并获得最佳匹配的 CPN。

我们可以利用 Netsuite 如何包含名称,并推断具有匹配 CPN 的最长的完全限定客户名称是最好使用的名称。

尽管下面的代码未经测试,但它基于我在其他上下文中所做的分层搜索。 请注意,我发现您的许多伪对象样式都非常模糊,并且没有增加任何代码可读性或类型安全性。 这只是一个自包含的脚本。

define(["N/search", "N/log"], function(Search, _Log) {
    var TAG = "pi_cs_so_v2";

    function hasConsole(){
        return typeof window == 'object' && window.console && window.console.log;
    }

    var Log = {

        debug : function(tag, msg) {
            hasConsole ? window.console.log(tag, msg) : _Log.debug(tag, msg);
            
        },
        error : function(tag, msg) {
            hasConsole ? window.console.error(tag, msg) : _Log.error(tag, msg);
        }
    };

    function fieldChanged(context) {

        var nr = context.currentRecord;
        if (context.sublistId !== "item" || context.fieldId !== "item") return;  //return false <- fieldChanged is void
        Log.debug(TAG, "fieldChanged, executing CPN extension");

        var item = nr.getCurrentSublistValue({sublistId: context.sublistId, fieldId: "item"});
        var customer = nr.getValue("entity");

        if(!customer || !item) return;

        //if (!parent || parent === "" || !item || item === "") return false; the === "" will never be evaluated
        // var parent = nr.getValue({ // this call doesn't exist
        //                 join: "entity",
        //                 fieldId: "parent",
        //                 name: "name" // where did you get this field id from?
        //             }); 

        const custInfo = Search.lookupFields({
            type:'customer',
            id:customer,
            columns:['internalid', 'entityid', 'parent']
        });

        // should have fully qualified customer name parent : sub-parent : customer


        var cpn = findPartNumber(custInfo.entityid, item);
        if (!cpn) return;

        nr.setCurrentSublistValue({sublistId: context.sublistId, fieldId: "custcol_cpn_transaction", value: cpn.id});
        nr.setCurrentSublistValue({sublistId: context.sublistId, fieldId: "custcol24", value: cpn.customer});
        Log.debug(TAG, "Found CPN: " + JSON.stringify(cpn));
        return; // field changed is void; no return value
    }


    /**
     * Search for the customer part number, assumes there is only ever a single result
     * @param customer
     * @param item
     * @returns {id: cpn record id, customer: customerId owning the cpn} | null
     */

    function findPartNumber(custInfo, item) {

        var cpnFilters = null;

        var commonColumns = [
                Search.createColumn({'name': 'entityid', join:'custrecord_cpn_customer'}),
                Search.createColumn({'name': 'custrecord_cpn_customer'})
            ];

        if(custInfo.parent && custInfo.parent.length){
            cpnFilters = [
                ["custrecord_cpn_item","anyof",item], 'AND',
                [
                    ["custrecord_cpn_customer","anyof",custInfo.parent[0].value], 'OR', // the top level
                    getCustHierarcyClauses(custInfo)
                ]
            ];

        }else{
           cpnFilters = [
                ["custrecord_cpn_customer","anyof",custInfo.internalid],
                "AND",
                ["custrecord_cpn_item","anyof",item]
            ];
        }

        var bestCPN = null;

        Search.create({
            type: "customrecord_true_cpn",
            filters:cpnFilters,
            columns: commonColumns
        }).run().each(function(result){
            if(!bestCPN) {
                bestCPN = {
                    id:result.id, 
                    entity: result.getValue({name:'entityid', join:'custrecord_cpn_customer'}),
                    customer:result.getValue({name:'custrecord_cpn_customer'})
                };
            } else{ // need to get the closest defined CPN;  assumes lower level of company could have their own preferred CPN.
                var testCPN = {
                    id: result.id,
                    entity: result.getValue({name:'entityid', join:'custrecord_cpn_customer'}),
                    customer:result.getValue({name:'custrecord_cpn_customer'})
                };
                if(testCPN.entity.length > bestCPN.entity.length) bestCPN = testCPN;
            }
            return true;
        });
        return bestCPN;
    }

    function getCustHierarcyClauses(custInfo){
        var fullNames = custInfo.entityid.split(' : ').slice(0, -1); // last name is the direct company name and no inference needed

        var filters =  ["custrecord_cpn_customer","anyof",custInfo.internalid]; 
        var topParentId = custInfo.parent[0].value;

        if(fullNames.length == 1){ // shouldn't have gotten here if only 1
            return filters;
        }

        for(var i = 1; i< fullNames.length; i++){
            filters.push('OR', [
                ["custrecord_cpn_customer.parent","anyof",topParentId], 'AND',
                ["custrecord_cpn_customer.entityid","is",fullNames.slice(0,i).join(' : ')] // need to qualify by name because we only want direct line of hierarchy
            ]);
        }
        return filters;


    }
 

    return {
        postSourcing: fieldChanged
    };
});

暂无
暂无

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

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