Пример #1
0
        public KeyValuePair <long, bool> UpdateSchedule(user_schedule_sleep model, bool isAllDay)
        {
            model.uss_time_from = ParseScheduleTime(model.uss_time_from_calc.Value.ToString("HH:mm"));
            model.uss_time_to   = ParseScheduleTime(model.uss_time_to_calc.Value.ToString("HH:mm"));

            if (model.uss_time_to_calc.Value.TimeOfDay < model.uss_time_from_calc.Value.TimeOfDay)
            {
                model.uss_time_to_calc = model.uss_date.AddDays(1).Date.Add(model.uss_time_to_calc.Value.TimeOfDay);
                model.uss_time_to      = model.uss_time_to + TimeSpan.TicksPerDay;
            }
            else if (model.uss_time_to_calc.Value.TimeOfDay > model.uss_time_from_calc.Value.TimeOfDay && isAllDay)
            {
                // Set the same date in both field
                model.uss_time_to_calc = new DateTime(model.uss_time_from_calc.Value.Year,
                                                      model.uss_time_from_calc.Value.Month,
                                                      model.uss_time_from_calc.Value.Day,
                                                      model.uss_time_to_calc.Value.Hour,
                                                      model.uss_time_to_calc.Value.Minute,
                                                      model.uss_time_to_calc.Value.Second,
                                                      model.uss_time_to_calc.Value.Millisecond);
            }
            else if (model.uss_time_to_calc.Value.Date > model.uss_time_from_calc.Value.Date)
            {
                model.uss_time_to = model.uss_time_to + TimeSpan.TicksPerDay;
            }

            var existingSchdule = _unitOfWork.SleepRepository.Query()
                                  .Where(m =>
                                         m.uss_time_from_calc < model.uss_time_to_calc &&
                                         model.uss_time_from_calc < m.uss_time_to_calc &&
                                         m.uss_user_id == model.uss_user_id &&
                                         m.uss_key != model.uss_key)
                                  .ToList();

            if (existingSchdule != null && existingSchdule.Count > 0)
            {
                return(new KeyValuePair <long, bool>(0, false));
            }

            _unitOfWork.SleepRepository.Update(model);
            _unitOfWork.Save();
            _unitOfWork.Commit();
            return(new KeyValuePair <long, bool>(model.uss_key, true));
        }
Пример #2
0
        private SchedulerResponseViewModel ImportSchedule(DataTable tableSchedules, string loggedinUserId, string loggedinUserName, bool SkipErrors, string impType)
        {
            var listColumns = new List <string>();
            SchedulerResponseViewModel response = new SchedulerResponseViewModel();

            // generate columns list
            foreach (DataColumn col in tableSchedules.Columns)
            {
                if (!listColumns.Contains(col.ColumnName) && col.ColumnName.ToLower() != "date")
                {
                    listColumns.Add(col.ColumnName);
                }
            }

            // if there are column to import
            if (listColumns.Count() == 0)
            {
                return(response);
            }

            // get user's info based on initials in CSV
            var listUsers = _unitOfWork.ApplicationUsers
                            .Where(x => listColumns.Contains(x.UserInitial))
                            .Select(x => new { x.UserInitial, x.Id, x.FirstName, x.LastName })
                            .ToList();
            var distinctScheduleUserIds = listUsers.Select(x => x.Id).ToList();
            // temp schedules
            var listSchedule = new List <user_schedule_sleep>();
            var currentTime  = DateTime.Now.ToEST();

            // process all columns
            int rowCount = 2; // first row is header that's why initializing it from 2
            int colCount = 1;

            foreach (DataRow row in tableSchedules.Rows)
            {
                colCount = 1;
                DateTime schDate      = new DateTime();
                bool     hasValidDate = true;
                if (string.IsNullOrEmpty(row["Date"].ToString()))
                {
                    continue;
                }

                try { schDate = Convert.ToDateTime(row["Date"]); } catch { hasValidDate = false; }
                if (hasValidDate)
                {
                    foreach (string currentColumn in listColumns)
                    {
                        string columnData = Convert.ToString(row[currentColumn]);
                        if (!string.IsNullOrEmpty(currentColumn) && !string.IsNullOrEmpty(columnData))
                        {
                            var splitShift = columnData.Split('|');
                            foreach (string schItem in splitShift)
                            {
                                string[] times  = null;
                                string   userId = null;
                                try
                                {
                                    try { if (!string.IsNullOrEmpty(schItem.Trim()))
                                          {
                                              times = schItem.Trim().Split('-').Where(m => !string.IsNullOrEmpty(m)).ToArray();
                                          }
                                    } catch { response.ParseErrors.Add($"Invalid Time {schItem} on Row {rowCount} and Column {colCount}"); }
                                    if (userId == null)
                                    {
                                        try { userId = listUsers.Where(x => x.UserInitial.ToLower() == currentColumn.ToLower()).FirstOrDefault()?.Id; } catch { response.ParseErrors.Add($"Invalid Initial {currentColumn} on Row {rowCount} and Column {colCount}"); }
                                    }

                                    if (userId != null && times != null)
                                    {
                                        if (times.Length == 2)
                                        {
                                            var schEntry = new user_schedule_sleep
                                            {
                                                uss_date            = schDate,
                                                uss_user_id         = userId,
                                                uss_time_from       = ParseScheduleTime(times[0]), //TimeSpan.Parse(times[0]).Ticks,
                                                uss_time_to         = ParseScheduleTime(times[1]), //TimeSpan.Parse(times[1]).Ticks,
                                                uss_is_active       = true,
                                                uss_created_by      = loggedinUserId,
                                                uss_created_by_name = loggedinUserName,
                                                uss_created_date    = currentTime,
                                            };



                                            // next day's time check
                                            if (schEntry.uss_time_to < schEntry.uss_time_from)
                                            {
                                                schEntry.uss_time_to = schEntry.uss_time_to + TimeSpan.TicksPerDay;
                                            }

                                            schEntry.uss_time_from_calc = schEntry.uss_date.Date.AddTicks(schEntry.uss_time_from);
                                            schEntry.uss_time_to_calc   = schEntry.uss_date.Date.AddTicks(schEntry.uss_time_to);

                                            listSchedule.Add(schEntry);
                                        }
                                        else
                                        {
                                            response.ParseErrors.Add($"Invalid Time {schItem} on Row {rowCount} and Column {colCount}");
                                            response.Success = false;
                                        }
                                    }
                                }
                                catch
                                {
                                    response.ParseErrors.Add($"Parse Data issue on Row {rowCount} and Column {colCount}");
                                }
                            }
                        }
                        colCount++;
                    }
                }
                else
                {
                    response.Success = false;
                    response.ParseErrors.Add($"Invalid Date {row["Date"].ToString()} on Row {rowCount} and Column {colCount}");
                }
                rowCount++;
            }
            if (listSchedule != null && listSchedule.Count() > 0 && response.Success || (listSchedule != null && listSchedule.Count() > 0 && SkipErrors))
            {
                try
                {
                    var distinctDates = listSchedule.Select(x => x.uss_date).Distinct().ToList();
                    var oldEntries    = _unitOfWork.SleepRepository.Query().Where(x => distinctDates.Any(y => y == x.uss_date)).ToList();

                    #region Get Only Required Physician
                    PhysicianDictionary physicianDictionary = new PhysicianDictionary();
                    var ids                 = physicianDictionary.GetRecordAsList(impType);
                    var foundIds            = _adminService.GetAllUsersIds(ids);
                    HashSet <string> resIds = new HashSet <string>(oldEntries.Select(s => s.uss_user_id.ToString()));
                    var matchIds            = resIds.Intersect(foundIds).ToList();
                    //var _oldEntries = oldEntries.Where(x => matchIds.Contains(x.uss_user_id)).ToList();
                    var _oldEntries = oldEntries.Where(x => matchIds.Contains(x.uss_user_id)).Where(x => distinctScheduleUserIds.Contains(x.uss_user_id)).ToList();
                    #endregion
                    _unitOfWork.BeginTransaction();
                    // remove old entries
                    if (_oldEntries != null && _oldEntries.Count() > 0)
                    {
                        _unitOfWork.SleepRepository.DeleteRange(_oldEntries);
                        _unitOfWork.Save();
                    }
                    // add schedule entries
                    if (listSchedule.Count() > 0)
                    {
                        _unitOfWork.SleepRepository.InsertRange(listSchedule);
                        _unitOfWork.Save();
                    }
                    _unitOfWork.Commit();
                    return(new SchedulerResponseViewModel {
                        Message = "Schedule is updated.", Success = true
                    });
                }
                catch (Exception ex)
                {
                    try { _unitOfWork.Rollback(); }
                    catch
                    {
                        throw ex;
                    }
                }
                finally { listSchedule = null; }
            }
            return(response);
        }