const logger = require('@pubsweet/logger') const get = require('lodash/get') const createNewTeam = async (collectionId, role, userId, TeamModel) => { let permissions, group, name switch (role) { case 'handlingEditor': permissions = 'handlingEditor' group = 'handlingEditor' name = 'Handling Editor' break case 'reviewer': permissions = 'reviewer' group = 'reviewer' name = 'Reviewer' break case 'author': permissions = 'author' group = 'author' name = 'author' break default: break } const teamBody = { teamType: { name: role, permissions, }, group, name, object: { type: 'collection', id: collectionId, }, members: [userId], } let team = new TeamModel(teamBody) team = await team.save() return team } const setupManuscriptTeam = async (models, user, collectionId, role) => { const teams = await models.Team.all() user.teams = user.teams || [] const filteredTeams = teams.filter( team => team.group === role && team.object.type === 'collection' && team.object.id === collectionId, ) if (filteredTeams.length > 0) { let team = filteredTeams[0] team.members.push(user.id) try { team = await team.save() user.teams.push(team.id) await user.save() return team } catch (e) { logger.error(e) } } else { const team = await createNewTeam(collectionId, role, user.id, models.Team) user.teams.push(team.id) await user.save() return team } } const removeTeamMember = async (teamId, userId, TeamModel) => { const team = await TeamModel.find(teamId) const members = team.members.filter(member => member !== userId) team.members = members await team.save() } const getTeamMembersByCollection = async (collectionId, role, TeamModel) => { const teams = await TeamModel.all() // const members = get( // teams.find( // team => // team.group === role && // team.object.type === 'collection' && // team.object.id === collectionId, // ), // 'members', // ) const team = teams.find( team => team.group === role && team.object.type === 'collection' && team.object.id === collectionId, ) return team.members } const getTeamByGroupAndCollection = async (collectionId, role, TeamModel) => { const teams = await TeamModel.all() return teams.find( team => team.group === role && team.object.type === 'collection' && team.object.id === collectionId, ) } module.exports = { createNewTeam, setupManuscriptTeam, removeTeamMember, getTeamMembersByCollection, getTeamByGroupAndCollection, }