Ejemplo n.º 1
0
        public async Task <IActionResult> CreatePeriod([FromRoute] int budgetId, [FromBody] PeriodRequest request)
        {
            var userId = User.Claims.FirstOrDefault(c => c.Type == "id").Value;

            // check if user exists
            var userExists = await _identityService.CheckIfUserExists(userId);

            if (!userExists)
            {
                return(NotFound(new ErrorResponse(new ErrorModel {
                    Message = $"There is no user with id: {userId}"
                })));
            }

            // check if new period budgetId is correct
            var budget = await _budgetService.GetBudgetAsync(budgetId);

            if (budget == null)
            {
                return(NotFound(new ErrorResponse(new ErrorModel {
                    Message = $"There is no budget with id: {budgetId}"
                })));
            }

            if (budget.UserId != userId)
            {
                return(Forbid());
            }


            // Check if new period dates are between any other period dates
            var periodList = await _periodService.GetBudgetPeriodsAsync(budgetId);

            if (periodList.Any(x => x.FirstDay <= request.FirstDay && x.LastDay >= request.FirstDay))
            {
                return(BadRequest(new ErrorResponse(new ErrorModel {
                    FieldName = nameof(request.FirstDay), Message = "First day of new period cannot be between other period dates"
                })));
            }
            if (periodList.Any(x => x.FirstDay <= request.LastDay && x.LastDay >= request.LastDay))
            {
                return(BadRequest(new ErrorResponse(new ErrorModel {
                    FieldName = nameof(request.LastDay), Message = "Last day of new period cannot be between other period dates"
                })));
            }

            // create new period
            var period = await _periodService.NewPeriodAsync(request, userId);

            if (period == null)
            {
                return(BadRequest(new ErrorResponse(new ErrorModel {
                    Message = "Could not create new period"
                })));
            }

            var locationUri = _uriService.GetPeriodUri(budgetId, period.Id);

            return(Created(locationUri, new Response <PeriodResponse>(_mapper.Map <PeriodResponse>(period))));
        }