示例#1
0
        public async Task <IHttpActionResult> GetCoachingProcess(string id, string lastModified = null)
        {
            var db         = IlevusDBContext.Create();
            var filters    = Builders <CoachingProcess> .Filter;
            var updates    = Builders <CoachingProcess> .Update;
            var collection = db.GetCoachingProcessCollection();

            try
            {
                if (!string.IsNullOrEmpty(lastModified))
                {
                    var modified = await collection.CountAsync(filters.And(
                                                                   filters.Eq("Id", id),
                                                                   filters.Gt("LastModified", DateTime.Parse(lastModified))
                                                                   ));

                    if (modified == 0)
                    {
                        return(Ok(false));
                    }
                }
                var process = (await collection.FindAsync(filters.Eq("Id", id))).FirstOrDefault();
                if (process != null)
                {
                    var coachee = await UserManager.FindByIdAsync(process.CoacheeId);

                    var coach = await UserManager.FindByIdAsync(process.CoachId);

                    if (process.Sessions.Count == 0)
                    {
                        var session = new CoachingSession();
                        await collection.UpdateOneAsync(filters.Eq("Id", id), updates.Push("Sessions", session));

                        process.Sessions.Add(session);
                    }
                    if (process.Steps == null || process.Steps.Count == 0)
                    {
                        await collection.UpdateOneAsync(filters.Eq("Id", id), updates.Set("Steps", coach.Professional.ProcessSteps));

                        process.Steps = coach.Professional.ProcessSteps;
                    }
                    return(Ok(new CoachingProcessViewModel(process, coach, coachee)));
                }
                return(NotFound());
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
示例#2
0
        public async Task <IHttpActionResult> NewSession(string id)
        {
            var db         = IlevusDBContext.Create();
            var filters    = Builders <CoachingProcess> .Filter;
            var updates    = Builders <CoachingProcess> .Update;
            var collection = db.GetCoachingProcessCollection();

            try
            {
                var user = await UserManager.FindByNameAsync(User.Identity.Name);

                var process = (await collection.FindAsync(filters.Eq("Id", id))).FirstOrDefault();
                if (process != null)
                {
                    var session = process.Sessions[process.Sessions.Count - 1];
                    if (session.Status < 10 || !process.CoachId.Equals(user.Id))
                    {
                        return(BadRequest("Você não pode criar uma nova sessão antes de finalizar a atual."));
                    }
                    var newSession = new CoachingSession();
                    process.Sessions.Add(newSession);
                    process.LastModified = newSession.Creation;

                    await collection.UpdateOneAsync(filters.Eq("Id", id),
                                                    updates.Combine(
                                                        updates.AddToSet("Sessions", newSession),
                                                        updates.Set("LastModified", newSession.Creation)
                                                        )
                                                    );

                    var coachee = await UserManager.FindByIdAsync(process.CoacheeId);

                    var coach = await UserManager.FindByIdAsync(process.CoachId);

                    return(Ok(new CoachingProcessViewModel(process, coach, coachee)));
                }
                return(NotFound());
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
        public String GetiCal(CoachingSession session, string subject, string method = "")
        {
            if (String.IsNullOrEmpty(session.CoachingProgram.Coach.Email))
            {
                throw new Exception("Organizer provided was null");
            }

            var iCal = new iCalendar
            {
                Method  = "PUBLISH",
                Version = "2.0",
            };

            var evt = iCal.Create <Event>();

            switch (method)
            {
            case "CANCELLED":
                iCal.Method = method;
                evt.Status  = EventStatus.Cancelled;
                break;

            case "REQUEST":
                iCal.Method = method;
                break;

            default:
                break;
            }

            evt.Summary     = subject;
            evt.Start       = new iCalDateTime(session.StartedAt);
            evt.End         = new iCalDateTime(session.FinishedAt);
            evt.Description = subject;
            evt.IsAllDay    = false;
            evt.UID         = String.Format("rightnow.oztrain.com.au-{0}", session.Id);
            evt.Organizer   = new Organizer(session.CoachingProgram.Coach.Email);
            evt.Sequence    = session.Sequence;

            return(new iCalendarSerializer().SerializeToString(iCal));
        }
        public async Task <IHttpActionResult> PutCoachingSession(int id, CoachingSession dto)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var isAdmin         = AppUserManager.IsInRole(currentUser.Id, "Admin");
            var coachingSession = AppDb.CoachingSessions
                                  .Where(i =>
                                         i.CoachingProgram.Coach.Id == currentUser.Id ||
                                         i.CoachingProgram.Coachee.Id == currentUser.Id ||
                                         isAdmin)
                                  .FirstOrDefault(i => i.Id == id);

            if (coachingSession == null)
            {
                return(BadRequest("Session Not Found"));
            }

            var updateICal = coachingSession.StartedAt != dto.StartedAt || coachingSession.FinishedAt != dto.FinishedAt;

            if (updateICal)
            {
                coachingSession.Sequence += 1;
            }
            coachingSession.StartedAt  = dto.StartedAt;
            coachingSession.FinishedAt = dto.FinishedAt;
            coachingSession.IsClosed   = dto.IsClosed;
            coachingSession.UpdatedAt  = DateTime.Now;

            try
            {
                await AppDb.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CoachingSessionExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            var newRecord = AppDb.CoachingSessions
                            .Include(i => i.CoachingProgram.Coach)
                            .Include(i => i.CoachingProgram.Coachee)
                            .FirstOrDefault(i => i.Id == coachingSession.Id);
            var subject           = String.Format("right.now. Coaching Session with {0} and {1}", newRecord.CoachingProgram.Coach.GetFullName(), newRecord.CoachingProgram.Coachee.GetFullName());
            var ical              = GetiCal(newRecord, subject, "REQUEST");
            var attachment        = System.Net.Mail.Attachment.CreateAttachmentFromString(ical, String.Format("{0}.ics", subject));
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coach.Email, "right.now. Video Coaching Session Updated", emailContentCoach, updateICal ? attachment : null);
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Updated.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coachee.Email, "right.now. Video Coaching Session Updated", emailContentCoachee, updateICal ? attachment : null);

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IHttpActionResult> PostCoachingSession(CoachingSession coachingSession)
        {
            var currentUser = AppUserManager.FindById(User.Identity.GetUserId());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var db = AppDb.Database.BeginTransaction())
            {
                try
                {
                    var start = coachingSession.StartedAt;
                    var end   = coachingSession.FinishedAt;
                    // check if the coach is double booked
                    //var dbCoach = AppDb.CoachingSessions
                    //    .Where(i => i.CoachingProgram.Coach.Id == coachingSession.CoachingProgram.CoachId)
                    //    .Where(i => (i.StartedAt >= start && i.StartedAt < end) || (i.FinishedAt > start && i.FinishedAt <= end))
                    //    .ToList();
                    //if (dbCoach.Count() > 0)
                    //{
                    //    throw new Exception("Coach cannot be double booked");
                    //}

                    // check if the coachee is double booked
                    //var dbCoachee = AppDb.CoachingSessions
                    //    .Where(i => i.CoachingProgram.Coachee.Id == coachingSession.CoachingProgram.CoacheeId)
                    //    .OnAtSameTime(coachingSession.StartedAt, coachingSession.FinishedAt);
                    //if (dbCoach.Count() > 0)
                    //{
                    //    throw new Exception("Coachee cannot be double booked");
                    //}

                    AppDb.CoachingSessions.Add(coachingSession);
                    await AppDb.SaveChangesAsync();

                    db.Commit();
                }
                catch (Exception)
                {
                    db.Rollback();
                }
            }

            var newRecord = AppDb.CoachingSessions
                            .Include(i => i.CoachingProgram.Coach)
                            .Include(i => i.CoachingProgram.Coachee)
                            .FirstOrDefault(i => i.Id == coachingSession.Id);
            var subject           = String.Format("right.now. Coaching Session with {0} and {1}", newRecord.CoachingProgram.Coach.GetFullName(), newRecord.CoachingProgram.Coachee.GetFullName());
            var ical              = GetiCal(newRecord, subject);
            var attachment        = System.Net.Mail.Attachment.CreateAttachmentFromString(ical, String.Format("{0}.ics", subject));
            var emailContentCoach = ViewRenderer.RenderView("~/Views/Email/Session Created.cshtml",
                                                            new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coach.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coach.Email, "right.now. Video Coaching Session Created", emailContentCoach, attachment);
            var emailContentCoachee = ViewRenderer.RenderView("~/Views/Email/Session Created.cshtml",
                                                              new System.Web.Mvc.ViewDataDictionary {
                { "Session", newRecord },
                { "Url", String.Format("{0}/#/program/{1}/", Request.RequestUri.Authority, newRecord.CoachingProgramId) },
                { "StartedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.StartedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
                { "FinishedAt", TimeZoneInfo.ConvertTimeFromUtc(newRecord.FinishedAt, TimeZoneInfo.FindSystemTimeZoneById(newRecord.CoachingProgram.Coachee.Timezone)) },
            });

            EmailSender.SendEmail(newRecord.CoachingProgram.Coachee.Email, "right.now. Video Coaching Session Created", emailContentCoachee, attachment);

            return(CreatedAtRoute("DefaultApi", new { id = coachingSession.Id }, coachingSession));
        }