summaryrefslogblamecommitdiffstats
path: root/server/lib/grouphelper.js
blob: 417c1d168259a0dfc6bc4029162ca40bda2259ea (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13



                                                         








                                                                         
                                                           



                                                                              


                                                                                    



                                                                       
                             








                                                                                        


                                                        
 


                               
                                   
/* global __appdir */
var path = require('path')
var db = require(path.join(__appdir, 'lib', 'sequelize'))

async function getAllChildren (groups, groupBlacklist, clientBlacklist) {
  const knownGroupMap = {}
  const knownClientMap = {}
  if (groupBlacklist) groupBlacklist.forEach(group => {
    knownGroupMap[group.id] = true
  })
  if (clientBlacklist) clientBlacklist.forEach(client => {
    knownGroupMap[client.id] = true
  })
  return getAllChildrenByIds(groups.map(x => x.id), {}, {})
}

async function getAllChildrenByIds (groupIds, knownGroupMap, knownClientMap) {
  let [subgroups, clients] = await Promise.all([
    db.group.findAll({ where: { '$parents.id$': groupIds }, include: ['parents'] }),
    db.client.findAll({ where: { '$groups.id$': groupIds }, include: ['groups'] })
  ])

  subgroups = subgroups.filter(subgroup => !knownGroupMap[subgroup.id])
  clients = clients.filter(client => !knownClientMap[client.id])

  if (subgroups.length > 0) {
    let groupIds = subgroups.map(x => x.id)
    for (let i in groupIds) {
      knownGroupMap[groupIds[i]] = true
    }
    let clientIds = clients.map(x => x.id)
    for (let i in clientIds) {
      knownClientMap[clientIds[i]] = true
    }
    let subChildren = await getAllChildrenByIds(groupIds, knownGroupMap, knownClientMap)
    subgroups = [...subgroups, ...subChildren.subgroups]
    clients = [...clients, ...subChildren.clients]
  }

  return { subgroups, clients }
}

module.exports = { getAllChildren }