public async Task<IHttpActionResult> Respond(InviteRSVP model) { if (!ModelState.IsValid) return BadRequest("Data provided is invalid"); var result = await _invitationService.HandleInviteResponse(model); if (result.Success) return Ok(); return BadRequest(result.Error); }
public async Task<ValidationResult> HandleInviteResponse(InviteRSVP model) { try { //Parse guid Guid? guid = ParseGuid(model.Id); if (guid == null) { Result.Error = "Failed to parse invitation id"; return Result; } //Attempt to load the Invitation from the db Invitation inv = await _inviteRepo.GetByIdAsync(guid.Value); if (inv == null) { Result.Error = "Invitation does not exist for id : " + model.Id; return Result; } //Make sure we aren't processing a previously processed invite if (inv.Responded) { Result.Error = "Invitation has already been processed"; return Result; } //If we are accepting the invitation if (model.Accept) { //Handle the type of invitation switch (inv.TypeId) { //If calendar add member to calendar case (int)LookUpEnums.InvitationTypes.Calendar: Calendar cal = await _calendarRepo.Get(x => x.Id == inv.CalendarId.Value) .Include(x => x.Members).FirstOrDefaultAsync(); if (cal == null) return AddError("Calendar no longer exists. The owner may have deleted the calendar"); //Only add the user if they aren't already a member if (cal.Members.All(x => x.UserId != inv.RecipientId)) { cal.Members.Add(new CalendarMember { UserId = inv.RecipientId}); _calendarRepo.Update(cal); } break; //If Event add member to event case (int)LookUpEnums.InvitationTypes.Event: //Check we have a valid destination calendar to add the event too. Guid? destCalId = ParseGuid(model.DestCalendarId); if (destCalId == null) return AddError("Failed to parse the destination calendar id"); Event evnt = await _eventRepo.Get(x => x.Id == inv.EventId.Value) .Include(x => x.Members).FirstOrDefaultAsync(); if (evnt == null) return AddError("Event no longer exists. The owner may have deleted the event"); //Only add the user if they aren't already a member if (evnt.Members.All(x => x.UserId != inv.RecipientId)) { evnt.Members.Add(new EventMember { UserId = inv.RecipientId }); _eventRepo.Update(evnt); } //Check the calendar exists Calendar destCalendar = await _calendarRepo.GetByIdAsync(destCalId.Value); if (destCalendar == null) return AddError("404 : Destination Calendar not found"); //Add the dest calendar to the events calendars if (evnt.Calendars.All(x => x.Id != destCalId.Value)) { evnt.Calendars.Add(destCalendar); _eventRepo.Update(evnt); } break; } } //Set our invite to responded. inv.Responded = true; //Update database record _inviteRepo.Update(inv); await SaveChangesAsync(); Result.Success = true; return Result; } catch (Exception ex) { Result.Error = ex.Message; return Result; } }