Beispiel #1
0
        public HttpResponseMessage UpdateStatus(int id, ServiceModel.UpdateThingStatusViewModel viewModel)
        {
            var thing = context.GetAll <DomainModel.Thing>()
                        .FirstOrDefault(u => u.Id == id);

            DomainModel.ThingStatus realStatus;

            if (!Enum.TryParse <DomainModel.ThingStatus>(viewModel.Status, true, out realStatus))
            {
                ModelState.AddModelError("", "Invalid Status");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            if (thing == null)
            {
                ModelState.AddModelError("", "Invalid Thing");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            var user = context.GetAll <DomainModel.User>()
                       .FirstOrDefault(u => u.Id == viewModel.UserId);

            if (user == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "Invalid user"));
            }

            if (thing.OwnerId != user.Id && !thing.AssignedTo.Any(at => at.AssignedToUserId == user.Id) && !thing.Team.Members.Admins().Any(a => a.Id == user.Id))
            {
                ModelState.AddModelError("", "A thing's status can only be completed by someone assigned to it, the thing's owner, or a team administrator.");
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            thing.UpdateStatus(user, realStatus);
            context.SaveChanges();

            if (thing.Status == DomainModel.ThingStatus.Completed)
            {
                emailService.ThingCompleted(thing.AssignedTo.Select(x => x.AssignedToUser).ToArray(), user, thing).Send();
            }

            var sThing   = thing.MapToServiceModel();
            var response = Request.CreateResponse(HttpStatusCode.OK, sThing);

            response.Headers.Location = new Uri(Request.RequestUri, "/api/thing/" + thing.Id.ToString());
            return(response);
        }