public async Task <IOperationResult <Meeting> > StartMeeting(int meetingId, int userId)
        {
            var user = await _userRepository.Find(u => u.Id == userId, u => u.UserRoles);

            if (user == null)
            {
                return(BasicOperationResult <Meeting> .Fail("El usuario no fue encontrado"));
            }

            var meeting = await _meetingRepository.Find(
                m => m.Id == meetingId &&
                m.Status == MeetingStatus.Accepted &&
                m.TutorId == userId,
                m => m.Tutor, m => m.Student, m => m.Subject);

            if (meeting == null)
            {
                return(BasicOperationResult <Meeting> .Fail("La tutoría no fue encontrada"));
            }

            meeting.Status = MeetingStatus.InProgress;
            meeting.RealStartedDateTime = DateTime.Now.GetNowInCorrectTimezone();
            _meetingRepository.Update(meeting);

            await _meetingRepository.Save();

            await _notificationManager.NotifyMeetingHasStarted(meeting);

            return(BasicOperationResult <Meeting> .Ok(meeting));
        }
        public async Task <IOperationResult <ISet <Meeting> > > GetMeetingsHistory(int userId)
        {
            bool userExists = await _userRepository.Exists(u => u.Id == userId && u.IsActive && u.IsEmailValidated);

            if (!userExists)
            {
                return(BasicOperationResult <ISet <Meeting> > .Fail("El usuario indicado no fue encontrado, verifique e intente nuevamente."));
            }

            ISet <RoleTypes> roles = await _userRepository.GetRolesForUser(userId);

            RoleTypes role = roles.FirstOrDefault();

            IEnumerable <Meeting> meetings = await _getMeetingsByRole[role](userId);

            MeetingStatus[] statusesToFilterBy =
            {
                MeetingStatus.Complete,
                MeetingStatus.Cancelled,
                MeetingStatus.InProgress,
                MeetingStatus.Rejected,
                MeetingStatus.Accepted
            };

            HashSet <Meeting> filteredMeetings = meetings.Where(m => statusesToFilterBy.Contains(m.Status))
                                                 .OrderBy(m => m.StartDateTime)
                                                 .ThenBy(m => m.RealStartedDateTime)
                                                 .ToHashSet();

            return(BasicOperationResult <ISet <Meeting> > .Ok(filteredMeetings));
        }
        public async Task <IOperationResult <Meeting> > CreateMeeting(Meeting meeting)
        {
            if (meeting == null)
            {
                return(BasicOperationResult <Meeting> .Fail("El objeto que envió es inválido"));
            }

            var validation = await ValidateMeeting(meeting);

            if (!validation.Success)
            {
                return(validation);
            }

            meeting.Status = MeetingStatus.Pending;

            _meetingRepository.Create(meeting);

            await _meetingRepository.Save();

            var response = await _meetingRepository.Find(m => m.Id == meeting.Id, m => m.Subject, m => m.Tutor, m => m.Student);

            await _notificationManager.NotifyStudentMeetingWasCreated(meeting.StudentId, meeting.Subject.Name, meeting.Tutor.FullName);

            await _notificationManager.NotifyParentsOfMeetingCreatedForStudent(meeting);

            return(BasicOperationResult <Meeting> .Ok(response));
        }
        public async Task <IOperationResult <IEnumerable <Meeting> > > GetStudentTutorMeetings(int userId)
        {
            IEnumerable <Meeting> meetings;
            var user = await _userRepository.Find(u => u.Id == userId, u => u.UserRoles);

            if (user == null)
            {
                return(BasicOperationResult <IEnumerable <Meeting> > .Fail("El usuario no fue encontrado"));
            }

            if (user.UserRoles.Any(ur => ur.RoleId == (int)RoleTypes.Tutor))
            {
                meetings = await _meetingRepository.FindAll(s => s.TutorId == userId);
            }
            else if (user.UserRoles.Any(ur => ur.RoleId == (int)RoleTypes.Student))
            {
                meetings = await _meetingRepository.FindAll(s => s.StudentId == userId);
            }
            else
            {
                return(BasicOperationResult <IEnumerable <Meeting> > .Fail("El usuario no es un tutor o un estudiante"));
            }

            return(BasicOperationResult <IEnumerable <Meeting> > .Ok(meetings));
        }
Beispiel #5
0
        public async Task <IOperationResult <bool> > UpdateUserProfile(User user, int userId)
        {
            try
            {
                var oldUser = await _userRepository.Find(u => u.Id == userId);

                oldUser.Address            = user.Address;
                oldUser.Name               = user.Name;
                oldUser.LastName           = user.LastName;
                oldUser.Gender             = user.Gender;
                oldUser.Latitude           = user.Latitude;
                oldUser.Longitude          = user.Longitude;
                oldUser.Email              = user.Email;
                oldUser.PersonalId         = user.PersonalId;
                oldUser.UserName           = user.UserName;
                oldUser.AboutMe            = user.AboutMe;
                oldUser.PhoneNumber        = user.PhoneNumber;
                oldUser.NormalizedUserName = user.UserName.ToUpper();
                oldUser.NormalizedEmail    = user.Email.ToUpper();

                _userRepository.Update(oldUser);

                await _userRepository.Save();

                return(BasicOperationResult <bool> .Ok(true));
            }
            catch (Exception e)
            {
                return(BasicOperationResult <bool> .Fail(e.Message));
            }
        }
Beispiel #6
0
        public IOperationResult <bool> DeleteAccountingEntry(long entryId)
        {
            try
            {
                var debitCredit = _debitCreditEntryRepository.Find(entryId).Entity;

                if (debitCredit == null)
                {
                    return(BasicOperationResult <bool> .Fail("EntryNotFound"));
                }

                _debitCreditEntryRepository.Delete(debitCredit);

                AccountingEntry debitEntry = _accountEntryRepository.Find(e => e.Id == debitCredit.DebitEntryId);
                _accountEntryRepository.Remove(debitEntry);

                AccountingEntry creditEntry = _accountEntryRepository.Find(e => e.Id == debitCredit.CreditEntryId);
                _accountEntryRepository.Remove(creditEntry);
                _accountEntryRepository.Save();

                return(BasicOperationResult <bool> .Ok(true));
            }
            catch (System.Exception ex)
            {
                return(BasicOperationResult <bool> .Fail(ex.Message));
            }
        }
        public async Task <IOperationResult <Meeting> > CancelMeeting(int meetingId, int userId)
        {
            var user = await _userRepository.Find(u => u.Id == userId, u => u.UserRoles);

            if (user == null)
            {
                return(BasicOperationResult <Meeting> .Fail("El usuario no fue encontrado"));
            }

            var meeting = await _meetingRepository.Find(s => s.Id == meetingId, s => s.Subject);

            if (meeting == null)
            {
                return(BasicOperationResult <Meeting> .Fail("La tutoría no fue encontrada"));
            }

            if (!(meeting.StudentId == userId || meeting.TutorId == userId))
            {
                return(BasicOperationResult <Meeting> .Fail("El usuario no esta asociado a esta tutoría"));
            }


            meeting.Status         = MeetingStatus.Cancelled;
            meeting.CancelerUserId = userId;
            var amount = CalculateMeetingAmount(meeting);

            _meetingRepository.Update(meeting);

            await _meetingRepository.Save();

            await _notificationManager.NotifyMeetingWasCanceled(meeting, userId, amount);

            return(BasicOperationResult <Meeting> .Ok(meeting));
        }
        public async Task <IOperationResult <ParentAuthorization> > CreateParentAuthorization(int meetingId, ParentAuthorization answer)
        {
            var meeting = await _meetingRepository.Find(m => m.Id == meetingId,
                                                        m => m.Tutor, m => m.Student, m => m.Subject);

            if (meeting == null)
            {
                return(BasicOperationResult <ParentAuthorization> .Fail("La tutoría agendada no fue encontrada"));
            }

            var authorization = new ParentAuthorization
            {
                AuthorizationDate = DateTime.Now,
                ParentId          = answer.ParentId,
                Status            = answer.Status,
                Reason            = answer.Reason
            };

            _parentAuthorizationRepository.Create(authorization);
            await _parentAuthorizationRepository.Save();

            meeting.ParentAuthorizationId = authorization.Id;
            meeting.Status = authorization.Status == ParentAuthorizationStatus.Approved
                ? MeetingStatus.Approved
                : MeetingStatus.Rejected;
            _meetingRepository.Update(meeting);

            ParentAuthorizationStatus status = answer.Status;

            await _meetingRepository.Save();

            await _notificationActions[status](meeting, authorization);

            return(BasicOperationResult <ParentAuthorization> .Ok(authorization));
        }
        public async Task <IOperationResult <bool> > ToggleStudentAccountActivation(int studentId, int parentId)
        {
            var oldUser = await _userRepository.Find(
                u => u.Id == studentId && u.UserRoles.Any(ur => ur.RoleId == (int)RoleTypes.Student),
                u => u.UserRoles, u => u.Parents);

            if (oldUser == null)
            {
                return(BasicOperationResult <bool> .Fail("El estudiante no fue encontrado"));
            }

            if (oldUser.Parents.All(p => p.ParentId != parentId))
            {
                return(BasicOperationResult <bool> .Fail("El estudiante no esta relacionado con el Padre indicado"));
            }

            oldUser.IsActive = !oldUser.IsActive;

            _userRepository.Update(oldUser);

            await _userRepository.Save();

            await _mailService.SendWhenAccountStateToggled(oldUser);

            return(BasicOperationResult <bool> .Ok(true));
        }
Beispiel #10
0
        public async Task <IOperationResult <User> > RegisterTutorUser(User newUser, string password, ISet <RoleTypes> roles)
        {
            if (roles.Count() <= 0)
            {
                return(BasicOperationResult <User> .Fail("No roles given to create user"));
            }

            newUser.IsActive = false;
            IdentityResult userCreateResult = await _userManager.CreateAsync(newUser, password);

            if (!userCreateResult.Succeeded)
            {
                return(BasicOperationResult <User> .Fail(GetErrorsFromIdentityResult(userCreateResult.Errors)));
            }

            User createdUser = await _userManager.FindByEmailAsync(newUser.Email);

            var emailValidation = await GetEmailToken(createdUser.Id);

            await _mailService.SendEmailToRegisteredUser(newUser, emailValidation.ValidationToken.ToString());

            IEnumerable <UserRole> userRoles = roles.Select(r => new UserRole {
                RoleId = (int)r, UserId = createdUser.Id
            });

            _userRoleRepository.Set.AddRange(userRoles);

            await _userRoleRepository.Save();

            User user = await _userRepository.Set
                        .Include(u => u.UserRoles)
                        .FirstOrDefaultAsync(u => u.Email == createdUser.Email);

            return(BasicOperationResult <User> .Ok(user));
        }
        public async Task <IOperationResult <string> > NotifyParentsOfMeetingUpdatedForStudent(Meeting meeting)
        {
            var studentResult = await GetUser(meeting.StudentId);

            if (!studentResult.Success)
            {
                return(BasicOperationResult <string> .Fail(studentResult.Message.Message));
            }

            User student = studentResult.Entity;

            ISet <User> parents = await _userRepository.GetAllParentsForStudent(student.Id);

            if (!parents.Any())
            {
                return(BasicOperationResult <string> .Fail("No fueron encontrados padres para este estudiante"));
            }

            string message =
                $"{student.FullName} ha hecho un cambio en la tutoría de {meeting.Subject.Name}. Su autorización no es requerida";


            await _notificationService.SendNotificationToMultipleUsers(parents, message, "Tutoria Actualizada");

            return(BasicOperationResult <string> .Ok("Notificación enviada"));
        }
        public async Task <IOperationResult <ISet <User> > > GetTutorNotInCurMeeting(int meetingId)
        {
            var meeting = await _meetingRepository.Find(
                m => m.Id == meetingId && m.Status == MeetingStatus.Rejected,
                m => m.Subject, m => m.Subject.Tutors);

            if (meeting == null)
            {
                return(BasicOperationResult <ISet <User> > .Fail("La tutoría rechazada no fue encontrada"));
            }

            var tutorsResult = await GetTutorsBySubjectId(meeting.SubjectId);

            if (!tutorsResult.Success)
            {
                return(tutorsResult);
            }

            var rejections = await _rejectedMeetingRepository.FindAll(r => r.MeetingId == meeting.Id);

            ISet <User> tutors = tutorsResult
                                 .Entity
                                 .Where(t => t.Id != meeting.TutorId && rejections.All(r => r.TutorId != t.Id))
                                 .ToHashSet();

            if (!tutors.Any())
            {
                return(BasicOperationResult <ISet <User> > .Fail("No hay más tutores disponibles para esta matería, lo sentimos, estamos trabajando por obtener más"));
            }

            return(BasicOperationResult <ISet <User> > .Ok(tutors));
        }
        public async Task <IOperationResult <string> > NotifyParentsOfMeetingCreatedForStudent(Meeting meeting)
        {
            var studentResult = await GetUser(meeting.StudentId);

            if (!studentResult.Success)
            {
                return(BasicOperationResult <string> .Fail(studentResult.Message.Message));
            }

            User student = studentResult.Entity;

            ISet <User> parents = await _userRepository.GetAllParentsForStudent(student.Id);

            if (!parents.Any())
            {
                return(BasicOperationResult <string> .Fail("No fueron encontrados padres para este estudiante"));
            }

            string message =
                $"{student.FullName} ha solicitado una tutoría de {meeting.Subject.Name}. Presione el mensaje para obtener más información";

            var data = new Dictionary <string, string>
            {
                { "parentMeetingId", meeting.Id.ToString() }
            };

            await _notificationService.SendNotificationToMultipleUsers(parents, message, "Tutoria Solicitada", data);

            return(BasicOperationResult <string> .Ok("Notificación enviada"));
        }
        public async Task <IOperationResult <string> > NotifyMeetingHasStarted(Meeting meeting)
        {
            string subject = "Tutoría Iniciada";

            User student = meeting.Student;
            User tutor   = meeting.Tutor;

            ISet <User> parents = await _userRepository.GetAllParentsForStudent(student.Id);

            if (!parents.Any())
            {
                return(BasicOperationResult <string> .Fail("No fueron encontrados padres para este estudiante"));
            }

            string messageToParents =
                $"La tutoría de {student.FullName} del tema: {meeting.Subject.Name} ha iniciado.";

            string messageToUsers = $"La tutoría para {meeting.Subject.Name} ha sido iniciada, entra a la aplicación para ver más detalles.";

            var data = new Dictionary <string, string>
            {
                { "startedMeetingId", meeting.Id.ToString() }
            };

            await _notificationService.SendNotificationToMultipleUsers(parents, messageToParents, subject, data);

            await _notificationService.SendNotificationToUser(student, messageToUsers, subject, data);

            await _notificationService.SendNotificationToUser(tutor, messageToUsers, subject, data);

            return(BasicOperationResult <string> .Ok("Tutoria Completada"));
        }
        public async Task <IOperationResult <string> > NotifySolicitedMeetingByStudentAnswered(Meeting meeting)
        {
            var tutorResult = await GetUser(meeting.TutorId);

            var student = await GetUser(meeting.StudentId);

            User tutorUser = tutorResult.Entity;

            string message = meeting.Status == MeetingStatus.Accepted
                ? $"Su tutoría ha sido aceptada y agendada con {tutorUser.FullName} para la materia {meeting.Subject.Name}"
                : $"Su tutoría ha sido rechazada por {tutorUser.FullName}, proceda a elegir otro tutor";

            string subject = meeting.Status == MeetingStatus.Accepted ? "Tutoría Aceptada" : "Tutoría Rechazada";

            var data = new Dictionary <string, string>();

            data.Add("answeredMeetingId", meeting.Id.ToString());

            if (meeting.Status == MeetingStatus.Rejected)
            {
                data.Add("meetingRejected", "true");
            }

            await _notificationService.SendNotificationToUser(student.Entity, message, subject, data);

            return(BasicOperationResult <string> .Ok("Notification was sent"));
        }
Beispiel #16
0
        public IOperationResult <AccountingEntry> FindAccountingEntry(long accountingEntryId)
        {
            AccountingEntry accountingEntry = _accountEntryRepository.Find(currency => currency.Id == accountingEntryId);

            return(accountingEntry != null
                ? BasicOperationResult <AccountingEntry> .Ok(accountingEntry)
                : BasicOperationResult <AccountingEntry> .Fail("NotFound"));
        }
Beispiel #17
0
        IOperationResult <T> IGenericRepository <T> .Update(T entity)
        {
            EntityEntry entityEntry = _context.Entry(entity);

            entityEntry.State = EntityState.Modified;

            return(BasicOperationResult <T> .Ok());
        }
Beispiel #18
0
        public IOperationResult <T> Update(T entity)
        {
            entity.UpdatedDate = DateTime.Now.GetNowInCorrectTimezone();
            var entityEntry = _context.Entry(entity);

            entityEntry.State = EntityState.Modified;

            return(BasicOperationResult <T> .Ok(entity));
        }
Beispiel #19
0
        public async Task <IOperationResult <User> > GetUserById(int userId)
        {
            var user = await _userRepository.Find(u => u.Id == userId);

            if (user == null)
            {
                return(BasicOperationResult <User> .Fail("Los datos del usuario no fueron encontrados"));
            }

            return(BasicOperationResult <User> .Ok(user));
        }
Beispiel #20
0
        public async Task <IOperationResult <User> > GetUserProfile(int userId)
        {
            var user = await _userRepository.Set.Include(u => u.UserRoles).FirstAsync(u => u.Id == userId);

            if (user == null)
            {
                return(BasicOperationResult <User> .Fail("User was not found"));
            }

            return(BasicOperationResult <User> .Ok(user));
        }
        public async Task <IOperationResult <Subject> > GetSubject(int subjectId)
        {
            var subject = await _subjectRepository.Find(s => s.Id == subjectId);

            if (subject == null)
            {
                return(BasicOperationResult <Subject> .Fail("The subject was not found"));
            }

            return(BasicOperationResult <Subject> .Ok(subject));
        }
        public async Task <IOperationResult <Meeting> > GetMeetingForParent(int meetingId, int parentId)
        {
            var meeting = await _meetingRepository.GetMeetingForParent(meetingId, parentId);

            if (meeting == null)
            {
                return(BasicOperationResult <Meeting> .Fail("La tutoría agendada no fue encontrada"));
            }

            return(BasicOperationResult <Meeting> .Ok(meeting));
        }
        private async Task <IOperationResult <User> > GetUser(int userId)
        {
            User user = await _userRepository.Find(u => u.Id == userId, u => u.UserRoles);

            if (user == null)
            {
                return(BasicOperationResult <User> .Fail("El usuario no fue encontrado"));
            }

            return(BasicOperationResult <User> .Ok(user));
        }
Beispiel #24
0
        public async Task <IOperationResult <IEnumerable <Rating> > > GetUserRatings(int userId)
        {
            var rating = await _ratingRepository.FindAll(r => r.UserId == userId);

            if (rating == null)
            {
                return(BasicOperationResult <IEnumerable <Rating> > .Fail("Los ratings no están disponibles"));
            }

            return(BasicOperationResult <IEnumerable <Rating> > .Ok(rating));
        }
        public async Task <IOperationResult <IEnumerable <User> > > GetTutorsForSubject(int subjectId)
        {
            var tutorSubjects = await _tutorSubjectRepository.FindAll(ts => ts.SubjectId == subjectId, ts => ts.Tutor);

            var tutors = tutorSubjects.Select(ts => ts.Tutor);

            if (!tutors.Any())
            {
                return(BasicOperationResult <IEnumerable <User> > .Fail("No hay tutores asociados a esta materia"));
            }

            return(BasicOperationResult <IEnumerable <User> > .Ok(tutors));
        }
Beispiel #26
0
        public async Task <IOperationResult <IEnumerable <Role> > > GetAllRoles()
        {
            var roles = await _roleRepository.Set
                        .OrderBy(r => r.Name)
                        .ToListAsync();

            if (roles.Count == 0)
            {
                return(BasicOperationResult <IEnumerable <Role> > .Fail("No roles where found"));
            }

            return(BasicOperationResult <IEnumerable <Role> > .Ok(roles));
        }
Beispiel #27
0
        private async Task <IOperationResult <Rating> > ValidateRating(Rating rating)
        {
            var validator = new RatingValidator();

            ValidationResult validationResult = await validator.ValidateAsync(rating);

            if (!validationResult.IsValid)
            {
                return(BasicOperationResult <Rating> .Fail(validationResult.JSONFormatErrors()));
            }

            return(BasicOperationResult <Rating> .Ok());
        }
Beispiel #28
0
        public async Task <IOperationResult <decimal> > GetUserAvgRatingAsync(int userId)
        {
            var ratings = await _ratingRepository.FindAll(r => r.UserId == userId);

            if (!ratings.Any())
            {
                return(BasicOperationResult <decimal> .Fail("El rating no esta disponible"));
            }

            decimal avgRating = ratings.Sum(r => r.Calification) / ratings.Count() / 2;

            return(BasicOperationResult <decimal> .Ok(avgRating));
        }
        private async Task <IOperationResult <Subject> > ValidateSubject(Subject subject)
        {
            var validator = new SubjectValidator();

            ValidationResult validationResult = await validator.ValidateAsync(subject);

            if (!validationResult.IsValid)
            {
                return(BasicOperationResult <Subject> .Fail(validationResult.JSONFormatErrors()));
            }

            return(BasicOperationResult <Subject> .Ok());
        }
Beispiel #30
0
        public async Task <IOperationResult <IEnumerable <User> > > GetStudentsByParentId(int userId)
        {
            var parentStudents = await _parentStudentRepository
                                 .FindAll(x => x.ParentId == userId,
                                          x => x.Student);

            if (parentStudents == null || !parentStudents.Any())
            {
                return(BasicOperationResult <IEnumerable <User> > .Fail("Los datos del usuario no fueron encontrados"));
            }

            var studentsUsers = parentStudents.Select(ps => ps.Student);

            return(BasicOperationResult <IEnumerable <User> > .Ok(studentsUsers));
        }