How can i start a scheduled script with a button? - button

i want to create a button in a form that executes a scheduled script but nothing that i try works
I have tried the method addButton to call a function that create a task for the scheluded script but it only execute on form load
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(["N/task", "N/ui/serverWidget"], function(task, serverWidget) {
function beforeLoad(context) {
context.form.addButton({
id: "custpage_setTask",
label: "Execute scheduled",
functionName: executeScheduled()
});
}
return {
beforeLoad: beforeLoad
};
function executeScheduled() {
var scriptTask = task.create({
taskType: task.TaskType.SCHEDULED_SCRIPT,
scriptId: 'customscript_sdr_ss_product_shortage',
deploymentId: 'customdeployprodshortsearch'
});
var scriptTaskId = scriptTask.submit();
log.debug('scriptTaskId', scriptTaskId);
}
});
that execute the scheduled script but only in the form loading and then the button does not do anything, please help and thanks for reading

I managed to do it at the end. It was creating 3 scripts, a user event that calls a client script, that do a get request to a suitelet with the function that creates the task for the scheduled script
This is the User event:
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define(["N/task", "N/ui/serverWidget"], function(task, serverWidget) {
function beforeLoad(context) {
// internal id of the client script on file cabinet
context.form.clientScriptFileId = 2343;
context.form.addButton({
id: "custpage_setTask",
label: "Execute scheduled",
functionName: 'redirect'
});
}
return {
beforeLoad: beforeLoad,
};
});
This is the client script:
/**
*#NApiVersion 2.x
*#NScriptType ClientScript
*/
define(["N/url", "N/https"], function(url, https) {
function pageInit(context) {}
function redirect() {
var output = url.resolveScript({
scriptId: "customscript_sss_sl_startschedulescript",
deploymentId: "customdeploy_sss_sl_startschedulescript"
});
log.debug('url', output);
var response = https.get({
url: output
});
log.debug('response', response);
}
return {
pageInit: pageInit,
redirect: redirect
};
});
and this is the suitelet:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(["N/task"], function(task) {
function onRequest(context) {
executeScheduled();
}
function executeScheduled() {
var scriptTask = task.create({
taskType: task.TaskType.SCHEDULED_SCRIPT,
scriptId: "customscript_sdr_ss_product_shortage",
deploymentId: "customdeployprodshortsearch"
});
var scriptTaskId = scriptTask.submit();
log.debug("scriptTaskId", scriptTaskId);
}
return {
onRequest: onRequest
};
});
I hope this helps another one with the same problem.

I believe you also need to export the button function.
return {
beforeLoad: beforeLoad,
executeScheduled:executeScheduled
};
You also need to change your button options
context.form.addButton({
id: "custpage_setTask",
label: "Execute scheduled",
functionName: executeScheduled
});

Related

Meteor subscribe is not loading data from the server

I am having difficulties with meteor 1.6. First, I have created a database instance and tried to subscribe in the client. through form, I am able to input the data into my database. But could not retrieve it through the subscribe. can anybody tell me what wrong have I done in my code?
import { Template } from "meteor/templating";
import { Notes } from "../lib/collection";
import { Meteor } from "meteor/meteor";
// import { ReactiveDict } from 'meteor/reactive-dict';
import "./main.html";
/*
Template.body.onCreated(function bodyOnCreated() {
this.state = new ReactiveDict();
Meteor.subscribe("db1");
}); */
Template.Display.helpers({
notes() {
Meteor.subscribe("db1");
return Meteor.call('data');
}
});
Template.body.events({
"click .delete": function() {
Notes.remove(this._id);
},
"submit .formSubmit": function(event) {
event.preventDefault();
let target = event.target;
let name = target.name.value;
Meteor.call("inputs", name);
target.name.value = "";
return false;
},
"click .userDetail": function() {
if (confirm("Delete the user Detail ?")) {
Notes.remove(this._id);
}
}
});
here is the code for publication :
import { Mongo } from 'meteor/mongo';
export const Notes = new Mongo.Collection('notes');
Meteor.methods({
inputs:(name)=> {
if (!Meteor.user()) {
throw Meteor.Error("Logged in");
}
Notes.insert({
name: name,
createdAt: new Date()
});
},
data:()=>{
return Notes.find({});
}
});
Meteor.subscribe("notes"); should be in Template.body.onCreated lifycycle method. you need to write a
publish code seperately and not inside the Meteor.method. see below format,
Meteor.publish('notes', function tasksPublication() {
return Notes.find({});
});
Inside the helper just call the subscribed Collection a below,
Template.Display.helpers({
notes() {
return Notes.find({});
}
});
**NOTE: ** Never use Meteor.call inside the helper method. helpers are reactive and real time.

Creative sdk: How to get Base64 image data after save

How I can get the base64 format while saving the image?
onSave: function(imageID, newURL) {
originalImage.src = newURL;
featherEditor.close();
}
Here is some code I used in an Angular 1 / Cordova (Phonegap) app, obviously you might want to strip out the promises, and its also not in any way refactored (just two copy/paste jobs) but does the the treat. You also need the cordova file plugin installed.
function _launchEditor(imageUrl, options) {
/* 2.a) Prep work for calling `.edit()` */
var deferred = $q.defer();
function success(newUrl) {
/**
* This function will handle the conversion from a file to base64 format
*
* #path string
* #callback function receives as first parameter the content of the image
*/
function getFileContentAsBase64(path, callback) {
window.resolveLocalFileSystemURL(path, gotFile, error);
function gotFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
var content = this.result;
callback(content);
};
// The most important point, use the readAsDatURL Method from the file plugin
reader.readAsDataURL(file);
});
}
}
getFileContentAsBase64(newUrl, function (base64Image) {
//window.open(base64Image);
// Then you'll be able to handle the myimage.png file as base64
deferred.resolve({
data: base64Image,
url: newUrl
})
});
}
function error(error) {
deferred.reject(error);
}
if (!options) {
options = {
outputType: CSDKImageEditor.OutputType.JPEG,
tools: [
CSDKImageEditor.ToolType.CROP,
CSDKImageEditor.ToolType.ORIENTATION,
CSDKImageEditor.ToolType.TEXT,
CSDKImageEditor.ToolType.DRAW
],
quality: 50
}
}
/* 2.b) Launch the Image Editor */
CSDKImageEditor.edit(success, error, imageUrl, options);
return deferred.promise;
}
Then just call with
_launchEditor(<ImageUrl>)
.then(function(data){
//data.url = creativesdk saved image url
//data.data = base64 image data
})

Lambda nodeJS 4.3 not finishing/executing success callback

Despite running the log statement immediately above it, my call to callback(null) isn't working. Even tried wrapping it in a try catch block but got nothing.
For reference, here's the full function:
var Firebase = require('firebase');
var request = require('request');
//noinspection AnonymousFunctionJS
/**
*
* #param event - from Lambda
* #param context - from Lambda
* #param callback - from Lambda
*/
exports.handler = function (event, context, callback) {
var AUTOPILOT_API_KEY = getKey(event.stage, 'AUTOPILOT_API_KEY');
var AUTOPILOT_JOURNEY_ID = getKey(event.stage, 'AUTOPILOT_JOURNEY_ID');
activate();
function activate () {
console.log('event:', event);
if (validPayload(event, context)) {
addDefaultPresets(event.uid);
addToAutopilot(event.user, event.uid);
}
}
/**
* checks that the necessary payload has been received
* if YES: returns true and allows process to continue
* if NO: throws context.fail with useful error message(s)
* operating under custom error code naming convention of
* http code + 3 digit ULM error code
* #param event - from Lambda
* #param context - from Lambda
* #returns {boolean} - whether the payload contains the required data
*/
function validPayload (event, context) {
return true; // REDACTED FOR BREVITY
}
/**
* Adds the user to Autopilot as a contact and adds them
* to the journey with trigger id 0001
* #param {Object} user
* #param {string} uid generate by Firebase as unique identifier of registered user
*/
function addToAutopilot (user, uid) {
// REDACTED FOR BREVITY
request({
method: 'POST',
url: 'https://api2.autopilothq.com/v1/trigger/' + AUTOPILOT_JOURNEY_ID + '/contact',
headers: {
'autopilotapikey': AUTOPILOT_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}, function (error, response, body) {
//noinspection MagicNumberJS
if (response.statusCode !== 200) {
errorResponse.status = response.statusCode;
errorResponse.error = {
errorMessage: error,
user: event.user,
response: response,
body: body
};
console.log('should throw ERROR callback');
context.fail(JSON.stringify(errorResponse));
} else {
console.log('should throw SUCCESS callback');
console.log(JSON.stringify({
status: response.statusCode,
message: "User successfully added to Autopilot account & journey"
}));
callback(null);
}
console.log('Finished addToAutopilot()');
});
}
/**
* Adds a collection of presets the the account of the new user
* #param uid {String} - Firebase UID
*/
function addDefaultPresets (uid) {
// REDACTED FOR BREVITY
var presets = ref.child('users').child(uid).child('presets');
console.log('Starting addDefaultPresets()');
activate();
function activate () {
console.info('activating...');
// for each field
fields.forEach(function (field) {
// iterate over each preset
presetData[field].forEach(function (label) {
// and add to firebase db via addDefaultPreset() if unique
presetIsUnique(field, label);
})
});
console.log('Finished addDefaultPresets()');
}
function presetIsUnique (field, label) {
presets.child(field).orderByChild('label')
.equalTo(label)
.once('value', function (snapshot) {
var val = snapshot.val();
if (!val) {
addDefaultPreset(field, label);
} else {
console.error('already exists', field, label);
}
});
}
function addDefaultPreset (field, label) {
//noinspection MagicNumberJS
presets.child(field).push().set({
creator: 'default',
dateAdded: Math.floor(Date.now() / 1000),
label: label
}, setCallback);
}
function setCallback (err) {
if (err) {
console.error(err);
} else {
console.info('added preset');
}
}
}
function getKey (stage, keyId) {
var keys = {
AUTOPILOT_API_KEY: {
staging: 'dev123',
prod: 'prod123'
},
AUTOPILOT_JOURNEY_ID: {
staging: 'XXX',
product: 'XXXX'
},
FIREBASE_URL: {
staging: 'https://staging.firebaseio.com/',
prod: 'https://prod.firebaseio.com/'
}
};
if (stage === 'prod') {
return keys[keyId][stage];
} else {
return keys[keyId]['staging'];
}
}
};
It seems like firebase is keeping something in the event loop. By default, lambda waits until the event loop is empty before terminating. You can set context.callbackWaitsForEmptyEventLoop = false to tell lambda to terminate the function soon after the callback is called, even if there is still items in the event loop.
After hours and hours of debugging here is something that worked for me:
var firebase = require('firebase');
var app = firebase.initializeApp(config);
...
...
...
app.delete().then(function(){
var response = {
statusCode: 200,
body: JSON.stringify({
message: 'Success'
}),
};
callback(null, response);
});
You can read more about delete in the official documentation:
Make the given App unusable and free the resources of all associated
services.
Hope this is helpful!

How do I dynamically publish collections via a Meteor method?

I dynamically create collections with this method:
createPlist: function(jid) {
try {
Plist[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log("oops, I did it again");
}
Plist[jid].insert({
...,
...,
public:true,
uid:this.userId
});
}
Then I am wanting to publish these selectively, and I am attempting to do it via a method:
getPlist: function(jid,pid) {
// var future = new Future();
try {
Plist[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log("oops, I did it again");
}
Meteor.publish(pid, function() {
console.log(Plist[jid].find({}));
// future["return"](Plist[jid].find({}));
return Plist[jid].find();
});
// return future.wait();
},
This returns 'undefined' to my Template helper, and returns nothing (i.e. waits forever) using Future.
Any user can log in and create a Plist collection, which can be either public or not. A user can also subscribe to any collection where public is true. The variable jid is passed to the method 'getPlist' from the template. It is stored in the user's Session.
Thanks! I hope I have explained it well enough!
And of course the template:
Template.plist.helpers({
getPlist: function() {
Pl = []
jid = Session.get('jid');
//alert(jid);
pid = "pl_"+jid;
// console.log(pid);
Meteor.call('getPlist', jid, pid, function(err,res) {
console.log(res); //returns undefined
try {
Pl[jid] = new Meteor.Collection(pid);
} catch(e) {
console.log(e);
}
Meteor.subscribe(pid);
// return Pl[jid].find({}).fetch();
});
}

iron-router except fails?

So i'm just getting started with iron-router, and I've been building a login system. It works via a .onBeforeAction hook before every route, checking if the user is logged in. However, there are a few routes I want public, so I've added an except option, as per the docs. Except the problem is it doesn't work :( can anybody see why?
Router.route('/new', function () {
name: 'new',
this.render('newComp');
});
Router.route('/c/:_id', {
name: 'compPage',
data: function() { return Comps.findOne(this.params._id); }
});
Router.route('/c/:_id/embed', function () {
name: 'embed',
this.layout('empty'),
this.render('compEmbed', {
data: function () {
return Comps.findOne({_id: this.params._id});
}
});
});
function loginFunction(){
// all properties available in the route function
// are also available here such as this.params
if (!Meteor.user()) {
// if the user is not logged in, render the Login template
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.layout('empty');
this.render('login');
}
} else {
// otherwise don't hold up the rest of hooks or our route/action function
this.next();
}
}
Router.onBeforeAction( loginFunction, {
except: ['embed'] // this aint working
});
The problem seems to be in your route definition, the name param should be in the third param of Router.route(), like this (so your route actually didn't have a name, thus the except:['route.name'] doesn't work):
Router.route('/c/:_id/embed', function () {
this.layout('empty'),
this.render('compEmbed', {
data: function () {
return Comps.findOne({_id: this.params._id});
}
});
}, {
name: 'embed',
});
More info about named routes here: http://eventedmind.github.io/iron-router/#named-routes

Resources