I have a problem with creating a json dynamically. I retrieve the data of a sent json:
body.value look like :
{
hubspotProperty: 'question3',
response: 'Nous utilisons un google drive mais il est très peu utilisé'
},
{
hubspotProperty: 'question2',
response: 'Nous complétons le CRM quand nous avons ' +
'le temps et au bon vouloir du commercial'
},
{
hubspotProperty: 'question1',
response: "Nous n'avons aucun processus " +
"automatisé et nous n'en voyons pas " +
"l'intérêt"
}
]
but I want the hubspot property to be the key of the new json and the response to be my I don't now how I can do this .
Help me please
Bonjour, the simplest way to make json:
var someValue = "Jean"
var jsonString = `{"nom":"${someValue}"}`
Take care of the "backwards ticks" `
Regarding the json which comes in to you:
var exampleJson = `{ "hubspotProperty": "question3" }`
It is this easy ...
var args = JSON.parse(exampleJson)
var value = args.hubspotProperty
console.log("it's done .. " + value)
Related
I'm trying to implement an email price alerts system. In my situation, one email can have multiple price alerts, thus, conflicting with SendGrid when sending the alert as it receives the following error:
message: 'Each email address in the personalization block should be ' +
'unique between to, cc, and bcc. We found the first duplicate ' +
'instance of [xxxxxxx#gmail.com] in the personalizations.0.to ' +
'field.',
field: 'personalizations.0',
help: 'http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.recipient-errors'
I have not found anything that shows my use case. The best that I get is to send the same email to multiple different recipients such as: https://sendgrid.com/docs/for-developers/sending-email/personalizations/#sending-the-same-email-to-multiple-recipients
Is this something that can be achieved with SendGrid?!
My function:
function sendEmail (emailz, subject, body) {
const email = {
to: emailz,
from: 'salut#xxxxxxxxx.ro',
subject: subject,
text: body,
html: body
}
return sgMail.send(email)
.catch(error => {
console.error(error)
if (error.response) {
const {message, code, response} = error;
const {headers, body} = response;
console.error(body);
}
});
}
Actual email sending done:
try {
await sendEmail(
emailul,
'Alerta notificare pret!!!',
`Pretul produsului pe care il urmaresti este de ${pretulCurent} , sub alerta de pret setata de ${pretulDorit}. <br /> Produsul tau este: ${titlul} : ${link} `
)
} catch (e) {
await sendEmail('S-a produs o eroare', e.message)
throw e
}
Any help would be greatly appreciated. If this cannot be done using SendGrid, can you give me some pointers on other services where this situation might apply ?
Okay, if I understand you correctly, the problem here seems to be avoiding duplicates in your to email field. I suggest you check for duplicates before pushing to SendGrid (SendGrid won't do it for you) for each batch/job.
SendGrid accepts either an array of strings, or comma-delimited values, so you could try something like this:
var finalEmailul = [];
// for each email in the list, check - if it doesn't exist, push it in
if(finalEmailul.indexOf(emailul) < 0){
finalEmailul.push(emailul);
};
// then use 'finalEmailul' in your 'sendEmail' function
try {
await sendEmail(
finalEmailul, // <- use here. If you want it to be comma-delimited, use finalEmailul.join(",")
'Alerta notificare pret!!!',
`Pretul produsului pe care il urmaresti este de ${pretulCurent} , sub alerta de pret setata de ${pretulDorit}. <br /> Produsul tau este: ${titlul} : ${link} `
)
} catch (e) {
await sendEmail('S-a produs o eroare', e.message)
throw e
}
i try to import some data in my firestore, this works quite well.
The data are german, english and spanish languages, so I have á,í, ä,...
My .json file is correct and when i opened it via xcode and vs code everything looks fine.. When i start my import and take a look at my database, those letters will be replaced by icons...
And i dont know why ... Does anybody know how to fix this?
As an example this is my .json :
{
"exercisesTest" : [
{
"exercises": "a_01",
"description_d": "Stell dich schulterbreit hin und stütz deine Hände in die Hüfte. Senk deinen Oberkörper ab, so als wolltest du dich auf einen Stuhl setzen. Achte darauf, dass deine Füße während der ganzen Bewegung immer fest am Boden bleiben und sich immer über den Fußgelenken befinden.",
"description_e": "Take a stance with your feet shoulder-width apart and put your hands on your hips. Lower your upper body as if you were sitting on a chair. Make sure that your feet remain firmly on the ground during the whole movement. Your knees should always be above the ankles.",
"description_s": "Ponte en posición con los pies separados a la anchura de los hombros y pon las manos sobre las caderas. Baja la parte superior del cuerpo como si estuvieras sentado en una silla. Asegúrate de que tus pies permanezcan firmemente en el suelo durante todo el movimiento. Las rodillas deben estar siempre por encima de los tobillos."}]}
and this is my firebase db...
Import will be done by my .js file and works fine, except the icons :p
const admin = require('./node_modules/firebase-admin');
const serviceAccount = require("./serviceAccountKey.json");
const data = require("./data.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "xxxx"
});
data && Object.keys(data).forEach(key => {
const nestedContent = data[key];
if (typeof nestedContent === "object") {
Object.keys(nestedContent).forEach(docTitle => {
admin.firestore()
.collection(key)
.doc(docTitle)
.set(nestedContent[docTitle])
.then((res) => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
});
}
});
Thanks for your help!
Okay, i deleted my whole .json file and create a new one with a different csv to json - now it works...
used this csv to json + validator
https://csvjson.com/json_validator
I'm creating an assistant for an italian restaurant using DialogFlow.
I've set the language to spanish, and everything seems to go fine, but when i show the final date of the reservation it is shown in english (Friday and May in attached picture's case).
Is it possible to change it?
This is the code that generates the above particular response to a table booking process:
function createBooking(agent) {
let guests = agent.parameters.comensales;
let time = new Date(agent.parameters.time);
let date = new Date(agent.parameters.date);
let bookingDate = new Date(date);
var numeroReserva = Math.random().toString(16).slice(2, 8).toUpperCase();
bookingDate.setHours(time.getHours());
bookingDate.setMinutes(time.getMinutes());
let now = new Date();
if (guests < 1){
agent.add('You need to reserve a table for at least one person. Please try again!');
} else if (bookingDate < now){
agent.add(`No puedes reservar una fecha pasada. Por favor, inténtalo de nuevo!`);
} else if (bookingDate.getFullYear() > now.getFullYear()) {
agent.add(`No puedes hacer una reserva para ${bookingDate.getFullYear()} todavía. Por favor, elige una fecha en ${now.getFullYear()}.`);
} else {
let timezone = parseInt(agent.parameters.time.toString().slice(19,22));
bookingDate.setHours(bookingDate.getHours() + timezone);
agent.add(`Perfecto. He reservado una mesa para ${guests} el ${bookingDate.toString().slice(0,21)}`);
agent.add(`Tu código de reserva es: ${numeroReserva}`);
agent.add('Nos vemos pronto!');
agent.add('Buon appetito!');
}
}
The code running the fulfillment runs within Google's compute infrastructure which has a default locale/language of US English. When a request arrives for fullfilment from Dialog flow, that request carries with it the language that we are to use to respond. See the languageCode in the Webhook Request JSON. When we use the APIs in Node.js, it looks like this data is available in the agent.locale property.
Looking at the JavaScript Date object, we seem to have a method on it called toLocaleString() which converts a date/time into a string but additionally supplies the language (locale) to be used to create the language specific content and format. If we put all this together, we might find that the following code line may work:
agent.add(`Perfecto. He reservado una mesa para ${guests} el ${bookingDate.toLocalString(agent.locale).slice(0,21)}`);
This may take a few tests to get right. I'd start by logging agent.locale as a test to ensure that it has the value we expect/hope.
It's late but for those who face with this problem. You know you can do it like this:
let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',
hour12: false, hour: 'numeric', minute: 'numeric' };
var curr_date = new Date();
agent.add(`Sono le ` + curr_date.toLocaleString('it-IT', options));
If someone likes to use moment.js
you can add library to your project from fulfillment inline editor.
Go to Fulfillment, click on "package.json"
add the following lines in dependencies
"moment": "^2.24.0",
"moment-timezone": "^0.5.31"
Then back to index.js and add the following line to import it
const moment = require('moment-timezone');
and then you can handle like this in your function
if(agent.locale === 'en'){
moment.locale('en-US');
agent.add(`Now is ` + moment().tz(your_time_zone).format('LLLL'));
}
else if(agent.locale === 'it-IT' || agent.locale === 'it'){
moment.locale('it');
agent.add(`Sono le ` + moment().tz(your_time_zone).format('LLLL'));
}
The sample of response is " Sono le martedì 20 ottobre 2020 15:30"
or "Now is Tuesday, October 20, 2020 3:31 PM"
I try to request an address using conv.ask(new Place(options)) but it does not seem to work.
Google correctly asks the user for permission, but he never understands any address.
Google : Pour vous livrer, je dois d'abord vérifier votre position. Est-ce que je peux récupérer cette information depuis votre compte Google ?
Me : oui
Google : A quelle adresse souhaitez-vous être livré ?
Me : 2 rue Paul Prouteau 92250
Google : Excusez-moi, A quelle adresse souhaitez-vous être livré ?
Me : A mon domicile
Google : Je n'ai toujours pas compris. Dites par exemple : "23 rue Faidherbe à Paris". A quelle adresse souhaitez-vous être livré ?
Me : 23 rue Faidherbe à Paris
Google : Malheureusement, je ne peux pas vous aider.
I created my intent on Dialogflow and hosted my code on Firebase Spark plan.
app.intent('ask_for_place_detail', (conv) => {
const options = {
context: 'Pour vous livrer',
prompt: 'A quelle adresse souhaitez-vous être livré ?',
};
conv.ask(new Place(options));
});
app.intent('ask_for_place_confirmation', (conv, params, place, status) => {
if (!place) return conv.ask(`Désolé, nous n'avons pas trouvé d'addresse`);
// the place also carries formattedAddress, and coordinates fields
const {name} = place;
if (place.name) conv.ask(`ok, on vous livre à ${name}`);
});
I do not see any error in the logs and I think I have enabled the correct Google Map APIs.
Can you help me ?
Make sure your place confirmation intent has the following event "actions_intent_PLACE"
Helper functions need respective events to be handled in the intents while designing in the Dialogflow or other NLP frameworks. If you are using Dialogflow, add this event.
I duplicate my action in English and it's works in the simulator!
So, there is maybe a bug with the French version.
I am new to Netsuite and I was asked to perform a script that was launched from an application programmed in java. The script with a function to generate a Purchase Order in Netsuite and other function to list the Purchase Order created earlier. It turns out that for this I am using the api SuiteScript but when creating the Purchase Order run the java application and launches the script but it gives the following error:
Aug 03, 2015 2:49:00 PM com.gargoylesoftware.htmlunit.WebClient printContentIfNecessary
INFO: {"error": {"code": "user_error", "message": "Please enter value (s) for: Vendor"}}
Javascript function to create is:
function CreatePurchase_Orders(datain){
var output = '';
nlapiLogExecution('DEBUG','createRecord','ingreso la consulta' ) ;
nlapiLogExecution('DEBUG','createRecord', 'Ingresa: '+ datain);
//var msg = validateTimeBills(datain);
var msg = null;
if (msg){
var err = new Object();
err.status = "failed";
err.message= msg;
return err;
}
var Purchase_Orders = datain.Purchase_Order;
nlapiLogExecution('DEBUG','createRecord', 'obtuvo el objeto: '+ Purchase_Orders);
for (var Purchase_Orderobject in Purchase_Orders){
var Purchase_Order = Purchase_Orders[Purchase_Orderobject];
var transdate = Purchase_Order.Transdate;
var Form = Purchase_Order.Form;
var Vendor = Purchase_Order.Vendor;
var Currency = Purchase_Order.Currency;
var Item = Purchase_Order.Item;
nlapiLogExecution('DEBUG','campos','transdate: '+ transdate+'/Form: '+Form + ' /Vendor: ' + Vendor + ' /Currency: ' + Currency
+ ' /Item: ' + Item);
var Purchase_Order = nlapiCreateRecord('purchaseorder');
var nlobjAssistant = nlapiCreateAssistant ( 'asistente' , false ) ;
var Purchase_Orderid = 1;//nlapiSubmitRecord( Purchase_Order , true, true);
if(Purchase_Order){
nlapiLogExecution('DEBUG', 'Purchase_Order ' + Purchase_Orderid + ' successfully created', '');
nlapiLogExecution('DEBUG', 'createRecord', 'creo el record');
}
Purchase_Order.setFieldValue('transdate', transdate);
Purchase_Order.setFieldValue('inpt_customform1', Form);
Purchase_Order.setFieldValue('vendor', Vendor);
Purchase_Order.setFieldValue('inpt_currency7', Currency);
Purchase_Order.setFieldValue('inpt_item', Item);
Purchase_Order.setFieldText('quantity_formattedValue', '1');
Purchase_Order.setFieldText('rate_formattedValue', '1');
Purchase_Order.setFieldText('amount_formattedValue', '1');
Purchase_Order.setFieldText('inpt_taxcode', 'VAT_MX:UNDEF_MX');
Purchase_Order.setFieldText('grossamt_formattedValue', '1');
Purchase_Order.setFieldText('tax1amt_formattedValue', '0');
Purchase_Order.setFieldText('expectedreceiptdate', '24/6/2015');
//var Purchase_Orderid = 1;//nlapiSubmitRecord( Purchase_Order , true, true);
var submitRecord = nlapiSubmitRecord(Purchase_Order);//,true);
nlapiLogExecution('DEBUG', 'submirRecord ' + submitRecord);
}
var mesg = new Object();
mesg.status = "OK";
mesg.message= nlobjAssistant.getAllFields();
return mesg;
}
And the function code in Java is:
WebClient client = new WebClient(BrowserVersion.FIREFOX_31);
client.getOptions().setJavaScriptEnabled(false);
client.getOptions().setThrowExceptionOnScriptError(false);
WebRequest requestSettings = new WebRequest(new URL(url),HttpMethod.POST);
requestSettings.setAdditionalHeader("Host", "rest.na1.netsuite.com");
requestSettings.setAdditionalHeader("User-Agent", "SuiteScript-Call");
requestSettings.setAdditionalHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
requestSettings.setAdditionalHeader("Accept-Language", " es-cl,es;q=0.8,en-us;q=0.5,en;q=0.3");
requestSettings.setAdditionalHeader("Accept-Encoding", "gzip, deflate");
requestSettings.setAdditionalHeader("Content-Type", "application/json");
requestSettings.setAdditionalHeader("Pragma", "no-cache");
requestSettings.setAdditionalHeader("Cache-Control", "no-cache");
requestSettings.setAdditionalHeader("Referer", "http://localhost:8084");
requestSettings.setAdditionalHeader("Cookie", "");
requestSettings.setAdditionalHeader("Connection", "keep-alive");
requestSettings.setAdditionalHeader("Authorization", "NLAuth nlauth_account=" + account + ", nlauth_email=" + mail + ", nlauth_signature=" + pass + ", nlauth_role=" + role + "");
Gson gson = new Gson();
//objeto llenado estaticamente de forma momentanea, se debe leer desde archivo externo
Purchase_Order purchaseOrder = new Purchase_Order("25/06/2015","formTest","vendorTest","CurrencyTest","itemTest");
String cuerpo = gson.toJson(purchaseOrder);
System.out.println(cuerpo);
// Set the request parameters
requestSettings.setRequestBody(cuerpo);
Page page = client.getPage(requestSettings);
WebResponse response = page.getWebResponse();
String json = response.getContentAsString();
System.out.println(json);
With this javascript function you should create me a record Purchase Order but I can not find the error and the solution if someone could please help me I would appreciate it a lot.
PS: if you have to create a customized form could tell me how?
thanks!
Here are some points :
As your error message says Please enter value (s) for: Vendor, you're missing the value for vendor field, which is mandatory. In your piece of code you're passing wrong internalid value for vendor. You should use entity instead of vendor
Purchase_Order.setFieldValue('entity', Vendor); // where vendor is the internal id of the vendor record
For setting custom form you can use
Purchase_Order.setFieldValue('customform', Form); // where Form is the id of the custom form
I also noticed that you're setting some values in purchase order which I suspect are to be a kind of custom one. If that is the case, then your custom field internal id should be prefixed with custbody.
For all the standard fields internal id you can refer to the Suite script Records Browser.