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); } }
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); } }
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() })); } } }