/// <summary>
        /// Sends approval notification card to team.
        /// </summary>
        /// <param name="groupEntity">Employee resource group entity.</param>
        /// <param name="serviceBasePath">Service URL.</param>
        /// <param name="groupCreatorName">Group creator name.</param>
        /// <returns>A task representing asynchronous operation.</returns>
        public async Task SendGroupApprovalNotificationAsync(
            EmployeeResourceGroupEntity groupEntity,
            string serviceBasePath,
            string groupCreatorName)
        {
            var teamNotificationAttachment = this.cardHelper.GetApprovalCard(groupEntity, groupCreatorName);

            await this.SendProactiveNotificationCardAsync(teamNotificationAttachment, serviceBasePath);
        }
        /// <summary>
        /// Get approval notification card attachment.
        /// </summary>
        /// <param name="groupEntity">Employee resource group entity.</param>
        /// <param name="groupCreatorName">Group creator name.</param>
        /// <param name="approvalStatusText">Represents the approval status text.</param>
        /// <returns>Approval notification card attachment.</returns>
        public Attachment GetApprovalCard(EmployeeResourceGroupEntity groupEntity, string groupCreatorName, string approvalStatusText = null)
        {
            string cardTemplate;

            this.logger.LogInformation("Get approval card initiated.");
            var approvalCardContents = new ApprovalCardData()
            {
                RequestSubmittedText   = this.localizer.GetString("ApproveCardRequestSubmitted"),
                ApprovalStatusText     = string.IsNullOrEmpty(approvalStatusText) ? this.localizer.GetString("PendingApprovalText") : approvalStatusText,
                ApprovalStatus         = groupEntity.ApprovalStatus.ToString(),
                GroupDescriptionText   = groupEntity.GroupDescription,
                NameText               = this.localizer.GetString("NameText"),
                GroupNameText          = groupEntity.GroupName,
                TagsText               = this.localizer.GetString("TagText"),
                ApproveTagsName        = !string.IsNullOrEmpty(groupEntity.Tags) ? string.Join(", ", JsonConvert.DeserializeObject <List <string> >(groupEntity.Tags)) : string.Empty,
                LocationText           = this.localizer.GetString("LocationText"),
                LocationName           = groupEntity.Location,
                CreatedByNameText      = this.localizer.GetString("CreatedByNameText"),
                CreatedByName          = groupCreatorName,
                SearchEnableText       = this.localizer.GetString("SearchEnabledText"),
                SearchEnableStatusText = groupEntity.IncludeInSearchResults ? this.localizer.GetString("YesText") : this.localizer.GetString("NoText"),
                ApproveButtonText      = this.localizer.GetString("ApproveButtonText"),
                RejectButtonText       = this.localizer.GetString("RejectButtonText"),
                ApprovedCommandText    = Constants.ApprovedText,
                RejectCommandText      = Constants.RejectedText,
                GroupId = groupEntity.GroupId,
            };

            if (groupEntity.ApprovalStatus == (int)ApprovalStatus.PendingForApproval)
            {
                cardTemplate = this.GetCardTemplate(CardCacheConstants.AdminNotificationCardJsonTemplate, ApprovalCardFileName);
            }
            else
            {
                cardTemplate = this.GetCardTemplate(CardCacheConstants.AdminApprovalCardJsonTemplate, ApprovalUpdatedCardFileName);
            }

            var template = new AdaptiveCardTemplate(cardTemplate);
            var card     = template.Expand(approvalCardContents);

            AdaptiveCard adaptiveCard = AdaptiveCard.FromJson(card).Card;
            Attachment   attachment   = new Attachment()
            {
                ContentType = AdaptiveCard.ContentType,
                Content     = adaptiveCard,
            };

            this.logger.LogInformation("Get approval card succeeded.");

            return(attachment);
        }
        public async Task <List <TeamUserMapping> > RunAsync(
            [ActivityTrigger] EmployeeResourceGroupEntity resourceGroupEntity,
            ILogger log)
        {
            try
            {
                var groupEntity = await this.employeeResourceGroupRepository.GetAsync(resourceGroupEntity.PartitionKey, resourceGroupEntity.GroupId);

                var teamUserMappings = new List <TeamUserMapping>();

                if (groupEntity == null)
                {
                    log.LogInformation($"Resource group does not exist :{resourceGroupEntity.GroupName}");

                    return(null);
                }

                // Get active pair up users based on 'IsPaused' flag.
                var userMappings = await this.teamUserPairUpMappingRepository.GetActivePairUpUsersAsync(groupEntity.TeamId);

                foreach (var userMapping in userMappings)
                {
                    try
                    {
                        // Get user details.
                        var userData = await this.usersService.GetUserAsync(userMapping.UserObjectId);

                        // Entity for pair-up mappings to be sent to service bus.
                        teamUserMappings.Add(new TeamUserMapping()
                        {
                            UserGivenName     = userData.DisplayName,
                            UserObjectId      = userData.Id,
                            UserPrincipalName = userData.UserPrincipalName,
                            TeamId            = groupEntity.TeamId,
                            TeamName          = groupEntity.GroupName,
                        });
                    }
                    catch (Exception ex)
                    {
                        log.LogError($"Unable to fetch user details of user:{userMapping.UserObjectId} {ex.Message}");
                    }
                }

                return(teamUserMappings);
            }
            catch (Exception ex)
            {
                log.LogError($"Error while creating pair-up mappings to be sent to service bus: {ex.Message} for Team: {resourceGroupEntity.TeamId}");
                throw;
            }
        }
Beispiel #4
0
        public async Task RunAsync(
            [ActivityTrigger] EmployeeResourceGroupEntity resourceGroupEntity,
            ILogger log)
        {
            try
            {
                var serviceUrl = await this.appSettingsService.GetServiceUrlAsync();

                // Get team members.
                var userEntities = await this.memberService.GetMembersAsync(
                    teamId : resourceGroupEntity.TeamId,
                    tenantId : this.options.Value.TenantId,
                    serviceUrl : serviceUrl);

                foreach (var userEntity in userEntities)
                {
                    // Get user details from mapping storage table if already exists.
                    var userMapping = await this.teamUserPairUpMappingRepository.GetAsync(userEntity.AadId, resourceGroupEntity.TeamId);

                    if (userMapping == null)
                    {
                        var mappingEntity = new TeamUserPairUpMappingEntity
                        {
                            TeamId       = resourceGroupEntity.TeamId,
                            UserObjectId = userEntity.AadId,
                            IsPaused     = false,
                        };

                        log.LogInformation($"Inserting pair-up entity into table storage: {userEntity.AadId}");
                        await this.teamUserPairUpMappingRepository.CreateOrUpdateAsync(mappingEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                log.LogError($"Error while inserting pair-up matches: {ex.Message} for Team: {resourceGroupEntity.TeamId}");
                throw;
            }
        }
        public async Task <ActionResult <EmployeeResourceGroupEntity> > CreateEmployeeResourceGroupAsync([FromBody] EmployeeResourceGroupEntity employeeResourceGroupEntity)
        {
            try
            {
                if (employeeResourceGroupEntity == null)
                {
                    this.logger.LogWarning("Employee resource group entity is null.");
                    return(this.BadRequest(this.localizer.GetString("ResourceGroupNullOrEmptyErrorMessage")));
                }

                // Storage call to get employee resource group entity if present already.
                var groupEntity = await this.employeeResourceGroupRepository.GetFilterDataByGroupLinkOrGroupNameAsync(
                    employeeResourceGroupEntity.GroupType,
                    employeeResourceGroupEntity.GroupLink,
                    employeeResourceGroupEntity.GroupName);

                if (groupEntity != null)
                {
                    this.logger.LogInformation($"Resource group entity already present with same group name {groupEntity.GroupName} or link :{groupEntity.GroupLink}.");
                    return(this.BadRequest(this.localizer.GetString("GroupAlreadyExistsErrorMessage")));
                }

                this.logger.LogInformation("Initiated call to store employee resource group entity.");
                var userId = this.HttpContext.User.FindFirstValue(Constants.ClaimTypeUserId);

                // Validating if resource group type is 'Teams', user must be member of that group and they should belongs to same tenant.
                if (employeeResourceGroupEntity.GroupType == (int)ResourceGroupType.Teams)
                {
                    string tenantId = ParseTeamIdExtension.GetTenantIdFromDeepLink(employeeResourceGroupEntity.GroupLink);

                    if (!this.options.Value.AllowedTenants.Contains(tenantId))
                    {
                        this.logger.LogError($"Tenant is not valid: {tenantId}");
                        return(this.BadRequest(this.localizer.GetString("InvalidTenantErrorMessage")));
                    }

                    string teamId             = ParseTeamIdExtension.GetTeamIdFromDeepLink(employeeResourceGroupEntity.GroupLink);
                    string groupId            = ParseTeamIdExtension.GetGroupIdFromDeepLink(employeeResourceGroupEntity.GroupLink);
                    var    groupMembersDetail = await this.groupMembersService.GetGroupMembersAsync(groupId);

                    var groupMemberAadIds = groupMembersDetail.Select(row => row.Id).ToList();

                    if (!groupMemberAadIds.Contains(userId))
                    {
                        this.logger.LogError($"User {userId} is not a member of the team {teamId}");
                        return(this.Forbid(this.localizer.GetString("InvalidGroupMemberErrorMessage")));
                    }

                    employeeResourceGroupEntity.TeamId = teamId;
                    employeeResourceGroupEntity.IsProfileMatchingEnabled = true;
                }
                else
                {
                    employeeResourceGroupEntity.IsProfileMatchingEnabled = false;
                }

                employeeResourceGroupEntity.Group             = Constants.ResourceGroupTablePartitionKey;
                employeeResourceGroupEntity.GroupId           = this.tableRowKeyGenerator.CreateNewKeyOrderingOldestToMostRecent();
                employeeResourceGroupEntity.ApprovalStatus    = (int)ApprovalStatus.PendingForApproval;
                employeeResourceGroupEntity.CreatedOn         = DateTime.UtcNow;
                employeeResourceGroupEntity.CreatedByObjectId = userId;
                employeeResourceGroupEntity.MatchingFrequency = (int)MatchingFrequency.Monthly;
                await this.employeeResourceGroupRepository.CreateOrUpdateAsync(employeeResourceGroupEntity);

                this.logger.LogInformation("Resource group - HTTP post call succeeded");

                return(this.Created(this.Request.GetDisplayUrl(), employeeResourceGroupEntity));
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error while creating new employee resource group entity.");
                throw;
            }
        }