Exemplo n.º 1
0
        public HttpResponseMessage Post(ServiceModel.AddThingViewModel newThing)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.ToJson()));
            }

            var thingCreator = context.GetAll <DomainModel.User>()
                               .FirstOrDefault(u => u.Id == newThing.CreatedById);

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

            var team = context.GetAll <DomainModel.Team>()
                       .FirstOrDefault(u => u.Id == newThing.TeamId);

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

            var thing = new DomainModel.Thing(team, thingCreator);

            thing.Description = newThing.Description;

            foreach (var userId in newThing.AssignedTo)
            {
                var assignedTo = context.GetAll <DomainModel.User>()
                                 .FirstOrDefault(u => u.Id == userId);

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

                thing.AssignedTo.Add(new DomainModel.UserThing(thing, assignedTo, thingCreator));
            }

            emailService.ThingAssigned(thing.AssignedTo.Select(x => x.AssignedToUser).ToArray(), thing, thingCreator).Send();

            context.Add(thing);
            context.SaveChanges();

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

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