How to send Email with Letter Template Using suite script - netsuite

I am trying to send an email using suitescript2 i am trying to attach the the Letter template programaticaly. Is there any way attach my custom letter template?
function templatemerge() {
var myMergeResult = render.mergeEmail({
templateId: 12,
entity: {
type: 'customer',
id: 31921
},
recipient: {
type: 'customer',
id: 31921
},
supportCaseId: 'NULL',
transactionId: 'NULL',
customRecord: 'custrecordid'
});
}
templatemerge();
function sendEmailWithAttachement() {
var newId = context.newRecord;
var emailbody = 'attachment';
var senderId = -5;
var recipientEmail = 'red#imi.com';
email.send({
author: senderId,
recipients: recipientEmail,
subject: 'Item Fulfillments',
body: emailbody
});
}
sendEmailWithAttachement();

If, by letter template, you mean email template. Here is a basic idea (I pulled that part from a larger script file that I am using) of how to do it.
var emailTemp4=nlapiLoadRecord('emailtemplate',emailTempID4);
var emailSubj4=emailTemp4.getFieldValue('subject');
var emailBody4=emailTemp4.getFieldValue('content');
var renderer4=nlapiCreateTemplateRenderer();
renderer4.setTemplate(emailSubj4);
renderSubj4=renderer4.renderToString();
renderer4.setTemplate(emailBody4);
renderBody4=renderer4.renderToString();
nlapiSendEmail(-4,'RecipientEmail#domain.com',renderSubj4,renderBody4,null,null);

Related

I want to merge json data fetched from first api to second api data. Both api have userid as parameter in common. Please help me

app.get("/user/:id", (request, res)=>{
async function getToDoUser(){
const todoData = await fetch('https://jsonplaceholder.typicode.com/todos');
this api contains 200 entries
const response = await todoData.json();
const kuch = request.params.id;
const todoUserData = await fetch(`https://jsonplaceholder.typicode.com/users/${kuch}`);
this api will only give one entry
const userResponse = await todoUserData.json();
let responseArray = [];
var todos = {};
var target = {};
for(let i = 0; i<response.length;i++){
todos = new todoModel({
userId: response[i]["userId"],
id: response[i]["id"],
title: response[i]["title"],
completed: response[i]["completed"]
})
I have added the entries from 1st api
responseArray.push({userId: response[i]["userId"],
id: response[i]["id"],
title: response[i]["title"],
completed: response[i]["completed"]
})
}
const todoUser = new todoUserModel({
userid: userResponse["userid"],
name: userResponse["name"],
username: userResponse["username"],
email: userResponse["email"],
address: {
street: userResponse['address["street"]'],
suite: userResponse['address["suite"]'],
city: userResponse['address["city"]'],
zipcode: userResponse['addresss["zipcode"]'],
geo: {
lat:userResponse['address[geo["lat"]]'],
lng: userResponse['address[geo["lng"]]']
}
},
phone: userResponse["phone"],
website: userResponse["website"],
company: {
name: userResponse['company["nam"]'],
catchPhrase: userResponse['company["catchPhrase"]'],
bs: userResponse['company["bs"]']
},
till here 2nd api gives data and from here i want to add data from 1st api where the user id should be equal
todo: {
userId: response['0']['userid'],
userid in todo should be equal to userid in todoUser
all entries from todo with userid same as userid in todouser api
id: response['0']['id']
}
})
_.extend(target, todoUser);
// here i have merged data from todouser to new json object named target
res.send(target);
// here sending response
}
getToDoUser();
})

Suitescript: Workflow Action script sent emails not appearing in transaction tab

I have created a workflow action script to send emails so that I can process the incoming messages later on with a email plugin (this might be redundant though I am just experimenting with workflow action scripts at the moment)
This is the script:
/**
*#NApiVersion 2.x
*#NScriptType WorkflowActionScript
*/
define(["N/email", "N/render", "N/record"], function (email, render, record) {
function onAction(context) {
var transaction = context.newRecord;
var transactionId = transaction.getValue({ fieldId: "tranid" });
log.debug("transaction Id", transactionId);
var recipient = transaction.getValue({
fieldId: "custbody_first_approver",
});
var recipientId = parseInt(recipient);
var vendorId = transaction.getValue({ fieldId: "entity" });
var mergeResult = render.mergeEmail({
templateId: 11,
entity: {
type: "vendor",
id: parseInt(vendorId),
},
recipient: {
type: "employee",
id: parseInt(recipient),
},
supportCaseId: null,
transactionId: transactionId,
customRecord: null,
});
var emailSubject = mergeResult.subject;
var emailBody = mergeResult.body;
email.send({
author: -5,
recipients: parseInt(recipient),
subject: "test",
body: emailBody,
relatedRecords: {
transactionId: transactionId,
},
});
}
return {
onAction: onAction,
};
});
The email is being sent though a copy of it only seems to be getting stored against the recipient's (who is an employee) entity record.
Looking at the Netsuite guide on the 'N/email' module, it suggests the
relatedRecords: {
transactionId: transactionId,
},
part of the script should be controlling where the message is stored. However, there is nothing in the transaction record under the related records or any other tab.
What do I need to change to get a copy of the email message saved against the transaction record?
Thanks
I found the cause of the issue. It was this line:
var transactionId = transaction.getValue({ fieldId: "tranid" });
It needed to be
var transactionId = transaction.getValue({ fieldId: "id" });
in order to pick up the internal id of the record and not just the transaction number.
All references to it in the script needed to be converted to integer values since otherwise I kept getting the "Wrong parameter type: options.transactionId is expected as number" error.
I converted this by using parseInt(transactionId) every time I referred to the transaction ID

Missing Stripe Connect Custom Account Information for Node.js

Currently working on server side info for Stripe connect and I'm having issues figuring out the correct parameters for creating a stripe connect account. I'm stuck on tax_id (ein) at the moment. Can someone please give me the correct abbreviation for this any others I may be missing on Node.js.
For example when it came to the name of the business Stripes API just say "name". Yet I kept getting the error 'Received unknown parameters: name'. But after some help looking online I saw that the correct way was to write out 'business_name' even through this was no where in the Stripe API.
here is my code: Hope this helps guide some people in the right direction as well (:
app.post('/newConnectCompanyAcct', (req, res) => {
// Creating New Connect Account...
//User
var company = req.body.business_name
var ein = req.body.business_tax_id
var first = req.body.first_name
var last = req.body.last_name
var email = req.body.email
var phone = req.body.phone
var birthDay = req.body.birthDay
var birthMonth = req.body.birthMonth
var birthYear = req.body.birthYear
var ssn = req.body.personal_id_number
var time = req.body.Time
var ip = req.body.iP
//Acct Type
var type = req.body.type
//Address
var line1 = req.body.line1
var line2 = req.body.line2
var zipcode = req.body.postal_code
var city = req.body.city
var state = req.body.state
var lastFour = req.body.lastFour
console.log('the email ' + email);
console.log('the phone ' + phone);
stripe.accounts.create({
type: "custom",
country: 'US',
requested_capabilities: ['card_payments','transfers'],
product_description: "example description",
mcc: "7299",
business_name: company,
tax_id: ein,
legal_entity: {
address: {
line1: line1,
line2: line2,
postal_code: zipcode,
city: city,
state: state
},
// relationship: {
// representative: true,
// title: "Manager"
// },
dob: {
day: birthDay,
month: birthMonth,
year: birthYear
},
first_name: first,
last_name: last,
type: type,
personal_phone_number: phone,
personal_email: email,
ssn_last_4: lastFour,
personal_id_number: ssn,
personal_address: {
line1: line1,
line2: line2,
postal_code: zipcode,
city: city,
state: state
}
},
tos_acceptance: {
date: Math.floor(Date.now() / 1000),
ip: ip
}
}).then((accounts) => {
console.log(accounts)
// Send customerId -> Save this for later use
return res.status(200).send(accounts.id)
}).catch((error) => {
console.log('error while creating new account' + error)
return res.status(500).send(JSON.stringify({ success: false, error: error }))
});
});

Generate GUID at runtime without using form in NetSuite

Hye there,
I'm trying to prepare a scheduled script in NetSuite which will pick a particular directory from file cabinet and deploy it on SFTP server. I'm using 2.0 module and here is my code -
require(["N/sftp",'N/record','N/file'], function(sftp,record,file) {
function onRequest() {
var myPwdGuid = "13139ac567b14f74bdaXXXXXXX";
var myHostKey = "AAAAB3NzaC1ycXXXXX";
var connection = sftp.createConnection({
username: 'Your user name',
passwordGuid: myPwdGuid,
url: 'Your host name',
directory: '/directory to upload files/',
hostKey: myHostKey
});
var myFileToUpload = file.create({
name: 'originalname.js',
fileType: file.fileType.PLAINTEXT,
contents: 'I am a test file. Hear me roar.'
});
connection.upload({
directory: 'relative/path/to/remote/dir',
filename: 'newFileNameOnServer.js',
file: myFileToUpload,
replaceExisting: true
});
var downloadedFile = connection.download({
directory: 'relative/path/to/file',
filename: 'downloadMe.js'
});
}
onRequest();
return {
onRequest: onRequest
};
});
Now the issue is when i try to run these lines of code i get an error saying "AN_ERROR_OCCURRED_WHILE_DECRYPT_PASSWORDGUID".
What i've found so far through my research is GUID can only be generated by SuitLet form having credential field which will again require GET and POST method. However i Dont want to create a suitelet and invoke it manually in order to generate GUID. All i want to to do is - Run a scheduled script which will Establish connection to SFTP. Pick a directory in file cabinet and upload it on SFTP.
Any help would be greatly appreciated! Thanks in advance!
Its easier and faster than you might think. Take the below code and load it to NetSuite. Create a script file and deployment quick, run the SUITElet to get your GUID, paste that value into your Scheduled Script and don't mess with it again unless the password changes.
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define([
'N/ui/serverWidget',
'N/https'
],
function (
ui,
https
) {
var HOST_KEY_TOOL_URL = 'https://ursuscode.com/tools/sshkeyscan.php?url=';
function getFormTemplate() {
var form;
form = ui.createForm({
title: 'Password Form'
});
form.addSubmitButton({
label: 'Submit'
});
return form;
}
function addSelectorFields(form) {
var select = form.addField({
id: 'selectaction',
type: ui.FieldType.SELECT,
label: 'Select Action'
});
select.addSelectOption({
value: 'getpasswordguid',
text: 'Get Password GUID'
});
select.addSelectOption({
value: 'gethostkey',
text: 'Get Host Key'
});
return form;
}
function addPasswordGUID1Fields(form) {
var frm = form;
frm.addField({
id: 'restricttoscriptids',
type: ui.FieldType.TEXT,
label: 'Restrict To Script Ids'
}).isMandatory = true;
frm.addField({
id: 'restricttodomains',
type: ui.FieldType.TEXT,
label: 'Restrict To Domains'
}).isMandatory = true;
return frm;
}
function addPasswordGUID2Fields(form, restrictToScriptIds, restrictToDomains) {
form.addCredentialField({
id: 'password',
label: 'Password',
restrictToScriptIds: restrictToScriptIds.replace(' ', '').split(','),
restrictToDomains: restrictToDomains.replace(' ', '').split(',')
});
return form;
}
function addHostKeyFields(form) {
form.addField({
id: 'url',
type: ui.FieldType.TEXT,
label: 'URL (Required)'
});
form.addField({
id: 'port',
type: ui.FieldType.INTEGER,
label: 'Port (Optional)'
});
form.addField({
id: 'hostkeytype',
type: ui.FieldType.TEXT,
label: 'Type (Optional)'
});
return form;
}
function onRequest(option) {
var method;
var form;
var selectAction;
var port;
var hostKeyType;
var restricttoscriptids;
var restricttodomains;
var password;
var theResponse;
var myUrl;
var url;
method = option.request.method;
form = getFormTemplate(method);
if (method === 'GET') {
form = addSelectorFields(form);
}
if (method === 'POST') {
selectAction = option.request.parameters.selectaction;
if (selectAction === 'getpasswordguid') {
form = addPasswordGUID1Fields(form);
} else if (selectAction === 'gethostkey') {
form = addHostKeyFields(form);
} else {
password = option.request.parameters.password;
url = option.request.parameters.url;
port = option.request.parameters.port;
hostKeyType = option.request.parameters.hostkeytype;
restricttoscriptids = option.request.parameters.restricttoscriptids;
restricttodomains = option.request.parameters.restricttodomains;
if (restricttoscriptids && restricttodomains) {
form = addPasswordGUID2Fields(form, restricttoscriptids, restricttodomains);
}
if (password) {
form.addField({
id: 'passwordguidresponse',
type: ui.FieldType.LONGTEXT,
label: 'PasswordGUID Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = password;
}
if (url) {
myUrl = HOST_KEY_TOOL_URL + url + '&port=' + port + '&type=' + hostKeyType;
theResponse = https.get({ url: myUrl }).body;
form.addField({
id: 'hostkeyresponse',
type: ui.FieldType.LONGTEXT,
label: 'Host Key Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = theResponse;
}
}
}
option.response.writePage(form);
}
return {
onRequest: onRequest
};
});
The ability to directly hard-code an SFTP password is not supported in NetSuite. NetSuite uses password tokenization in order to prevent scripts from having access to user credentials. For this reason, only an authenticated user may store a password, and a script may only access it via an identifier (GUID/Token).

Node + Mailchimp NPM: How to add a subscriber to a list and include their first and last name?

Mailchimp is almost a perfect company, except their Node API documentation is non-existent. How can I add a subscriber to my new list and include their first name and last name? The code below successfully adds the subscriber, but first and last names are not being added.
var MCapi = require('mailchimp-api');
MC = new MCapi.Mailchimp('***********************-us3');
addUserToMailchimp = function(user, callback) {
var merge_vars = [
{ EMAIL: user.email },
{ LNAME: user.name.substring(user.name.lastIndexOf(" ")+1) },
{ FNAME: user.name.split(' ')[0] }
];
MC.lists.subscribe({id: '1af87a08af', email:{email: user.email}, merge_vars: merge_vars, double_optin: false }, function(data) {
console.log(data);
}, function(error) {
console.log(error);
});
}; // addUserToMailchimp
The supplied merge variables should be passed as a single object, not an array of objects. Please see my example below:
var mcReq = {
id: 'mail-chimp-list-id',
email: { email: 'subscriber-email-address' },
merge_vars: {
EMAIL: 'subscriber-email-address',
FNAME: 'subscriber-first-name',
LNAME: 'subscriber-last-name'
}
};
// submit subscription request to mail chimp
mc.lists.subscribe(mcReq, function(data) {
console.log(data);
}, function(error) {
console.log(error);
});
It looks like you supplied your actual mail chimp API key in your question. If so, you should remove it immediately.

Resources