Generated tasks for an entity

I’m checking if it will be worth generating tasks based on picked groups of tasks, sort of like templates for a set of tasks. An entity may make use of multiple templates.

You then click on a button of the entity once you have selected your templates, and it generates them under a different Type in the same App, and reference the order ID in a different text field of the task.

Wondering if there’s a better way to go about it; either the setup as a whole, or the way of generating. Any ideas or feedback?

A concern I have is if you’re generating the set of tasks more than once by accident.

It works, but could probably better with for instance referencing the Customer type instead of a text field with ID.

The fields of concern here are highlighted with green, with Bestilling as the entrypoint.
Bestilling has multiple Oppgave Template, which is made up of a set of Oppgave.

Select the template(s) in Bestilling, click button, and the Oppgave's are “copied” over to Oppgave (purple) with a text field referencing an order/customer ID in Bestilling.

Bestilling button

const api = context.getService("fibery");
const e = args.currentEntities[0];

// Get full schema for current entity
const t = await api.getEntityById(e.type, e.id, ["Oppgave maler"]);

if (!t["Oppgave maler"].length) return; // Quit early if no task templates assigned.

// Access the map for tasks and merge all templates in to array of their ID's
const templateIds = [].concat(...t["Oppgave maler"]).map(o => o.id);

// Get the tasks of these ID's, return arrays of 'Oppgave' entity, which is referred to as plural 'Oppgaves' in type 'Ressurser/Oppgave Template'.
let allTasks = await api.getEntitiesByIds("Ressurser/Oppgave Template", templateIds, ["Oppgaves"]);

// [{id: "x", Oppgaves:[{id: "x"},{id: "x"}]}, {id: "x", Oppgaves:[{id: "x"},{id: "x"}]}]
allTasks = [].concat(...allTasks.map(template => template["Oppgaves"].map(oppgave => oppgave.id)));

// allTasks are now ID's of specific tasks ["x","x"]. Ignore editor's warning on 'allTasks'
let tasks = await api.getEntitiesByIds("Ressurser/Oppgave", allTasks, ["Name"]);

// 'tasks' is now array of objects: {id: "x", "Name":"Some task"}
// Create tasks in current app
await asyncForEach(tasks, async _t=> {
    await api.createEntity(e.type.split("/")[0] + "/Oppgave", { "Name": _t.Name, "Kundenummer": e.Kundenummer })
});

// Async await forEach to avoid pending promise error
async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

Bestilling, picking and generating tasks

Tasks generated from clicking button

image

A task template, with a set of tasks