how to update quantity in Odoo-erp using odoo-xmlrpc library? - javascript

im trying to create a javascript function using nodejs which uses odoo-xmlrpc library to perform paiment in odoo online database.In order to do that i have to decrease the quantity of the product somehow or create a stock move.
i found this code but nothing works correctly:
var Odoo = require('odoo-xmlrpc');
var odoo = new Odoo({
url:'https://mydomain.odoo.com',
db:'mydb',
username: 'mydatabase',
password: 'password'});
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var params = [[{
'product_id': 2,
'product_uom_id':2,
'location_id':9,
'picking_type_id':2,
'location_dest_id': 13,
}]];
odoo.execute_kw('stock.move','create', params, function(err, value) {
if (err) { return console.log(err); }
console.log(value);});
});
maybe can someone help me :)

Related

NODE.JS, Express, mySQL2 : Issues appending an object inside of another object

I'm having an issue in trying to add the results of a query into an object. I am new to Node and Express so I apologize if I am making some stupid mistakes. I have been reading docs and watching videos pretty much non stop while I try to get this to work. Async is still wierd for my brain so I am sure I am doing things wrong, the function I placed seems wrong, I would appreciate so much any videos or articles you know of that could aid my comprehension as well haha!
Basically I have a table called stages, where the user can add or remove stages. I am pulling all the stages and then trying to add the projects that belong in those stages as an array of objects.
Ok so here is the code:
var myStages = []; //Global variable to hold stages.
//Get all the Stages
app.get('/', (req, res) => {
pool.getConnection((err, connection) => {
if(err) throw err;
console.log(`Connected as ID ${connection.threadId}`);
//Query
connection.query('SELECT * FROM solarcrm_stages', (err, rows) => {
connection.release();
if(!err) {
getProjects(rows);
} else {
console.log(err);
}
})
function getProjects(stages) {
myStages = stages;
Object.entries(myStages).forEach(entry => {
const[key] = entry;
connection.query('SELECT * FROM project WHERE iProjectStage = ?', [myStages[key]['iStageID']], (err, rows) => {
connection.release();
if(!err) {
myStages[key]['Projects'] = rows;
console.log(myStages); //Projects shows up as 'Projects: [ [TextRow] ]'
} else {
console.log(err);
}
});
});
}
})
})
The current result I get is this, Stage 1 has projects that should appear but shows [TextRow], Stage 2 should be empty as it is:
[
TextRow {
iStageID: 1,
sStageName: 'Stage1',
sStateIcon: 'null',
bActive: 1,
iOrderID: 1,
sStageDesc: null,
Projects: [ [TextRow] ]
},
TextRow {
iStageID: 2,
sStageName: 'Stage 2',
sStateIcon: 'null',
bActive: 1,
iOrderID: 2,
sStageDesc: null,
Projects: []
}
]
Thank you so much for any help or guidance you can offer.

Splitting a var into another var that contains only numbers

Currently I'm getting my data out of a SQL Server 2012 using a powershell and the mssql plugin. I'm trying to extract out data using queries, so I had a query to get the particular information and then use express.js to send the data over to a textbox. This is the code currently.
Server.JS
app.get('/Warning', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'Atiqah',
password: 'password',
server: 'DESKTOP-5045H9Q',
database: 'TestDB'
};
// connect to your database
sql.connect(config, function (err) {
var record;
if (err) console.log(err);
// create Request object
var request = new sql.Request();
var stringrequest =
// query to the database and get the records
request.query("SELECT COUNT([EntryType]),EntryType FROM TestTable GROUP BY EntryType", function (err, recordset) {
if (err) console.log(err)
// send records as a response
record = recordset;
console.log("You are currently connected to " + JSON.stringify(config));
res.send(JSON.stringify(recordset));
//console.log("Query submitted is " + JSON.stringify(stringrequest));
});
});
Index2.html
function myFunction() {
$.get("/Warning", function (string) {
$('#txtWarning').val(string);
});
}
<body onload="myFunction()">
<textarea rows="8" cols="70" id="txtWarning"></textarea></body>
The data that i get out of the textbox would be something like this:
{"recordsets":[[{"":734,"EntryType":"\"Warning\""},{"":1049,"EntryType":"\"Error\""}]],"recordset":[{"":734,"EntryType":"\"Warning\""},{"":1049,"EntryType":"\"Error\""}],"output":{},"rowsAffected":[2]}
How do I go around only getting the numbers out of this var? Any help would be much appreciated. The output that I wanted would look something like this.
734, 1049, 734, 1049.
Simple solution:
var data = {}; //your object here
var nums = [];
Object.keys(data)
.filter(x => Array.isArray(data[x]))
.forEach(x => {
data[x].forEach(y => {
nums.push(y[""]);
})
});

Node JS Multiple Select

Hi i am trying to use two selects in one JS file in node js and sql server. I am unable to figure out the syntax for this. I need a select to get all the persons from a table and another select to count the total number of persons in that table.Will it be possible to put those two selects in a single JS file. If so can someone help me with the syntax?
Here is the code i tried and i am getting the error
"cant Set headers after they are sent"
var sql = require("mssql");
var dbConfig = {
server: "XXXXX",
database: "XXXXX",
user: "XXXXX",
password: "XXXX",
port: 1433
};
exports.list = function(req, res){
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from PERSON', function (err, recordset) {
if (err)
console.log(err)
else
console.log(recordset)
res.render('personinfo_itwx', { data: recordset });
});
request.query('select count(*) from PERSON', function (err, recordset) {
if (err)
console.log(err)
else
console.log(recordset1)
res.render('personinfo_itwx', { data: recordset1 });
});
});
};
#Aditya I'm not sure it's the best way to do so, although I would simply make two different requests, in order to achieve what you need. As I mentioned my in my comment, easiest way, would be to use (for instance) async library. And here's example you've asked for.
WARNING: I did not look at mysql docs
const async = require('async')
// {
async.series([
function(next)
{
new sql.Request()
.query('SELECT * from PERSON', next(err, resultList))
},
function(next)
{
new sql.Request()
.query('SELECT COUNT(*) from PERSON', next(err, count))
}
], (err, result) =>
{
/*
err: String
- if any of the shown above return an error - whole chain will be canceled.
result: Array
- if both requests will be succesfull - you'll end up with an array of results
---
Now you can render both results to your template at once
*/
})
// }
Surely, if you want manipulate with errors or results once you get them - you always may push error and results to new function, play with your data, and return the callback afterwards. Like so:
function(next)
{
new sql.Request()
.query('SELECT * from PERSON', (err, resultList) =>
{
if (err)
{
return next(err, null)
}
/*
data manipulation
*/
return next(null, resultList)
})
},

Sending an AlchemyData News query using Node.js (watson-developer-cloud module)

I'm currently working with Node.js using the watson-developer-cloud Node.js SDK and I'm having problems when sending a query that includes an entity.
This is my code:
// require watson's node sdk and fs
var watson = require('watson-developer-cloud');
var fs = require('fs');
// Define output file
var outputJSONFile = '/home/vagrant/Desktop/node/dir/data.json';
// Create alchemy_data_news object using our api_key
var alchemy_data_news = watson.alchemy_data_news({
api_key: ''
});
// Define params for the query and what values to return
// Accepted returne values:
// docs.alchemyapi.com/v1.0/docs/full-list-of-supported-news-api-fields
var params = {
start: 'now-1m',
end: 'now',
count: 2,
qs: ['q.enriched.url.enrichedTitle.entities.entity.text=apple'],
return: ['enriched.url.url,enriched.url.title']
};
// Call getNews method and return json
alchemy_data_news.getNews(params, function (err, news) {
if (err) {
console.log('error:', err);
} else {
fs.writeFile(outputJSONFile, JSON.stringify(news, null, 2), function(err) {
if (err) {
console.log('WriteFile Error:', err);
} else {
console.log("JSON saved to " + outputJSONFile);
}
});
}
});
I'm still trying to figure out how to send the entities parameters using the params object.
While digging up through some code I came across qs so I have been using that to test but I haven't had success at all.
Any suggestions are greatly appreciated.
P.S: I'm trying to pass:
q.enriched.url.enrichedTitle.entities.entity.text=apple
q.enriched.url.enrichedTitle.entities.entity.type=company
If you look at the node-sdk source code for AlchemyDataNews, you will see that the top level parameters are being sent as query strings.
Then params map should be:
var params = {
start: 'now-1m',
end: 'now',
count: 2,
return: ['enriched.url.url,enriched.url.title'],
// fields here
'q.enriched.url.enrichedTitle.entities.entity.text': 'apple',
'q.enriched.url.enrichedTitle.entities.entity.type': 'company'
};

Mongoose's model.update not working in Node.js

I have a Node.js app that is updating data in a MongoDB database using Mongoose.
I have setup the Mongoose model and I am able to successfully use the model.find, and model.remove functions, but I can't get the model.update function to work.
Can anyone help me?
/* ------------------------ Finding/Querying works ----------------------
Flot.find({ "label": "Trips Per Day"}, function (err, docs) {
res.jsonp(docs || err);
});
*/
/* ------------------------ Removing works -----------------------
Flot.remove({ "label": "Trips Per Client" }, function (err) {
if (err) return handleError(err);
res.json(err || "removed");
});
*/
var conditions = { "label": "Average Tons per Delivery" };
var update = { "label": "Average Tons per Delivery 2" };
var options = { };
var callback = function callback(err, numberAffected, rawResponse) {
if (err) return handleError(err);
console.log('Error: ', err);
console.log('NumberAffected: ', numberAffected);
console.log('RawResponse: ', rawResponse);
res.json(err || rawResponse || numberAffected );
};
Gage.update( conditions, update, options, callback );
I was able to get this working with node-mongodb-native. I'm still not sure why Mongoose wasn't working, but at least I got something to work.
var query = {"label": "Average Tons per Delivery"};
var update = {"type": "vertical"};
var options = {};
MongoClient.connect('mongodb://localhost/db', function(err, db) {
if(err) throw err;
db.collection('justgage').findAndModify(
query,
[['_id','asc']],
{$set: update},
options,
function(err, object) {
res.jsonp("Ok");
});
});

Categories