Ejemplo n.º 1
0
        public ActionResult RecordByAttachment(int id)
        {
            using (Entity context = new Entity())
            {
                t_observation_attachment attachment = context.t_observation_attachment.Find(id);
                if (attachment == null)
                {
                    throw new ArgumentException("Invalid ObservationAttachmentID: " + id.ToString());
                }

                t_observation observation = context.t_observation.Find(attachment.observation_id);
                if (observation == null)
                {
                    throw new ArgumentException("Invalid observationId: " + attachment.observation_id.ToString());
                }

                t_site site = context.t_site.Find(observation.site_id);
                if (site == null)
                {
                    throw new ArgumentException("Invalid siteId: " + observation.site_id.ToString());
                }

                t_indicator indicator = context.t_indicator.Find(observation.indicator_id);
                if (indicator == null)
                {
                    throw new ArgumentException("Invalid indicatorId: " + observation.indicator_id.ToString());
                }

                return(View("Record", (new Observation(indicator, site, observation.begin_date))));

                //RedirectToAction("Record", (new Observation(observation.site_id, site, observation.begin_date)));
                //return RedirectToAction("Record", new { indicatorId = observation.indicator_id, siteId = observation.site_id, beginDate = observation.begin_date });
                //return Record(observation.indicator_id, observation.site_id, observation.begin_date);
            }
        }
Ejemplo n.º 2
0
        private void SetProperties(int indicatorId, int siteId, t_observation observation, bool loadChildren)
        {
            IndicatorId = indicatorId;
            SiteId      = siteId;
            t_observation_entry firstEntry = observation?.entries?.FirstOrDefault();

            CreatedBy = firstEntry?.createdby?.full_name;
            CreatedOn = firstEntry?.created_date;
            UpdatedBy = firstEntry?.updateby?.full_name;
            UpdatedOn = firstEntry?.updated_date;

            // Observation entries.
            Entries = StoredProcedures.GetObservations(IndicatorId, SiteId, BeginDate);

            if (loadChildren)
            {
                // Aim and Indicator
                Indicator = new Indicator(IndicatorId, false);
                Aim       = new Aim(Indicator.AimId, false);

                // Other Aim Indicators
                // NOTE: Don't use UserAssignedObjects here. Only show active aims/indicators.
                var aims =
                    Context.t_indicator.Find(indicatorId).aim.activity.aims
                    .Where(e => e.active == true).OrderBy(e => e.sort);
                AimsAndIndicators = new List <Tuple <string, int, string> >();
                foreach (var aim in aims)
                {
                    AimsAndIndicators.Add(new Tuple <string, int, string>("Aim", aim.aim_id, aim.get_name_translated(CurrentLanguageId)));
                    foreach (var ind in aim.indicators.Where(e => e.active == true).OrderBy(e => e.sort))
                    {
                        AimsAndIndicators.Add(new Tuple <string, int, string>("Indicator", ind.indicator_id, ind.get_name_translated(CurrentLanguageId)));
                    }
                }

                // Populate date period selector's initial set of date periods.
                DatePeriods =
                    ObservationDatePeriod.GetDatePeriods(IndicatorId, siteId, BeginDate, null)
                    .ToDictionary(k => k.BeginDate.ToString("yyyy-MM-dd"), v => v);

                // One-time population of min/max tolerance dictionary.

                MinMaxTolerance = GetMinMaxTolerance();

                // Child collections.
                Changes     = observation?.changes?.OrderBy(e => e.start_date).Select(e => new ObservationChange(e)).ToList();
                Attachments = observation?.attachments?.Select(e => new ObservationAttachment(e)).Where(a => (a.Active == true) ||
                                                                                                        (a.CreatedByUserId == CurrentUserId) ||
                                                                                                        (CurrentUser.IsInRole(BusinessLayer.Identity.Role.SystemAdministrator))).ToList();
                Comments = observation?.comments?.OrderBy(e => e.created_date).Select(e => new ObservationComment(e)).ToList();
                History  = observation?.change_history?.OrderBy(e => e.change_history_id).Select(e => new ObservationHistory(e)).ToList();

                using (Entity context = new Entity())
                    Sexes = context.t_sex.OrderBy(e => e.sex_id).ToDictionary(e => e.sex_code, e => e.sex_description);
            }
        }
Ejemplo n.º 3
0
        public Observation(t_observation observation)
        {
            ObservationId      = observation.observation_id;
            BeginDate          = observation.begin_date;
            EndDate            = observation.end_date;
            IsAgeDisaggregated = observation.is_age_disaggregated;
            IsSexDisaggregated = observation.is_sex_disaggregated;

            SetProperties(observation.indicator_id, observation.site_id, observation, false);
        }
Ejemplo n.º 4
0
        public Observation(t_indicator indicator, t_site site, DateTime?beginDate)
        {
            t_observation observation =
                indicator.observations.Where(e => e.begin_date == beginDate && e.site_id == site.site_id).FirstOrDefault();

            if (observation == null)
            {
                if (beginDate.HasValue)
                {
                    BeginDate = beginDate.Value;
                    ObjectParameter endDate = new ObjectParameter("end_date", typeof(DateTime));
                    Context.p_get_period_end_date(beginDate, indicator.data_collection_frequency_fieldid, endDate);
                    EndDate = (DateTime)endDate.Value;
                }
                else
                {
                    DateTime lastDay = beginDate ?? indicator.aim.activity.end_date ?? DateTime.Now;
                    p_get_latest_date_period_Result result =
                        Context.p_get_latest_date_period(lastDay, indicator.data_collection_frequency_fieldid).FirstOrDefault();
                    BeginDate = result.begin_date.Value;
                    EndDate   = result.end_date.Value;
                }

                IsAgeDisaggregated = indicator.disaggregate_by_age;
                IsSexDisaggregated = indicator.disaggregate_by_sex;
            }
            else
            {
                ObservationId      = observation.observation_id;
                BeginDate          = observation.begin_date;
                EndDate            = observation.end_date;
                IsAgeDisaggregated = observation.is_age_disaggregated;
                IsSexDisaggregated = observation.is_sex_disaggregated;
            }

            SetProperties(indicator.indicator_id, site.site_id, observation, true);
        }
Ejemplo n.º 5
0
        private int?UpsertObservation(dynamic model)
        {
            int      indicatorId = (int)model.IndicatorId;
            int      siteId      = (int)model.SiteId;
            DateTime beginDate   = Convert.ToDateTime(model.BeginDate).Date;

            // Check if the observation already exists. There are a few scenarios:
            // 1) New observation which does not exist.
            // 2) "New" observation which has been created since user went into disconnected mode.
            // 3) Existing observation being updated.
            // 4) "Existing" observation which no longer exists for some reason. (Shouldn't happen, but who knows?)
            t_observation entity = Context.t_observation.Where(x => x.indicator_id == indicatorId && x.site_id == siteId && x.begin_date == beginDate).FirstOrDefault();

            if (entity == null)
            {
                entity = new t_observation()
                {
                    indicator_id         = indicatorId,
                    site_id              = siteId,
                    begin_date           = beginDate,
                    end_date             = Convert.ToDateTime(model.EndDate).Date,
                    createdby_userid     = CurrentUserId,
                    created_date         = Convert.ToDateTime(model.CreatedOn),
                    is_age_disaggregated = model.IsAgeDisaggregated,
                    is_sex_disaggregated = model.IsSexDisaggregated
                };
                Context.t_observation.Add(entity);
            }
            else
            {
                entity.updatedby_userid = CurrentUserId;
                entity.updated_date     = Convert.ToDateTime(model.CreatedOn);
            }
            Context.SaveChanges();

            // Load the indicator. Needed for parsing entry records.
            Context.Entry(entity).Reference(e => e.indicator).Load();
            string indicatorType = entity.indicator.indicator_type_fieldid;

            // Wipe out pre-existing entry values. We can't just delete them because of the audit trail.
            var entries = new Dictionary <string, t_observation_entry>();

            foreach (var entry in entity.entries)
            {
                entry.numerator   = null;
                entry.denominator = null;
                entry.count       = null;
                entry.rate        = null;
                entry.yes_no      = null;
                entries.Add(String.Format("{0}|{1}", entry.indicator_age_range_id, entry.indicator_gender), entry);
            }

            // Parse model entries. These may or may not already existing in the db (depending on disaggregation options).
            foreach (var modelEntry in model.EntriesCollection)
            {
                string key = String.Format("{0}|{1}", modelEntry.Value.age_range_id, modelEntry.Value.sex_code);
                t_observation_entry entry = null;
                if (entries.ContainsKey(key))
                {
                    entry = entries[key];
                }
                else
                {
                    entry = new t_observation_entry()
                    {
                        observation_id         = entity.observation_id,
                        indicator_age_range_id = modelEntry.Value.age_range_id,
                        indicator_gender       = modelEntry.Value.sex_code,
                        createdby_userid       = CurrentUserId,
                        created_date           = Convert.ToDateTime(model.CreatedOn)
                    };
                    entries.Add(key, entry);   // dictionary
                    entity.entries.Add(entry); // database
                }
                switch ((string)modelEntry.Value.type)
                {
                case "numerator":
                    entry.numerator = modelEntry.Value.value;
                    break;

                case "denominator":
                    entry.denominator = modelEntry.Value.value;
                    break;

                default:
                    switch (indicatorType)
                    {
                    case "indcnt":
                        entry.count = modelEntry.Value.value;
                        break;

                    case "indrat":
                        entry.rate = modelEntry.Value.value;
                        break;

                    case "indyes":
                        entry.yes_no = model.value;
                        break;
                    }
                    break;
                }
            }
            Context.SaveChanges();

            // Different logic than the other upserts because of collision scenarios.
            // If the ID has changed for some reason, return the new ID so that child
            // objects (changes, attachments, comments) can be mapped to it.
            if (model.ObservationId.ToString() == entity.observation_id.ToString())
            {
                return(null);
            }
            else
            {
                return(entity.observation_id);
            }
        }
Ejemplo n.º 6
0
        private Dictionary <string, int> GetMinMaxTolerance()
        {
            var    dictMinMax = new Dictionary <string, int>();
            Entity context    = new Entity();

            int?variance = null;

            t_observation previous_observation = context.t_observation.Where(e => (e.indicator_id == IndicatorId) && (e.site_id == SiteId) && (e.begin_date < BeginDate)).OrderByDescending(d => d.begin_date).FirstOrDefault();

            if (previous_observation == null)
            {
                return(dictMinMax);
            }

            ICollection <t_observation_entry> previous_entries = context.t_observation_entry.Where(e => e.observation_id == previous_observation.observation_id).ToList();

            try  //attempt to use indicator change variance
            {
                if (!String.IsNullOrEmpty(Indicator.ChangeVariable))
                {
                    variance = Convert.ToInt16(Indicator.ChangeVariable);
                }
            }
            catch (Exception)
            {
                variance = null;
            }



            decimal?variance_percentage = (variance ?? Convert.ToDecimal(Settings.ObservationDefaultTolerancePercentage)) * .01m;
            decimal?variance_ratio      = (variance ?? Convert.ToDecimal(Settings.ObservationDefaultToleranceRatio)) * .01m;
            decimal?variance_count      = (variance ?? Convert.ToDecimal(Settings.ObservationDefaultToleranceCount)) * .01m;
            decimal?variance_average    = (variance ?? Convert.ToDecimal(Settings.ObservationDefaultToleranceAverage)) * .01m;


            foreach (t_observation_entry entry in previous_entries)
            {
                string item;
                int?   range_id;
                item     = entry.indicator_gender ?? " ";
                range_id = entry.indicator_age_range_id ?? 0;
                int?minAmount = 0;
                int?maxAmount = 0;

                int?    current_data_percent = 0;
                int?    current_data_ratio   = 0;
                decimal current_data_average = 0;

                if (entry.denominator != 0 && entry.denominator != null)
                {
                    current_data_percent = Convert.ToInt16((Convert.ToDecimal(entry.numerator) / Convert.ToDecimal(entry.denominator) * 100));
                    current_data_ratio   = Convert.ToInt16((Convert.ToDecimal(entry.numerator) / Convert.ToDecimal(entry.denominator) * Indicator.RatioPer));
                    current_data_average = Convert.ToDecimal((entry.numerator) / Convert.ToDecimal(entry.denominator) * 100m);
                }


                switch (Indicator.Type)
                {
                case IndicatorType.Count:
                    if (entry.count < 10)
                    {
                        minAmount = 0;
                        maxAmount = 99999;
                    }
                    else if (entry.count < 20)
                    {
                        variance  = Convert.ToInt16(1.5m * variance_count * entry.count);
                        minAmount = entry.count - variance;
                        maxAmount = entry.count + variance;
                    }
                    else
                    {
                        variance  = Convert.ToInt16(variance_count * entry.count);
                        minAmount = entry.count - variance;
                        maxAmount = entry.count + variance;
                    }
                    break;

                case IndicatorType.Percentage:
                    if (entry.denominator < 10)
                    {
                        minAmount = 0;
                        maxAmount = 99999;
                    }
                    else if (entry.denominator < 20)
                    {
                        variance  = Convert.ToInt16(1.5m * variance_percentage * 100m);
                        minAmount = current_data_percent - variance;
                        maxAmount = current_data_percent + variance;
                    }
                    else
                    {
                        variance  = Convert.ToInt16(variance_percentage * 100m);
                        minAmount = current_data_percent - variance;
                        maxAmount = current_data_percent + variance;
                    }
                    break;

                case IndicatorType.Ratio:
                    if (entry.denominator < 10)
                    {
                        minAmount = 0;
                        maxAmount = 99999;
                    }
                    else if (entry.denominator < 20)
                    {
                        variance  = Convert.ToInt16(1.5m * variance_ratio * current_data_ratio);
                        minAmount = current_data_ratio - variance;
                        maxAmount = current_data_ratio + variance;
                    }
                    else
                    {
                        variance  = Convert.ToInt16(variance_ratio * current_data_ratio);
                        minAmount = current_data_ratio - variance;
                        maxAmount = current_data_ratio + variance;
                    }
                    break;

                case IndicatorType.Average:
                    if (entry.denominator < 10)
                    {
                        minAmount = 0;
                        maxAmount = 99999;
                    }
                    else if (entry.denominator < 20)
                    {
                        variance  = Convert.ToInt16(1.5m * variance_average * current_data_average);
                        minAmount = current_data_percent - variance;
                        maxAmount = current_data_percent + variance;
                    }
                    else
                    {
                        variance  = Convert.ToInt16(variance_average * current_data_average);
                        minAmount = current_data_percent - variance;
                        maxAmount = current_data_percent + variance;
                    }
                    break;
                }

                dictMinMax.Add("MIN" + item + range_id.ToString(), minAmount ?? 0);
                dictMinMax.Add("MAX" + item + range_id.ToString(), maxAmount ?? 99999);
            }

            return(dictMinMax);
        }
Ejemplo n.º 7
0
        public JsonResult Record([System.Web.Http.FromBody] ObservationEntryCollection model)
        {
            using (Entity context = new Entity())
            {
                try
                {
                    bool isNewObservation = false;

                    t_observation observation =
                        context.t_observation.Where(
                            e => e.indicator_id == model.IndicatorId && e.site_id == model.SiteId &&
                            e.begin_date == model.BeginDate).FirstOrDefault();
                    if (observation == null)
                    {
                        isNewObservation = true;
                        observation      = new t_observation()
                        {
                            indicator_id     = model.IndicatorId,
                            site_id          = model.SiteId,
                            begin_date       = model.BeginDate,
                            end_date         = model.EndDate,
                            createdby_userid = CurrentUser.Id,
                            created_date     = DateTime.Now
                        };
                        context.t_observation.Add(observation);
                    }
                    else
                    {
                        observation.updatedby_userid = CurrentUser.Id;
                        observation.updated_date     = DateTime.Now;
                    }
                    if ((observation.is_age_disaggregated && !model.IsAgeDisaggregated) ||
                        (observation.is_sex_disaggregated && !model.IsSexDisaggregated))
                    {
                        // Switching from disaggregated to aggregated. Remove pre-existing entries.
                        context.t_observation_entry.RemoveRange(observation.entries);
                    }
                    observation.is_age_disaggregated = model.IsAgeDisaggregated;
                    observation.is_sex_disaggregated = model.IsSexDisaggregated;
                    context.SaveChanges();

                    foreach (ObservationEntry entry in model.Entries)
                    {
                        var oe =
                            context.t_observation_entry.Where(e =>
                                                              e.observation_id == observation.observation_id &&
                                                              e.indicator_age_range_id == (entry.AgeRangeId.HasValue ? entry.AgeRangeId : null) &&
                                                              e.indicator_gender == (entry.SexCode != null ? entry.SexCode : null)).FirstOrDefault();
                        if (oe == null)
                        {
                            oe = new t_observation_entry()
                            {
                                observation_id         = observation.observation_id,
                                indicator_age_range_id = entry.AgeRangeId,
                                indicator_gender       = entry.SexCode,
                            };
                            context.t_observation_entry.Add(oe);
                        }
                        oe.numerator   = entry.Numerator;
                        oe.denominator = entry.Denominator;
                        oe.count       = entry.Count;
                        oe.rate        = entry.Ratio;
                        oe.yes_no      = entry.YesNo;
                        if (isNewObservation || oe.createdby_userid == 0)
                        {
                            oe.createdby_userid = CurrentUser.Id;
                            oe.created_date     = DateTime.Now;
                            observation.entries.Add(oe);
                        }
                        if (!isNewObservation)
                        {
                            oe.updatedby_userid = CurrentUser.Id;
                            oe.updated_date     = DateTime.Now;
                        }
                    }
                    context.SaveChanges();

                    t_observation_entry firstEntry =
                        context.t_observation_entry.Include(e => e.createdby).Include(e => e.updateby)
                        .Where(e => e.observation_id == observation.observation_id).First();
                    return(Json(new
                    {
                        success = true,
                        ObservationId = observation.observation_id,
                        CreatedBy = firstEntry.createdby.full_name,
                        CreatedOn = firstEntry.created_date.ToString("d"),
                        UpdatedBy = firstEntry.updateby?.full_name,
                        UpdatedOn = firstEntry.updated_date?.ToString("d")
                    }));
                }
                catch (Exception ex)
                {
                    return(Json(new
                    {
                        success = false,
                        responseText = "An error occurred: " + ex.ToString()
                    }));
                }
            }
        }