How to make calls using a pool of phone numbers as caller IDs in Voximplant? - voximplant

I want to make calls using a pool of phone numbers as caller IDs. I want my script to chose a random number of what I have and show it to my customers. Can I do this with Voximplant?

There's no "random caller ID" in Voximplant, but you can easily do it with common JS, like this:
//pool of disposable callerIDs
let number_pool = ["73832349068",
"79666667368",
"79666667369",
"19073314185"]
//random index generation
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let index;
//incoming call leg
VoxEngine.addEventListener(AppEvents.CallAlerting, function (e) {
//picking random callerID
index=getRandomInt(number_pool.length);
const confirmedCallerId = number_pool[index];
//outbound call leg to call destination from randomly selected callerID
const out = VoxEngine.callPSTN(e.destination, confirmedCallerId);
VoxEngine.easyProcess(e.call, out);
});

Related

How do perform a graph query and join?

I apologize for the title, I don't exactly know how to word it. But essentially, this is a graph-type query but I know RavenDB's graph functionality will be going away so this probably needs to be solved with Javascript.
Here is the scenario:
I have a bunch of documents of different types, call them A, B, C, D. Each of these particular types of documents have some common properties. The one that I'm interested in right now is "Owner". The owner field is an ID which points to one of two other document types; it can be a Group or a User.
The Group document has a 'Members' field which contains an ID which either points to a User or another Group. Something like this
It's worth noting that the documents in play have custom IDs that begin with their entity type. For example Users and Groups begin with user: and group: respectively. Example IDs look like this: user:john#castleblack.com or group:the-nights-watch. This comes into play later.
What I want to be able to do is the following type of query:
"Given that I have either a group id or a user id, return all documents of type a, b, or c where the group/user id is equal to or is a descendant of the document's owner."
In other words, I need to be able to return all documents that are owned by a particular user or group either explicitly or implicitly through a hierarchy.
I've considered solving this a couple different ways with no luck. Here are the two approaches I've tried:
Using a function within a query
With Dejan's help in an email thread, I was able to devise a function that would walk it's way down the ownership graph. What this attempted to do was build a flat array of IDs which represented explicit and implicit owners (i.e. root + descendants):
declare function hierarchy(doc, owners){
owners = owners || [];
while(doc != null) {
let ownerId = id(doc)
if(ownerId.startsWith('user:')) {
owners.push(ownerId);
} else if(ownerId.startsWith('group:')) {
owners.push(ownerId);
doc.Members.forEach(m => {
let owner = load(m, 'Users') || load(m, 'Groups');
owners = hierarchy(owner, owners);
});
}
}
return owners;
}
I had two issues with this. 1. I don't actually know how to use this in a query lol. I tried to use it as part of the where clause but apparently that's not allowed:
from #all_docs as d
where hierarchy(d) = 'group:my-group-d'
// error: method hierarchy not allowed
Or if I tried anything in the select statement, I got an error that I have exceeded the number of allowed statements.
As a custom index
I tried the same idea through a custom index. Essentially, I tried to create an index that would produce an array of IDs using roughly the same function above, so that I could just query where my id was in that array
map('#all_docs', function(doc) {
function hierarchy(n, graph) {
while(n != null) {
let ownerId = id(n);
if(ownerId.startsWith('user:')) {
graph.push(ownerId);
return graph;
} else if(ownerId.startsWith('group:')){
graph.push(ownerId);
n.Members.forEach(g => {
let owner = load(g, 'Groups') || load(g, 'Users');
hierarchy(owner, graph);
});
return graph;
}
}
}
function distinct(value, index, self){ return self.indexOf(value) === index; }
let ownerGraph = []
if(doc.Owner) {
let owner = load(doc.Owner, 'Groups') || load(doc.Owner, 'Users');
ownerGraph = hierarchy(owner, ownerGraph).filter(distinct);
}
return { Owners: ownerGraph };
})
// error: recursion is not allowed by the javascript host
The problem with this is that I'm getting an error that recursion is not allowed.
So I'm stumped now. Am I going about this wrong? I feel like this could be a subquery of sorts or a filter by function, but I'm not sure how to do that either. Am I going to have to do this in two separate queries (i.e. two round-trips), one to get the IDs and the other to get the docs?
Update 1
I've revised my attempt at the index to the following and I'm not getting the recursion error anymore, but assuming my queries are correct, it's not returning anything
// Entity/ByOwnerGraph
map('#all_docs', function(doc) {
function walkGraph(ownerId) {
let owners = []
let idsToProcess = [ownerId]
while(idsToProcess.length > 0) {
let current = idsToProcess.shift();
if(current.startsWith('user:')){
owners.push(current);
} else if(current.startsWith('group:')) {
owners.push(current);
let group = load(current, 'Groups')
if(!group) { continue; }
idsToProcess.concat(group.Members)
}
}
return owners;
}
let owners = [];
if(doc.Owner) {
owners.concat(walkGraph(doc.Owner))
}
return { Owners: owners };
})
// query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners = "group:my-group-id"
// alternate query (no results)
from index Entity/ByOwnerGraph as x
where x.Owners ALL IN ("group:my-group-id")
I still can't use this approach in a query either as I get the same error that there are too many statements.

Suitescript: copying sublist data from one record to another

I have a before load user event function on an invoice record that create a button called 'create vendor bill'.
When this button is pressed, a new vendor bill record is opened. The UE script:
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define([
"N/url",
"N/record",
"N/runtime",
"N/ui/serverWidget",
"N/redirect",
], function (url, record, runtime, serverWidget, redirect) {
var exports = {};
/**
* #param {UserEventContext.beforeLoad} context
*/
function beforeLoad(context) {
if (
context.type == context.UserEventType.EDIT ||
context.type == context.UserEventType.VIEW
) {
var record = context.newRecord;
var recordId = record.id;
var recordType = record.type;
var customer = record.getValue({ fieldId: "entity" });
log.debug("entity", customer);
var scriptObj = runtime.getCurrentScript();
var customForm = scriptObj.getParameter({
name: "custscript_custom_form_vb",
});
var recordSublist = record.getSublist({ sublistId: "item" });
log.debug("item", recordSublist);
var form = context.form;
log.debug("form", form);
var userVarStr = record;
log.debug("uservarstr", userVarStr);
var userVarURL = url.resolveRecord({
recordType: "vendorbill",
params: {
entity: parseInt(customer),
supportcase: recordId,
cf: parseInt(customForm),
},
});
form.addButton({
id: "custpage_button_test",
label: "Create Vendor Bill",
functionName: "getDetails('" + userVarURL + "')",
});
}
}
exports.beforeLoad = beforeLoad;
return exports;
});
Once the page redirects to the vendor bill form, a client script (deployed on the form), sets the field values on the body of the vendor bill using the parameters passed in the url
This is working as expected.
Where I am getting stuck is trying to work out how to pass the 'item' sublist values to from the invoice to the vendor bill?
Would I pass this as an array?
From what I understand, there is a limit to the number of characters that can be passed via the url.
I can't find anything online or in the Netsuite documentation that deals with passing sublist values between records
For starters I would want to see the Client Script.
One option would be to only pass the Invoice Record ID and Type. Then you can create a Suitelet to be used as a proxy and get the sublist data by a saved search.
Something to keep in mind is that if the sublist is very very long you may reach a execution timeout so you may want to consider triggering a MapReduce script to populate the sublist again you would pass it the recType and ID of the invoice and vendor bill and then use a saved search to get the data.
There are other approaches but I would need to see the client script.

Best way to create a table with each possible combination of product options and variations

I need to implement in PostgreSQL a table for each combination of option and variation.
This is my existing tables:
Imagine this scenario:
Product: T-Shirt
Options: Size, Color
Variations: Size:Small,Medium,Large | Color:White,Black,Yellow
I need to have a row for each combination to control quantity and price seperately.
So i need a row with Size:Small,Color:White, one with Size:Small,Color:Black etc...
It isn't necessary to execute all in SQL, i manipulate the data in program logic in Go.
I thought about making a table with:
id |price | quantity | option1_id | option2_id | option3_id
and compare the values that i get from my form and get the appropriate price and qty.However i do not know how to guarantee that the options on my form are displayed on the correct order as to not put the option id on my query.
Is there better option?Perhaps saving the combination in JSON on one column and loading in a array in JS and manipulating it there?
To explain it a bit better(hopefully):
I display on my site some select inputs with the options and variations that i have inserted,like this.
Where each option on the dropdown menu has a value of variation_id and the name of the menu is the option_id,ex. 120:1400 where 120 is the option_id and 1400 is the variant attached to it and currently selected.So when user adds product to cart it sends this JSON to server[{"option_id":3,"variant_id":13},{"option_id":433,"variant_id":1085}]
I know how to make a table with each possible combination, but i don't know how to link the variants selected to the one row on my table.
I want to implement the same way that Woocommerce does it.
This is the Attributes(Options)
And those are the Variations that are generated
As you can see there's an entry for each possible configuration.
Currently i have set up the Name and Values of the third image. product_option has the name of the option and there are multiple product_variation rows pointed to the option_id, each with a variation name like Small,Medium etc...
I don't know how to create a new table like the 4th image.
I have found a way.It's called Cartesian Product.
Here is how it's done.
This is a function that i found online,from this repo https://github.com/schwarmco/go-cartesian-product
func Iter(params ...[]interface{}) chan []interface{} {
// create channel
c := make(chan []interface{})
// create waitgroup
var wg sync.WaitGroup
// call iterator
wg.Add(1)
iterate(&wg, c, []interface{}{}, params...)
// call channel-closing go-func
go func() { wg.Wait(); close(c) }()
// return channel
return c
}
// private, recursive Iteration-Function
func iterate(wg *sync.WaitGroup, channel chan []interface{}, result []interface{}, params ...[]interface{}) {
// dec WaitGroup when finished
defer wg.Done()
// no more params left?
if len(params) == 0 {
// send result to channel
channel <- result
return
}
// shift first param
p, params := params[0], params[1:]
// iterate over it
for i := 0; i < len(p); i++ {
// inc WaitGroup
wg.Add(1)
// create copy of result
resultCopy := append([]interface{}{}, result...)
// call self with remaining params
go iterate(wg, channel, append(resultCopy, p[i]), params...)
}
}
Here's how you can use it
a := []interface{}{"Small", "Medium", "Large"}
b := []interface{}{"White", "Black", "Yellow"}
var d [][]interface{}
d = append(d,a)
d = append(d,b)
c := Iter(d...)
for product := range c {
fmt.Println(product)
}
I then store each product as a JSON string to the database

Does realm Javascript supports Join, Group By and Aggregation functions

To develop a React Native mobile app that shows statistics data, following functions to be used widely, does Realm will meet the needs?
Join
Group by
Aggregation
AutoIncrement
Kindly suggest any other ORM/DB that will be best fit for the statistical app?
Alternative
You can get date in Realm Database then by useign js group by
// Accepts the array and key
const groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[currentValue[key]] = result[currentValue[key]] || []).push(
currentValue
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};
// Group by color as key to the person array
const personGroupedByColor = groupBy(person, 'color');

"update" query - error invalid input synatx for integer: "{39}" - postgresql

I'm using node js 0.10.12 to perform querys to postgreSQL 9.1.
I get the error error invalid input synatx for integer: "{39}" (39 is an example number) when I try to perform an update query
I cannot see what is going wrong. Any advise?
Here is my code (snippets) in the front-end
//this is global
var gid=0;
//set websockets to search - works fine
var sd = new WebSocket("ws://localhost:0000");
sd.onmessage = function (evt)
{
//get data, parse it, because there is more than one vars, pass id to gid
var received_msg = evt.data;
var packet = JSON.parse(received_msg);
var tid = packet['tid'];
gid=tid;
}
//when user clicks button, set websockets to send id and other data, to perform update query
var sa = new WebSocket("ws://localhost:0000");
sa.onopen = function(){
sa.send(JSON.stringify({
command:'typesave',
indi:gid,
name:document.getElementById("typename").value,
}));
sa.onmessage = function (evt) {
alert("Saved");
sa.close;
gid=0;//make gid 0 again, for re-use
}
And the back -end (query)
var query=client.query("UPDATE type SET t_name=$1,t_color=$2 WHERE t_id = $3 ",[name, color, indi])
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
connection.send("o");
client.end();
});
Why this not work and the number does not get recognized?
Thanks in advance
As one would expect from the initial problem, your database driver is sending in an integer array of one member into a field for an integer. PostgreSQL rightly rejects the data and return an error. '{39}' in PostgreSQL terms is exactly equivalent to ARRAY[39] using an array constructor and [39] in JSON.
Now, obviously you can just change your query call to pull the first item out of the JSON array. and send that instead of the whole array, but I would be worried about what happens if things change and you get multiple values. You may want to look at separating that logic out for this data structure.