Ejemplo n.º 1
0
        /// <summary>
        /// 新增PeriodData数据并且更新到PeriodUserInfo
        /// </summary>
        /// <param name="data"></param>
        /// <param name="userName"></param>
        private void addPeriodData(PeriodInfo data, string userName)
        {
            PeriodData pd = new PeriodData()
            {
                MC_Begin    = data.MC_Begin,
                MC_Days     = data.MC_Days,
                MC_Cycle    = data.MC_Cycle,
                MC_Finish   = data.MC_Begin.AddDays(data.MC_Cycle),
                Period_Type = 1,
                UserName    = userName
            };

            periodDB.PeriodData.Add(pd);
            // 修改再上次经期的结束时间
            PeriodData lpd = getLastPeriodData(userName);

            if (lpd != null)
            {
                lpd.MC_Finish = data.MC_Begin;
                lpd.MC_Cycle  = Convert.ToInt32(lpd.MC_Finish.Subtract(lpd.MC_Begin).TotalDays);
            }
            var pui = periodDB.PeriodUserInfo.SingleOrDefault(m => m.UserName == userName);

            if (pui != null)
            {
                pui.Last_MC_Begin = data.MC_Begin;
                pui.MC_Cycle      = data.MC_Cycle;
                pui.MC_days       = data.MC_Days;
                periodDB.SaveChanges();
            }
            // 保存数据
            periodDB.SaveChanges();
        }
Ejemplo n.º 2
0
        // 渲染历史月经数据
        public PeriodResult RenderPeriodHistory(int year, int month, PeriodData data, PeriodResult result)
        {
            //var peroid_list = from m in peroid
            DateTime first_day = new DateTime(year, month, 1);
            DateTime last_day  = first_day.AddMonths(1);
            DateTime period    = data.MC_Begin;

            // 填充历史经期
            for (int i = 0; i < data.MC_Days; i++)
            {
                var item = period.AddDays(i);
                if (item >= first_day && item < last_day)
                {
                    result.p_days.Add(item.Day);
                }
            }
            var safe_day_last  = period.AddDays(data.MC_Cycle - 3);
            var safe_day_first = period.AddDays(data.MC_Days + 4);
            var danger_day     = (safe_day_last.Subtract(safe_day_first).Days) / 2 - 2;

            for (int i = 0; i < 5; i++)
            {
                // 填充易孕期
                var item = safe_day_first.AddDays(danger_day + i);
                if (item >= first_day && item < last_day)
                {
                    result.e_days.Add(item.Day);
                }
            }
            return(result);
        }
Ejemplo n.º 3
0
        public async Task <bool> CheckPeriodGivenDate(IStObjMap stObjMap, IAuthenticationInfo authenticationInfo, DateTime begDate, DateTime endDate)
        {
            var sqlDatabase = stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            var group       = stObjMap.StObjs.Obtain <CustomGroupTable>();
            int userId      = authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                GroupQueries       groupQueries       = new GroupQueries(ctx, sqlDatabase);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, sqlDatabase);

                GroupData groupData = await groupQueries.GetIdSchoolByConnectUser(userId);

                PeriodData periodData = await timedPeriodQueries.GetCurrentPeriod(groupData.ZoneId);

                int shouldBeGreater = begDate.CompareTo(periodData.BegDate);
                int shouldBeLower   = endDate.CompareTo(periodData.EndDate);

                if (shouldBeGreater >= 0 && shouldBeLower <= 0)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        }
Ejemplo n.º 4
0
        public async Task <bool> CheckInPeriod(IStObjMap stObjMap, IAuthenticationInfo authenticationInfo)
        {
            var sqlDatabase = stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            var group       = stObjMap.StObjs.Obtain <CustomGroupTable>();
            int userId      = authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                GroupQueries       groupQueries       = new GroupQueries(ctx, sqlDatabase);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, sqlDatabase);

                GroupData groupData = await groupQueries.GetIdSchoolByConnectUser(userId);

                PeriodData periodData = await timedPeriodQueries.GetCurrentPeriod(groupData.ZoneId);

                DateTime currentDateTime        = DateTime.UtcNow;
                int      shoulbBeLowerOrEqual   = DateTime.Compare(periodData.BegDate, currentDateTime);
                int      shouldBeGreaterOrEqual = DateTime.Compare(periodData.EndDate, currentDateTime);

                if (shoulbBeLowerOrEqual > 0 || shouldBeGreaterOrEqual < 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> GetEventSchoolByName(string eventName, string schoolName)
        {
            var sqlDataBase = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            int userId      = _authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                EventQueries       eventQueries       = new EventQueries(ctx, sqlDataBase);
                GroupQueries       groupQueries       = new GroupQueries(ctx, sqlDataBase);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, sqlDataBase);

                GroupData groupData = await groupQueries.GetIdSchoolByConnectUser(userId);

                EventData eventData;

                if (groupData == null)
                {
                    int idSchool = await groupQueries.GetIdSchoolByName(schoolName);

                    PeriodData periodData = await timedPeriodQueries.GetLastPeriodBySchool(idSchool);

                    eventData = await eventQueries.GetEventSchoolBylNameAndPeriodId(eventName, periodData.ChildId);
                }
                else
                {
                    eventData = await eventQueries.GetEventSchoolBylNameAndPeriodId(eventName, groupData.ZoneId);
                }


                return(Ok(eventData));
            }
        }
Ejemplo n.º 6
0
        public JsonResult setItCome(int year, int month, int day)
        {
            PeriodData pd          = getLastPeriodData(User.Identity.Name);
            DateTime   periodStart = new DateTime(year, month, day);

            if (pd != null)
            {
                if (periodStart >= pd.MC_Begin.AddDays(14))
                {
                    PeriodInfo info = new PeriodInfo()
                    {
                        MC_Begin = periodStart,
                        MC_Days  = pd.MC_Days,
                        MC_Cycle = Convert.ToInt32(periodStart.Subtract(pd.MC_Begin).TotalDays)
                    };
                    addPeriodData(info, User.Identity.Name);
                    return(Json(new { result = "SUCCESS" }));
                }
                else
                {
                    PeriodInfo info = new PeriodInfo()
                    {
                        MC_Begin = periodStart,
                        MC_Days  = pd.MC_Days,
                        MC_Cycle = pd.MC_Cycle
                    };
                    updatePeriodData(info, User.Identity.Name);
                    return(Json(new { result = "SUCCESS" }));
                }
            }
            return(Json(new { result = "FAIL" }));
        }
Ejemplo n.º 7
0
        /******** 经期助手辅助程序 ********/
        /// <summary>
        /// 更新最近一次的经期数据,并同步到PeriodUserInfo
        /// </summary>
        /// <param name="data"></param>
        /// <param name="userName"></param>
        private void updatePeriodData(PeriodInfo data, string userName)
        {
            // 获取最近一次的经期数据
            PeriodData pd = (from m in periodDB.PeriodData
                             where m.UserName == userName
                             orderby m.MC_Begin descending
                             select m).FirstOrDefault();

            if (pd != null)
            {
                // 修改上一次经期结束时间
                PeriodData lpd = getLastPeriodData(pd.MC_Begin, userName);
                if (lpd != null)
                {
                    lpd.MC_Finish = data.MC_Begin;
                    lpd.MC_Cycle  = Convert.ToInt32(lpd.MC_Finish.Subtract(lpd.MC_Begin).TotalDays);
                }
                // 修改记录
                pd.MC_Begin  = data.MC_Begin;
                pd.MC_Cycle  = data.MC_Cycle;
                pd.MC_Days   = data.MC_Days;
                pd.MC_Finish = data.MC_Begin.AddDays(data.MC_Cycle);
                // 更新PeriodUserInfo
                var pui = periodDB.PeriodUserInfo.SingleOrDefault(m => m.UserName == userName);
                if (pui != null)
                {
                    pui.Last_MC_Begin = data.MC_Begin;
                    pui.MC_Cycle      = data.MC_Cycle;
                    pui.MC_days       = data.MC_Days;
                    periodDB.SaveChanges();
                }
                // 保存数据
                periodDB.SaveChanges();
            }
        }
Ejemplo n.º 8
0
        public IDictionary <Period, PeriodData> GetPeriodData(string schoolkey, int periodLength)
        {
            string cacheKey = "PeriodLength:" + periodLength + ":PeriodData:" + schoolkey;
            IDictionary <Period, PeriodData> periodData;

            if (_memoryCache.TryGetValue(cacheKey, out periodData))
            {
                return(periodData);
            }

            var schoolCalendarDays = StudentDataRepository.GetSchoolCalendarDays(schoolkey);

            IReadOnlyCollection <Period> Periods = Enum.GetValues(typeof(Period))
                                                   .Cast <Period>()
                                                   .ToArray();

            periodData = new SortedList <Period, PeriodData>();
            foreach (var period in Periods)
            {
                periodData[period] = new PeriodData();
            }

            schoolCalendarDays.ForEach((Action <SchoolCalendarDim>)(schoolCalendarDay =>
            {
                var periodIndex = schoolCalendarDay.GetPeriodIndex(periodLength);
                if (periodIndex > 2)
                {
                    return;
                }

                var period      = (Period)periodIndex;
                var periodDatum = periodData[period];
                periodDatum.CalendarDates.Add(schoolCalendarDay.Date);
            }));


            int i = 0;

            foreach (var periodDatum in periodData.Values)
            {
                if (periodDatum.CalendarDates.Count < periodLength)
                {
                    periodDatum.CalendarDates.Clear();
                }
                i++;
            }

            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetSize(200)//Size amount
                                    .SetPriority(CacheItemPriority.High)
                                    .SetSlidingExpiration(TimeSpan.FromMinutes(15))
                                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(60));

            _memoryCache.Set(cacheKey, periodData, cacheEntryOptions);

            return(periodData);
        }
Ejemplo n.º 9
0
 public PulseData()
 {
     IPulse        = new SimpleData(Properties.Settings.Default.I, 0x01);
     IIPulse       = new SimpleData(Properties.Settings.Default.II, 0x02);
     IIIPulse      = new SimpleData(Properties.Settings.Default.III, 0x03);
     I_IIDistance  = new SimpleData(Properties.Settings.Default.I_II, 0x04);
     I_IIIDistance = new SimpleData(Properties.Settings.Default.I_III, 0x05);
     Period        = new PeriodData(Properties.Settings.Default.T, 0x06, 0x07);
     Strobe        = new SimpleData(Properties.Settings.Default.St, 0x09);
     StrobePos     = new SimpleData(Properties.Settings.Default.I_St, 0x08);
 }
Ejemplo n.º 10
0
        private bool ValidateRecords(PeriodData data, IEnumerable <Datamart> records)
        {
            var valido           = true;
            var tuvoPosiciones   = data.Posiciones.Count > 1;
            var tuvoMovimiento   = data.Posiciones.Any(p => p.Velocidad > 0);
            var generoKilometros = records.Any(r => r.Kilometers > 0);

            if (tuvoPosiciones && tuvoMovimiento && !generoKilometros)
            {
                valido = false;
            }

            return(valido);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> GetAllTypeProjectsOfASchool(int idSchool, char type)
        {
            SqlDefaultDatabase db = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            int userId            = _authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                ProjectQueries     projectQueries     = new ProjectQueries(ctx, db);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, db);
                TimedUserQueries   timedUserQueries   = new TimedUserQueries(ctx, db);
                UserQueries        userQueries        = new UserQueries(ctx, db);
                GroupQueries       groupQueries       = new GroupQueries(ctx, db);

                PeriodData periodData = await timedPeriodQueries.GetLastPeriodBySchool(idSchool);

                //Implementer check date period

                TimedUserData timedUserData = await timedUserQueries.GetTimedUser(userId, periodData.ChildId);

                if (timedUserData == null)
                {
                    timedUserData = new TimedUserData
                    {
                        TimedUserId = 0
                    };
                }

                IEnumerable <AllProjectInfoData> projectData = await projectQueries.GetAllTypeProjectSpecificToSchoolWithTimedUserNote(periodData.ChildId, type, timedUserData.TimedUserId);

                for (var i = 0; i < projectData.Count(); i++)
                {
                    IEnumerable <UserByProjectData> userByProject = await userQueries.GetUserByProject(projectData.ElementAt( i ).ProjectStudentId);

                    projectData.ElementAt(i).BegDate = userByProject.ElementAt(0).BegDate;
                    projectData.ElementAt(i).EndDate = userByProject.ElementAt(0).EndDate;

                    foreach (var e in userByProject)
                    {
                        IEnumerable <GroupData> groupDatas = await groupQueries.GetAllGroupByTimedUser(e.TimedUserId);

                        projectData.ElementAt(i).FirstName.Add(e.FirstName);
                        projectData.ElementAt(i).LastName.Add(e.LastName);
                        projectData.ElementAt(i).TimedUserId.Add(e.TimedUserId);
                        projectData.ElementAt(i).UserId.Add(e.UserId);
                    }
                }
                return(Ok(projectData));
            }
        }
Ejemplo n.º 12
0
        public JsonResult setItGone(int year, int month, int day)
        {
            PeriodData pd         = getLastPeriodData(User.Identity.Name);
            DateTime   periodDone = new DateTime(year, month, day);

            if (pd != null)
            {
                PeriodInfo info = new PeriodInfo()
                {
                    MC_Begin = pd.MC_Begin,
                    MC_Cycle = pd.MC_Cycle,
                    MC_Days  = Convert.ToInt32(periodDone.AddDays(1).Subtract(pd.MC_Begin).TotalDays)
                };
                updatePeriodData(info, User.Identity.Name);
                return(Json(new { result = "SUCCESS" }));
            }
            return(Json(new { result = "FAIL" }));
        }
Ejemplo n.º 13
0
        public List <PeriodData> GetPeriod()
        {
            var               header    = ServiceContainer.GetService <PesWeb.Service.Modules.EvaManage>();
            List <Period>     GetPeriod = header.GetAllPeriod().ToList();
            List <PeriodData> pd        = new List <PeriodData>();

            foreach (Period p in GetPeriod)
            {
                PeriodData newp = new PeriodData();
                newp.Code       = p.Code;
                newp.Period_Id  = p.Period_Id;
                newp.StartDate  = p.StartDate.ToString().Replace('-', '/').Substring(0, 10);
                newp.FinishDate = p.FinishDate.ToString().Replace('-', '/').Substring(0, 10);
                newp.Status     = p.Status;
                pd.Add(newp);
            }
            return(pd);
        }
Ejemplo n.º 14
0
        public JsonResult getClickDateResult(int year, int month, int day)
        {
            DateTime clickDate = new DateTime(year, month, day);
            bool     it_come   = false;
            bool     it_gone   = false;

            if (clickDate < DateTime.Now.AddDays(1).Date)
            {
                PeriodData pd  = getLastPeriodData(User.Identity.Name);
                PeriodData lpd = getLastPeriodData(pd.MC_Begin, User.Identity.Name);
                if (clickDate >= pd.MC_Begin.AddDays(3) && clickDate < pd.MC_Begin.AddDays(13))
                {
                    it_gone = true;
                }
                if (lpd == null)
                {
                    if (clickDate > pd.MC_Begin.AddDays(-45))
                    {
                        it_come = true;
                    }
                }
                else
                {
                    if (clickDate > lpd.MC_Begin.AddDays(14))
                    {
                        it_come = true;
                    }
                }
            }
            if (it_come && it_gone)
            {
                return(Json(new { result = "MODAL", message = "1" }));
            }
            else if (it_come)
            {
                return(Json(new { result = "MODAL", message = "0" }));
            }
            else
            {
                return(Json(new { result = "INFO", message = "测试" }));
            }
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <AllProjectInfoData> > GetProjectsEvaluate(int idSchool)
        {
            SqlDefaultDatabase db = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            int userId            = _authenticationInfo.ActualUser.UserId;

            using (var ctx = new SqlStandardCallContext())
            {
                ProjectQueries     projectQueries     = new ProjectQueries(ctx, db);
                TimedPeriodQueries timedPeriodQueries = new TimedPeriodQueries(ctx, db);
                TimedUserQueries   timedUserQueries   = new TimedUserQueries(ctx, db);
                UserQueries        userQueries        = new UserQueries(ctx, db);
                GroupQueries       groupQueries       = new GroupQueries(ctx, db);

                PeriodData periodData = await timedPeriodQueries.GetLastPeriodBySchool(idSchool);

                //Implementer check date period

                IEnumerable <AllProjectInfoData> projectData = await projectQueries.GetAllProjectTimedByJuryId(userId, periodData.ChildId);

                return(projectData);
            }
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> ChangeDateOfPeriod([FromBody] PeriodChangeDateModel periodChangeDateModel)
        {
            int userId      = _authenticationInfo.ActualUser.UserId;
            var sqlDataBase = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();
            var group       = _stObjMap.StObjs.Obtain <CustomGroupTable>();

            using (var ctx = new SqlStandardCallContext())
            {
                TimedPeriodQueries timedPeriod = new TimedPeriodQueries(ctx, sqlDataBase);

                PeriodData period = await timedPeriod.GetPeriodById(periodChangeDateModel.idPeriod);

                await timedPeriod.UpdatePeriodDate(periodChangeDateModel.idPeriod, periodChangeDateModel.begDate, periodChangeDateModel.endDate);

                if (periodChangeDateModel.begDate.Year > period.BegDate.Year || periodChangeDateModel.begDate.Year < period.BegDate.Year)
                {
                    string groupName = periodChangeDateModel.begDate.Year + "-0" + periodChangeDateModel.begDate.Month;

                    await group.Naming.GroupRenameAsync(ctx, userId, periodChangeDateModel.idPeriod, groupName);
                }
                return(Ok());
            }
        }
        protected override List <StudentAttendanceEvent> GetMetricAttendanceEvents(List <StudentAttendanceEvent> studentAttendanceEvents, PeriodData periodData)
        {
            var attendanceEvents = studentAttendanceEvents.Where(studentAttendanceEvent => periodData.CalendarDates.Any() &&
                                                                 studentAttendanceEvent.EventDate.IsBetween(periodData.CalendarDates.Min(), periodData.CalendarDates.Max()));

            return(attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsStudentSectionAttendanceEvent &&
                                          (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                           studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                   .ToList());
        }
Ejemplo n.º 18
0
 protected abstract List <StudentAttendanceEvent> GetMetricAttendanceEvents(List <StudentAttendanceEvent> studentAttendanceEvents, PeriodData periodData);
Ejemplo n.º 19
0
        public override IDictionary <string, List <StudentMetric> > GetAllStudentMetricsForSchool(string schoolKey)
        {
            string cacheKey = "schoolKey:" + schoolKey + " MetricId:" + GetMetricId();

            IDictionary <string, List <StudentMetric> > returnMap;

            if (_memoryCache.TryGetValue(cacheKey, out returnMap))
            {
                return(returnMap);
            }

            int periodLength = GetPeriodLength();

            returnMap = new Dictionary <string, List <StudentMetric> >();
            IDictionary <Period, PeriodData> periodDataDictionary = GetPeriodData(schoolKey, periodLength);
            PeriodData firstPeriodData  = periodDataDictionary[Period.First];
            PeriodData secondPeriodData = periodDataDictionary[Period.Second];
            IDictionary <string, List <StudentAttendanceEvent> > studentAttendanceEventDictionary     = getStudentAttendanceEvents(schoolKey);
            IDictionary <string, List <StudentSchoolDim> >       studentSchoolAssociationsDictionary  = StudentDataRepository.GetStudentSchoolAssociationsDictionary(schoolKey);
            IDictionary <string, List <StudentSectionDim> >      studentSectionAssociationsDictionary = getStudentSectionAssociationsDictionary(schoolKey);


            foreach (string studentKey in studentAttendanceEventDictionary.Keys)
            {
                List <StudentAttendanceEvent> studentAttendanceEvents    = studentAttendanceEventDictionary[studentKey];
                List <StudentSchoolDim>       studentSchoolAssociations  = studentSchoolAssociationsDictionary.ContainsKey(studentKey) ? studentSchoolAssociationsDictionary[studentKey] : new List <StudentSchoolDim>();
                List <StudentSectionDim>      studentSectionAssociations = studentSectionAssociationsDictionary.ContainsKey(studentKey) ? studentSectionAssociationsDictionary[studentKey] : new List <StudentSectionDim>();

                //var firstPeriodAttendanceEvents = studentAttendanceEvents.Where(studentAttendanceEvent => firstPeriodData.CalendarDates.Any()
                //                                                                && studentAttendanceEvent.EventDate.IsBetween(firstPeriodData.CalendarDates.Min(), firstPeriodData.CalendarDates.Max()));


                List <StudentAttendanceEvent> firstPeriodMetricAttendanceEvents = GetMetricAttendanceEvents(studentAttendanceEvents, firstPeriodData);
                //var firstPeriodDailyAttendanceRateAttendanceEvents = firstPeriodAttendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance()
                //                                                && (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence)
                //                                                    || studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                //                                            .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                //                                            .ToList();



                List <StudentAttendanceEvent> secondPeriodMetricAttendanceEvents = GetMetricAttendanceEvents(studentAttendanceEvents, secondPeriodData);

                var firstPeriodDenominator = GetDaysStudentWasEnrolled(IsClassPeriodAbsenceRateMetric(), firstPeriodData.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;

                if (firstPeriodDenominator >= periodLength)
                {
                    var  secondPeriodDenominator = GetDaysStudentWasEnrolled(IsClassPeriodAbsenceRateMetric(), secondPeriodData.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;
                    var  firstPeriodNumerator    = GetPeriodNumerator(firstPeriodMetricAttendanceEvents, firstPeriodDenominator);
                    var  firstPeriodRatio        = ((decimal)firstPeriodNumerator / firstPeriodDenominator).RoundTo(3);
                    var  secondPeriodNumerator   = GetPeriodNumerator(secondPeriodMetricAttendanceEvents, secondPeriodDenominator);
                    int? trend;
                    bool flag;
                    GetTrendByAttendance(firstPeriodDenominator, secondPeriodDenominator, firstPeriodNumerator, secondPeriodNumerator, _metricInfo.RateDirection, out trend, out flag);
                    var metricStateType = _metricInfo.GetMetricStateType(firstPeriodRatio, null);
                    var metricState     = MetricUtility.GetMetricState(metricStateType.Value);

                    if (!returnMap.ContainsKey(studentKey))
                    {
                        returnMap[studentKey] = new List <StudentMetric>();
                    }
                    returnMap[studentKey].Add(new StudentMetric
                    {
                        Id             = _metricInfo.Id,
                        Name           = string.Format(_metricInfo.DisplayName, periodLength),
                        Value          = firstPeriodRatio.Display().DisplayValue(DISPLAY_FORMAT_ATTENDANCE_RATE),
                        TrendDirection = trend ?? null,
                        State          = metricState
                    });
                }
            }

            _memoryCache.Set(cacheKey, returnMap, _cacheEntryOptions);
            return(returnMap);
        }
Ejemplo n.º 20
0
        private void ProcessPeriod(Coche vehicle, DateTime from, DateTime to)
        {
            using (var transaction = SmartTransaction.BeginTransaction(IsolationLevel.ReadUncommitted))
            {
                try
                {
                    // Set environment data
                    var inicio = new DateTime(from.Year, from.Month, from.Day, from.Hour, 0, 0);
                    var fin    = new DateTime(to.Year, to.Month, to.Day, to.Hour, 59, 59);

                    // Deletes all previously generated datamart records for the current vehicle and time span.
                    var t = new TimeElapsed();
                    DaoFactory.DatamartDAO.DeleteRecords(vehicle.Id, inicio, fin);
                    var ts = t.getTimeElapsed().TotalSeconds;
                    if (ts > 1)
                    {
                        STrace.Trace(GetType().FullName, string.Format("DeleteRecords en {0} segundos", ts));
                    }

                    var records          = new List <Datamart>();
                    var registrosValidos = false;

                    using (var data = new PeriodData(DaoFactory, vehicle, inicio, fin))
                    {
                        records          = GenerateRecords(data);
                        registrosValidos = ValidateRecords(data, records);
                        if (!registrosValidos)
                        {
                            STrace.Error(GetType().FullName, string.Format("Registros no válidos para el vehículo: {0}", vehicle.Id));
                        }
                    }

                    t.Restart();
                    foreach (var record in records)
                    {
                        DaoFactory.DatamartDAO.Save(record);
                    }

                    ts = t.getTimeElapsed().TotalSeconds;
                    if (ts > 1)
                    {
                        STrace.Trace(GetType().FullName, string.Format("Save en {0} segundos", ts));
                    }

                    transaction.Commit();

                    if (!registrosValidos)
                    {
                        var parametros = new[] { "Se generaron registros de Datamart posiblemente inválidos para el vehículo: " + vehicle.Id, vehicle.Id.ToString("#0"), DateTime.Today.ToString("dd/MM/yyyy HH:mm") };
                        SendMail(parametros);
                        STrace.Error(GetType().FullName, "Se generaron registros de Datamart posiblemente inválidos para el vehículo: " + vehicle.Id);
                    }
                }
                catch (Exception ex)
                {
                    AddError(ex);
                    transaction.Rollback();
                }
                finally
                {
                    ClearData();
                    DoSleep();
                }
            }
        }
Ejemplo n.º 21
0
        private List <Datamart> GenerateRecords(PeriodData data)
        {
            var datamarter = new Datamarter(data);

            if (data.Posiciones.Count == 0)
            {
                var distancia = data.PosicionAnterior != null && data.PosicionSiguiente != null
                    ? data.GetDistancia(data.PosicionAnterior, data.PosicionSiguiente, data.Inicio, data.Fin)
                    : 0;

                return(datamarter.CreateNoReportDatamartRecords(data.Inicio, data.Fin, distancia));
            }

            var listado = new List <Datamart>();

            //if (data.PosicionAnterior == null && data.Posiciones[0].FechaMensaje > data.Inicio)
            //{
            //    listado.AddRange(datamarter.CreateNoReportDatamartRecords(data.Inicio, data.Posiciones[0].FechaMensaje, 0));
            //}

            var posIndex     = 0;
            var inicio       = data.Inicio;
            var lastPosition = data.PosicionAnterior ?? data.Posiciones[0];

            foreach (var fecha in data.FechasDeCorte)
            {
                var minSpeed = int.MaxValue;
                var maxSpeed = 0;
                var sumSpeed = 0;
                var lastHash = string.Empty;
                var posCount = 0;
                var km       = 0.0;

                if (fecha < lastPosition.FechaMensaje)
                {
                    listado.AddRange(datamarter.CreateNoReportDatamartRecords(inicio, fecha, 0));
                    inicio = fecha;
                    continue;
                }

                for (; posIndex < data.Posiciones.Count && data.Posiciones[posIndex].FechaMensaje < fecha; posIndex++)
                {
                    var position    = data.Posiciones[posIndex];
                    var hash        = data.GetHash(position);
                    var timeBetween = position.FechaMensaje.Subtract(lastPosition.FechaMensaje);
                    if (inicio >= position.FechaMensaje || timeBetween == TimeSpan.Zero)
                    {
                        lastPosition = position;
                        lastHash     = hash;
                        continue;
                    }

                    var distancia = inicio > lastPosition.FechaMensaje
                                                     ? data.GetDistancia(lastPosition, position, inicio, null)
                                                     : data.GetDistancia(lastPosition, position, null, null);

                    var nextIsLast = !(posIndex + 1 < data.Posiciones.Count && data.Posiciones[posIndex + 1].FechaMensaje < fecha);
                    var cortar     = hash != lastHash;
                    var noreport   = timeBetween.TotalMinutes > NoReportMinutes;
                    var firstPos   = posCount == 0;

                    if (!firstPos && (cortar || noreport || nextIsLast))
                    {
                        var estadoMotor    = EstadoMotor.FromPosicion(lastPosition);
                        var estadoVehiculo = EstadoVehiculo.FromPosicion(lastPosition);
                        var zona           = lastPosition.Zona;
                        var avgSpeed       = sumSpeed / posCount;
                        var datamart       = datamarter.CreateDatamartRecord(inicio,
                                                                             noreport ? lastPosition.FechaMensaje : position.FechaMensaje,
                                                                             km, estadoMotor, estadoVehiculo, avgSpeed, minSpeed, maxSpeed, zona);
                        listado.Add(datamart);

                        km = distancia;
                        if (noreport)
                        {
                            var datamarts = datamarter.CreateNoReportDatamartRecords(lastPosition.FechaMensaje, position.FechaMensaje, km);
                            listado.AddRange(datamarts);
                            km = 0;
                        }

                        minSpeed = position.Velocidad;
                        maxSpeed = position.Velocidad;
                        sumSpeed = position.Velocidad;
                        inicio   = position.FechaMensaje;
                        posCount = 1;
                    }
                    else
                    {
                        km       += distancia;
                        sumSpeed += position.Velocidad;
                        if (position.Velocidad < minSpeed)
                        {
                            minSpeed = position.Velocidad;
                        }
                        if (position.Velocidad > maxSpeed)
                        {
                            maxSpeed = position.Velocidad;
                        }
                        posCount++;
                    }

                    lastPosition = position;
                    lastHash     = hash;
                }

                if (inicio < fecha)
                {
                    var ultima = posIndex < data.Posiciones.Count - 1
                                                 ? data.Posiciones[posIndex + 1]
                                                 : data.PosicionSiguiente;
                    km += ultima == null ? 0
                                           : (inicio > lastPosition.FechaMensaje
                                                      ? data.GetDistancia(lastPosition, ultima, inicio, fecha)
                                                      : data.GetDistancia(lastPosition, ultima, null, fecha));

                    if (posCount == 0)
                    {
                        var datamart2 = datamarter.CreateNoReportDatamartRecords(inicio, fecha, km);
                        listado.AddRange(datamart2);
                    }
                    else
                    {
                        var estadoMotor2    = EstadoMotor.FromPosicion(lastPosition);
                        var estadoVehiculo2 = EstadoVehiculo.FromPosicion(lastPosition);
                        var zona            = lastPosition.Zona;
                        var avgSpeed2       = posCount > 0 ? sumSpeed / posCount : 0;
                        var datamart2       = datamarter.CreateDatamartRecord(inicio, fecha, km, estadoMotor2,
                                                                              estadoVehiculo2, avgSpeed2, minSpeed, maxSpeed, zona);
                        listado.Add(datamart2);
                    }
                }

                inicio = fecha;
            }

            return(listado);
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            using (var ctx = new ASAEntitiesContext())
            {
                //Sender sen = new Sender()
                //{
                //    Title = "mr",
                //    ForName1 = "Sat",
                //    ForName2 = "Ch",
                //    SurName = "Gat",
                //    Email = "*****@*****.**",
                //    AddressLine1 = "awdas",
                //    AddressLine2 = "asdasdsa",
                //    AddressLine3 = "www",
                //    Country = "UK",
                //    Postcode = "E11",
                //    Mobile = "01111",
                //    SenderPassword = "******",
                //    Telephone = "5131",
                //    Type = SenderType.Individual,
                //    HMRCUserId = "VATDEC180a01",
                //    HMRCPassword = "******"

                //};
                //ctx.Sender.Add(sen);
                //ctx.SaveChanges();
                GovTalkMessage msg = new GovTalkMessage()
                {
                };
                //SuccessResponseIRmarkReceipt ir = new SuccessResponseIRmarkReceipt
                //{

                //};
                //SuccessResponse resp = new SuccessResponse()
                //{
                //    //IRmarkReceipt = ir,
                //    AcceptedTime = DateTime.Now,
                //    AcceptedTimeSpecified = true,
                //    ResponseData_IsEmpty = true,



                //};

                //ctx.SucessResponse.Add(resp);
                ctx.SaveChanges();

                Client clt = new Client()
                {
                    Name  = "London Borough Of Redbride",
                    RegNo = "Reg123456789",
                    VATNo = "VAT123456"
                };

                ctx.Client.Add(clt);
                ctx.SaveChanges();

                Business bu = new Business()
                {
                    BusinessName   = "TEST",
                    BusinessId     = 1,
                    TradingName    = "TEST",
                    RegisteredDate = DateTime.Now,
                    VATRegNo       = "123456",
                    SenderId       = 1
                };
                BusinessAddress bud = new BusinessAddress()
                {
                    Line1    = "test",
                    Line2    = "test2",
                    Line3    = "test3",
                    Line4    = "test5",
                    Postcode = "IG1",
                    Country  = "UK"
                };
                bu.BusinessAddress = bud;

                //ctx.BusinessAddress.Add(bud);
                //ctx.Business.Add(bu);
                // ctx.SaveChanges();



                PeriodData per = new PeriodData()
                {
                    StartPeriod = DateTime.Now.AddMonths(-3),
                    EndPeriod   = DateTime.Now,
                    PeriodrefId = "2017-04",
                    Status      = SubmissionStatus.Draft
                };
                VAT100 vat = new VAT100()
                {
                };
                //per.VAT100 = vat;


                bu.Periods.Add(per);

                Client cl = new Client()
                {
                    //Id = 1,
                    Name  = "consoleC",
                    RegNo = "123",
                    VATNo = "1234567"
                };

                ClientAddress cd = new ClientAddress()
                {
                    Address1        = "First line of add",
                    Address2        = "Second line of add",
                    City            = "Lonodn",
                    ClientAddressId = 1,
                    Country         = "UK",
                    PostCode        = "SS1",
                };

                PeriodData per1 = new PeriodData()
                {
                    StartPeriod = DateTime.Now.AddMonths(-3),
                    EndPeriod   = DateTime.Now,
                    PeriodrefId = "2017-07",
                    Status      = SubmissionStatus.Draft
                };
                bu.Periods.Add(per1);

                //works above


                cl.ClientAddress = cd;
                //ctx.Client.Add(cl);
                //ctx.SaveChanges();
                //ctx.SaveChanges();
                //var cup = ctx.ClientAddress.FirstOrDefault();
                //cup.Address1 = "New Update address";
                //var c = ctx.Client.FirstOrDefault();

                //c.ClientAddress = cup;

                //ctx.Client.Add(c);


                // ctx.Client.Add(cl);
                InvoiceDetail invd = new InvoiceDetail();
                invd.No        = "LBR-1";
                invd.IssueDate = DateTime.Now;
                invd.DueDate   = DateTime.Now.AddDays(7);
                invd.Note      = "test";
                invd.Ref       = "nothing";
                invd.Discount  = "10%";

                InvoiceItem item     = new InvoiceItem();
                var         itemguid = Guid.Parse("00000000-0000-0000-0000-000000000000");
                item.Id          = itemguid;
                item.Description = "apple";
                item.Quantity    = "1";
                item.Price       = "1";
                item.Total       = "1";
                item.SubTotal    = "1";
                item.VAT         = "0";
                item.VATRate     = "0";



                List <InvoiceItem> items = new List <InvoiceItem>();
                items.Add(item);
                var myguid = Guid.Parse("3551A09E-DE21-A325-6DF4-40281A4FEBE0");
                //var inv = ctx.Invoice.Where(i => i.InvoiceId == myguid)
                //            .Include(d => d.InvoiceDetail)
                //            .Include(it => it.InvoiceItems)
                //            .FirstOrDefault();


                //ctx.Entry(inv).CurrentValues.SetValues(inv);
                //foreach (var it in items)
                //{
                //    var existingChild = inv.InvoiceItems.Where(c => c.Id == it.Id).SingleOrDefault();
                //    if(existingChild!=null)
                //    {
                //        ctx.Entry(existingChild).CurrentValues.SetValues(it);

                //    }
                //    else
                //    {
                //        Console.WriteLine("add new item");
                //        inv.InvoiceItems.Add(item);
                //    }
                //}

                //ctx.Entry(inv).State = EntityState.Modified;

                //Invoice myinvoice = new Invoice();
                //myinvoice.ClientId = 3;
                //myinvoice.InvoiceDetail = invd;
                //myinvoice.InvoiceItems = items;
                //ctx.Invoice.Add(myinvoice);
                //ctx.SaveChanges();
                // bu.Periods.Add(per1);

                // ctx.Business.Add(bu);

                //cl.ClientAddress = cd;
                //ctx.Client.Add(cl);
                //ctx.SaveChanges();
            }
        }
Ejemplo n.º 23
0
 public void AddPeriodData(PeriodData data)
 {
     _periodRepository.Add(data);
 }
Ejemplo n.º 24
0
        public GovTalkMessage CreateGovTalkMessage(Sender sender, Business business, PeriodData periodData, VAT100 vatData, bool testInLive)
        {
            string classType   = !testInLive ? "HMRC-VAT-DEC" : "HMRC-VAT-DEC-TIL";
            string gatewayTest = !testInLive ? "0" : "1";

            //Gov Talk message
            GovTalkMessage govTalkMessage = new GovTalkMessage();
            //Gov Talk header
            GovTalkMessageHeader header = new GovTalkMessageHeader();
            //sender details
            GovTalkMessageHeaderSenderDetails senderDetails          = new GovTalkMessageHeaderSenderDetails();
            GovTalkMessageHeaderSenderDetailsIDAuthentication idauth = new GovTalkMessageHeaderSenderDetailsIDAuthentication();

            idauth.SenderID = sender.HMRCUserId;
            GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication aauth = new GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication();

            aauth.Method = GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthenticationMethod.clear;
            aauth.Role   = "principal";
            aauth.Item   = sender.HMRCPassword;
            GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication[] authentications = new GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication[1];
            authentications[0]             = aauth;
            idauth.Authentication          = authentications;
            senderDetails.IDAuthentication = idauth;
            senderDetails.EmailAddress     = sender.Email;
            //message details
            GovTalkMessageHeaderMessageDetails messagedetails = new GovTalkMessageHeaderMessageDetails();

            messagedetails.Class                   = classType;
            messagedetails.Qualifier               = GovTalkMessageHeaderMessageDetailsQualifier.request;
            messagedetails.Function                = GovTalkMessageHeaderMessageDetailsFunction.submit;
            messagedetails.FunctionSpecified       = true;
            messagedetails.CorrelationID           = "";
            messagedetails.Transformation          = GovTalkMessageHeaderMessageDetailsTransformation.XML;
            messagedetails.GatewayTest             = gatewayTest;
            messagedetails.TransformationSpecified = true;
            header.MessageDetails                  = messagedetails;
            header.SenderDetails                   = senderDetails;
            //Gov Talk details
            GovTalkMessageGovTalkDetails govTalkDetails = new GovTalkMessageGovTalkDetails();
            //keys
            GovTalkMessageGovTalkDetailsKey key = new GovTalkMessageGovTalkDetailsKey();

            key.Type  = ConfigurationManager.AppSettings["GovTalkDetailsKeyType"];
            key.Value = business.VATRegNo.ToString();
            GovTalkMessageGovTalkDetailsKey[] keys = new GovTalkMessageGovTalkDetailsKey[1];
            keys[0] = key;
            //Channel routing
            GovTalkMessageGovTalkDetailsChannelRoutingChannel channel = new GovTalkMessageGovTalkDetailsChannelRoutingChannel();

            channel.Version         = ConfigurationManager.AppSettings["ChannelVersion"];
            channel.Product         = ConfigurationManager.AppSettings["ChannelProduct"];
            channel.ItemElementName = ItemChoiceType.URI;
            channel.Item            = ConfigurationManager.AppSettings["ChannelUri"];
            GovTalkMessageGovTalkDetailsChannelRouting channelRouting = new GovTalkMessageGovTalkDetailsChannelRouting();

            channelRouting.Channel = channel;
            GovTalkMessageGovTalkDetailsChannelRouting[] channelRoutings = new GovTalkMessageGovTalkDetailsChannelRouting[1];
            channelRoutings[0]            = channelRouting;
            govTalkDetails.Keys           = keys;
            govTalkDetails.ChannelRouting = channelRoutings;

            //Gov Talk Body
            GovTalkMessageBody body = new GovTalkMessageBody();
            //populate body content with ir68 data
            //IR68 ir68 = new IR68(periodData, vatData);         //commented out to use method instead of object instantiation with period/vat data
            //IRenvelope iRenvelope = ir68.CreateIREnvelopeBody(sender, business);

            IRenvelope iRenvelope = CreateIRenvelopeBody(sender, business, periodData, vatData);
            //serialse ir object data into xml elements and add to Gov Talk body
            //XElement xe = XElement.Parse(SerializeIrEnvelope(iRenvelope));
            XElement   xe       = XElement.Parse(IREnvelopeToXDocument(iRenvelope).ToString());
            XmlElement xelement = ToXmlElement(xe);

            XmlElement[] xmlElements = new XmlElement[1];
            xmlElements[0] = xelement;
            body.Any       = xmlElements;
            govTalkMessage.EnvelopeVersion = ConfigurationManager.AppSettings["GovTalkMessageEnvelopeVersion"];
            govTalkMessage.Header          = header;
            govTalkMessage.GovTalkDetails  = govTalkDetails;
            govTalkMessage.Body            = body;
            return(govTalkMessage);
        }
Ejemplo n.º 25
0
 public void AddNextQuaterPeriod(PeriodData period)
 {
     _periodRepository.Add(period);
     // SaveCommit();
 }
Ejemplo n.º 26
0
        public HttpResponseMessage Post(SubmissionViewModel model)
        {
            if (ModelState.IsValid) //always returning true
            {
                string testInLive = model.RunMode;
                bool   mode       = testInLive.Equals("1") ? true : false;

                var sender = new Sender
                {
                    Title          = model.BussinessViewModel.Sender.Title,
                    ForName1       = model.BussinessViewModel.Sender.ForName1,
                    ForName2       = model.BussinessViewModel.Sender.ForName2,
                    SurName        = model.BussinessViewModel.Sender.SurName,
                    Email          = model.BussinessViewModel.Sender.Email,
                    AddressLine1   = model.BussinessViewModel.Sender.AddressLine1,
                    AddressLine2   = model.BussinessViewModel.Sender.AddressLine2,
                    AddressLine3   = model.BussinessViewModel.Sender.AddressLine3,
                    Postcode       = model.BussinessViewModel.Sender.Postcode,
                    SenderPassword = model.BussinessViewModel.Sender.SenderPassword,
                    Type           = model.BussinessViewModel.Sender.Type,
                    Mobile         = model.BussinessViewModel.Sender.Mobile,
                    Telephone      = model.BussinessViewModel.Sender.Telephone,
                    HMRCPassword   = model.BussinessViewModel.Sender.HMRCPassword,
                    HMRCUserId     = model.BussinessViewModel.Sender.HMRCUserId,
                    Country        = model.BussinessViewModel.Sender.Country,
                    SenderId       = model.BussinessViewModel.Sender.SenderId
                };

                var address = new BusinessAddress
                {
                    Line1             = model.BussinessViewModel.BusinessAddress.Line1,
                    Line2             = model.BussinessViewModel.BusinessAddress.Line2,
                    Line3             = model.BussinessViewModel.BusinessAddress.Line3,
                    Line4             = model.BussinessViewModel.BusinessAddress.Line4,
                    Country           = model.BussinessViewModel.BusinessAddress.Country,
                    Postcode          = model.BussinessViewModel.BusinessAddress.Postcode,
                    BusinessAddressId = model.BussinessViewModel.BusinessAddress.BusinessAddressId
                };
                var business = new Business
                {
                    BusinessName   = model.BussinessViewModel.BusinessName,
                    RegisteredDate = model.BussinessViewModel.RegisteredDate,
                    VATRegNo       = model.BussinessViewModel.VATRegNo,
                    TradingName    = model.BussinessViewModel.TradingName,
                    BusinessId     = model.BussinessViewModel.BusinessId,
                    RegNo          = model.BussinessViewModel.RegNo,
                    VATRate        = model.BussinessViewModel.VATRate,
                    SenderId       = model.BussinessViewModel.SenderId
                };

                var perioddata = new PeriodData
                {
                    PeriodrefId = model.PeriodViewModel.PeriodRefId,
                    StartPeriod = model.PeriodViewModel.StartPeriod,
                    EndPeriod   = model.PeriodViewModel.EndPeriod,
                    PeriodId    = model.PeriodViewModel.PeriodId,
                    BusinessId  = model.BussinessViewModel.BusinessId
                };
                var vatData = new VAT100()
                {
                    Box1        = model.VAT100ViewModel.VATDueOnOutputs.ToString("N"),
                    Box2        = model.VAT100ViewModel.VATDueOnECAcquisitions.ToString("N"),
                    Box3        = model.VAT100ViewModel.TotalVAT.ToString("N"),
                    Box4        = model.VAT100ViewModel.VATReclaimedOnInputs.ToString("N"),
                    Box5        = model.VAT100ViewModel.NetVAT.ToString("N"),
                    Box6        = model.VAT100ViewModel.NetSalesAndOutputs.ToString(),
                    Box7        = model.VAT100ViewModel.NetPurchasesAndInputs.ToString(),
                    Box8        = model.VAT100ViewModel.NetECSupplies.ToString(),
                    Box9        = model.VAT100ViewModel.NetECAcquisitions.ToString(),
                    LastUpdated = model.VAT100ViewModel.LastUpdated
                };

                SubmissionManager submissionmanager = new SubmissionManager(_gatewayService);

                //create govtalk message
                var submissionResponse = submissionmanager.SendSubmissionRequest(sender, business, perioddata, vatData, mode);
                //read correlationId and poll uri from response
                //TODO: every time it fails delete the request and resubmit on sucess capt response and send back to client

                //  List<Object> responses = new List<Object>();
                Dictionary <string, List <XElement> > dicresponses = new Dictionary <string, List <XElement> >();
                if (submissionResponse.Errors.Count == 0)
                {
                    //submission passes send poll request
                    string correlationId = submissionResponse.CorrelationId.ToString();
                    string polluri       = submissionResponse.FollowOnUri.ToString();
                    if (!(String.IsNullOrEmpty(correlationId) && String.IsNullOrEmpty(polluri)))
                    {
                        var pollResponse = submissionmanager.SendPollRequest(correlationId, polluri, mode);
                        if (pollResponse.Errors.Count == 0)
                        {
                            //success get success response
                            perioddata.Status = SubmissionStatus.Accepted; //update status as accepted by HMRC and VAT info in the vat table
                            perioddata.VAT100 = vatData;                   // attaching new vat data to update

                            //perioddata.HmrcResponses.Add(pollResponse);

                            var nextQuaterStartDate = submissionmanager.AddMonthsCustom(perioddata.StartPeriod, 3);
                            var nextQuaterEndDate   = submissionmanager.AddMonthsCustom(perioddata.EndPeriod, 3);

                            var nextPeriod = new PeriodData()
                            {
                                StartPeriod = nextQuaterStartDate,
                                EndPeriod   = nextQuaterEndDate,
                                BusinessId  = business.BusinessId,
                                PeriodrefId = nextQuaterEndDate.ToString("yyyy-MM"),
                                Status      = SubmissionStatus.Draft
                            };
                            business.BusinessAddress     = address;
                            business.Sender              = sender;
                            business.NextQuaterStartDate = nextQuaterStartDate; //update bussiness model props with next quater start and end dates
                            business.NextQuaterEndDate   = nextQuaterEndDate;

                            perioddata.HmrcResponses.Add(pollResponse);
                            business.Periods.Add(perioddata);
                            business.Periods.Add(nextPeriod);
                            _gatewayService.UpdateEntities(business);
                            //  _gatewayService.Save(pollResponse);
                            var strContent      = HelperMethods.ExtractBodyContent(pollResponse.ResponseData.ToString());
                            var successResponse = HelperMethods.Deserialize <SuccessResponse>(strContent);
                            //save the response in the DB
                            //_gatewayService.AddNextQuaterPeriod(nextPeriod); //Add next VAT quater in the database

                            //business.Periods.Add(nextPeriod);
                            //_gatewayService.UpdateNextQuaterInBVM(business);
                            // _gatewayService.SaveResponse(successResponse); // commit to DB after adding all above objects to repositories
                            //if (successResponse != null)
                            //{
                            //TODO: serialise sucessresponse, sucessresponseirmark, message type
                            var str  = HelperMethods.Serialize(successResponse);
                            var xdoc = XDocument.Parse(str, LoadOptions.PreserveWhitespace);
                            ////select only body element from xdoc

                            var hmrcresponsemsgnode = (from d in xdoc.Descendants()
                                                       where d.Name.LocalName == "Message"
                                                       select d).ToList();
                            var vatperiodnode = (from m in xdoc.Descendants()
                                                 where m.Name.LocalName == "VATPeriod"
                                                 select m).ToList();
                            var paymentBodyNode = (from p in xdoc.Descendants()
                                                   where p.Name.LocalName == "Body"
                                                   select p).ToList();
                            var errorsNode = (from p in xdoc.Descendants()
                                              where p.Name.LocalName == "Error"
                                              select p).ToList();

                            dicresponses.Add("hmrcResponse", hmrcresponsemsgnode);
                            dicresponses.Add("vatPeriod", vatperiodnode);
                            dicresponses.Add("paymentDetails", paymentBodyNode);
                            dicresponses.Add("Errors", errorsNode);
                            //responses.Add(successResponse);
                            return(Request.CreateResponse <Dictionary <string, List <XElement> > >(HttpStatusCode.OK, dicresponses));
                        }
                        else
                        {
                            //failure bus valid failed handle here
                            //delete the request and resubmit as new request as mentioned in the gov site
                            submissionmanager.SendDeleteRequest(correlationId, mode, polluri);
                            var temp       = XDocument.Parse(pollResponse.ResponseData);
                            var pollerrors = (from p in temp.Descendants()
                                              where p.Name.LocalName == "Error"
                                              select p).ToList();

                            dicresponses.Add("Errors", pollerrors);
                            // responses.Add(pollResponse);
                        }
                    }
                    else
                    {
                        //id or uri is null
                        // responses.Add(submissionResponse);
                        var temp             = XDocument.Parse(submissionResponse.ResponseData);
                        var submissionerrors = (from p in temp.Descendants()
                                                where p.Name.LocalName == "Error"
                                                select p).ToList();

                        dicresponses.Add("Errors", submissionerrors);

                        return(Request.CreateResponse <Dictionary <string, List <XElement> > >(HttpStatusCode.BadRequest, dicresponses));
                    }
                }
                else
                {
                    //return submission failure response
                    // responses.Add(submissionResponse);
                    var temp             = XDocument.Parse(submissionResponse.ResponseData);
                    var submissionerrors = (from p in temp.Descendants()
                                            where p.Name.LocalName == "Error"
                                            select p).ToList();

                    dicresponses.Add("Errors", submissionerrors);
                }
                return(Request.CreateResponse <Dictionary <string, List <XElement> > >(HttpStatusCode.OK, dicresponses));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));

            //}
            //throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "data is null" });
        }
Ejemplo n.º 27
0
        public List <StudentMetric> GetStudentMetrics(string studentKey, string schoolKey)
        {
            List <StudentMetric> studentMetrics = new List <StudentMetric>();
            string format = "{0:P1}";
            var    currentSchoolYearDim = _context.CurrentSchoolYearDims.FirstOrDefault();

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

            string studentKeyStr = studentKey + "";
            var    studentSchoolAttendanceEventFactDbRecords = _context.StudentSchoolAttendanceEventFacts
                                                               .Where(student => student.StudentKey == studentKeyStr && student.SchoolYear == currentSchoolYearDim.SchoolYear)
                                                               .ToList();

            var studentSchoolAssociations = _context.StudentSchoolDims
                                            .Where(s => s.StudentKey.Equals(studentKey.ToString()) && s.SchoolKey.Equals(schoolKey.ToString()))
                                            .ToList();

            StudentSchoolAttendanceEventFact previousAttendanceEvent = null;
            var studentAttendanceEvents = new List <StudentAttendanceEvent>();

            foreach (var attendanceEvent in studentSchoolAttendanceEventFactDbRecords)
            {
                if (previousAttendanceEvent != null && previousAttendanceEvent.EventDate == attendanceEvent.EventDate)
                {
                    //Found multiple daily attendance events on the same day: {@attendanceEvent} AND {@duplicateAttendanceEvent}", previousAttendanceEvent, attendanceEvent);
                    continue;
                }

                studentAttendanceEvents.Add(new StudentAttendanceEvent
                {
                    DailyAttendanceCalculcationSource = DailyAttendanceCalculcationSource.BothAttendanceEventSources,
                    EventDate                         = attendanceEvent.EventDate,
                    AttendanceEventReason             = attendanceEvent.AttendanceEventReason,
                    AttendanceEventCategoryDescriptor = attendanceEvent.AttendanceEventCategoryDescriptor
                });

                previousAttendanceEvent = attendanceEvent;
            }

            var studentSectionAssociations = _context.StudentSectionDims
                                             .Where(s => s.StudentKey.Equals(studentKey.ToString()) && s.SchoolKey.Equals(schoolKey.ToString()))
                                             .ToList();


            var studentSectionAttendanceEventFactDbRecords = _context.StudentSectionAttendanceEventFacts
                                                             .Where(student => student.StudentKey == studentKeyStr && student.SchoolYear == currentSchoolYearDim.SchoolYear)
                                                             .ToList();

            if (studentAttendanceEvents.Any() && studentSectionAttendanceEventFactDbRecords.Any())
            {
                studentSectionAttendanceEventFactDbRecords = studentSectionAttendanceEventFactDbRecords.Where(p => !studentAttendanceEvents.Any(x => x.EventDate == p.EventDate))
                                                             .OrderBy(p => p.EventDate)
                                                             .ToList();
            }

            StudentSectionAttendanceEventFact previousSectionAttendanceEvent = null;

            foreach (var studentAttendanceEvent in studentSectionAttendanceEventFactDbRecords)
            {
                var studentSectionAssociation = studentSectionAssociations
                                                .Where(x => studentAttendanceEvent.EventDate.IsInRange(x))
                                                .Where(x => string.Equals(x.SectionIdentifier, studentAttendanceEvent.SectionIdentifier, StringComparison.OrdinalIgnoreCase))
                                                .Where(x => string.Equals(x.SessionName, studentAttendanceEvent.SessionName, StringComparison.OrdinalIgnoreCase))
                                                .Where(x => string.Equals(x.LocalCourseCode, studentAttendanceEvent.LocalCourseCode, StringComparison.OrdinalIgnoreCase))
                                                .FirstOrDefault();

                if (studentSectionAssociation == null)
                {
                    //"Found an attendance event for a student not currently enrolled in the section: {@attendanceEvent}", studentAttendanceEvent);
                    continue;
                }

                if (previousSectionAttendanceEvent != null &&
                    previousSectionAttendanceEvent.EventDate == studentAttendanceEvent.EventDate &&
                    string.Equals(previousSectionAttendanceEvent.SectionIdentifier, studentAttendanceEvent.SectionIdentifier, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(previousSectionAttendanceEvent.SessionName, studentAttendanceEvent.SessionName, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(previousSectionAttendanceEvent.LocalCourseCode, studentAttendanceEvent.LocalCourseCode, StringComparison.OrdinalIgnoreCase))
                {
                    //Found an attendance event on the same day for the same section: {@attendanceEvent}", studentAttendanceEvent);
                    continue;
                }

                studentAttendanceEvents.Add(new StudentAttendanceEvent
                {
                    DailyAttendanceCalculcationSource = DailyAttendanceCalculcationSource.BothAttendanceEventSources,
                    EventDate                         = studentAttendanceEvent.EventDate,
                    AttendanceEventReason             = studentAttendanceEvent.AttendanceEventReason,
                    StudentSectionDim                 = studentSectionAssociation,
                    AttendanceEventCategoryDescriptor = studentAttendanceEvent.AttendanceEventCategoryDescriptor
                });

                previousSectionAttendanceEvent = studentAttendanceEvent;
            }

            var schoolMinMaxDateDim = _context.SchoolMinMaxDateDims.Where(s => s.SchoolKey.Equals(schoolKey.ToString())).FirstOrDefault();

            if (schoolMinMaxDateDim == null)
            {
                //"No entry found in analytics.SchoolMinMaxDateDim
                return(null);
            }

            var ytdGradingPeriod = new GradingPeriodDim
            {
                BeginDate = schoolMinMaxDateDim.MinDate.Value,
                EndDate   = schoolMinMaxDateDim.MaxDate.Value,
                GradingPeriodDescription = string.Empty,
                IsYearToDate             = true
            };

            int temp;
            int schoolKeyInt       = int.TryParse(schoolKey, out temp) ? temp : 0;
            var schoolCalendarDays = _context.SchoolCalendarDims.Where(s => s.SchoolKey == schoolKeyInt).ToList();

            DateTime?          _lastAttendanceDateForStudent = null;
            HashSet <DateTime> _excusedAbsences   = new HashSet <DateTime>();
            HashSet <DateTime> _unexcusedAbsences = new HashSet <DateTime>();

            foreach (var studentAttendanceEvent in studentAttendanceEvents)
            {
                if (_lastAttendanceDateForStudent == studentAttendanceEvent.EventDate)
                {
                    continue;
                }

                if (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) && studentAttendanceEvent.IsForDailyAttendance())
                {
                    _excusedAbsences.Add(studentAttendanceEvent.EventDate);
                    _lastAttendanceDateForStudent = studentAttendanceEvent.EventDate;
                }
                else if (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence) && studentAttendanceEvent.IsForDailyAttendance())
                {
                    _unexcusedAbsences.Add(studentAttendanceEvent.EventDate);
                    _lastAttendanceDateForStudent = studentAttendanceEvent.EventDate;
                }
            }

            HashSet <DateTime> _schoolCalendarDays = new HashSet <DateTime>();

            schoolCalendarDays.ForEach(s => _schoolCalendarDays.Add(s.Date));

            var daysStudentWasEnrolled = _schoolCalendarDays
                                         .DaysInRange(studentSchoolAssociations)
                                         .DaysInRange(studentSectionAssociations)
                                         .ToArray();

            if (!daysStudentWasEnrolled.Any())
            {
                // Do no calculations for students that were not enrolled for any instructional days
                return(null);
            }

            _unexcusedAbsences.RemoveWhere(x => _excusedAbsences.Contains(x));
            var excusedAbsences   = _excusedAbsences.CountDaysInRange(ytdGradingPeriod);
            var unExcusedAbsences = _unexcusedAbsences.CountDaysInRange(ytdGradingPeriod);

            var ytdTotalDaysAbsences = excusedAbsences + unExcusedAbsences;
            var ytdUnexcusedAbsences = unExcusedAbsences;

            Metric metric          = Metric.StudentTotalDaysAbsent;
            var    metricStateType = metric.GetMetricStateType(ytdTotalDaysAbsences, null);
            var    metricState     = MetricUtility.GetMetricState(metricStateType.Value);

            studentMetrics.Add(new StudentMetric
            {
                Name           = "Days Absent",
                Value          = ytdTotalDaysAbsences.ToString(),
                State          = metricState,
                TrendDirection = null
            });

            metric          = Metric.StudentTotalUnexcusedDaysAbsent;
            metricStateType = metric.GetMetricStateType(ytdUnexcusedAbsences, null);
            metricState     = MetricUtility.GetMetricState(metricStateType.Value);

            studentMetrics.Add(new StudentMetric
            {
                Name           = "Unexcused Days",
                Value          = ytdUnexcusedAbsences.ToString(),
                State          = metricState,
                TrendDirection = null
            });


            IReadOnlyCollection <Period> Periods = Enum.GetValues(typeof(Period))
                                                   .Cast <Period>()
                                                   .ToArray();

            IDictionary <Period, PeriodData> _periodData = new SortedList <Period, PeriodData>();

            foreach (var period in Periods)
            {
                _periodData[period] = new PeriodData();
            }

            List <int> ReportingPeriodLengths = ((ReportingPeriodLength[])Enum.GetValues(typeof(ReportingPeriodLength))).Select(c => (int)c).ToList();

            ReportingPeriodLengths.ForEach(_periodLength =>
            {
                schoolCalendarDays.ForEach(schoolCalendarDay =>
                {
                    var periodIndex = schoolCalendarDay.GetPeriodIndex(_periodLength);
                    if (periodIndex > 2)
                    {
                        return;
                    }

                    var period     = (Period)periodIndex;
                    var periodData = _periodData[period];
                    periodData.CalendarDates.Add(schoolCalendarDay.Date);
                });
                foreach (var periodData in _periodData.Values)
                {
                    periodData.DailyAttendanceRateEvents = 0;
                    periodData.ClassPeriodAbsenceRateAttendanceEvents = 0;
                    periodData.TardyAttendanceEvents = 0;
                }

                var firstPeriod = _periodData[Period.First];

                var attendanceEvents = studentAttendanceEvents.Where(studentAttendanceEvent => firstPeriod.CalendarDates.Any() &&
                                                                     studentAttendanceEvent.EventDate.IsBetween(firstPeriod.CalendarDates.Min(), firstPeriod.CalendarDates.Max()));

                var dailyAttendanceRateAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance() &&
                                                                                 (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                                  studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                                                          .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                                          .ToList();
                firstPeriod.DailyAttendanceRateEvents = dailyAttendanceRateAttendanceEvents.Count;

                var classPeriodAbsenceRateAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsStudentSectionAttendanceEvent &&
                                                                                    (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                                     studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                                                             .ToList();
                firstPeriod.ClassPeriodAbsenceRateAttendanceEvents = classPeriodAbsenceRateAttendanceEvents.Count;


                var tardyAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance() &&
                                                                   studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.Tardy))
                                            .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                            .ToList();
                firstPeriod.TardyAttendanceEvents = tardyAttendanceEvents.Count;


                if (firstPeriod.CalendarDates.Count < _periodLength)
                {
                    // Business Rule: School with less instructional days than reporting period days.
                    return;
                }
                var secondPeriod = _periodData[Period.Second];
                attendanceEvents = studentAttendanceEvents.Where(studentAttendanceEvent => secondPeriod.CalendarDates.Any() &&
                                                                 studentAttendanceEvent.EventDate.IsBetween(secondPeriod.CalendarDates.Min(), secondPeriod.CalendarDates.Max()));

                dailyAttendanceRateAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance() &&
                                                                             (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                              studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                                                      .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                                      .ToList();
                secondPeriod.DailyAttendanceRateEvents = dailyAttendanceRateAttendanceEvents.Count;

                classPeriodAbsenceRateAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsStudentSectionAttendanceEvent &&
                                                                                (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                                 studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                                                         .ToList();
                secondPeriod.ClassPeriodAbsenceRateAttendanceEvents = classPeriodAbsenceRateAttendanceEvents.Count;


                tardyAttendanceEvents = attendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance() &&
                                                               studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.Tardy))
                                        .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                        .ToList();
                secondPeriod.TardyAttendanceEvents = tardyAttendanceEvents.Count;


                var firstPeriodDenominator = GetDaysStudentWasEnrolled(false, firstPeriod.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;
                if (firstPeriodDenominator >= _periodLength)
                {
                    var secondPeriodDenominator = GetDaysStudentWasEnrolled(false, secondPeriod.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;

                    var firstPeriodNumerator  = firstPeriodDenominator - firstPeriod.DailyAttendanceRateEvents;
                    var firstPeriodRatio      = ((decimal)firstPeriodNumerator / firstPeriodDenominator).RoundTo(3);
                    var secondPeriodNumerator = secondPeriodDenominator - secondPeriod.DailyAttendanceRateEvents;

                    int?trend;
                    bool flag;
                    GetTrendByAttendance(firstPeriodDenominator, secondPeriodDenominator, firstPeriodNumerator, secondPeriodNumerator, RateDirection.OneToZero, out trend, out flag);

                    Metric metric       = _periodLength == (int)ReportingPeriodLength.LastXDays ? Metric.StudentDailyAttendanceRateLastXDays : Metric.StudentDailyAttendanceRateLastYDays;
                    var metricStateType = metric.GetMetricStateType(firstPeriodRatio, null);
                    var metricState     = MetricUtility.GetMetricState(metricStateType.Value);

                    studentMetrics.Add(new StudentMetric
                    {
                        Name           = string.Format("Daily Attendance Rate - Last {0} Days", _periodLength),
                        Value          = firstPeriodRatio.Display().DisplayValue(format),
                        TrendDirection = trend ?? null,
                        State          = metricState
                    });

                    firstPeriodNumerator  = firstPeriod.TardyAttendanceEvents;
                    firstPeriodRatio      = ((decimal)firstPeriodNumerator / firstPeriodDenominator).RoundTo(3);
                    secondPeriodNumerator = secondPeriod.TardyAttendanceEvents;

                    GetTrendByAttendance(firstPeriodDenominator, secondPeriodDenominator, firstPeriodNumerator, secondPeriodNumerator, RateDirection.ZeroToOne, out trend, out flag);

                    metric          = _periodLength == (int)ReportingPeriodLength.LastXDays ? Metric.StudentTardyRateLastXDays : Metric.StudentTardyRateLastYDays;
                    metricStateType = metric.GetMetricStateType(firstPeriodRatio, null);
                    metricState     = MetricUtility.GetMetricState(metricStateType.Value);

                    studentMetrics.Add(new StudentMetric
                    {
                        Name           = string.Format("Tardy Rate - Last {0} Days", _periodLength),
                        Value          = firstPeriodRatio.Display().DisplayValue(format),
                        TrendDirection = trend ?? null,
                        State          = metricState
                    });
                }

                firstPeriodDenominator = GetDaysStudentWasEnrolled(true, firstPeriod.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;
                if (firstPeriodDenominator >= _periodLength)
                {
                    var secondPeriodDenominator = GetDaysStudentWasEnrolled(true, secondPeriod.CalendarDates, studentSchoolAssociations, studentSectionAssociations).Count;

                    var firstPeriodNumerator  = firstPeriod.ClassPeriodAbsenceRateAttendanceEvents;
                    var firstPeriodRatio      = ((decimal)firstPeriodNumerator / firstPeriodDenominator).RoundTo(3);
                    var secondPeriodNumerator = secondPeriod.ClassPeriodAbsenceRateAttendanceEvents;

                    int?trend;
                    bool flag;
                    GetTrendByAttendance(firstPeriodDenominator, secondPeriodDenominator, firstPeriodNumerator, secondPeriodNumerator, RateDirection.ZeroToOne, out trend, out flag);

                    Metric metric       = _periodLength == (int)ReportingPeriodLength.LastXDays ? Metric.StudentClassPeriodAbsenceRateLastXDays : Metric.StudentClassPeriodAbsenceRateLastYDays;
                    var metricStateType = metric.GetMetricStateType(firstPeriodRatio, null);
                    var metricState     = MetricUtility.GetMetricState(metricStateType.Value);

                    studentMetrics.Add(new StudentMetric
                    {
                        Name           = string.Format("Class Period Absence Rate - Last {0} Days", _periodLength),
                        Value          = firstPeriodRatio.Display().DisplayValue(format),
                        TrendDirection = trend ?? null,
                        State          = metricState
                    });
                }
            });


            var ytdNumerator                   = 0;
            var _daysStudentWasEnrolled        = 0;
            var ytdDailyAttendanceRateAbsences = studentAttendanceEvents.Where(studentAttendanceEvent => (studentAttendanceEvent.IsForDailyAttendance() &&
                                                                                                          (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                                                           studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence))))
                                                 .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                                 .ToList()
                                                 .Count();

            _daysStudentWasEnrolled = GetDaysStudentWasEnrolled(false, _schoolCalendarDays, studentSchoolAssociations, studentSectionAssociations).Count;
            ytdNumerator            = _daysStudentWasEnrolled - ytdDailyAttendanceRateAbsences;
            var ytdDailyAttendanceRate = ((decimal)ytdNumerator / _daysStudentWasEnrolled).RoundTo(3);

            metric          = Metric.StudentDailyAttendanceRateYearToDate;
            metricStateType = metric.GetMetricStateType(ytdDailyAttendanceRate, null);
            metricState     = MetricUtility.GetMetricState(metricStateType.Value);

            studentMetrics.Add(new StudentMetric
            {
                Name           = "Daily Attendance Rate - Year to Date",
                Value          = ytdDailyAttendanceRate.Display().DisplayValue(format),
                State          = metricState,
                TrendDirection = null,
            });


            var ytdClassPeriodAttendanceRateAbsences = studentAttendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsStudentSectionAttendanceEvent &&
                                                                                     (studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.ExcusedAbsence) ||
                                                                                      studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.UnexcusedAbsence)))
                                                       .ToList()
                                                       .Count();

            _daysStudentWasEnrolled = GetDaysStudentWasEnrolled(true, _schoolCalendarDays, studentSchoolAssociations, studentSectionAssociations).Count;
            ytdNumerator            = ytdClassPeriodAttendanceRateAbsences;
            var ytdClassPeriodAttendanceRate = ((decimal)ytdNumerator / _daysStudentWasEnrolled).RoundTo(3);

            metric          = Metric.StudentClassPeriodAbsenceRateYearToDate;
            metricStateType = metric.GetMetricStateType(ytdClassPeriodAttendanceRate, null);
            metricState     = MetricUtility.GetMetricState(metricStateType.Value);

            studentMetrics.Add(new StudentMetric
            {
                Name           = "Class Period Absence Rate - Year to Date",
                Value          = ytdClassPeriodAttendanceRate.Display().DisplayValue(format),
                State          = metricState,
                TrendDirection = null,
            });


            var ytdTardyRateAbsences = studentAttendanceEvents.Where(studentAttendanceEvent => studentAttendanceEvent.IsForDailyAttendance() &&
                                                                     studentAttendanceEvent.AttendanceEventCategoryDescriptor.Equals(AttendanceEventCategoryDescriptor.Tardy))
                                       .DistinctBy(studentAttendanceEvent => studentAttendanceEvent.EventDate)
                                       .ToList()
                                       .Count();

            _daysStudentWasEnrolled = GetDaysStudentWasEnrolled(false, _schoolCalendarDays, studentSchoolAssociations, studentSectionAssociations).Count;
            ytdNumerator            = ytdTardyRateAbsences;
            var ytdTardyRate = ((decimal)ytdNumerator / _daysStudentWasEnrolled).RoundTo(3);

            metric          = Metric.StudentTardyRateYearToDate;
            metricStateType = metric.GetMetricStateType(ytdTardyRate, null);
            metricState     = MetricUtility.GetMetricState(metricStateType.Value);

            studentMetrics.Add(new StudentMetric
            {
                Name           = "Tardy Rate - Year to Date",
                Value          = ytdTardyRate.Display().DisplayValue(format),
                State          = metricState,
                TrendDirection = null,
            });

            return(studentMetrics);
        }
Ejemplo n.º 28
0
        public async Task <List <string> > GetGroupUserAccessPanel(int idZone)
        {
            List <string> listGroupToReturn = new List <string>();
            int           userId            = _authenticationInfo.ActualUser.UserId;
            var           sqlDataBase       = _stObjMap.StObjs.Obtain <SqlDefaultDatabase>();

            if (userId == 0)
            {
                listGroupToReturn.Add("Anon");
                return(listGroupToReturn);
            }

            listGroupToReturn.Add("User");

            using (var ctx = new SqlStandardCallContext())
            {
                TimedPeriodQueries timedPeriod   = new TimedPeriodQueries(ctx, sqlDataBase);
                TimedUserQueries   timedUser     = new TimedUserQueries(ctx, sqlDataBase);
                GroupQueries       groupsQueries = new GroupQueries(ctx, sqlDataBase);
                UserQueries        userQueries   = new UserQueries(ctx, sqlDataBase);
                DateTime           dateNow       = DateTime.UtcNow;
                List <PeriodData>  periods       = await timedPeriod.GetNumberWishPeriodBySchool(idZone, 2);

                PeriodData period = null;


                for (int i = 0; i < periods.Count; i++)
                {
                    if (periods[i].BegDate.DayOfYear <= dateNow.DayOfYear && periods[i].EndDate.DayOfYear >= dateNow.DayOfYear)
                    {
                        period = periods[i];
                        break;
                    }
                }

                if (period == null)
                {
                    period = periods[0];
                }
                TimedUserData timedUserData = await timedUser.GetTimedUser(userId, period.ChildId);

                if (timedUserData == null)
                {
                    int adminIdZoneSchool = await groupsQueries.GetSpecificIdGroupByZoneIdAndGroupName(idZone, "Administration");

                    if (await userQueries.VerifyGroupUser(userId, adminIdZoneSchool) != 0)
                    {
                        listGroupToReturn.Add("Administration");
                    }

                    return(listGroupToReturn);
                }

                listGroupToReturn = await timedUser.getWhichCat(timedUserData.TimedUserId, listGroupToReturn);

                if (!listGroupToReturn.Contains("StaffMember"))
                {
                    return(listGroupToReturn);
                }

                List <string> listGroupsOfTimedUser = new List <string>();

                listGroupsOfTimedUser = await groupsQueries.GetAllGroupOfTimedUserByPeriod(period.ChildId, timedUserData.TimedUserId);

                for (int i = 0; i < listGroupsOfTimedUser.Count; i++)
                {
                    if (listGroupsOfTimedUser[i] == "Administration")
                    {
                        listGroupToReturn.Add("Administration");
                    }
                    else if (listGroupsOfTimedUser[i] == "Teacher")
                    {
                        listGroupToReturn.Add("Teacher");
                    }
                }

                if (!listGroupToReturn.Contains("Administration"))
                {
                    int adminIdZoneSchool = await groupsQueries.GetSpecificIdGroupByZoneIdAndGroupName(idZone, "Administration");

                    if (await userQueries.VerifyGroupUser(userId, adminIdZoneSchool) != 0)
                    {
                        listGroupToReturn.Add("Administration");
                    }
                }


                return(listGroupToReturn);
            }
        }
Ejemplo n.º 29
0
        public async Task <PeriodData> GetPeriodById(int periodId)
        {
            PeriodData result = await _controller.QuerySingleOrDefaultAsync <PeriodData>("SELECT OrderedChild = ChildOrderByKey.ToString(), ChildId, ZoneId, BegDate, EndDate FROM CK.vZoneDirectChildren  JOIN IPR.tTimePeriod  on ChildId = TimePeriodId WHERE TimePeriodId = @TimePeriodId ORDER BY ChildOrderByKey DESC; ", new { TimePeriodId = periodId });

            return(result);
        }
Ejemplo n.º 30
0
        public async Task <PeriodData> GetCurrentPeriod(int zoneId)
        {
            PeriodData result = await _controller.QuerySingleOrDefaultAsync <PeriodData>("SELECT * FROM IPR.tTimePeriod WHERE TimePeriodId = @ZoneId;", new { ZoneId = zoneId });

            return(result);
        }