Ok, I finally found an answer to the above...
I made one fundamental error in the above code, I assumed that the parent setting of a task is the parent task name when in fact it should be the parent task ID allocated to it by the Tasks API.
Then I realised that the parent of a task should be set after it has been inserted into the TasksList and not as part of the initialisation of the new task, so here is what it now looks like:
var taskListID = getTasklistId_(tasklistName);
var parentTask = getParentTask_(projectName,taskListID);
var taskDetails = {
title: title,
notes: notes,
parent: parentTask["id"],
position: parentTask["idx"]
};
var newTask = Tasks.newTask().setTitle(title);
newTask = Tasks.Tasks.insert(newTask, taskListID, taskDetails);
newTask.setParent(parentTask["id"]);
as you can see I have to reset the parent of the new task. The getParentTask_
function returns the parent-task ID and last child element position to insert the new task
function getParentTask_(taskName, taskListId) {
var tasks = Tasks.Tasks.list(taskListId);
var taskID;
var position;
if (tasks.items) {
for (var i = 0; i < tasks.items.length; i++) {
var task = tasks.items[i];
if(taskName == task.title){
taskID = task.id;
Logger.log('Task with title "%s" and ID "%s" was found.', task.title, task.id);
}
//lets pick up the last child task's position in order to insert the new task below
if(taskID == task.parent) position = task.position;
}
}
if( taskID == null){
var newTask = Tasks.newTask().setTitle(taskName);
newTask = Tasks.Tasks.insert(newTask,taskListId);
taskID = newTask.id;
position = newTask.position;
}
var result = {
id: taskID,
idx: position
};
return result;
}
I hope the above helps someone to be creative with the Google Mail Tasks API.
PS: I used this to link the Wordpress WP Project Manager plugin which creates auto-mailers of new tasks and comments. For the full implementation, you can see this post.