POST Email Using Web API not reflecting "sender" and "torecipients" data - javascript

I want to create Email using MS Dynamics Web API.
Here I am posting data
{
"sender": "test#test.com",
"torecipients": "test2#test.com",
"subject": "Test Subject New 1234567",
"description": "Test Description New 1234567"
}
But sender and torecipients are not reflecting in Dynamics CRM.
Only subject & description are displaying.
Is there anything I am missing?

You have to populate collection valued navigation property email_activity_parties for filling up From & To fields. sender & torecipients are fields just for reporting purpose with emailaddress of those activity parties.
var email = {};
email["subject"] = "Email demo from Web API";
email["description"] = "This a web api test";
email["regardingobjectid_contact#odata.bind"] = "/contacts(C41CE33F-D0A0-E611-811E-5065F38C8781)";
//activityparty collection
var activityparties = [];
//from party
var from = {};
from["partyid_systemuser#odata.bind"] = "/systemusers(8D23B2C1-9869-4C3F-9A80-BA51375C1784)";
from["participationtypemask"] = 1;
//to party
var to = {};
to["partyid_contact#odata.bind"] = "/contacts(C41CE33F-D0A0-E611-811E-5065F38C8781)";
to["participationtypemask"] = 2;
activityparties.push(to);
activityparties.push(from);
//set to and from to email
email["email_activity_parties"] = activityparties;
Read more
Edit:
JSON will look like this:
{
"subject": "Test Subject New 1234567",
"description": "Test Description New 1234567",
"regardingobjectid_contact#odata.bind": "/contacts(<GUID>)",
"email_activity_parties": [
{
"partyid_contact#odata.bind": "/contacts(<GUID>)",
"participationtypemask": 2
},
{
"partyid_systemuser#odata.bind": "/systemusers(<GUID>)",
"participationtypemask": 1
}
]
}

Related

How to merge array into JSON array

I have a JSON file that I need to add Comments into and then update the file.
I've created an array for the new comments
//ADDING NEW COMMENTS
//add new comment within project
$scope.updatecomments = [];
$scope.addnewcomment = function() {
$scope.updatecomments.push({
"Author": "test",
"Text": $scope.NewComment
})
}
I can post the new comments into the JSON file but it overrides the past comments.
I have tried to merge the older comments with the new comments with the following
$scope.updatecomments = [];
$scope.addnewcomment = function() {
$scope.updatecomments.push({"Author": "test" ,"Text": $scope.NewComment}).concat($scope.Comments, $scope.updatecomments);
}
$scope.updatecomments = [].concat($scope.updatecomments,
$scope.projectDetails.Comments);
$scope.addnewcomment = function() {
$scope.updatecomments.push({
"Author": "test",
"Text": $scope.NewComment
});
}
I also tried making a new function that when called combines the two and then post the combined array
$scope.combine = [];
$scope.combineComments = function (){
var jsonStr = $scope.projectDetails.Comments;
var obj = JSON.parse(jsonStr);
obj['Comments'].push({"Author":"Test","Text":$scope.NewComment});
jsonStr = JSON.stringify(obj);
}
}
I have been going over this for the past few days now and can't seem to get it. Any help would be greatly appreciated!
EDIT
Sample Data of already existing data in JSON file
{
"Comments":[{
"Author": "John Doe",
"Text": "Work completed"
}]
}
Want to add to this (is from html input text tag) stored as NewComment
{
"Comments":[{
"Author": "Test",
"Text": "Project flagged"
}]
}
Edit 2
This is how I'm getting my projects data
/FIND PROJECTS - ADD TO LIST
$scope.projectList = [];
for (var id = 0; id < 30; id++) {
var targetURL = 'https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.'+id+'.json';
$http.get(targetURL).then(
function successCall(response){
$scope.projectList.push(response.data);
}
);
}
I then use this to access the selected information
//script
$scope.showData = function(x){
$scope.projectDetails = x;
};
//html
<ul class = 'pList'>
<li ng-repeat = 'x in projectList' class = 'pbList'>
<button class = 'pbutton' ng-click = 'showData(x)'>
<label ng-model ='pID'>Project ID: </label>{{x.ProjectID}} <br>
<label id ='pName'>Project Name: </label> {{x.Name}} <br>
<label id ='bID'>Building ID: </label>{{x.BuildingID}}<br>
<label id ='sDate'>Start Date: </label>{{x.StartDate}}
</button>
</li>
</ul>
Then I have the following variables to post
$scope.updateProject = function (projectDetails){
var updateproject = {
"ProjectID":$scope.projectDetails.ProjectID,
"Name":$scope.projectDetails.Name,
"BuildingID":$scope.projectDetails.BuildingID,
"StartDate":$scope.projectDetails.StartDate,
"EndDate":$scope.projectDetails.EndDate,
"Status":$scope.projectDetails.Status,
"ContactPerson":$scope.projectDetails.ContactPerson,
"Contractor":$scope.projectDetails.Contractor,
"ProjectManager":$scope.projectDetails.ProjectManager,
"Works": $scope.projectDetails.works,
"Comments":$scope.updatecomments,
};
$http.post("https://happybuildings.sim.vuw.ac.nz/api/sooleandr/update.project.json", updateproject).then(
function success(){
alert("Project Successfully Posted");
},
function error(){
alert("Error: Couldn't post to server");
}
)
};
It posts perfectly fine but it currently overrides the comments. I want to be able to add a new comment and still keep all the past comments. So I want to be able to push/add the comments into the full POST.JSON array.
Hope this makes a bit more sense
OK, updating answer after looking at provided code.
It appears you may be under the impression that $scope.projectDetails.Comments is a JSON string, when, in fact.. it's the actual Comments array.
I would try this for the addnewcomment function:
//ADDING NEW COMMENTS
//add new comment within project
$scope.updatecomments = undefined;
$scope.addnewcomment = function() {
$scope.updatecomments = $scope.updatecomments || $scope.projectDetails.Comments;
$scope.updatecomments.push({
"Author": "test",
"Text": $scope.NewComment
})
}
IF it just so happens to be a JSON string (highly unlikely), then I would update the combine function to this:
$scope.combineComments = function (){
var jsonStr = $scope.projectDetails.Comments;
var obj = JSON.parse(jsonStr);
obj.push({"Author":"Test","Text":$scope.NewComment});
jsonStr = JSON.stringify(obj);
}
}
EDIT
I'm adding another answer from my original because of the possibility things will break when there are no updated comments
//ADDING NEW COMMENTS
//add new comment within project
$scope.addnewcomment = function() {
$scope.projectDetails.Comments.push({
"Author": "test",
"Text": $scope.NewComment
})
}
Then in the POST, change to:
"Comments":$scope.projectDetails.Comments
I have figured out how to combine the two with
$scope.combinecomments = [];
$scope.combine = function (){
$scope.combinecomments.push($scope.projectDetails.Comments);
$scope.combinecomments.push($scope.updatecomments);
}
Except now it doesn't post the combined comments
$scope.ProjectID='$scope.ProjectID';
$scope.Name = '$scope.Name';
$scope.BuildingID = '$scope.BuildingID';
$scope.StartDate = '$scope.StartDate';
$scope.EndDate = '$scope.EndDate';
$scope.Status = '$scope.Status';
$scope.ContactPerson = '$scope.ContactPerson';
$scope.Contractor ='$scope.Contractor';
$scope.ProjectManager = '$scope.ProjectManager';
$scope.Works = '$scope.works';
$scope.Comments ='$scope.comments';
$scope.updateProject = function (projectDetails){
var updateproject = {
"ProjectID":$scope.projectDetails.ProjectID,
"Name":$scope.projectDetails.Name,
"BuildingID":$scope.projectDetails.BuildingID,
"StartDate":$scope.projectDetails.StartDate,
"EndDate":$scope.projectDetails.EndDate,
"Status":$scope.projectDetails.Status,
"ContactPerson":$scope.projectDetails.ContactPerson,
"Contractor":$scope.projectDetails.Contractor,
"ProjectManager":$scope.projectDetails.ProjectManager,
"Works": $scope.projectDetails.works,
"Comments":$scope.combinecomments,
};
$http.post("https://happybuildings.sim.vuw.ac.nz/api/sooleandr/update.project.json", updateproject).then(
function success(){
alert("Project Successfully Posted");
},
function error(){
alert("Error: Couldn't post to server");
}
)
};
It successfully posts the project except for the comments. It doesn't seem to like my combined array. When I post $scope.updatecomments it will post that but not the $scope.combinecomments.
I'll make a new question for this.

Trying to send data from javascript to python POS odoo using rpc.query

I am trying to send my data in the list to their fields so i can retrieve them into another screen in same module / project.
The list i am trying to send :
var vals = {
'token_number':Token,
'partner_id':customer_name,
'queue_line_ids':queue_lines,
}
where Token is random number generated on custom_button click,customer_name is the id of customer obtained by "this.pos.get_order().cid" and queuelines is array of product and their info obtained from orderlines.
The rpc.query i wrote by referring to point_of_sale in odoo13/addon/ :
return rpc.query({
model: 'pos.queue',
method: 'create',
args: [vals],
}).then(function () {
console.log("Success")
}).catch(function (reason){
var error = reason.message;
console.log(error);
});
The pos.queue in my module's model.py :
class POSOrderQueue(models.Model):
_name = 'pos.queue'
token_number = fields.Integer(string="Token Number", store=True)
partner_id = fields.Char(store=True)
pos_order_id = fields.Char(store=True)
order_progress = fields.Selection([('in_queue', 'In Queue'),
('in_progress', 'In Progress'),
('done', 'Done')], string="Order progress", default='inqueue', store=True)
no_items = fields.Integer(string='No of Items', store=True)
queue_line_ids = fields.One2many('pos.queue.line', 'queue_id')
def create(self):
val = {
"token_number": self.token_number,
"partner_id": self.partner_id,
"queue_line_ids": self.queue_line_ids,
}
self.env['pos.queue'].create(val)
Yes so i was finding solution to pass orderline data in my database along with other as i came a long way from time this question was passed so i felt obliged to share my findings and modification which enable to pass token number Customer id Estimated time & status.
Following are the modification i did so far
The list :
val_list = {
'token_number':Token,
'partner_id':customer_name,
'pos_order_id':torder.name,
'est_time':e_time,
'order_progress':torder.order_progress,
};
where torder is this.pos.get_order().
MY rpc query become like (thanks to my supervisor)
return rpc.query({
model: 'pos.queue',
method: 'create_token',
args:[val_list],
}).then(function () {
console.log("Success")
}).catch(function (reason){
var error = reason.message;
console.log(error);
});
the model became like:
class POSOrderQueue(models.Model):
_name = 'pos.queue'
token_number = fields.Integer(string="Token Number", store=True)
partner_id = fields.Char(store=True)
pos_order_id = fields.Char(store=True)
est_time = fields.Text(string="estimated time", store=True)
order_progress = fields.Selection([('in_queue', 'In Queue'),
('in_progress', 'In Progress'), ('cancel', 'Cancel'),
('done', 'Done')], string="Order progress", default='in_queue', store=True)
no_items = fields.Integer(string='No of Items', store=True)
queue_line_ids = fields.One2many('pos.queue.line', 'queue_id')
#api.model
def create_token(self, val_list):
res = super(POSOrderQueue, self).create(val_list)
print("yes working")
return res
class POSOrderQueueLine(models.Model):
_name = 'pos.queue.line'
queue_id = fields.Many2one('pos.queue')
product_name = fields.Char(store=True)
product_quant = fields.Integer()
product_price = fields.Float()
def create(self, vals):
res = super(POSOrderQueueLine, self).create(vals)
return res
The problem is partially solved but i can't acheive my last objective which is to pass orderline data through rpc query into my model pos.queue.line so it can be viewable in my custom view of odoo13 which is like this
screenshot of my view table

How to turn google sheet data into json

I am currently trying to have a script that I can use in order to turn google sheet data into json that can include neighboring AND nested objects. Currently what I have is a script that can allow for the sheet data to turn into json that allows for nesting objects BUT it does not allow the ability to end one object and start a new one so there cannot be any neighboring objects and instead there's one parent object with children objects in it which is not what I'm after. I'm hoping that I'm just missing something in the current script in order to be able to end and start new objects so I will add the script below, thank you for any contributions to this question!
function formJSON() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var data = sheet.getDataRange().getValues();
var currentObject = {};
var output = currentObject;
for (var i = 0; i < data.length; i++) {
if (data[i][1]) {
currentObject[data[i][0]] = data[i][1];
}
else {
var newObject = {};
currentObject[data[i][0]] = newObject;
currentObject = newObject;
}
}
Logger.log(JSON.stringify(output));
}
EDIT: Here I will provide the current result vs the result I'm after. The first result is from the sheet I have added as an image.
Current Result:
{
"": {
"asset": {
"button": {
"viewPDF": "View PDF",
"viewSurvey": "View Survey",
"viewPPT": "View PPT",
"viewLink": "View Link",
"rejoinMeeting": "Rejoing Meeting",
"labels": {
"associatedWith": "Associated Content",
"attendees": "Attendees in this session",
"filesAndDocs": "Files and Documents",
"location": "Location",
"messages": {
"errorRetrieving": "There was an error retrieving the session details",
"noAttendees": "Nobody is watching this session currently",
"browser": {
"messages": {
"notSupported": "Your browser is not supported",
"update": "Please update"
}
}
}
}
}
}
}
}
Desired Result:
"asset": {
"buttons": {
"viewPDF": "View PDF",
"viewSurvey": "View Web Page",
"viewPPT": "View Presentation",
"viewLink": "View Link",
"rejoinMeeting": "Rejoin Meeting"
},
"labels": {
"associatedWith": "Associated Content",
"attendees": "Attendees in this Session",
"filesAndDocs": "Files and Documents",
"location": "Location",
"notStarted": "This session hasn't started yet.",
"playlist": "Session Playlist",
"premiumSponsors": "Premium Sponsors",
},
"messages": {
"errorRetrieving": "There was an error retrieving the session details.",
"noAttendees": "Nobody is watching this session currently",
"pointsForDocument": "viewing a document",
"pointsForRatingAsset": "rating this asset",
"pointsForVideo": "watching a video",
"problemSaving": "There was a problem saving your rating. Please try again."
}
},
"browser": {
"messages": {
"notSupported": "Your Browser Is Not Supported",
"update": "Please download the most up-to date version of one of the following and try again"
}
},
Please have a look at the following:
var data = sheet.getDataRange().getValues();
var currentObject = {};
var title ='';
var newObject = {};
for (var i = 0; i < data.length; i++) {
if (data[i][1]) {
newObject[data[i][0]] = data[i][1];
}
else {
if(data[i][0] !="" && data[i][0] !=" "){
if(title != ""){
currentObject[title] = newObject;
}
title = data[i][0];
newObject = {};
}
}
}
Logger.log(JSON.stringify(currentObject));
While this is not a full solution, I think that it should point you into the right direciton.
The idea is that you should have some variable (in this case title) which is defined / overwriten in the else statement and which is the key to which nested objects will be assigned during the next if conditions
Once the else condition is entered again, title is overwritten wiht the next nested object key.

How do I fix TypeError undefined in JavaScript? All fields exist for the object

In my piece of code below I receive a JSON object from a java Servlet and access the properties of that object.
JSON object:
{
"redirect": "/index.html",
"logout": "/_cloudshellProxy/_ah/logout?continue\u003d%2Findex.html",
"status": true,
"register": true,
"user": {
"email": "s#example.com",
"username": "Yevesky",
"college": {
"name": "Lafayette College",
"key": "aglzcHN0ZWFtMTlyFAsSB0NvbGxlZ2UYgICAgICAswgM"
},
"key": "aglzcHN0ZWFtMTlyEQsSBFVzZXIYgICAgICgxAgM"
}
}
Here is how I handle the object from the servlet.
fetch("/getUserInfo").then(response => response.json()).then(object =>
{
jsonObject = object;
console.log(jsonObject);
setUpUserPage(jsonObject);
loadClasses();
});
function setUpUserPage(json){
const jsonData = json;
var name = document.createElement("h3");
name.innerText = String(jsonData.username);
var uni = document.createElement("h6");
uni.innerText = String(jsonData.college.name); // Error occurs here
var classification = document.createElement("h6");
console.log(jsonData.classes);
if (jsonData?.isProf)
{
classification.innerText = "Professor";
}
else
{
classification.innerText = "Student";
}
var email = document.createElement("h6");
email.innerText = String(jsonData.email);
var spacer = document.createElement("BR");
//change nickname link
var changeNicknameP = document.createElement("p");
changeNicknameP.innerText = "Change your nickname: ";
var anchor = document.createElement("A");
var link = document.createTextNode("here");
anchor.setAttribute("href", "#");
anchor.appendChild(link);
changeNicknameP.appendChild(anchor);
var profileContainer = document.getElementById("profile-container");
profileContainer.appendChild(name);
profileContainer.appendChild(uni);
profileContainer.appendChild(classification);
profileContainer.appendChild(email);
profileContainer.appendChild(spacer);
profileContainer.appendChild(changeNicknameP);
}
The problem is I do not understand why I am getting a "TypeError: Cannot read property 'name' of undefined" if the object has such a property?
Is it just JavaScript or I am not following a procedure.
I do print the JSON object on console everytime to see if indeed the property exist.
This is because you probably made a mistake. "college" is a property of user, not your jsonData. Replace your line with this :
uni.innerText = String(jsonData.user.college.name);
Don't forget to check properties of your object if response can change (for example is user or college are optionnal properties in some case)
PS: sorry I can't post a comment because I dont have enough point on SO.

User ID not posting to Firebase

I'm trying to allow logged-in users post a title and description with their Google ID to Firebase, but the user ID is giving an undefined error in the console.
The error is only triggered when addIdea() function is called, when the form is posted. Form elements are simply ng-models for title and desc.
var app = angular.module("fluttrApp", ["firebase"]);
app.controller("fluttrCtrl", function($scope, $firebase) {
var ref = new Firebase("[forge].firebaseio.com/ideas");
var auth = new FirebaseSimpleLogin(ref, function(error, user) {
if (!user) {
auth.login('google', {
rememberMe: true
});
}
else {
console.log(user.displayName);
console.log(user.uid)
$scope.displayName = user.displayName;
$scope.uid = user.uid;
}
});
var sync = $firebase(ref);
$scope.ideas = sync.$asArray();
$scope.title = "";
$scope.desc = "";
$scope.addIdea = function(title, desc, uid) {
$scope.displayName = user.displayName;
$scope.uid = user.uid;
$scope.ideas.$add(
{
"title": title,
"desc": desc,
"user": uid
}
);
//The user id needs to be pulled and we need to post
//the idea id generated here to the user branch
$scope.title = '';
$scope.desc = '';
}
});
The object user is undefined because it is out of the scope of the $scope.addIdea() function.
It exists only in the callback of FirebaseSimpleLogin call.
Take a look at this example Monitoring Authentication for reference.

Categories