Round robin leads assignment

In workflows documentation there is a brief expatriation on how to implement a round robin leads assignment - https://docs.twenty.com/user-guide/workflows/internal-automations#lead-assignment-round-robin But i can't really find a code example for the "Code action to determine next rep in rotation" step, nor any documentation for the code step of the workflow at all, could please somebody share?
5 Replies
martmull
martmull2w ago
you can do something like this i guess:
export const main = ({ lastAssignedRepId, reps }: {
lastAssignedRepId: string | null;
reps: Array<{ id: string }>;
}) => {
if (!lastAssignedRepId) {
// No previous assignment: start from the first rep
return { nextRepId: reps[0].id};
}

const index = reps.findIndex(r => r.id === lastAssignedRepId);

if (index === -1 || index === reps.length - 1) {
// Last rep was not found or it was the last in the list → wrap to first
return { nextRepId: reps[0].id };
}

// Otherwise → pick the next rep in sequence
return { nextRepId: reps[index + 1].id };
}
export const main = ({ lastAssignedRepId, reps }: {
lastAssignedRepId: string | null;
reps: Array<{ id: string }>;
}) => {
if (!lastAssignedRepId) {
// No previous assignment: start from the first rep
return { nextRepId: reps[0].id};
}

const index = reps.findIndex(r => r.id === lastAssignedRepId);

if (index === -1 || index === reps.length - 1) {
// Last rep was not found or it was the last in the list → wrap to first
return { nextRepId: reps[0].id };
}

// Otherwise → pick the next rep in sequence
return { nextRepId: reps[index + 1].id };
}
you can add a step before to search all your active reps
Vladislav
VladislavOP6d ago
Hi, thank you! To be honest i couldn't really get the model you had in your example, should lastAssignedRepId be a field of the model and reps a relation? like i'm undestandifn the code, but don't clearly understand the data model it's working with
martmull
martmull5d ago
lastAssignedRepId is an optional parameter of the function that is computed in the first step of the workflow "Search Records to find the last assigned rep". reps are the list of the reps which can be assigned to a lead. It can be extracted from another search step. Is that clearer? Don't hesitate to ask questions if still blurry
No description
Vladislav
VladislavOP5d ago
Thanks! Now i got it, i was confused at first on assigning values to the variables, but figured it out now. The UI is a bit hard to get from the first time, i'm personally missing a hover on the assignment button.
No description
martmull
martmull5d ago
Thanks for the report @Thomas

Did you find this page helpful?