public JsonResult SaveMeterReading(string authTicket, int meterInstId, DateTime? date, double? reading, int actingUserId, int actualUserId, double? rate) { // First, verify that the logged-in user has the necessary permissions to // save a meter reading (including permission to use the specified userIds.) var user = GetUserFromAuthTicket(authTicket); if (user == null) { // No user found based on auth ticket. return Json(new JsonResponse(false, "Invalid authentication ticket - no user found.")); } if (user.Id != actualUserId) { // Bizarre - the auth ticket is not for the specified user id. return Json(new JsonResponse(false, "Unauthorized action: The specified authentication ticket does not match the provided actual user ID.")); } if (actingUserId != actualUserId && !user.IsAdmin) { // Acting as is only allowed for admins. return Json(new JsonResponse(false, "Unauthorized action: You do not have permission to act for that user.")); } if (!date.HasValue || date.Value > DateTime.Now) { return Json(new JsonResponse(false, "Reading date must be equal to or earlier than the current date.")); } string error; var success = new MeterDalc().SaveMeterReading(new MeterReading() { MeterInstallationId = meterInstId, DateTime = date.Value, Reading = reading, ActingUserId = actingUserId, ActualUserId = actualUserId, Rate = rate }, out error); return Json(new JsonResponse(success, error)); }
private JsonResult GetAssociatedWells(int meterInstId) { try { var wells = new MeterDalc().GetAssociatedWells(meterInstId); return Json(new JsonResponse(true, new { Wells = wells.ToArray(), MeterInstId = meterInstId }), JsonRequestBehavior.AllowGet); } catch (Exception ex) { return Json(new JsonResponse(false, ex.Message)); } }
/// <summary> /// Returns a hash of UnitOfMeasure records; Key:id, Value:name /// </summary> /// <returns></returns> public JsonResult GetUnitOfMeasurementDefinitions() { // This is brain damaged, but .NET refuses to serialize a dictionary to JSON // when the key is anything other than a string or an object. They say the rationale // is that dictionaries in Javascript are always keyed with strings, which I // believe to be false, but in any case this is a workaround to convert the // integer key to a string. /drainbramage var dict = new MeterDalc().GetUnitOfMeasurementDefinitions().ToDictionary( x => x.Key.ToString(), x => x.Value ); return Json(dict, JsonRequestBehavior.AllowGet); }
/// <summary> /// Returns the past [count] meter readings for the specified meter installation ID (meterInstId). /// JSON result format is a <see cref="HPEntities.Entities.JsonResponse"/> object, with data /// format of: /// { /// MeterInstallationId: 0, /// Readings:[ /// { /// Date:"1/1/2011", /// Reading: (null or int), /// Volume: (null or int), /// UnitOfMeasureId: 0, /// ActingId: 0, /// ActualId: 0 /// }, /// { ... } /// ] /// } /// </summary> /// <param name="meterInstId"></param> /// <returns></returns> public JsonResult GetRecentMeterReadings(int meterInstId, int count) { bool success = true; List<string> errors = new List<string>(); object data = null; try { data = new MeterDalc().GetRecentReadings(meterInstId, null, count); } catch (Exception ex) { success = false; errors.Add(ex.Message); } if (data != null) { return Json(new JsonResponse(success, data, errors.ToArray()), JsonRequestBehavior.AllowGet); } else { return Json(new JsonResponse(success, errors.ToArray()), JsonRequestBehavior.AllowGet); } }
/// <summary> /// Save "adds" and "deletes" to support streamline meter reading /// </summary> /// <param name="authTicket"></param> /// <param name="actingUserId"></param> /// <param name="actualUserId"></param> /// <param name="addsAndDeletes"></param> /// <returns></returns> public JsonResult ApplyReadingEdits(string authTicket, int actingUserId, int actualUserId, string addsAndDeletes) { int num; User userFromAuthTicket = this.GetUserFromAuthTicket(authTicket); if (userFromAuthTicket == null) { return base.Json(new JsonResponse(false, new string[] { "Invalid authentication ticket - no user found." })); } if (userFromAuthTicket.Id != actualUserId) { return base.Json(new JsonResponse(false, new string[] { "Unauthorized action: The specified authentication ticket does not match the provided actual user ID." })); } if (!((actingUserId == actualUserId) || userFromAuthTicket.IsAdmin)) { return base.Json(new JsonResponse(false, new string[] { "Unauthorized action: You do not have permission to act for that user." })); } JsonApplyMeterReadingsObject obj2 = JsonConvert.DeserializeObject<JsonApplyMeterReadingsObject>(addsAndDeletes); string errorMessage = ""; MeterReading[] adds = new MeterReading[obj2.adds.Length]; string[] deletes = new string[obj2.deletes.Length]; if (obj2.adds.Length > 0) { for (num = 0; num < adds.Length; num++) { JsonFlexMeterReadingObject obj3 = obj2.adds[num]; adds[num] = new MeterReading { MeterInstallationId = int.Parse(obj3.MeterInstallationID), DateTime = obj3.ReadingDateJson, Reading = obj3.ReadingValue, ActingUserId = actingUserId, ActualUserId = actualUserId, Rate = obj3.GallonsPerMinute, ReadingType = new int?(obj3.ReadingType), IsSubmitted = new int?(obj3.IsSubmitted), ReportingYear = new int?(obj3.ReportingYear) }; } } if (obj2.deletes.Length > 0) { for (num = 0; num < deletes.Length; num++) { deletes[num] = obj2.deletes[num].MeterInstallationReadingID; } } bool success = new MeterDalc().ApplyReadingEdits(adds, deletes, out errorMessage); return base.Json(new JsonResponse(success, new string[] { errorMessage })); }
/// <summary> /// /// </summary> /// <param name="ca"></param> /// <param name="wellIdsInsideCA">The well IDs for the CA as returned by a spatial query.</param> /// <returns></returns> private Dictionary<int, JsonErrorCondition> GetMeterInstallationErrors(ContiguousAcres ca, IEnumerable<int> wellIdsInsideCA) { var ret = new Dictionary<int, JsonErrorCondition>(); var mdalc = new MeterDalc(); var rptgDalc = new ReportingDalc(); if (ca.Wells == null) { ca.Wells = new WellDalc().GetWells(wellIdsInsideCA.ToArray()).ToArray(); } // Check for irregularities in meter installations. // 1. If a meter has a well associated with it that's outside the CA, note it. foreach (var well in ca.Wells) { try { foreach (var miid in well.MeterInstallationIds) { var wids = mdalc.GetAssociatedWells(miid).Select(x => x.WellId).Except(wellIdsInsideCA); if (wids.Count() > 0) { // There's a well associated that's not in the CA. // Check to see if there's a user response. ret[miid] = new JsonErrorCondition() { wellIds = wids.ToArray(), errorCondition = "Associted well IDs " + string.Join(", ", wids.Select(x => "#" + x.ToString())) + " are outside the contiguous area.", userResponse = rptgDalc.GetMeterInstallationErrorResponse(miid, ActualUser.ActingAsUserId ?? ActualUser.Id) }; } } } catch (MeterNotFoundException ex) { // Suggests that the meter installation was deleted, // but is still associated with the well for some reason. // TODO: Not sure how to handle this. } } return ret; }
/// <summary> /// Creates a dynamic object representing the page state. /// This method will attempt to load and deserialize JSON /// from the database if it exists for this user (updating /// relevant properties appropriately), and if no existing /// JSON exists will construct a new object with which the /// user can report water usage. /// </summary> /// <returns></returns> protected dynamic GetPageStateJson(User user) { // Only update the _current_ reporting year or unsubmitted var pageStateJson = new ReportingDalc().GetReportingSummary(user.IsAdmin ? (user.ActingAsUserId ?? user.Id) : user.Id); ReportingSummary pageState = null; try { pageState = JsonConvert.DeserializeObject<ReportingSummary>(pageStateJson); } catch (Exception ex) { // There was a problem deserializing. // TODO: Notify user, possibly admins! throw; } if (pageState == null) { pageState = new ReportingSummary(); } /// Returns the volume (Item1) and a bool indicating whether rollover occurred (Item2) /// Args: meterInstallationId, meterreadings Func<int, IEnumerable<JsonMeterReading>, Tuple<int, bool>> calculateVolume = (meterInstallationId, readings) => { double runningTotal = 0d; if (readings.Count() == 0) { return new Tuple<int, bool>((int)runningTotal, false); } bool rolledOver = false; var prevReading = readings.First(); foreach (var currentReading in readings.Skip(1)) { double delta = 0; if (currentReading.reading.GetValueOrDefault() < prevReading.reading.GetValueOrDefault()) { // Rollover occurred rolledOver = true; // Retrieve the rollover value for this meter installation var rollover = new MeterDalc().GetMeterInstallations(meterInstallationId).First().RolloverValue; delta = (rollover - prevReading.reading.Value) + currentReading.reading.Value; } else { delta = currentReading.reading.GetValueOrDefault() - prevReading.reading.GetValueOrDefault(); } runningTotal += delta * (prevReading.rate.HasValue ? prevReading.rate.Value : 1); prevReading = currentReading; } return new Tuple<int, bool>((int)runningTotal, rolledOver); }; // Only show Approved CAs unless the user is an admin var contigAcres = new GisDalc().GetContiguousAcres(user, true).Where(ca => user.IsAdmin || ca.IsApproved); // Key: CA ID, Value: well ids var wellIds = new Dictionary<int, HashSet<int>>(); Dictionary<int, ContiguousAcres> validAcres = new Dictionary<int, ContiguousAcres>(); // There may be load errors that got persisted from a previous page load, but we // only want to show current ones so clear the list. pageState.loadErrors.Clear(); if (contigAcres.Count() > 0) { // Only create the service if contigAcres has stuff, because SOAP takes time var service = new GisServiceSoapClient(); foreach (var ca in contigAcres) { string result = ""; // This call is prone to failure whenever the GIS service is down. try { result = service.GetWellIDsByCA(ca.OBJECTID); } catch (Exception ex) { pageState.loadErrors.Add("Unable to load well associations for any CAs: the GIS service appears to be down!"); } try { int[] ids = JsonConvert.DeserializeObject<int[]>(result.Trim('{', '}')); wellIds[ca.caID] = new HashSet<int>(ids); validAcres[ca.caID] = ca; } catch (JsonException ex) { pageState.loadErrors.Add("Error loading CA ID " + ca.caID + ": " + ex.Message + " Service response: " + result); } } } var mdalc = new MeterDalc(); var rptgDalc = new ReportingDalc(); var wellDalc = new WellDalc(); var wells = wellDalc.GetWells(wellIds.SelectMany(x => x.Value).ToArray()); var meterInstallations = mdalc.GetMeterInstallations(wells.SelectMany(x => x.MeterInstallationIds).ToArray()).GroupBy(x => x.Id).Select(x => x.First()).ToDictionary(x => x.Id, x => x); // In addition to the wells retrieved by the spatial query, we also need to // retrieve wells attached to the meters on that initial set. wells = wells.Concat(wellDalc.GetWellsByMeterInstallationIds(meterInstallations.Select(x => x.Key).ToArray())) .Distinct((a,b) => a.WellId == b.WellId); Func<int, Dictionary<int, JsonBankedWaterRecord>> getBankedWaterTable = caId => { return rptgDalc.GetHistoricalBankedWater(caId).ToDictionary(x => x.year, x => x); }; // func to populate a JsonCA in the current reporting year Func<ContiguousAcres, JsonContiguousAcres> createNewJsonCA = ca => { ca.Wells = wellDalc.GetWells(wellIds[ca.caID].ToArray()).ToArray(); var reportedVolumes = mdalc.GetReportedVolumeGallons(ca.Wells.SelectMany(w => w.MeterInstallationIds), ca.caID, CurrentReportingYear); JsonContiguousAcres ret = new JsonContiguousAcres(ca, CurrentReportingYear); ReportedVolume rvol; ret.meterReadings = new Dictionary<int, JsonMeterReadingContainer>(); MeterInstallation meter = null; foreach (var miid in ret.wells.SelectMany(x => x.meterInstallationIds).Distinct()) { meterInstallations.TryGetValue(miid, out meter); var container = new JsonMeterReadingContainer() { meterInstallationId = miid, calculatedVolumeGallons = reportedVolumes.TryGetValue(miid, out rvol) ? rvol.CalculatedVolumeGallons : 0, acceptCalculation = rvol == null || !rvol.UserRevisedVolumeUnitId.HasValue, userRevisedVolume = rvol != null && rvol.UserRevisedVolume.HasValue ? rvol.UserRevisedVolume.Value : 0, userRevisedVolumeUnitId = rvol != null && rvol.UserRevisedVolumeUnitId.HasValue ? rvol.UserRevisedVolumeUnitId.Value : new int?(), totalVolumeAcreInches = 0, isNozzlePackage = meter != null ? meter.MeterType.Description().ToLower() == "nozzle package" : false, isElectric = meter != null ? meter.MeterType.Description().ToLower() == "electric" : false, isNaturalGas = meter != null ? meter.MeterType.Description().ToLower() == "natural gas" : false, isThirdParty = meter != null ? meter.MeterType.Description().ToLower() == "bizarro-meter" : false, depthToRedbed = -99999, //squeezeValue = 0, unitId = meter != null ? meter.UnitId : null, county = meter != null ? meter.County : "", rolloverValue = meter != null ? meter.RolloverValue : 0, countyId = meter != null ? meter.CountyId : -1, meterType = meter != null ? meter.MeterType.Description() : "", nonStandardUnits = meter != null && meter.MeterType != HPEntities.Entities.Enums.MeterType.standard ? new MeterDalc().GetUnits(meter.MeterType).Description() : "", meterMultiplier = meter.Multiplier != 0 ? meter.Multiplier : 1.0d // Make sure multiplier is not 0. NULL value is already converted to 1.0d in Dalc }; // Add depth to redbed if the meter is of 1) natural gas or 2) electric if (container.isNaturalGas || container.isElectric) { /* //ned skip this lookup until we really need to implement it var service1 = new GisServiceSoapClient(); string depthInString = service1.GetDepthToRedbedByMeter(miid); string depthInString = "Implement this later" double depth = -99999; if (!Double.TryParse(depthInString, out depth)) depth = -99999; */ double depth = 100; //take this out when the above works container.depthToRedbed = depth; } container.readings = (from mr in mdalc.GetReadings(miid, CurrentReportingYear).Reverse() // By default, they're ordered by reading date desc select new JsonMeterReading() { reading = mr.Reading, rate = mr.Rate, isValidBeginReading = ReportingDalc.IsMeterReadingValidBeginReading(mr, CurrentReportingYear), isValidEndReading = ReportingDalc.IsMeterReadingValidEndReading(mr, CurrentReportingYear), isAnnualTotalReading = ReportingDalc.IsMeterReadingAnnualTotal(mr, CurrentReportingYear), meterInstalltionReadingID = mr.MeterInstallationReadingId }).ToArray(); ret.meterReadings[miid] = container; } ret.meterInstallationErrors = GetMeterInstallationErrors(ca, wellIds[ca.caID]); ret.bankedWaterHistory = getBankedWaterTable(ca.caID); JsonBankedWaterRecord bankedWaterLastYear; ret.annualUsageSummary = new JsonAnnualUsageSummary() { contiguousArea = ca.AreaInAcres, annualVolume = 0, // this will only be populated after submittal allowableApplicationRate = rptgDalc.GetAllowableProductionRate(CurrentReportingYear), bankedWaterFromPreviousYear = ret.bankedWaterHistory.TryGetValue(CurrentReportingYear - 1, out bankedWaterLastYear) ? bankedWaterLastYear.bankedInches : 0 }; ret.isSubmitted = rptgDalc.IsSubmitted(ca.caID, CurrentReportingYear); ret.ownerClientId = ca.OwnerClientId; ret.isCurrentUserOwner = (this.ActualUser.ActingAsUserId ?? this.ActualUser.Id) == ca.OwnerClientId; return ret; }; JsonReportingYear year; if (pageState.years.TryGetValue(CurrentReportingYear, out year)) { // Check the existing year object and update as necessary // For now, wholly reload any CAs that have not yet been submitted. List<JsonContiguousAcres> removals = year.contiguousAcres.Where(ca => !ca.isSubmitted).ToList(); HashSet<int> submittedCaIds = new HashSet<int>(year.contiguousAcres.Where(ca => ca.isSubmitted).Select(x => x.number)); // Ensure that all the CAs are still applicable to this account - the CA IDs need // to match what's presently associated with the user account, else they're removed. foreach (var ca in removals) { year.contiguousAcres.Remove(ca); } // Add any CAs that were missing from the original state foreach (var kv in validAcres) { if (!submittedCaIds.Contains(kv.Value.caID)) { year.contiguousAcres.Add(createNewJsonCA(kv.Value)); } for (int i = 0; i < year.contiguousAcres.Count; i++) { if (year.contiguousAcres[i].number == kv.Value.caID) { year.contiguousAcres[i].meterInstallationErrors = GetMeterInstallationErrors(kv.Value, wellIds[kv.Value.caID]); year.contiguousAcres[i].wells = kv.Value.Wells.Select(w => new JsonWell(w)).ToArray(); } } //year.contiguousAcres.Where(jca => jca.number == kv.Value.caID).First().meterInstallationErrors = GetMeterInstallationErrors(kv.Value, wellIds[kv.Value.caID]); } foreach (var ca in year.contiguousAcres) { // This is used on the frontend to decide whether to show the user an editable form. // Only CA owners get the editable form. ca.isCurrentUserOwner = (this.ActualUser.ActingAsUserId ?? this.ActualUser.Id) == ca.ownerClientId; } } else { // No existing year record exists; create a new one year = new JsonReportingYear(); year.contiguousAcres = validAcres.Values.Select(ca => { return createNewJsonCA(ca); }).ToList(); pageState.years[CurrentReportingYear] = year; } // Populate meterInstallations by retrieving metadata for all used meter installations HashSet<int> meterInstallationIds = new HashSet<int>((from y in pageState.years from ca in y.Value.contiguousAcres from w in ca.wells select w.meterInstallationIds).SelectMany(x => x)); // Converting this directly to a dictionary will fail in the event that a meter // is associated with wells in multiple counties. However, that case doesn't really // make any sense and would break all sorts of other things (such as meter unit conversion factors // that are specific to counties), so we're going to assume that there's always // a single county. pageState.meterInstallations = mdalc.GetMeterInstallations(meterInstallationIds.ToArray()) .GroupBy(x => x.Id) .Select(mi => new JsonMeterInstallation(mi.First())) .ToDictionary( x => x.id, x => x ); pageState.currentReportingYear = CurrentReportingYear; pageState.isReportingAllowed = IsReportingAllowed; pageState.adminOverride = ((!IsReportingAllowed) && this.ActualUser.IsAdmin); pageState.cafoLookups = rptgDalc.GetCafoLookups(); // Go through and check all the submittal states of the CAs foreach (var ca in pageState.years[CurrentReportingYear].contiguousAcres) { ca.isSubmitted = rptgDalc.IsSubmitted(ca.number, CurrentReportingYear); if (ca.isSubmitted) { // If it was a submitted CA, the banked water history table // still needs to be loaded because it wasn't set above. ca.bankedWaterHistory = getBankedWaterTable(ca.number); } } return pageState; }