Example #1
0
        public IEnumerable <CourseMapContentRespond> Get(string id, string classRoomId)
        {
            var areArgumentsValid = !string.IsNullOrEmpty(id) &&
                                    !string.IsNullOrEmpty(classRoomId);

            if (!areArgumentsValid)
            {
                return(Enumerable.Empty <CourseMapContentRespond>());
            }

            if (!_userprofileRepo.CheckAccessPermissionToSelectedClassRoom(id, classRoomId))
            {
                return(Enumerable.Empty <CourseMapContentRespond>());
            }

            var now                     = _dateTime.GetCurrentTime();
            var classCalendar           = _classCalendarRepo.GetClassCalendarByClassRoomId(classRoomId);
            var canAccessToTheClassRoom = classCalendar != null &&
                                          classCalendar.LessonCalendars != null &&
                                          !classCalendar.DeletedDate.HasValue &&
                                          !classCalendar.CloseDate.HasValue &&
                                          classCalendar.ExpiredDate.HasValue &&
                                          classCalendar.ExpiredDate.Value.Date > now.Date;

            if (!canAccessToTheClassRoom)
            {
                return(Enumerable.Empty <CourseMapContentRespond>());
            }

            var result = classCalendar.LessonCalendars
                         .Where(it => !it.DeletedDate.HasValue)
                         .GroupBy(it => it.SemesterGroupName)
                         .Select(group => new CourseMapContentRespond
            {
                SemesterName = group.Key,
                LessonStatus = group.Select(it => new CourseMapLessonStatus
                {
                    LessonId       = it.LessonId,
                    IsLocked       = now.Date < it.BeginDate.Date,
                    LessonWeekName = string.Format("Week{0:00}", it.Order),
                }).ToList()
            }).ToList();
            var lessonQry     = result.SelectMany(it => it.LessonStatus);
            var currentLesson = lessonQry.LastOrDefault(it => !it.IsLocked);

            if (currentLesson != null)
            {
                currentLesson.IsCurrent = true;
            }
            else if (lessonQry.Any())
            {
                lessonQry.Last().IsCurrent = true;
            }
            return(result);
        }
Example #2
0
        private void createNewUserProfile(string email)
        {
            try
            {
                var isUserExisting = _userProfileRepo.GetUserProfileById(email) != null;
                if (isUserExisting)
                {
                    return;
                }

                const string DefaultProfileImageUrl = "http://placehold.it/100x100"; // HACK: Default user profile image
                var          newUserProfile         = new Repositories.Models.UserProfile
                {
                    id                   = email,
                    CourseReminder       = Repositories.Models.UserProfile.ReminderFrequency.Once,
                    CreatedDate          = _dateTime.GetCurrentTime(),
                    ImageProfileUrl      = DefaultProfileImageUrl,
                    IsEnableNotification = true,
                    Name                 = email,
                    Subscriptions        = Enumerable.Empty <Repositories.Models.UserProfile.Subscription>()
                };
                _userProfileRepo.UpsertUserProfile(newUserProfile);
                _logger.LogInformation($"Create new user profile { email } complete");
            }
            catch (Exception e)
            {
                _logger.LogCritical($"Can't create new userprofile { email }, error info: {e.ToString()}");
            }
        }
Example #3
0
        /// <summary>
        /// Find the user's last activate course and navigate user to that course
        /// </summary>
        public IActionResult Preparing()
        {
            var userprofile = _userprofileRepo.GetUserProfileById(User.Identity.Name);

            if (userprofile == null)
            {
                _logger.LogCritical($"User profile { User.Identity.Name } not found.");
                ViewBag.ErrorMessage = _errorMsgs.AccountNotFound;
                return(View("Error"));
            }

            var lastActiveSubscription = userprofile.Subscriptions
                                         .Where(it => !it.DeletedDate.HasValue)
                                         .Where(it => it.LastActiveDate.HasValue)
                                         .OrderByDescending(it => it.LastActiveDate)
                                         .FirstOrDefault();
            var isAnyActivatedSubscription = lastActiveSubscription != null;

            if (!isAnyActivatedSubscription)
            {
                ViewBag.ErrorMessage = _errorMsgs.NoLastActivatedCourse;
                return(View("Error"));
            }

            var classCalendar        = _classCalendarRepo.GetClassCalendarByClassRoomId(lastActiveSubscription.ClassRoomId);
            var isClassCalendarValid = classCalendar != null && classCalendar.LessonCalendars != null && classCalendar.LessonCalendars.Any(it => !it.DeletedDate.HasValue);

            if (!isClassCalendarValid)
            {
                ViewBag.ErrorMessage = _errorMsgs.EntireCourseIsIncomplete;
                return(View("Error"));
            }

            var now = _dateTime.GetCurrentTime();
            var currentLessonCalendar = classCalendar.LessonCalendars
                                        .Where(it => !it.DeletedDate.HasValue)
                                        .Where(it => now.Date >= it.BeginDate)
                                        .OrderByDescending(it => it.BeginDate)
                                        .FirstOrDefault() ?? classCalendar.LessonCalendars.OrderBy(it => it.BeginDate).FirstOrDefault();
            var isCurrentLessonValid = currentLessonCalendar != null;

            if (!isCurrentLessonValid)
            {
                ViewBag.ErrorMessage = _errorMsgs.EntireCourseIsIncomplete;
                return(View("Error"));
            }

            var redirectURL = $"/my#!/app/main/lesson/{ currentLessonCalendar.LessonId }/{ lastActiveSubscription.ClassRoomId }";

            return(Redirect(redirectURL));
        }
Example #4
0
        private void createNewUserProfile(string email)
        {
            const string DefaultProfileImageUrl = "http://placehold.it/100x100";
            var          newUserProfile         = new Repositories.Models.UserProfile
            {
                id                   = email,
                CourseReminder       = Repositories.Models.UserProfile.ReminderFrequency.Once,
                CreatedDate          = _dateTime.GetCurrentTime(),
                ImageProfileUrl      = DefaultProfileImageUrl,
                IsEnableNotification = true,
                Name                 = email,
                Subscriptions        = Enumerable.Empty <Repositories.Models.UserProfile.Subscription>()
            };

            _userProfileRepo.UpsertUserProfile(newUserProfile);
        }
        private void addNewSubscriptionToUser(string courseCatalogId)
        {
            // TODO: Check self purchase class room id (if it doesn't existing then create it)
            // TODO: Create new class calendar
            var userProfileId       = User.Identity.Name;
            var selectedUserProfile = _userprofileRepo.GetUserProfileById(userProfileId);
            var subscriptions       = selectedUserProfile.Subscriptions.ToList();
            var now = _dateTime.GetCurrentTime();

            subscriptions.Add(new UserProfile.Subscription
            {
                id              = Guid.NewGuid().ToString(),
                Role            = UserProfile.AccountRole.SelfPurchaser,
                LastActiveDate  = now,
                ClassRoomId     = "SELFPURCHASE_CLASS_ROOM_ID", // HACK: Set selfpurchase class room id
                ClassCalendarId = "CLASS_CALENDAR_ID",          // HACK: Set class's calendar id
                CreatedDate     = now,
                ClassRoomName   = "CLASS_ROOM_NAME",            // HACK: Class room name
                CourseCatalogId = courseCatalogId
            });
        }
        public PostNewCommentRespond Post(PostNewCommentRequest body)
        {
            var areArgumentsValid = body != null &&
                                    !string.IsNullOrEmpty(body.ClassRoomId) &&
                                    !string.IsNullOrEmpty(body.Description) &&
                                    !string.IsNullOrEmpty(body.LessonId) &&
                                    !string.IsNullOrEmpty(body.UserProfileId);

            if (!areArgumentsValid)
            {
                return(null);
            }

            UserProfile userprofile;
            var         canAccessToTheClassRoom = _userprofileRepo.CheckAccessPermissionToSelectedClassRoom(body.UserProfileId, body.ClassRoomId, out userprofile);

            if (!canAccessToTheClassRoom)
            {
                return(null);
            }

            var now = _dateTime.GetCurrentTime();
            var canAccessToTheClassLesson = _classCalendarRepo.CheckAccessPermissionToSelectedClassLesson(body.ClassRoomId, body.LessonId, now);

            if (!canAccessToTheClassLesson)
            {
                return(null);
            }

            var selectedUserActivity = _userActivityRepo.GetUserActivityByUserProfileIdAndClassRoomId(body.UserProfileId, body.ClassRoomId);

            if (selectedUserActivity == null)
            {
                return(null);
            }

            var selectedLesson = selectedUserActivity.LessonActivities.FirstOrDefault(it => it.LessonId == body.LessonId);

            if (selectedLesson == null)
            {
                return(null);
            }

            var id         = Guid.NewGuid().ToString();
            var newComment = new Comment
            {
                id                     = id,
                ClassRoomId            = body.ClassRoomId,
                CreatedByUserProfileId = body.UserProfileId,
                Description            = body.Description,
                LessonId               = body.LessonId,
                CreatedDate            = now,
                CreatorDisplayName     = userprofile.Name,
                CreatorImageUrl        = userprofile.ImageProfileUrl,
                Discussions            = Enumerable.Empty <Comment.Discussion>(),
            };

            _commentRepo.UpsertComment(newComment);

            selectedLesson.CreatedCommentAmount++;
            _userActivityRepo.UpsertUserActivity(selectedUserActivity);
            _notificationCtrl.SendNotification();
            return(new PostNewCommentRespond {
                ActualCommentId = id
            });
        }
Example #7
0
        public IEnumerable <NotificationRespond> GetContent(string id, string classRoomId)
        {
            var areArgumentsValid = !string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(classRoomId);

            if (!areArgumentsValid)
            {
                return(Enumerable.Empty <NotificationRespond>());
            }

            var notifications   = _notificationRepo.GetNotificationByUserIdAndClassRoomId(id, classRoomId).ToList();
            var anyNotification = notifications != null && notifications.Any(it => !it.HideDate.HasValue);

            if (!anyNotification)
            {
                return(Enumerable.Empty <NotificationRespond>());
            }

            var now          = _dateTime.GetCurrentTime();
            var unreadedMsgs = notifications.Where(it => !it.HideDate.HasValue).ToList();

            const int LastRetrieveDays = 7;
            var       needToReachQry   = unreadedMsgs
                                         .Where(it => !it.LastReadedDate.HasValue || it.LastReadedDate < it.LastUpdateDate)
                                         .Where(it => Math.Abs(it.CreatedDate.Date.Subtract(now).Days) <= LastRetrieveDays);

            var relatedUserProfiles = needToReachQry
                                      .SelectMany(it => it.ByUserProfileId)
                                      .Where(it => it != null)
                                      .Distinct()
                                      .Select(it => _userProfileRepo.GetUserProfileById(it))
                                      .Where(it => it != null)
                                      .ToList();

            var result = needToReachQry
                         .Select(it =>
            {
                var fromUserProfile = relatedUserProfiles
                                      .Where(uProfile => it.ByUserProfileId.Contains(uProfile.id))
                                      .Select(uProfile => new NotificationRespond.ActionInformation
                {
                    FromUserProfileId   = uProfile.id,
                    FromUserProfileName = uProfile.Name
                }).ToList();

                NotificationRespond.NotificationTag tag;
                switch (it.Tag)
                {
                case Notification.NotificationTag.Reminder:
                    tag = NotificationRespond.NotificationTag.Reminder;
                    break;

                case Notification.NotificationTag.TopicOfTheDay:
                    tag = NotificationRespond.NotificationTag.TOTD;
                    break;

                case Notification.NotificationTag.FriendCreateNewComment:
                    tag = NotificationRespond.NotificationTag.Comment;
                    break;

                case Notification.NotificationTag.FriendLikesALesson:
                case Notification.NotificationTag.SomeOneLikesYourComment:
                case Notification.NotificationTag.SomeOneLikesYourDiscussion:
                    tag = NotificationRespond.NotificationTag.Like;
                    break;

                case Notification.NotificationTag.SomeOneCreateDiscussionInYourComment:
                    tag = NotificationRespond.NotificationTag.Discussion;
                    break;

                default: return(null);
                }

                return(new NotificationRespond
                {
                    id = it.id,
                    Tag = tag,
                    FromUserProfiles = fromUserProfile,
                    Message = it.Message
                });
            })
                         .Where(it => it != null).ToList();

            return(result);
        }
Example #8
0
        public async Task <GetUserProfileRespond> Get(string id)
        {
            var isArgumentValid = !string.IsNullOrEmpty(id);

            if (!isArgumentValid)
            {
                return(null);
            }

            var userprofile = _userProfileRepo.GetUserProfileById(id);

            if (userprofile == null)
            {
                return(null);
            }
            var currentUser = System.Security.Claims.PrincipalExtensions.GetUserId(HttpContext.User);
            var user        = _userManager.FindByIdAsync(currentUser).Result;
            var isUserProfileSubscriptionValid = userprofile.Subscriptions != null && userprofile.Subscriptions.Any(it => it.LastActiveDate.HasValue);
            var userProfileInfo = new GetUserProfileRespond
            {
                UserProfileId      = userprofile.id,
                HasPassword        = _userManager.HasPasswordAsync(user).Result,
                FullName           = userprofile.Name,
                ImageUrl           = userprofile.ImageProfileUrl,
                SchoolName         = userprofile.SchoolName,
                IsPrivateAccout    = userprofile.IsPrivateAccount,
                IsReminderOnceTime = userprofile.CourseReminder == UserProfile.ReminderFrequency.Once
            };

            if (!isUserProfileSubscriptionValid)
            {
                return(userProfileInfo);
            }

            var lastActiveSubscription = userprofile.Subscriptions
                                         .Where(it => !it.DeletedDate.HasValue)
                                         .Where(it => it.LastActiveDate.HasValue)
                                         .OrderByDescending(it => it.LastActiveDate)
                                         .FirstOrDefault();

            userProfileInfo.CurrentClassRoomId     = lastActiveSubscription.ClassRoomId;
            userProfileInfo.CurrentClassCalendarId = lastActiveSubscription.ClassCalendarId;

            var classCalendar = await _classCalendarRepo.GetClassCalendarById(lastActiveSubscription.ClassCalendarId);

            var isClassCalendarValid = classCalendar != null && classCalendar.LessonCalendars != null && classCalendar.LessonCalendars.Any();

            if (!isClassCalendarValid)
            {
                return(userProfileInfo);
            }

            var now            = _dateTime.GetCurrentTime();
            var lessonCalendar = classCalendar.LessonCalendars
                                 .Where(it => !it.DeletedDate.HasValue)
                                 .Where(it => now.Date >= it.BeginDate)
                                 .OrderByDescending(it => it.BeginDate)
                                 .FirstOrDefault() ?? classCalendar.LessonCalendars.OrderBy(it => it.BeginDate).LastOrDefault();
            var currentLessonId = lessonCalendar?.LessonId;

            if (lessonCalendar == null)
            {
                return(userProfileInfo);
            }
            else
            {
                userProfileInfo.CurrentLessonId = lessonCalendar.LessonId;
                userProfileInfo.CurrentLessonNo = lessonCalendar.Order;
            }

            return(userProfileInfo);
        }
Example #9
0
        public PostNewDiscussionRespond Post(PostNewDiscussionRequest body)
        {
            var areArgumentsValid = body != null &&
                                    !string.IsNullOrEmpty(body.ClassRoomId) &&
                                    !string.IsNullOrEmpty(body.CommentId) &&
                                    !string.IsNullOrEmpty(body.Description) &&
                                    !string.IsNullOrEmpty(body.LessonId) &&
                                    !string.IsNullOrEmpty(body.UserProfileId);

            if (!areArgumentsValid)
            {
                return(null);
            }

            UserProfile userprofile;
            var         canAccessToTheClassRoom = _userprofileRepo.CheckAccessPermissionToSelectedClassRoom(body.UserProfileId, body.ClassRoomId, out userprofile);

            if (!canAccessToTheClassRoom)
            {
                return(null);
            }

            var now       = _dateTime.GetCurrentTime();
            var isTeacher = userprofile.Subscriptions.Any(it => !it.DeletedDate.HasValue && it.ClassRoomId == body.ClassRoomId && it.Role == UserProfile.AccountRole.Teacher);
            var canAccessToTheClassLesson = _classCalendarRepo.CheckAccessPermissionToSelectedClassLesson(body.ClassRoomId, body.LessonId, now, isTeacher);

            if (!canAccessToTheClassLesson)
            {
                return(null);
            }

            var selectedComment = _commentRepo.GetCommentById(body.CommentId);
            var isCommentValid  = selectedComment != null &&
                                  selectedComment.LessonId.Equals(body.LessonId, StringComparison.CurrentCultureIgnoreCase) &&
                                  selectedComment.id.Equals(body.CommentId, StringComparison.CurrentCultureIgnoreCase) &&
                                  !selectedComment.DeletedDate.HasValue;

            if (!isCommentValid)
            {
                return(null);
            }

            var selectedUserActivity = _userActivityRepo.GetUserActivityByUserProfileIdAndClassRoomId(body.UserProfileId, body.ClassRoomId);
            var isUserActivityValid  = selectedUserActivity != null && !selectedUserActivity.DeletedDate.HasValue;

            if (!isUserActivityValid)
            {
                return(null);
            }

            var selectedLesson = selectedUserActivity.LessonActivities.FirstOrDefault(it => it.LessonId == body.LessonId);

            if (selectedLesson == null)
            {
                return(null);
            }

            if (!isTeacher)
            {
                var isCommentOwner = selectedComment.CreatedByUserProfileId.Equals(body.UserProfileId, StringComparison.CurrentCultureIgnoreCase);
                if (!isCommentOwner)
                {
                    var canPostNewDiscussion = _userprofileRepo.CheckAccessPermissionToUserProfile(selectedComment.CreatedByUserProfileId);
                    if (!canPostNewDiscussion)
                    {
                        return(null);
                    }
                }
            }

            var id            = Guid.NewGuid().ToString();
            var discussions   = selectedComment.Discussions.ToList();
            var newDiscussion = new Comment.Discussion
            {
                id = id,
                CreatedByUserProfileId = body.UserProfileId,
                CreatorDisplayName     = userprofile.Name,
                CreatorImageUrl        = userprofile.ImageProfileUrl,
                Description            = body.Description,
                CreatedDate            = now,
            };

            discussions.Add(newDiscussion);
            selectedComment.Discussions = discussions;
            _commentRepo.UpsertComment(selectedComment);

            selectedLesson.ParticipationAmount++;
            _userActivityRepo.UpsertUserActivity(selectedUserActivity);
            _notificationCtrl.SendNotification();
            return(new PostNewDiscussionRespond {
                ActualCommentId = id
            });
        }
Example #10
0
        public void Post(SendFriendRequest body)
        {
            var areArgumentsValid = body != null &&
                                    !string.IsNullOrEmpty(body.FromUserProfileId) &&
                                    !string.IsNullOrEmpty(body.ToUserProfileId);

            if (!areArgumentsValid)
            {
                return;
            }

            var requestUserProfileIds = new List <string> {
                body.FromUserProfileId, body.ToUserProfileId
            };
            var relatedUserProfiles = _userprofileRepo.GetUserProfileById(requestUserProfileIds);
            var usersExisting       = relatedUserProfiles.Count() == requestUserProfileIds.Count();

            if (!usersExisting)
            {
                return;
            }

            var requests = _friendRequestRepo.GetFriendRequestByUserProfileId(body.FromUserProfileId)
                           .Where(it => it.ToUserProfileId.Equals(body.ToUserProfileId))
                           .ToList();
            var currentStatus  = requests.OrderByDescending(it => it.CreatedDate).FirstOrDefault();
            var isRequestValid = currentStatus == null?string.IsNullOrEmpty(body.RequestId) : currentStatus.id.Equals(body.RequestId);

            if (!isRequestValid)
            {
                return;
            }

            var now = _dateTime.GetCurrentTime();
            var isNewFriendRequest = currentStatus == null;

            if (isNewFriendRequest)
            {
                requests.ForEach(it => it.DeletedDate = now);
                var newRequestFrom = new FriendRequest
                {
                    id                = Guid.NewGuid().ToString(),
                    CreatedDate       = now,
                    FromUserProfileId = body.FromUserProfileId,
                    ToUserProfileId   = body.ToUserProfileId,
                    Status            = FriendRequest.RelationStatus.SendRequest
                };
                requests.Add(newRequestFrom);

                var newRequestTo = new FriendRequest
                {
                    id                = Guid.NewGuid().ToString(),
                    CreatedDate       = now,
                    FromUserProfileId = body.ToUserProfileId,
                    ToUserProfileId   = body.FromUserProfileId,
                    Status            = FriendRequest.RelationStatus.ReceiveRequest
                };
                requests.Add(newRequestTo);
                requests.ForEach(it => _friendRequestRepo.UpsertFriendRequest(it));
            }
            else
            {
                var isRequestInvalid = currentStatus.Status == FriendRequest.RelationStatus.SendRequest && body.IsAccept;
                if (isRequestInvalid)
                {
                    return;
                }

                var friendSideRequest = _friendRequestRepo.GetFriendRequestByUserProfileId(body.ToUserProfileId)
                                        .Where(it => it.ToUserProfileId.Equals(body.FromUserProfileId))
                                        .ToList();

                var currentFriendSideStatus = friendSideRequest.OrderByDescending(it => it.CreatedDate).FirstOrDefault();
                var fRequests = friendSideRequest.Except(new List <FriendRequest> {
                    currentFriendSideStatus
                });
                foreach (var item in fRequests)
                {
                    item.DeletedDate = now;
                }

                if (body.IsAccept)
                {
                    currentStatus.AcceptedDate           = now;
                    currentStatus.Status                 = FriendRequest.RelationStatus.Friend;
                    currentFriendSideStatus.AcceptedDate = now;
                    currentFriendSideStatus.Status       = FriendRequest.RelationStatus.Friend;
                }
                else
                {
                    currentStatus.DeletedDate           = now;
                    currentStatus.Status                = FriendRequest.RelationStatus.Unfriend;
                    currentFriendSideStatus.DeletedDate = now;
                    currentFriendSideStatus.Status      = FriendRequest.RelationStatus.Unfriend;
                }
                friendSideRequest.Add(currentStatus);
                friendSideRequest.ForEach(it => _friendRequestRepo.UpsertFriendRequest(it));
            }
        }
        public async Task <IActionResult> ChargeACreditCard(PurchaseCourseViewModel model)
        {
            try
            {
                var selectedUserProfile = _userprofileRepo.GetUserProfileById(User.Identity.Name);
                var isUserProfileValid  = selectedUserProfile != null && !selectedUserProfile.DeletedDate.HasValue;
                if (!isUserProfileValid)
                {
                    _logger.LogCritical($"User profile { User.Identity.Name } not found.");
                    ViewBag.ErrorMessage = _errorMsgs.AccountNotFound;
                    return(View("Error"));
                }

                var selectedCourse = _courseCtrl.GetCourseDetail(model.CourseId);
                if (selectedCourse == null)
                {
                    ViewBag.ErrorMessage = _errorMsgs.CourseNotFound;
                    return(View("Error"));
                }

                var selectedClassRoom = _classRoomRepo.GetPublicClassRoomByCourseCatalogId(model.CourseId);
                var isClassRoomValid  = selectedClassRoom != null && !selectedClassRoom.DeletedDate.HasValue;
                if (!isClassRoomValid)
                {
                    _logger.LogCritical($"ClassRoom of CourseId: { model.CourseId } not found.");
                    ViewBag.ErrorMessage = _errorMsgs.SelectedCourseIsNotAvailableForPurchase;
                    return(View("Error"));
                }

                var isAlreadyHaveTheSelectedCourse = !_myCourseCtrl.CanAddNewCourseCatalog(User.Identity.Name, model.CourseId);
                if (isAlreadyHaveTheSelectedCourse)
                {
                    return(RedirectToAction("entercourse", "my", new { @id = model.CourseId }));
                }

                if (ModelState.IsValid)
                {
                    var paymentResult      = Engines.Models.PaymentResult.Unknow;
                    var isPaymentSuccessed = false;
                    var newSubscriptionId  = Guid.NewGuid().ToString();
                    var newPaymentId       = string.Empty;
                    var now = _dateTime.GetCurrentTime();

                    try
                    {
                        // Pay with Paypal
                        paymentResult = _payment.ChargeCreditCard(new Engines.Models.PaymentInformation
                        {
                            Address             = model.PrimaryAddress.Address,
                            City                = model.PrimaryAddress.City,
                            Country             = model.PrimaryAddress.Country.ToString(),
                            PostalCode          = model.PrimaryAddress.ZipCode,
                            State               = model.PrimaryAddress.State,
                            TotalPrice          = selectedCourse.PriceUSD,
                            UserProfileId       = User.Identity.Name,
                            PurchaseForCourseId = model.CourseId,
                            FirstName           = model.CreditCardInfo.FirstName,
                            LastName            = model.CreditCardInfo.LastName,
                            ExpiredYear         = model.CreditCardInfo.ExpiredYear,
                            ExpiredMonth        = model.CreditCardInfo.ExpiredMonth,
                            CVV = model.CreditCardInfo.CVV.ToString(),
                            CreditCardNumber = model.CreditCardInfo.CardNumber,
                            CardType         = model.CreditCardInfo.CardType.ToString()
                        });
                    }
                    catch (Exception e)
                    {
                        _logger.LogError($"Paypal payment error, from user: { User.Identity.Name }, course id: { model.CourseId }, Error: { e.ToString() }");
                        ViewBag.ErrorMessage = _errorMsgs.CanNotChargeACreditCard;
                        return(View("Error"));
                    }
                    finally
                    {
                        isPaymentSuccessed = paymentResult == Engines.Models.PaymentResult.approved;
                        newSubscriptionId  = isPaymentSuccessed ? newSubscriptionId : "None";
                        var payment = createNewPayment(selectedCourse.id, selectedCourse.SideName, newSubscriptionId, model, selectedCourse.PriceUSD, now, isPaymentSuccessed);
                        await _paymentRepo.CreateNewPayment(payment);

                        newPaymentId = payment.id;
                    }

                    if (!isPaymentSuccessed)
                    {
                        ViewBag.ErrorMessage = _errorMsgs.CanNotChargeACreditCard;
                        return(View("Error"));
                    }

                    try
                    {
                        var requestLessonCatalogIds = selectedClassRoom.Lessons.Select(it => it.LessonCatalogId);
                        var lessonCatalogs          = _lessonCatalogRepo.GetLessonCatalogById(requestLessonCatalogIds).ToList();
                        var newClassCalendar        = createClassCalendar(selectedClassRoom, lessonCatalogs, now);
                        newClassCalendar.CalculateCourseSchedule();
                        newClassCalendar.ExpiredDate      = null;
                        selectedUserProfile.Subscriptions = addNewSelfPurchaseSubscription(selectedUserProfile.Subscriptions, selectedClassRoom, newClassCalendar.id, model.CourseId, now, newSubscriptionId);
                        var userActivity = selectedUserProfile.CreateNewUserActivity(selectedClassRoom, newClassCalendar, lessonCatalogs, now);

                        _classCalendarRepo.UpsertClassCalendar(newClassCalendar);
                        _userprofileRepo.UpsertUserProfile(selectedUserProfile);
                        _userActivityRepo.UpsertUserActivity(userActivity);

                        return(RedirectToAction("Finished", new { @id = newPaymentId }));
                    }
                    catch (Exception e)
                    {
                        _logger.LogCritical($"User: '******' already purchased course id: '{ model.CourseId }' with payment id: '{ newPaymentId }' but the system can't create new course.");
                        throw e;
                    }
                }
                return(View(model));
            }
            catch (Exception e)
            {
                _logger.LogError($"MongoDB: { e.ToString() }");
                ViewBag.ErrorMessage = _errorMsgs.CanNotConnectToTheDatabase;
                return(View("Error"));
            }
        }
        public LessonContentRespond Get(string id, string classRoomId, string userId)
        {
            var areArgumentsValid = !string.IsNullOrEmpty(id) &&
                                    !string.IsNullOrEmpty(classRoomId) &&
                                    !string.IsNullOrEmpty(userId);

            if (!areArgumentsValid)
            {
                return(null);
            }

            UserProfile userprofile;
            var         canAccessToTheClassRoom = _userprofileRepo.CheckAccessPermissionToSelectedClassRoom(userId, classRoomId, out userprofile);

            if (!canAccessToTheClassRoom)
            {
                return(null);
            }

            var subscription = userprofile.Subscriptions
                               .Where(it => !it.DeletedDate.HasValue)
                               .Where(it => it.ClassRoomId.Equals(classRoomId, StringComparison.CurrentCultureIgnoreCase))
                               .FirstOrDefault();

            var now = _dateTime.GetCurrentTime();
            var canAccessToTheClassLesson = _classCalendarRepo.CheckAccessPermissionToSelectedClassLesson(classRoomId, id, now);

            if (!canAccessToTheClassLesson)
            {
                return(null);
            }

            var selectedClassRoom = _classRoomRepo.GetClassRoomById(classRoomId);

            if (selectedClassRoom == null)
            {
                return(null);
            }

            var selectedLesson = selectedClassRoom.Lessons.FirstOrDefault(it => it.id.Equals(id, StringComparison.CurrentCultureIgnoreCase));

            if (selectedLesson == null)
            {
                return(null);
            }

            var selectedLessonCatalog = _lessonCatalogRepo.GetLessonCatalogById(selectedLesson.LessonCatalogId);

            if (selectedLessonCatalog == null)
            {
                return(null);
            }

            var selectedUserActivity = _userActivityRepo.GetUserActivityByUserProfileIdAndClassRoomId(userId, classRoomId);

            if (selectedUserActivity == null)
            {
                return(null);
            }
            var selectedLessonActivity = selectedUserActivity.LessonActivities.FirstOrDefault(it => it.LessonId.Equals(id, StringComparison.CurrentCultureIgnoreCase));

            if (selectedLessonActivity == null)
            {
                return(null);
            }

            var selectedSubscription = userprofile.Subscriptions.FirstOrDefault(it => it.ClassRoomId == classRoomId);

            if (selectedSubscription == null)
            {
                return(null);
            }
            selectedSubscription.LastActiveDate = now;
            _userprofileRepo.UpsertUserProfile(userprofile);

            var shouldUpdateSawPrimaryContent = !selectedLessonActivity.SawContentIds.Contains(selectedLessonCatalog.PrimaryContentURL);

            if (shouldUpdateSawPrimaryContent)
            {
                var sawList = selectedLessonActivity.SawContentIds.ToList();
                sawList.Add(selectedLessonCatalog.PrimaryContentURL);
                selectedLessonActivity.SawContentIds = sawList;
                _userActivityRepo.UpsertUserActivity(selectedUserActivity);
            }

            var isTeacher           = subscription.Role == UserProfile.AccountRole.Teacher;
            var isDisplayTeacherMsg = selectedUserActivity.HideClassRoomMessageDate.HasValue ?
                                      selectedClassRoom.LastUpdatedMessageDate > selectedUserActivity.HideClassRoomMessageDate.Value :
                                      true;

            return(new LessonContentRespond
            {
                Advertisments = selectedLessonCatalog.Advertisments,
                CourseCatalogId = selectedLessonCatalog.CourseCatalogId,
                CreatedDate = selectedLessonCatalog.CreatedDate,
                ExtraContentUrls = selectedLessonCatalog.ExtraContentUrls,
                FullDescription = selectedLessonCatalog.FullDescription,
                FullTeacherLessonPlan = isTeacher ? selectedLessonCatalog.FullTeacherLessonPlan : string.Empty,
                id = id,
                Order = selectedLessonCatalog.Order,
                PrimaryContentURL = selectedLessonCatalog.PrimaryContentURL,
                SemesterName = selectedLessonCatalog.SemesterName,
                ShortDescription = selectedLessonCatalog.ShortDescription,
                ShortTeacherLessonPlan = isTeacher ? selectedLessonCatalog.ShortTeacherLessonPlan : string.Empty,
                Title = selectedLessonCatalog.Title,
                UnitNo = selectedLessonCatalog.UnitNo,
                CourseMessage = isDisplayTeacherMsg ? selectedClassRoom.Message : null,
                IsTeacher = isTeacher,
                TotalLikes = selectedLesson.TotalLikes
            });
        }
        public LessonContentRespond Get(string id, string classRoomId, string userId)
        {
            var areArgumentsValid = !string.IsNullOrEmpty(id) &&
                                    !string.IsNullOrEmpty(classRoomId) &&
                                    !string.IsNullOrEmpty(userId);

            if (!areArgumentsValid)
            {
                return(null);
            }

            UserProfile userprofile;
            var         canAccessToTheClassRoom = _userprofileRepo.CheckAccessPermissionToSelectedClassRoom(userId, classRoomId, out userprofile);

            if (!canAccessToTheClassRoom)
            {
                return(null);
            }

            var subscriptions = userprofile.Subscriptions
                                .Where(it => !it.DeletedDate.HasValue)
                                .Where(it => it.ClassRoomId.Equals(classRoomId, StringComparison.CurrentCultureIgnoreCase));

            if (!subscriptions.Any())
            {
                return(null);
            }
            var now       = _dateTime.GetCurrentTime();
            var isTeacher = subscriptions.Any(it => it.Role == UserProfile.AccountRole.Teacher);
            var canAccessToTheClassLesson = _classCalendarRepo.CheckAccessPermissionToSelectedClassLesson(classRoomId, id, now, isTeacher);

            if (!canAccessToTheClassLesson)
            {
                return(null);
            }

            var selectedClassRoom = _classRoomRepo.GetClassRoomById(classRoomId);
            var isClassRoomValid  = selectedClassRoom != null && !selectedClassRoom.DeletedDate.HasValue;

            if (!isClassRoomValid)
            {
                return(null);
            }

            var selectedLesson = selectedClassRoom.Lessons.FirstOrDefault(it => it.id.Equals(id, StringComparison.CurrentCultureIgnoreCase));

            if (selectedLesson == null)
            {
                return(null);
            }

            var selectedLessonCatalog = _lessonCatalogRepo.GetLessonCatalogById(selectedLesson.LessonCatalogId);

            if (selectedLessonCatalog == null)
            {
                return(null);
            }

            var selectedUserActivity = _userActivityRepo.GetUserActivityByUserProfileIdAndClassRoomId(userId, classRoomId);
            var isUserActivityValid  = selectedUserActivity != null && !selectedUserActivity.DeletedDate.HasValue;

            if (!isUserActivityValid)
            {
                return(null);
            }
            var selectedLessonActivity = selectedUserActivity.LessonActivities.FirstOrDefault(it => it.LessonId.Equals(id, StringComparison.CurrentCultureIgnoreCase));

            if (selectedLessonActivity == null)
            {
                return(null);
            }

            var selectedSubscription = userprofile.Subscriptions.FirstOrDefault(it => it.ClassRoomId == classRoomId);

            if (selectedSubscription == null)
            {
                return(null);
            }
            selectedSubscription.LastActiveDate = now;
            _userprofileRepo.UpsertUserProfile(userprofile);

            var shouldUpdateSawPrimaryContent = !selectedLessonActivity.SawContentIds.Contains(selectedLessonCatalog.id);

            if (shouldUpdateSawPrimaryContent)
            {
                var sawList = selectedLessonActivity.SawContentIds.ToList();
                sawList.Add(selectedLessonCatalog.id);
                selectedLessonActivity.SawContentIds = sawList;
                _userActivityRepo.UpsertUserActivity(selectedUserActivity);
            }

            var isDisplayTeacherMsg = selectedUserActivity.HideClassRoomMessageDate.HasValue ?
                                      selectedClassRoom.LastUpdatedMessageDate > selectedUserActivity.HideClassRoomMessageDate.Value :
                                      true;

            var result = new LessonContentRespond
            {
                id              = id,
                Order           = selectedLessonCatalog.Order,
                SemesterName    = selectedLessonCatalog.SemesterName,
                UnitNo          = selectedLessonCatalog.UnitNo,
                CourseCatalogId = selectedLessonCatalog.CourseCatalogId,
                Title           = selectedLessonCatalog.Title,
                CreatedDate     = selectedLessonCatalog.CreatedDate,
                Advertisments   = selectedLessonCatalog.Advertisments,
                CourseMessage   = isDisplayTeacherMsg ? selectedClassRoom.Message : null,
                IsTeacher       = isTeacher,
                TotalLikes      = selectedLesson.TotalLikes,
                StudentItems    = selectedLessonCatalog.StudentItems ?? Enumerable.Empty <LessonCatalog.LessonItem>(),
                TeacherItems    = selectedLessonCatalog.TeacherItems ?? Enumerable.Empty <LessonCatalog.LessonItem>(),
                PostAssessments = selectedLessonCatalog.PostAssessments ?? Enumerable.Empty <LessonCatalog.AssessmentItem>(),
                PreAssessments  = selectedLessonCatalog.PreAssessments ?? Enumerable.Empty <LessonCatalog.AssessmentItem>(),
            };

            result.StudentItems    = result.StudentItems.OrderBy(it => it.Order);
            result.TeacherItems    = result.TeacherItems.OrderBy(it => it.Order);
            result.PostAssessments = result.PostAssessments.OrderBy(it => it.Order);
            result.PreAssessments  = result.PreAssessments.OrderBy(it => it.Order);
            return(result);
        }