Пример #1
0
        public async Task <IActionResult> CreateDepartment([FromBody] DepartmentDto deptResource)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var user = await _userRepo.GetUser(_userRepo.GetLoggedInUserId());

                if (deptResource.OrganizationId == null && user.OrganizationId != null)
                {
                    deptResource.OrganizationId = user.OrganizationId;
                }

                if (_deptRepo.CheckDepartmentCode(deptResource.Code, deptResource.OrganizationId))
                {
                    ModelState.AddModelError("Error", "The Department with this Code already exists.");
                    return(BadRequest(ModelState));
                }
                var org = await _orgRepo.GetOrganization(user.OrganizationId);

                if (org == null)
                {
                    return(NotFound());
                }

                var dept = _mapper.Map <DepartmentDto, OrganizationDepartment>(deptResource);
                dept.Deleted   = false;
                dept.Protected = false;
                org.OrganizationDepartments.Add(dept);
                await _unitOfWork.CompleteAsync();

                dept = await _deptRepo.GetDepartment(dept.Id);

                var result = _mapper.Map <OrganizationDepartment, DepartmentDto>(dept);
                return(Ok(result));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Error", "An error occured while performing this operation.");
                return(BadRequest(ModelState));
            }
        }