Name

sn_employee.ep_portalUtilSNC

Description

WARNING Customers should NOT modify this script The purpose of this script include is to provide default behaviours for the ep_portalUtil script include. To change the behaviour of these methods (or add new methods), Customers should override/add new methods to the ep_portalUtil script include.

Script

var ep_portalUtilSNC = Class.create();
ep_portalUtilSNC.prototype = {
  initialize: function(userId) {
      this.epUtils = new sn_employee.ep_Utils();
      this.defaultBanner = "1a8b35b0070c01108d6d78e99cd30063";
      if (userId) {
          // employeeProfileGR: GlideRecord of employee profile currently queried on.
          this.employeeProfileGR = this.epUtils.getEmployeeProfileRecord(userId);
          this.sysUserGR = this.epUtils.getSysUserRecord(userId);
          this.hrProfileGR = this.epUtils.getHRProfileRecord(userId);
      }
      this.editableFields = {
          'short_bio': {
              maxlength: 255,
              fieldType: 'textarea'
          },
          'nickname': {
              maxlength: 40,
              fieldType: 'string'
          },
          'preferred_pronoun': {
              fieldType: 'choice',
              options: this.getChoiceFieldOptions('preferred_pronoun')
          }
      };
      this.userSelectablePublicFields = ['preferred_pronoun'];
      this.isLoggedInUserProfile = (gs.getUserID() == userId);
  },

  /**
     returns {Boolean} Boolean indicating whether employee profile record exists or not
   */
  employeeProfileExists: function() {
      return !gs.nil(this.employeeProfileGR);
  },

  /**
     @param : deviceType => Not mandatory, if mobile is sent, then it will create the encoded query to only get mobile sections, otherwise will get portal visible fields
     Returns all available overview sections for specified employee
     returns {Array} Array of overview sections visible to logged in user
   */
  getOverviewSections: function(deviceType) {
      var employeeProfileGR = this.employeeProfileGR;
      var encodedQueryForVisibility = deviceType === "mobile" ? "section_visibilityINmobile,both" : "section_visibilityINportal,both";
      if (gs.nil(employeeProfileGR)) {
          return [];
      }
      var overviewSectionIDs = [];
      var overviewSections = {};
      var userId = employeeProfileGR.getValue('user');

      var overviewSectionGR = new GlideRecord('sn_employee_overview_section');
      overviewSectionGR.addActiveQuery();
      overviewSectionGR.orderBy('order');
      overviewSectionGR.orderBy('name');
      overviewSectionGR.addEncodedQuery(encodedQueryForVisibility);
      overviewSectionGR.query();

      while (overviewSectionGR.next()) {
          var sectionId = overviewSectionGR.getUniqueValue();
          overviewSectionIDs.push(sectionId);
          overviewSections[sectionId] = {
              'sysId': sectionId,
              'name': overviewSectionGR.getDisplayValue('name'),
              'order': overviewSectionGR.getDisplayValue('order'),
              'hideSectionName': !!overviewSectionGR.hide_section_name,
              'layout': overviewSectionGR.getValue('layout'),
              'fields': [],
          };
      }

      var overviewSectionFieldGR = new GlideRecord('sn_employee_overview_section_field');
      overviewSectionFieldGR.addActiveQuery();
      overviewSectionFieldGR.addQuery('section', 'IN', overviewSectionIDs);
      overviewSectionFieldGR.addQuery('field_visibility', 'IN', this._getFieldVisibilityCondition());
      overviewSectionFieldGR.orderBy('order');
      overviewSectionFieldGR.orderBy('field');
      overviewSectionFieldGR.query();

      while (overviewSectionFieldGR.next()) {
          var fieldName = overviewSectionFieldGR.getValue('field');
          if (this._hasAccessToField(fieldName)) {
              var fieldJSON = {
                  'sysId': overviewSectionFieldGR.getUniqueValue(),
                  'fieldLabel': employeeProfileGR.getElement(fieldName).getED().getLabel(),
                  'fieldType': employeeProfileGR.getElement(fieldName).getED().getInternalType(),
                  'fieldInternalValue': fieldName === 'user.manager' ? this.sysUserGR.getValue(fieldName.substring(5)) : employeeProfileGR.getValue(fieldName),
                  'fieldName': fieldName,
                  'fieldValue': employeeProfileGR.getDisplayValue(fieldName),
                  'order': overviewSectionFieldGR.getDisplayValue('order'),
                  'icon': overviewSectionFieldGR.getDisplayValue('icon'),
                  'ariaLabel': this._getFieldAriaLabel(fieldName, employeeProfileGR.getDisplayValue(fieldName))
              };
              if (this.editableFields[fieldName] && this.isLoggedInUserProfile) {
                  fieldJSON['isEditable'] = true;
                  fieldJSON['maxlength'] = this.editableFields[fieldName].maxlength;
                  fieldJSON['fieldType'] = this.editableFields[fieldName].fieldType;
                  if (fieldJSON['fieldType'] === 'choice') {
                      var choiceListArr = this.editableFields[fieldName].options;
                      var matchedIndex;
                      for (var choiceVar = 0; choiceVar < choiceListArr.length; choiceVar++) {
                          if (choiceListArr[choiceVar].label === fieldJSON.fieldValue)
                              matchedIndex = choiceVar;
                      }
                      fieldJSON['choiceIndex'] = matchedIndex ? matchedIndex : 0;

                      fieldJSON['options'] = this.editableFields[fieldName].options;
                  }
              }
              var isUserSelectablePublicField = (this.userSelectablePublicFields.indexOf(fieldName) >= 0);
              if (isUserSelectablePublicField)
                  fieldJSON['isPublic'] = this.isFieldPublic(fieldName);
              if (!isUserSelectablePublicField || this.isLoggedInUserProfile || fieldJSON['isPublic'])
                  overviewSections[overviewSectionFieldGR.getValue('section')].fields.push(fieldJSON);
          }
      }

      var nonEmptySections = [];
      overviewSectionIDs.forEach(function(sectionId) {
          if (overviewSections[sectionId].fields.length > 0) {
              nonEmptySections.push(overviewSections[sectionId]);
          }
      });
      return nonEmptySections;
  },

  /**
     Returns About Section and fields for Non-employee user.
     returns {Array} Array of sections visible for Non-employee user
   */
  getNonEmployeeSections: function() {
      if (!this.sysUserGR.canRead()) {
          return [];
      }
      var sections = [];
      var nonEmployeeFields = [];
      var nonEmployeeFieldsOnUserProfile = ['title', 'email', 'department', 'manager', 'phone', 'mobile_phone'];
      var iconsArray = ['briefcase', 'envelope', 'cube', 'sitemap', 'phone', 'phone'];
      var nonEmployeeFieldLabels = [gs.getMessage('Title'), gs.getMessage('Email'), gs.getMessage('Department'), gs.getMessage('Manager'), gs.getMessage('Business phone'), gs.getMessage('Mobile phone')];

      for (var i = 0; i < nonEmployeeFieldsOnUserProfile.length; i++) {
          var fieldName = nonEmployeeFieldsOnUserProfile[i];
          var fieldValue = this.sysUserGR.getDisplayValue(fieldName);
          var fieldJSON = {
              'sysId': gs.generateGUID(),
              'fieldName': fieldName,
              'fieldType': this.sysUserGR.getElement(fieldName).getED().getInternalType(),
              'fieldLabel': nonEmployeeFieldLabels[i],
              'fieldValue': fieldValue,
              'fieldInternalValue': this.sysUserGR.getValue(fieldName),
              'order': 100,
              'icon': iconsArray[i],
          };
          nonEmployeeFields.push(fieldJSON);
      }
      var aboutSection = {
          'sysId': gs.generateGUID(),
          'name': gs.getMessage('Work details'),
          'order': 100,
          'hideSectionName': false,
          'layout': 'two_column',
          'fields': nonEmployeeFields,
      };
      sections.push(aboutSection);
      return sections;
  },

  /**
     Returns field accessibility honoring field ACLs on User/HR profiles.
     @param {String} fieldName: Current field name.
     returns {Boolean} Field accessibility for logged in user
   */
  _hasAccessToField: function(fieldName) {
      /*if (this.employeeProfileGR.isValidField(fieldName)) {
          return true;
      }
      if (fieldName.startsWith('user.')) {
          return this.sysUserGR.getElement(fieldName.substring(5)).canRead();
      }
      if (fieldName.startsWith('hr_profile.') && !gs.nil(this.hrProfileGR)) {
          return this.hrProfileGR.getElement(fieldName.substring(11)).canRead();
      }
      return false;*/
      // added for fixing defect # DEF0268432
      return this.employeeProfileGR.getElement(fieldName).canRead();
  },

  /**
     Returns field visibility query string based on user id.
     returns {String} Field visibility condition as a string
   */
  _getFieldVisibilityCondition: function() {
      var loggedInUserSysId = gs.getUserID();
      var userId = this.employeeProfileGR.getValue('user');
      var fieldVisibilityQueryString = 'everyone';

      if (userId === loggedInUserSysId) { // If user viewing profile is employee itself
          fieldVisibilityQueryString += ',employee_only,employee_and_manager';
      } else if (this.epUtils.userReportsTo(userId, loggedInUserSysId)) { // If user viewing profile is a manager of employee
          fieldVisibilityQueryString += ',employee_and_manager,manager_only';
      }
      return fieldVisibilityQueryString;
  },

  /*
     Returns required attributes for a specified employee
     @param {GlideRecord} employeeProfileGR: GlideRecord of employee profile currently queried on.
     returns {JSON} JSON of employee profile
  */
  getEmployeeProfileDetails: function() {
      var employeeProfileGr = this.employeeProfileGR;
      var firstName = employeeProfileGr.getDisplayValue("user.first_name") ? (employeeProfileGr.getDisplayValue("user.first_name").charAt(0)) : "";
      var lastName = employeeProfileGr.getDisplayValue("user.last_name") ? (employeeProfileGr.getDisplayValue("user.last_name").charAt(0)) : "";
      var profileDetails = {
          "name": employeeProfileGr.getDisplayValue("user") || "",
          "pronoun": (this.isLoggedInUserProfile || this.isFieldPublic("preferred_pronoun")) ? employeeProfileGr.getDisplayValue("preferred_pronoun") || "" : "",
          "role": employeeProfileGr.getDisplayValue("user.title") || "",
          "department": employeeProfileGr.getDisplayValue("user.department") || "",
          "background_banner": employeeProfileGr.getDisplayValue("background_banner") ? employeeProfileGr.getValue("background_banner") : "",
          "profile_id": employeeProfileGr.getUniqueValue() || "",
          "user_id": employeeProfileGr.getValue("user") || "",
          "initials": firstName + "" + lastName
      };
      return profileDetails;
  },

  /*
     Returns the live profile for a specified employee
     @param {String} userID: userID of the user currently queried on.
     returns {GlideRecord} GlideRecord of live profile visible to logged in user
  */
  getLiveProfileDetails: function(userID) {
      var liveProfileGr = new GlideRecord("live_profile");
      liveProfileGr.addEncodedQuery("document=" + userID + "^type=user");
      liveProfileGr.query();
      if (liveProfileGr.next() && liveProfileGr.canRead()) {
          return liveProfileGr;
      }
      return null;
  },
  /*
     Deletes the employee profile banner for a specified employee
     @param {String} userID: userID of the user currently queried on.
  */
  deleteEmployeeProfileBanner: function() {
      var userID = this.employeeProfileGR.getValue('user');
      var profileGr = new GlideRecord("sn_employee_profile");
      profileGr.addQuery("user", userID);
      profileGr.query();
      if (profileGr.next() && profileGr.canWrite()) {
          profileGr.setValue("background_banner", "");
          profileGr.update();
      }
  },

  /*
      Deletes the employee profile picture for a specified employee
      @param {String} userID: userID of the user currently queried on.
  */
  deleteEmployeeProfilePicture: function() {
      var profileGr = this.getLiveProfileDetails(data.sysUserID);
      if (profileGr) {
          profileGr.setValue("photo", "");
          profileGr.update();
      }
  },

  getChoiceFieldOptions: function(fieldName) {
      var options = [];
      var choiceList = GlideChoiceList.getChoiceList('sn_employee_profile', 'preferred_pronoun');
      for (var choiceVar = 0; choiceVar < choiceList.getSize(); choiceVar++) {
          var choice = choiceList.getChoice(choiceVar);
          var cLabel = choice.getLabel();
          var cValue = choice.getValue();
          var option = {
              'label': cLabel,
              'value': cValue
          }
          options.push(option);
      }
      return options;
  },
  /*
      Update the data when user edits the editable fields in Overview widget
  */
  updateEditableFields: function(field, value) {
      if (this.isLoggedInUserProfile && !!this.editableFields[field]) {
          this.employeeProfileGR.setValue(field, value);
          this.employeeProfileGR.update();
      } else {
          gs.info("The user does not have write access to the field");
      }
  },

  /*
  	Returns the default employee profile banner
  */
  getDefaultBackgroundBanner: function() {
      var image = '';
      var imageGr = new GlideRecord("db_image");
      imageGr.addQuery("sys_id", ep_Constants.defaultEmployeeProfileBanner);
      imageGr.addActiveQuery();
      imageGr.query();
      if (imageGr.next()) {
          image = imageGr.getDisplayValue("image") ? imageGr.getValue("image") : "";
      }
      return image;
  },
  /* 
  	Add or remove the field name to the user preference "employee_profile.public_fields" 
  	@param {Boolean} makePublic: Input taken from user on Overview Widget under "Make it public"
  */
  updateUserPublicFieldPreference: function(fieldName, makePublic) {
      if (this.isLoggedInUserProfile && !!this.editableFields[fieldName]) {
          var preferenceValue = gs.getUser().getPreference(ep_Constants.PUBLIC_FIELD_USER_PREFERENCE);
          var publicFields = [];
          if (preferenceValue != null)
              publicFields = preferenceValue.split(',');
          if (makePublic && publicFields.indexOf(fieldName) < 0) {
              publicFields.push(fieldName);
              gs.getUser().savePreference(ep_Constants.PUBLIC_FIELD_USER_PREFERENCE, publicFields.toString());
          }
          if (!makePublic && publicFields.indexOf(fieldName) >= 0) {
              publicFields.splice(publicFields.indexOf(fieldName), 1);
              gs.getUser().savePreference(ep_Constants.PUBLIC_FIELD_USER_PREFERENCE, publicFields.toString());
          }
      }
  },
  /* 
  	Returns true if the user preference "employee_profile.public_fields" contains the given fieldName
  */
  isFieldPublic: function(fieldName) {
      var preferenceValue = '';
      if (this.isLoggedInUserProfile) {
          preferenceValue = gs.getUser().getPreference(ep_Constants.PUBLIC_FIELD_USER_PREFERENCE);
      } else {
          var userId = this.employeeProfileGR.getValue('user');
          var gr = new GlideRecord('sys_user_preference');
          gr.addQuery('name', ep_Constants.PUBLIC_FIELD_USER_PREFERENCE);
          gr.addQuery('user', userId);
          gr.query();
          if (gr.next()) {
              preferenceValue = gr.getValue('value');
          }
      }
      var publicFields = [];
      if (preferenceValue != null) {
          publicFields = preferenceValue.split(',');
      }
      return (publicFields.indexOf(fieldName) >= 0);
  },
  /*
      Returns the aria label of a field. 
      @param {String} fieldName: Name of the field"
      @param {String} fieledValue: Display value of the field"
  */
  _getFieldAriaLabel: function(fieldName, fieldValue) {
      if (fieldName === 'user.manager')
          return gs.getMessage('Open Profile: {0}', fieldValue);
      return fieldValue;
  },

  type: 'ep_portalUtilSNC'
};

Sys ID

faed5b0aeb333010ed7966d647522815

Offical Documentation

Official Docs: