Source: models/groups.js


/**
 * Class handles groups (basedata) and offers methods dealing with groups in core database
 * @class
 */
class groups {
  /**
   * @constructor
   * @param {object} alogger Logger to be used for output of class methods (usually req.app.logger)
   */
  constructor(alogger) {
    // always initialize all instance properties
    this.logger = alogger;
  }

  /**
   * Returns list of all existing groups
   * @param {function} callback rows
   */
  getListOfGroups(callback) {
    this.logger.debug('MODELS-GROUPS | Reading Groups');
    let query = "SELECT * FROM `groups`";

    global.coreDb.all(query, [], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error loading groups from core data: ' + err.message);
        return callback(null);
      } else {
        return callback(rows);
      }
    });
  }

  /**
   * Loads a group for a given group id
   * @param {integer} gId group id to load data for from core database
   * @param {function} callback row or null
   */
  getGroupForId(gId, callback) {
    this.logger.debug('MODELS-GROUPS | Reading Group for id ' + gId);
    let query = "SELECT * " +
      "FROM `groups` " +
      "WHERE id = ?";

    global.coreDb.all(query, [
      gId
    ], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error loading group from core data for id ' + gId + ': ' + err.message);
        return callback(null);
      } else {
        return callback(rows);
      }
    });
  }

  /**
   * Returns list of groups for admin UI table view
   * @param {function} callback rows or null
   */
  getlistOfGroupsForUI(callback) {
    this.logger.debug('MODELS-GROUPS | Reading Groups');
    let query = "SELECT groups.id," +
      "groups.groupname," +
      "organizations.id AS organizationid, " +
      "organizations.name AS organizationname, " +
      "organizations.city AS organizationcity " +
      "FROM `groups` " +
      "INNER JOIN organizations ON groups.organizationid = organizations.id";

    global.coreDb.all(query, [], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error loading groups from core data for UI: ' + err.message);
        return callback(null);
      } else {
        return callback(rows);
      }
    });
  }

  /**
   * Returns rows with groups for given organization id
   * @param {integer} orgId Organization id groups to be loaded for
   * @param {*} callback rows or null
   */
  getListOfGroupsForOrganization(orgId, callback) {
    this.logger.debug('MODELS-GROUPS | Reading Groups for organization ' + orgId);
    let query = "SELECT * FROM `groups` WHERE organizationid = ?";

    global.coreDb.all(query, [
      orgId
    ], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error loading groups for organization with id ' + orgId + ' from core data: ' + err.message);
        return callback(null);
      } else {
        return callback(rows);
      }
    });
  }

  /**
   * Returns rows with groups for given basedata id
   * @param {integer} basedataId basedata id groups should be loaded for
   * @param {function} callback rows or null
   */
  getListOfGroupsForBaseData(basedataId, callback) {
    this.logger.debug('MODELS-GROUPS | reading Groups for basedata record with id ' + basedataId + ' is referenced for');
    let query = "SELECT groupId FROM xt_basedata_groups WHERE basedataId = ?";

    global.coreDb.all(query, [
      basedataId
    ], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error loading groups for basedata with id ' + basedataId + ' from core data: ' + err.message);
        return callback(null);
      } else {
        return callback(rows);
      }
    });
  }

  /**
   * 
   * @param {Array} groupsArray Array of new groups to be added
   * @param {integer} basedataId basedata id the new groups shall be added for
   * @param {function} callback true or false (success)
   */
  assignGroupsToUser(groupsArray, basedataId, callback) {
    this.logger.debug('MODELS-GROUPS | Assigning Group(s) to user with userid: ' + basedataId);
    let delQuery = "DELETE FROM xt_basedata_groups WHERE basedataId = ?";
    let valuesPart = '';
    global.coreDb.run(delQuery,
      [
        basedataId
      ],
      function (err) {
        if (err) {
          this.logger.error('MODELS-GROUPS | Error removing existing groups for basedata with id ' + basedataId + ': ' + err.message);
          callback(false);
        } else {
          // successfully removed existing groups
          // Now add the new array as rows to core database
          if (Array.isArray(groupsArray)) {
            let values = [];
            groupsArray.forEach(group => {
              values.push('(' + basedataId + ', ' + group[0] + ')');
            });
            valuesPart = values.join(',');
          } else {
            valuesPart = '(' + basedataId + ', ' + groupsArray + ') ';
          }

          if (valuesPart.length > 1) {
            let query = "INSERT INTO xt_basedata_groups (basedataId, groupId) VALUES " + valuesPart + ";";
            global.coreDb.run(query, [], function (err) {
              if (err) {
                console.log('ERROR Adding new groups for basedata with id ' + basedataId + ' enty to core database: ' + err.message);
                callback(false);
              } else {
                callback(true);
              }
            });
          } else {
            callback(false);
          }
        }
      });
  }

  /**
   * 
   * @param {string} groupName Name of the group as group should be displayed in UI
   * @param {integer} orgId organization id the group should be added for
   * @param {function} callback success, true or false
   */
  addGroupforOrganization(groupName, orgId, callback) {
    this.doesGroupExistForOrganization(groupName, orgId, (groupExists) => {
      if ((groupExists !== null) && (groupExists !== true)) {
        // group seems not to exist -> add group to core database
        let query = "INSERT INTO `groups` (groupname, organizationid) VALUES (?, ?)";
        global.coreDb.run(query, [
          groupName, orgId
        ], function (err) {
          if (err) {
            console.log('ERROR Adding new group for organization with id ' + orgId + 'to core database: ' + err.message);
            callback(false);
          } else {
            callback(true);
          }
        });
      } else {
        // can not add group as group exists or check could not be performed
        callback(false);
      }
    })
  }

  /**
   * 
   * @param {integer} gId Group-ID
   * @param {string} groupName New group name
   * @param {integer} oId organization ID
   * @param {function} callback success, false or true
   */
  updateGroup(gId, groupName, oId, callback) {
    this.doesGroupExistForOrganization(groupName, oId, (bolExists) => {
      if (bolExists !== true) {
        let query = "UPDATE `groups` SET `groupname` = ?, organizationid = ?  WHERE `groups`.`id` = ?";
        global.coreDb.run(query, [
          groupName,
          oId,
          gId
        ], function (err) {
          if (err) {
            console.log('ERROR Updating group with id ' + gId + ' in core database: ' + err.message);
            return callback(false);
          } else {
            return callback(true);
          }
        })
      } else {
        return callback(false);
      }
    })
  }

  /**
   * Deletes a group from core database
   * @param {integer} gId group ID of group to be deleted
   * @param {function} callback success, true or false
   */
  deleteGroup(gId, callback) {
    let query = "DELETE from groups WHERE id = ?";
    global.coreDb.run(query, [
      gId
    ], function (err) {
      if (err) {
        console.log('ERROR Deleting group with id ' + gId + ' in core database: ' + err.message);
        return callback(false);
      } else {
        return callback(true);
      }
    })
  }

  /**
   * 
   * @param {string} groupName Name of the group
   * @param {integer} orgId organization id
   * @param {function} callback success true -> exists, false -> not existing, null -> error in query
   */
  doesGroupExistForOrganization(groupName, orgId, callback) {
    let query = "SELECT * FROM groups WHERE groupname = ? AND organizationid = ?";
    global.coreDb.all(query, [
      groupName,
      orgId
    ], (err, rows) => {
      if (err) {
        this._logger.error('GROUPS-MODEL | Error checking for existing group in organization: ' + err.message);
        return callback(null);
      } else {
        if (rows.length > 0) {
          return callback(true);
        } else {
          return callback(false);
        }
      }
    });
  }

}

// export the class
module.exports = groups;