Trigger Workflow from Script Netsuite - javascript

Okay, I have decided to strip this one back to the bare bones based on the Netsuite documentation and go from there.
With the below in place I receive the following error still -
"Syntax error: missing : after property id"
Any help is greatly appreciated.
/**
* #NApiVersion 2.0
* #NScriptType UserEventScript
*/
require(['N/task'],
function(task) {
var workflowTask = task.create({taskType: task.TaskType.WORKFLOW_TRIGGER});
workflowTask.recordType = 'customer';
workflowTask.recordId = 107;
workflowTask.workflowId = 3;
var taskId = workflowTask.submit();
return {
workflowTask};
});

Looks like you are missing the entry points for the UserEvent script. I don't see something like
exports.beforeSubmit = beforeSubmit;
exports.beforeLoad = beforeLoad ;
exports.afterSubmit = afterSubmit ;
return exports;

Related

In karate DSL how do i call javascript function in the 'Then' statement

I have written a JavaScript function but i'm unable to call it in the 'Then' statement of my request. I need the syntax to call a JavaScript function in the same
Background:
* def randomPhoneString = function(list) { var rand = Math.random(); Math.floor(rand * 100000000);}
Scenario: Get list
Given path '/example/test'
When method get
Then status 200
Then def resp = response.list
Then def List = randomPhoneString(resp)
Not a great example but it would be a usecase like this.
The error I'm getting is :
javascript evaluation failed: randomPhoneString(list)
Yes, your example is terrible :P it is still not clear what you are trying to do. I just tried this and it worked:
* def randomPhoneString = function() { var rand = Math.random(); return Math.floor(rand * 100000000) + '' }
* def temp = randomPhoneString()
* print temp
It printed:
[print] 59303272

Issue Searching NetSuite - nlapiSearchRecord

I am having trouble understanding what this error means.
org.mozilla.javascript.EcmaError: ReferenceError: "nlapiSearchRecord"
is not defined. (/SuiteScripts/PreventDuplicateCustomer.js#35)
I am attempting to create a script which searches for a duplicate record based on a specific field which is supposed to be unique. I would like to prevent creating duplicate 'CUSTOMER' records in NetSuite using the following script.
'
Does anyone see anything that jumps of the page as wrong with the code below?
// 2.0
define(["N/error", "N/log"], function (err, log) {
/**
* User Event 2.0 example showing usage of the Submit events
*
* #NApiVersion 2.x
* #NModuleScope SameAccount
* #NScriptType UserEventScript
* #appliedtorecord customer
*/
var exports = {};
function beforeSubmit(scriptContext) {
log.debug({
"title": "Before Submit",
"details": "action=" + scriptContext.type
});
if (doesCustomerExist(scriptContext)) {
throw err.create({
"name": "DUPLICATE_SFDC_ACCOUNT_ID",
"message": "Customer Already Contains SFDC Account Id",
"notifyOff": true
});
}
}
function doesCustomerExist(scriptContext) {
var sfdcAccountId = scriptContext.newRecord.getValue('custentitysfdc_account_id');
if(sfdcAccountId == null || sfdcAccountId == '') return false;
var searchFilter = new nlobjSearchFilter('custentitysfdc_account_id', null, 'is', sfdcAccountId, null);
var searchResult = nlapiSearchRecord('customer', null, searchFilter, null);
return (searchResult != null && searchResult.length > 0);
}
exports.beforeSubmit = beforeSubmit;
return exports;
});
nlapiSearchRecord() is a SuiteScript 1.0 function and you're trying to call it from a SuiteScript 2.0 script.
You need to add the N/search module to your 2.0 script and use the functionality provided in that module to perform a search. In the NetSuite help documentation, navigate to SuiteCloud -> SuiteScript 2.0 -> SuiteScript 2.0 API -> SuiteScript 2.0 Modules -> N/Search Module to learn how to perform a search with SuiteScript 2.0.

How to include js files in header of wordpress pages that are activated on-click

I am attempting to use wordpress to build a website that integrates google maps. I am doing some overlays with the maps and use the google developers API and Python to make the appropriate javascript. I have successfully written the js files and Python necessary to accomplish this.
My website is built in Worpress and I would like add a page (not the home page) that has n links and each one would populate a box with the corresponding map. I can take care of the layout and design issues but I am at a loss on how to:
a) Include the javascript as a file that
b) gets called upon clicking the link and thus populates that map without calling a new page
That is, the javascript is HUGE because it may include thousands of lat/lon points. Therefore including n of these written into the header is unreasonable. I want to simply call it from filename.js when the link is clicked.
There is a plugin that allows me to include whatever I want in the header. So, if I can find out where to put the *.js files (or txt file) in the directory tree and how to have the corresponding file activated upon click I should be good. Thanks!
This Display different maps with onClick event - Google Maps V3. kind of helps with doing an on-click display but everyone's solution was to make one map. I cannot do that. I am overlaying vast amounts of data.
Here is a way you can get that done. (Jump down to the get started part of the script.)
For brevity, I've included a bunch of scripts in one 'file', but you'll want to break them in to individual files.
You may also need to try the html and js in jsbin js bin example, b/c SO may or may not allow the dynamic loading of js.
(function(undefined) {
/**
* #author (#colecmc)
* #method turn collection into an array
* #param {object} collection - NodeList, HTMLCollection, etc. Should have an "item" method and/or a "length" property
*/
ToArray = collection => Array.prototype.slice.call(collection);
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
Observer = (function(undefined) {
/**
* pub sub
*/
'use strict';
var subUid = -1;
return {
topics: {},
subscribe: function(topic, func) {
/**
* #param {string} topic
* #param {function} func
* #returns {string} - a token such as '3'
* #example Observer.subscribe('any-valid-string',function(name,resp){
console.log(resp.prop);
});
*/
if (!Observer.topics[topic]) {
Observer.topics[topic] = [];
}
var token = (++subUid).toString();
Observer.topics[topic].push({
token: token,
func: func
});
return token;
},
publish: function publish(topic, args) {
/**
* #param {string} topic
* #param {object} args
* #returns {boolean} - true if topic is valid, false otherwise
* #example Observer.publish('any-valid-string',{
prop: 'this is a test'
});
*/
if (!Observer.topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = Observer.topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
},
unsubscribe: function unsubscribe(token) {
/**
* #param {string} token - value should be saved from the original subscription
* #example Observer.unsubscribe('2');
* #example Observer.unsubscribe(member); - where member is the value returned by Observer.subscribe();
*/
var m,
forEachTopic = function(i) {
if (Observer.topics[m][i].token === token) {
Observer.topics[m].splice(i, 1);
return token;
}
};
for (m in Observer.topics) {
if (Observer.topics.hasOwnProperty(m)) {
Observer.topics[m].forEach(forEachTopic);
}
}
return false;
}
};
}(undefined));
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
SetAttributes = function(el, attrs) {
/**
* #author (#colecmc)
* #method simple for in loop to help with creating elements programmatically
* #param {object} el - HTMLElement attributes are getting added to
* #param {object} attrs - object literal with key/values for desired attributes
* #example SetAttributes(info,{
* 'id' : 'utswFormInfo'
* 'class' : 'my-class-name'
* });
*/
'use strict';
var key;
for (key in attrs) {
if (attrs.hasOwnProperty(key)) {
el.setAttribute(key, attrs[key]);
}
}
return el;
};
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
GetScript = function(url, fullPath) {
/**
* #author (#colecmc)
* #version 1.0.4
* #requires Swlxws.SetAttributes, Swlxws.Observer
* #method dynamically add script tags to the page.
* #param {string} url - relative path and file name - do not include extension
* #param {string} fullPath - absolute path
* #example GetScript('myLocalScript');
* #example GetScript('','https://www.google-analytics.com/analytics.js');
*/
'use strict';
function onLoad(event) {
var result;
if (event.type === 'load') {
result = 1;
} else {
result = -1;
}
Observer.publish('get-script-onload-complete', {
successful: result,
eventData: event
});
}
var JSPATH = '/js/',
/* or where ever you keep js files */
el = document.createElement('script'),
attrs = {
defer: true,
src: null,
type: 'text/javascript'
};
/** look for a string based, protocol agnostic, js file url */
if (typeof fullPath === 'string' && fullPath.indexOf('http') === 0) {
attrs.src = fullPath;
}
/** look for any string with at least 1 character and prefix our root js dir, then append extension */
if (typeof url === 'string' && url.length >= 1) {
attrs.src = JSPATH + url + '.js';
}
SetAttributes(el, attrs);
el.addEventListener('load', onLoad);
el.addEventListener('error', onLoad);
document.body.appendChild(el);
return el;
};
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
/**
* Get Started
*/
function onClick(event) {
GetScript('', event.target.dataset.namespaceUrl);
}
Observer.subscribe('get-script-onload-complete', function(name, resp) {
/** check to make resp is what you expect, ie: the correct script loaded */
/** then it is safe to use */
});
ToArray(document.querySelectorAll('.load-scripts')).map(script => script.addEventListener('click', onClick, false));
}(undefined));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>How to include js files in header of wordpress pages that are activated on-click</title>
</head>
<body>
Load Google Analytics
</body>
</html>
You can use the function wp_enqueue_script() to load the necessary JS files on only the templates you want.
As for your large data set, I recommend that you cache it in an external .json file and use wp_enqueue_script() to load it only when necessary.
Well if the onclick event suggestion is pretty much what you want and you are just concerned about the large amount of data. Then there are a few ways to tackle it. I am not sure if the dataset is a js file or php/json files but i came across a similar issue on one of my projects, dont remember properly but i was doing something with maxmind's ip/location data set.
So i just splitted the large file into 3 smaller ones. Then i looped through each of the file and if the stuff that i was looking for was found in the file then i just breaked out. And definitely as Brian suggested caching and using a CDN would help a lot.

setConsoleIcon throwing weird error (Undocumented WinAPI to JS-Ctypes)

There's this undocumend winapi fetarue called setConsoleIcon. I discussed with this guy here:
https://github.com/john-peterson/john-peterson/issues/1#issuecomment-47852560
The C++ code is this:
void SetIcon(LPCTSTR icon) {
HMODULE hMainMod = GetModuleHandle(NULL);
HICON hMainIcon = ::LoadIcon(hMainMod, icon);
HMODULE hMod = LoadLibraryA("Kernel32.dll");
typedef BOOL (CALLBACK *InsHook)(unsigned long, HANDLE);
typedef DWORD (__stdcall *SCI)(HICON);
SCI pfnSetConsoleIcon = reinterpret_cast<SCI>(GetProcAddress(hMod, "SetConsoleIcon"));
pfnSetConsoleIcon(hMainIcon);
FreeLibrary(hMod);
}
I converted it to this:
Cu.import('resource://gre/modules/ctypes.jsm');
var kernel32 = ctypes.open('kernel32.dll');
var user32 = ctypes.open('user32.dll');
var SetConsoleIcon = kernel32.declare('SetConsoleIcon', ctypes.winapi_abi, ctypes.voidptr_t, // i have no idea what return value is so made it voidptr_t
ctypes.voidptr_t // HICON
);
/* http://msdn.microsoft.com/en-us/library/windows/desktop/ms648045%28v=vs.85%29.aspx
* HANDLE WINAPI LoadImage(
* __in_opt_ HINSTANCE hinst,
* __in_ LPCTSTR lpszName,
* __in_ UINT uType,
* __in_ int cxDesired,
* __in_ int cyDesired,
* __in_ UINT fuLoad
* );
*/
var LoadImage = user32.declare('LoadImageA', ctypes.winapi_abi, ctypes.voidptr_t,
ctypes.voidptr_t,
ctypes.char.ptr,
ctypes.unsigned_int,
ctypes.int,
ctypes.int,
ctypes.unsigned_int
);
var IMAGE_BITMAP = 0;
var IMAGE_ICON = 1;
var LR_LOADFROMFILE = 16;
var aDOMWindow = window;
var baseWindow = aDOMWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.treeOwner
.QueryInterface(Ci.nsIInterfaceRequestor)
.nsIBaseWindow;
var nativeHandle = baseWindow.nativeHandle;
var targetWindow_handle = ctypes.voidptr_t(ctypes.UInt64(nativeHandle));
var hIconBig = LoadImage(targetWindow_handle, 'C:\\Users\\noit\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\1agqx535.default2\\profilist32.ico', IMAGE_ICON, 256, 256, LR_LOADFROMFILE);
var hIconBigNull = LoadImage(null, 'C:\\Users\\noit\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\1agqx535.default2\\profilist32.ico', IMAGE_ICON, 256, 256, LR_LOADFROMFILE);
var void = SetConsoleIcon(hIconBig); //SetConsoleIcon(hIconBigNull);
If you comment out the final line and copy and run this you get no problems.
However if you uncomment it and use it with hIconBig or hIconBigNull you get this error:
(difference between two, is to hIconBig I pass window handle and to hIconBigNull i pass null as handle)
/*
"missing variable name
WCA_evalWithDebugger#resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:1069:7
WCA_onEvaluateJS#resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/actors/webconsole.js:734:9
DSC_onPacket#resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/server/main.js:1098:9
LDT_send/<#resource://gre/modules/devtools/dbg-client.jsm -> resource://gre/modules/devtools/server/transport.js:279:11
makeInfallible/<#resource://gre/modules/commonjs/toolkit/loader.js -> resource://gre/modules/devtools/DevToolsUtils.js:84:7"
*/
I can't explain this missing variable name. Any ideas?
The problem here is your var void = .... void is a reserved keyword in Javascript and therefore cannot be used in as a variable name.
Other random observations:
Use ctypes.void_t when declaring functions that are void or where you don't care about the return value.
Never call LoadImage with a window handle. It is supposed to be called with a module handle or null. You'll want to call it with null, since you're loading stand-alone images.
Using undocumented APIs is not a very good idea in general, and should be avoided if feasible. I know that first getting the console window handle with GetConsoleWindow() and then sending WM_SETICON works just fine, and that is using documented functionality.
I have no idea what you're trying to do here anyway. Firefox has (normally) no console window at all.

JSDoc auto-complete documentation in Eclipse is not working for Class.create()

I have something like:
/**
* #class
*/
NS.MyAwesomeObject = Class.create();
NS.MyAwesomeObject.prototype = {
/**
* #param id - the id
* #return - an alert dialog with an id
*/
initialize : function(id){
alert(id);
}
}
Am I missing something? I get up to NS. -> auto-complete: MyAwesomeObject, but I want NS.MyAwesomeObject. -> auto-complete: initialize(id).
It works fine for other cases when I don't use Class.create(). I googled and the solution was to add #class, but that didn't work for me.
Thanks!
It works by me. Btw Eclipse doesn't have jsDoc 3 support.
With jsDoc 3 your code looks so:
var NS = {};
/** #class */
NS.MyAwesomeObject = Class.create(
/** #lends NS.MyAwesomeObject.prototype */
{
/**
* #constructs
* #param {Number} id - the id
* #returns {Void} - an alert dialog with an id
*/
initialize:function (id) {
alert(id);
}
});
The code completion for jsDoc 3 works only with WebStorm (or others Jetbrains products) now.
Oo javascript code completion in any IDE (Had problem with this either.)

Categories

Resources