Пример #1
0
        public async Task <IActionResult> UpdateDoctorWorkingTime([FromBody] UpdateDoctorWorkingTimeModel model)
        {
            // Получаем id пользователя из токена. Id туда попал при выдаче токена во время авторизации
            var nameIdentifier = this.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
            int userId         = int.Parse(nameIdentifier.Value);

            // Достаем запись юзера
            User user = await _db.Users.FirstOrDefaultAsync(x => x.Id == userId);

            if (user == null)
            {
                return(NotFound());
            }

            Doctor doctor = await _db.Doctors.FirstOrDefaultAsync(x => x.User.Id == user.Id);

            if (doctor == null)
            {
                return(NotFound("Такой доктор не найден"));
            }

            foreach (var workingDay in model.workingTime)
            {
                DoctorWorkingTime newWorkingDay = new DoctorWorkingTime()
                {
                    Start         = workingDay.Start,
                    End           = workingDay.End,
                    Doctor        = doctor,
                    WeekdayNumber = workingDay.Day,
                };

                DoctorWorkingTime workingTime = _db.DoctorWorkingTimes.FirstOrDefault(x => x.WeekdayNumber == newWorkingDay.WeekdayNumber && x.Doctor.Id == newWorkingDay.Doctor.Id);

                // Если создаваемый день есть уже в бд, то обновляем, иначе создаем новый
                if (workingTime != null)
                {
                    workingTime.Start = newWorkingDay.Start;
                    workingTime.End   = newWorkingDay.End;
                }
                else
                {
                    _db.DoctorWorkingTimes.Add(newWorkingDay);
                }

                await _db.SaveChangesAsync();
            }

            return(Ok(new { success = true }));
        }
Пример #2
0
        public async Task <DoctorWorkingTime> GetAvailableWorkingTimeAsync(Guid id, DateTime date, FilterWorktime filter)
        {
            var doctorTime = await Context.Doctors
                             .IncludeMultiple(x => x.Appointments, x => x.WorkingSchedules, x => x.NoAttendances)
                             .Where(x => x.IsActive && x.Id == id)
                             .Select(x => new DoctorTimeProjection
            {
                WorkingHoursInDay = x.WorkingSchedules
                                    .Where(ws => ws.IsActive && date.Date >= ws.FromDate.Date)
                                    .Select(ws => ws.Hours.ToWorkingTimes(date.DayOfWeek))
                                    .FirstOrDefault(),
                TimeOffInDay = x.NoAttendances
                               .Where(na => na.IsActive && date.IsBetween(na.FromDate.Date, na.ToDate.Date))
                               .Select(na => TimeRangeUtils.GetTimeRange(na.FromDate, na.ToDate, date))
                               .ToArray(),
                TimeBusyInDay = x.Appointments
                                .Where(a => a.IsActive && a.Status != (int)AppointmentStatus.Cancelled && a.DoctorId == id && a.AppointmentDate.Date == date.Date)
                                .Select(a => new TimeRange(a.AppointmentDate.TimeOfDay, a.AppointmentDate.AddMinutes(a.TotalMinutes).TimeOfDay))
                                .ToArray()
            })
                             .FirstOrDefaultAsync();

            var result = new DoctorWorkingTime
            {
                DoctorId     = id,
                WorkingTimes = doctorTime.WorkingHoursInDay
                               .ConvertArray(wh =>
                                             TimeRangeUtils.GetTimeFrame(wh, doctorTime.TimeOffInDay, doctorTime.TimeBusyInDay, new TimeRange(filter.TimeFrom ?? new TimeSpan(0, 0, 0), new TimeSpan(23, 59, 59))))
                               .ToSingleArray()
            };

            if (filter.ServiceDuration.GetValueOrDefault() > 0)
            {
                result.WorkingTimes = result.WorkingTimes.Where(worktime => TimeRangeUtils.IsServiceTime(worktime, filter.ServiceDuration.Value, result.WorkingTimes)).ToArray();
            }

            return(result);
        }
Пример #3
0
        public async Task <IActionResult> SignUp([FromBody] RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Добавляем нового юзера, если указанного Email еще нет в бд
                User user = await _db.Users.FirstOrDefaultAsync(u => u.Email == model.Email);

                if (user == null)
                {
                    // ищем роль
                    RolesScroll roleKey    = model.Doctor == true ? RolesScroll.Doctor : RolesScroll.Patient;
                    int         intRoleKey = (int)roleKey;
                    Role        userRole   = await _db.Roles.FirstOrDefaultAsync(r => r.Id == intRoleKey);

                    // добавляем пользователя в бд
                    User newUser = new User()
                    {
                        Email = model.Email, Fio = model.Fio, Password = model.GetPassword(), RoleKey = userRole.Id
                    };
                    _db.Users.Add(newUser);
                    await _db.SaveChangesAsync();

                    // добавляем врача или пациента
                    switch (roleKey)
                    {
                    case RolesScroll.Doctor:

                        Doctor newDoctor = new Doctor()
                        {
                            User = newUser
                        };
                        _db.Doctors.Add(newDoctor);

                        // Jcjeifi fiwwdmccp, cmwicw98jc __dee9c0+ckei ncdjnj
                        for (int i = 1; i <= 5; i++)
                        {
                            DoctorWorkingTime newWorkingDay = new DoctorWorkingTime()
                            {
                                Start         = "08:00",
                                End           = "20:00",
                                Doctor        = newDoctor,
                                WeekdayNumber = i,
                            };
                            _db.DoctorWorkingTimes.Add(newWorkingDay);
                        }

                        break;

                    case RolesScroll.Patient:

                        Patient newPatient = new Patient()
                        {
                            User = newUser
                        };
                        _db.Patients.Add(newPatient);
                        break;
                    }
                    await _db.SaveChangesAsync();

                    // генерим токен с данными пользователя, чтоб юзер бл сразу авторизованным после регистрации
                    var    identity = GetIdentity(model.Email, model.GetPassword());
                    string jwt      = GenJWT(identity);
                    var    response = new
                    {
                        access_token = jwt
                    };

                    return(Ok(response));
                }
                else
                {
                    return(BadRequest(new { errorText = "Пользователь с таким емейлом уже зарегистрирован." }));
                }
            }
            return(BadRequest(model));
        }