'Lookup delegations for an entity, ordered either by
receiver (by_role=False) or by affiliation role (by_role=True)
@param entity: the delegating entity (pe_id)
@param role_type: limit the lookup to this affiliation role type,
(can use 0 to lookup 1:1 delegations)
@param by_role: group by affiliation roles
@return: a Storage {<receiver>: [group_ids]}, or
a Storage {<rolename>: {entities:[pe_ids], groups:[group_ids]}}'

def s3_get_delegations(self, entity, role_type=0, by_role=False):

    if ((not entity) or (not self.permission.delegations)):
        return None
    s3db = current.s3db
    dtable = s3db.pr_delegation
    rtable = s3db.pr_role
    atable = s3db.pr_affiliation
    if (None in (dtable, rtable, atable)):
        return None
    query = ((((((rtable.deleted != True) & (dtable.deleted != True)) & (atable.deleted != True)) & (rtable.pe_id == entity)) & (dtable.role_id == rtable.id)) & (atable.role_id == rtable.id))
    if (role_type is not None):
        query &= (rtable.role_type == role_type)
    rows = current.db(query).select(atable.pe_id, rtable.role, dtable.group_id)
    delegations = Storage()
    for row in rows:
        receiver = row[atable.pe_id]
        role = row[rtable.role]
        group_id = row[dtable.group_id]
        if by_role:
            if (role not in delegations):
                delegations[role] = Storage(entities=[], groups=[])
            delegation = delegations[role]
            if (receiver not in delegation.entities):
                delegation.entities.append(receiver)
            if (group_id not in delegation.groups):
                delegation.groups.append(group_id)
        elif (receiver not in delegations):
            delegations[receiver] = [group_id]
        else:
            delegations[receiver].append(group_id)
    return delegations
