Ejemplo n.º 1
0
        public async Task <IActionResult> CreateSuggestion([FromBody] CreateSuggestionViewModel model)
        {
            // Verify that everything is valid before calling the service
            var str = await _soStringService.GetStringByIdAsync(model.StringId);

            // if the string id is invalid
            if (str == null)
            {
                return(BadRequest(SuggestionCreationResult.InvalidStringId));
            }

            // empty suggestion
            if (model.Suggestion.IsNullOrEmpty())
            {
                return(BadRequest(SuggestionCreationResult.EmptySuggestion));
            }

            var usingRawString = model.RawString &&
                                 (await _authorizationService.AuthorizeAsync(User, TraducirPolicy.CanReview)).Succeeded;

            // fix whitespaces unless user is reviewer and selected raw string
            if (!usingRawString)
            {
                model.Suggestion = FixWhitespaces(model.Suggestion, str.OriginalString);
            }

            // if the suggestion is the same as the current translation
            if (str.Translation == model.Suggestion)
            {
                return(BadRequest(SuggestionCreationResult.SuggestionEqualsOriginal));
            }

            // if there's another suggestion with the same value
            if (str.Suggestions != null && str.Suggestions.Any(sug => sug.Suggestion == model.Suggestion))
            {
                return(BadRequest(SuggestionCreationResult.SuggestionAlreadyThere));
            }

            // if there are missing or extra values
            var variablesInOriginal   = VariablesRegex.Matches(str.OriginalString).Select(m => m.Value).ToArray();
            var variablesInSuggestion = VariablesRegex.Matches(model.Suggestion).Select(m => m.Value).ToArray();

            if (!usingRawString && variablesInOriginal.Any(v => !variablesInSuggestion.Contains(v)))
            {
                return(BadRequest(SuggestionCreationResult.TooFewVariables));
            }

            if (variablesInSuggestion.Any(v => !variablesInOriginal.Contains(v)))
            {
                return(BadRequest(SuggestionCreationResult.TooManyVariables));
            }

            var suggestionResult = await _soStringService.CreateSuggestionAsync(
                model.StringId,
                model.Suggestion,
                User.GetClaim <int>(ClaimType.Id),
                User.GetClaim <UserType>(ClaimType.UserType),
                model.Approve);

            if (suggestionResult)
            {
                return(new EmptyResult());
            }

            return(BadRequest(SuggestionCreationResult.DatabaseError));
        }