Example #1
0
        private void UpdateLocation(Guid?locationGuid, PersonCacher personCacher, LocationCacher locationCacher,
                                    ref bool saveNeeded)
        {
            if (locationGuid == null)
            {
                return;
            }

            var location = locationCacher.AllForThisElection.FirstOrDefault(l => l.LocationGuid == locationGuid);

            if (location == null)
            {
                return;
            }

            var oldCount = location.BallotsCollected;
            var newCount = personCacher.AllForThisElection.Count(
                p => p.VotingLocationGuid == location.LocationGuid && !String.IsNullOrEmpty(p.VotingMethod));

            if (oldCount == newCount)
            {
                return;
            }

            Db.Location.Attach(location);

            location.BallotsCollected = newCount;

            locationCacher.UpdateItemAndSaveCache(location);
            saveNeeded = true;
        }
Example #2
0
        public JsonResult DeleteVote(int vid)
        {
            if (UserSession.CurrentElectionStatus == ElectionTallyStatusEnum.Finalized)
            {
                return(new { Message = UserSession.FinalizedNoChangesMessage }.AsJsonResult());
            }

            VoteCacher voteCacher = new VoteCacher(Db);

            var vote = voteCacher.AllForThisElection.SingleOrDefault(v => v.C_RowId == vid);

            if (vote == null)
            {
                return(new { Message = "Not found" }.AsJsonResult());
            }

            var ballot       = CurrentRawBallot();
            var isSingleName = UserSession.CurrentElection.IsSingleNameElection;
            var location     = new LocationCacher(Db).AllForThisElection.Single(l => l.LocationGuid == ballot.LocationGuid);

            if (location.IsVirtual)
            {
                return(new { Message = "Cannot delete votes from an online ballot." }.AsJsonResult());
            }

            Db.Vote.Attach(vote);
            Db.Vote.Remove(vote);
            Db.SaveChanges();

            var allVotes = voteCacher.RemoveItemAndSaveCache(vote).AllForThisElection;

            var ballotStatusInfo = BallotAnalyzerLocal.UpdateBallotStatus(ballot, VoteInfosFor(ballot, allVotes), false);

            UpdateVotePositions(vote.BallotGuid, allVotes);

            var sum = _helper.BallotCount(location.LocationGuid, isSingleName, null, allVotes);

            new BallotCacher(Db).UpdateItemAndSaveCache(ballot);
            Db.SaveChanges();

            var ballotCounts = isSingleName ? new VoteCacher().AllForThisElection
                               .Where(v => v.BallotGuid == ballot.BallotGuid)
                               .Sum(v => v.SingleNameElectionCount) : 0;
            var ballotCountNames = isSingleName ? new VoteCacher().AllForThisElection
                                   .Count(v => v.BallotGuid == ballot.BallotGuid) : 0;

            return(new
            {
                Deleted = true,
                Votes = CurrentVotesForJs(GetCurrentBallot(), allVotes),
                BallotStatus = ballotStatusInfo.Status.Value,
                BallotStatusText = ballotStatusInfo.Status.DisplayText,
                ballotStatusInfo.SpoiledCount,
                LocationBallotsEntered = sum,
                BallotId = ballot.C_RowId,
                SingleBallotCount = ballotCounts,
                SingleBallotNames = ballotCountNames,
                VoteUpdates = GetVoteUpdatesOnDelete(vote.PersonGuid, voteCacher, isSingleName),
            }.AsJsonResult());
        }
Example #3
0
        public JsonResult SortLocations(List <int> idList)
        {
            //var ids = idList.Split(new[] { ',' }).AsInts().ToList();

            var locationCacher = new LocationCacher(SharedDbContext);

            var locations = locationCacher.AllForThisElection.Where(l => idList.Contains(l.Id)).ToList();

            var sortOrder = 1;

            foreach (var id in idList)
            {
                var newOrder = sortOrder++;

                var location = locations.SingleOrDefault(l => l.Id == id);

                if (location != null && location.SortOrder != newOrder)
                {
                    SharedDbContext.Location.Attach(location);
                    location.SortOrder = newOrder;

                    locationCacher.UpdateItemAndSaveCache(location);
                }
            }

            SharedDbContext.SaveChanges();

            return(new
            {
                Saved = true
            }.AsJsonResult());
        }
Example #4
0
        //TODO
        /// <Summary>Does this page need to show the location selector?</Summary>
        //public bool ShowLocationSelector(MenuHelper currentMenu)
        //{
        //    return currentMenu.ShowLocationSelection && HasLocations;
        //}

        public JsonResult UpdateStatus(int locationId, string status)
        {
            var locationCacher = new LocationCacher(SharedDbContext);

            var location = AllLocations.SingleOrDefault(l => l.Id == locationId);

            if (location == null)
            {
                return(new
                {
                    Saved = false
                }.AsJsonResult());
            }

            if (location.TallyStatus != status)
            {
                SharedDbContext.Location.Attach(location);
                location.TallyStatus = status;
                SharedDbContext.SaveChanges();

                locationCacher.UpdateItemAndSaveCache(location);
            }

            return(new
            {
                Saved = true,
                Location = LocationInfoForJson(location)
            }.AsJsonResult());
        }
Example #5
0
        protected Ballot CreateAndRegisterBallot()
        {
            var currentLocationGuid = UserSession.CurrentLocationGuid;

            if (!currentLocationGuid.HasContent())
            {
                var locationModel = new LocationModel();
                currentLocationGuid             = locationModel.GetLocations_Physical().First().LocationGuid;
                UserSession.CurrentLocationGuid = currentLocationGuid;
            }
            var computerCode = UserSession.CurrentComputerCode;

            var ballotCacher = new BallotCacher(Db);
            var firstBallot  = ballotCacher.AllForThisElection.Any();

            var ballot = new Ballot
            {
                BallotGuid          = Guid.NewGuid(),
                LocationGuid        = currentLocationGuid,
                ComputerCode        = computerCode,
                BallotNumAtComputer = NextBallotNumAtComputer(),
                StatusCode          = BallotStatusEnum.Empty,
                Teller1             = UserSession.GetCurrentTeller(1),
                Teller2             = UserSession.GetCurrentTeller(2)
            };

            Db.Ballot.Add(ballot);

            if (firstBallot)
            {
                var locationCacher = new LocationCacher(Db);
                var location       = locationCacher.AllForThisElection.FirstOrDefault(l => l.LocationGuid == currentLocationGuid);
                if (location != null && location.BallotsCollected.AsInt() == 0)
                {
                    var ballotSources = new PersonCacher(Db)
                                        .AllForThisElection
                                        .Count(p => !string.IsNullOrEmpty(p.VotingMethod) && p.VotingLocationGuid == currentLocationGuid);
                    location.BallotsCollected = ballotSources;
                    locationCacher.UpdateItemAndSaveCache(location);
                }
            }

            Db.SaveChanges();

            ballotCacher.UpdateItemAndSaveCache(ballot);

            SessionKey.CurrentBallotId.SetInSession(ballot.C_RowId);

            return(ballot); //TODO: used to be view
        }
Example #6
0
        private void UpdateLocationCounts(Guid?newVoteLocationGuid, Guid?oldVoteLocationGuid,
                                          PersonCacher personCacher)
        {
            // would be great to throw this into a remote queue to be processed later
            var locationCacher = new LocationCacher(Db);
            var saveNeeded     = false;

            UpdateLocation(newVoteLocationGuid, personCacher, locationCacher, ref saveNeeded);

            if (oldVoteLocationGuid != null && oldVoteLocationGuid != newVoteLocationGuid)
            {
                UpdateLocation(oldVoteLocationGuid, personCacher, locationCacher, ref saveNeeded);
            }

            if (saveNeeded)
            {
                Db.SaveChanges();
            }
        }
Example #7
0
        //    private void ClearOutOldComputerRecords()
        //    {
        //      // backward compatible... remove all records from database
        //
        //
        //      const int maxMinutesOfNoContact = 30;
        //      var computerCacher = new ComputerCacher(Db);
        //
        //      var now = DateTime.Now;
        //      var computers = computerCacher.AllForThisElection;
        //
        //      computerCacher.RemoveItemsAndSaveCache(
        //        computers.Where(c => !c.LastContact.HasValue
        //                             || (now - c.LastContact.Value).TotalMinutes > maxMinutesOfNoContact));
        //    }

        /// <Summary>Move this computer into this location (don't change the computer code)</Summary>
        public bool MoveCurrentComputerIntoLocation(int locationId)
        {
            var location = new LocationCacher(GetNewDbContext()).AllForThisElection.SingleOrDefault(l => l.Id == locationId);

            if (location == null)
            {
                // ignore the request
                return(false);
            }

            var computer = UserSession.CurrentComputer;

            AssertAtRuntime.That(computer != null, "computer missing");
            AssertAtRuntime.That(computer.ElectionGuid == location.ElectionGuid, "can't switch elections");

            computer.LocationGuid = location.LocationGuid;
            new ComputerCacher().UpdateComputer(computer);

            SessionKey.CurrentLocationGuid.SetInSession(location.LocationGuid);

            // reset ballot #
            SessionKey.CurrentBallotId.SetInSession(0);
            if (UserSession.CurrentElection.IsSingleNameElection)
            {
                // for single name elections, only have one ballot per computer per location. (But if altered from a normal election to a single name election, may have multiple.)

                //TODO
                //var ballotId =
                //  new BallotCacher(Db).AllForThisElection.Where(b => b.LocationGuid == location.LocationGuid
                //                                                   && b.ComputerCode == computer.ComputerCode)
                //    .OrderBy(b => b.BallotNumAtComputer)
                //    .Select(b => b.Id).FirstOrDefault();
                //if (ballotId != 0)
                //{
                //    SessionKey.CurrentBallotId.SetInSession(ballotId);
                //}
            }

            return(true);
        }
Example #8
0
        public JsonResult SortLocations(List <int> idList)
        {
            //var ids = idList.Split(new[] { ',' }).AsInts().ToList();

            var locationCacher = new LocationCacher(Db);

            var locations = locationCacher.AllForThisElection
                            .Where(l => idList.Contains(l.C_RowId))
                            .ToList();

            var sortOrder = 1;

            foreach (var id in idList)
            {
                var location = locations.SingleOrDefault(l => l.C_RowId == id);
                if (location == null)
                {
                    continue;
                }

                // keep "Online" at the bottom of this list.  Use Html/css to support this rule.
                var newOrder = location.IsTheOnlineLocation ? 90 : location.IsTheImportedLocation ? 91 : sortOrder++;

                if (location.SortOrder != newOrder)
                {
                    Db.Location.Attach(location);
                    location.SortOrder = newOrder;

                    locationCacher.UpdateItemAndSaveCache(location);
                }
            }

            Db.SaveChanges();

            return(new
            {
                Saved = true
            }.AsJsonResult());
        }
Example #9
0
        public JsonResult UpdateStatus(int locationId, string status)
        {
            var locationCacher = new LocationCacher(Db);

            var location = GetLocations_Physical().SingleOrDefault(l => l.C_RowId == locationId);

            if (location == null)
            {
                return(new
                {
                    Saved = false
                }.AsJsonResult());
            }

            if (location.IsVirtual)
            {
                return(new
                {
                    Saved = false
                }.AsJsonResult());
            }

            if (location.TallyStatus != status)
            {
                Db.Location.Attach(location);
                location.TallyStatus = status;
                Db.SaveChanges();

                locationCacher.UpdateItemAndSaveCache(location);
            }

            return(new
            {
                Saved = true,
                Location = LocationInfoForJson(location)
            }.AsJsonResult());
        }
Example #10
0
        public JsonResult SaveVote(int personId, int voteId, Guid?invalidReason, int lastVid, int count, bool verifying)
        {
            if (UserSession.CurrentElectionStatus == ElectionTallyStatusEnum.Finalized)
            {
                return(new { Message = UserSession.FinalizedNoChangesMessage }.AsJsonResult());
            }
            var locationModel = new LocationModel();

            if (locationModel.HasMultiplePhysicalLocations && UserSession.CurrentLocation == null)
            {
                return(new { Message = "Must select your location first!" }.AsJsonResult());
            }
            if (UserSession.GetCurrentTeller(1).HasNoContent())
            {
                return(new { Message = "Must select \"Teller at Keyboard\" first!" }.AsJsonResult());
            }

            var isSingleName = UserSession.CurrentElection.IsSingleNameElection;

            var ballot = GetCurrentBallot();

            if (ballot == null)
            {
                // don't have an active Ballot!
                return(new { Updated = false, Error = "Invalid ballot" }.AsJsonResult());
            }

            Db.Ballot.Attach(ballot);

            var voteCacher   = new VoteCacher(Db);
            var personCacher = new PersonCacher(Db);

            if (voteId != 0)
            {
                // update existing record

                // find info about the existing Vote
                var vote = voteCacher.AllForThisElection.SingleOrDefault(v => v.C_RowId == voteId);

                if (vote == null)
                {
                    // problem... client has a vote number, but we didn't find...
                    return(new { Updated = false, Error = "Invalid vote id" }.AsJsonResult());
                }
                if (vote.BallotGuid != ballot.BallotGuid)
                {
                    // problem... client is focused on a different ballot!
                    return(new { Updated = false, Error = "Invalid vote/ballot id" }.AsJsonResult());
                }

                Db.Vote.Attach(vote);

                vote.SingleNameElectionCount = count;

                var person1 = personCacher.AllForThisElection.SingleOrDefault(p => p.C_RowId == personId);
                vote.PersonCombinedInfo = person1?.CombinedInfo;

                if (UserSession.CurrentLocation.IsVirtual)
                {
                    // changing person on an online ballot

                    if (person1 == null)
                    {
                        vote.PersonGuid = null;
                    }
                    else
                    {
                        vote.PersonGuid = person1.PersonGuid;
                        invalidReason   = person1.IneligibleReasonGuid;
                    }

                    vote.StatusCode = invalidReason == null ? VoteStatusCode.Ok : VoteStatusCode.Spoiled;
                }

                DetermineInvalidReasonGuid(invalidReason, vote);

                vote.StatusCode =
                    VoteAnalyzer.DetermineStatus(new VoteInfo(vote, UserSession.CurrentElection, ballot,
                                                              UserSession.CurrentLocation, person1));

                Db.SaveChanges();

                var votes = voteCacher.UpdateItemAndSaveCache(vote).AllForThisElection;

                var ballotStatusInfo = BallotAnalyzerLocal.UpdateBallotStatus(ballot, VoteInfosFor(ballot, votes), true);
                var sum = _helper.BallotCount(ballot.LocationGuid, isSingleName, null, votes);

                ballot.Teller1 = UserSession.GetCurrentTeller(1);
                ballot.Teller2 = UserSession.GetCurrentTeller(2);

                new BallotCacher(Db).UpdateItemAndSaveCache(ballot);
                Db.SaveChanges();

                var ballotCounts = isSingleName ? new VoteCacher().AllForThisElection
                                   .Where(v => v.BallotGuid == ballot.BallotGuid)
                                   .Sum(v => v.SingleNameElectionCount) : 0;
                var ballotCountNames = isSingleName ? new VoteCacher().AllForThisElection
                                       .Count(v => v.BallotGuid == ballot.BallotGuid) : 0;

                return(new
                {
                    Updated = true,
                    BallotStatus = ballotStatusInfo.Status.Value,
                    BallotStatusText = ballotStatusInfo.Status.DisplayText,
                    ballotStatusInfo.SpoiledCount,
                    LocationBallotsEntered = sum,
                    BallotId = ballot.C_RowId,
                    SingleBallotCount = ballotCounts,
                    SingleBallotNames = ballotCountNames,
                    VoteUpdates = GetVoteUpdates(lastVid, voteCacher, isSingleName, personCacher),
                    LastVid = vote.C_RowId,
                    vote.InvalidReasonGuid,
                    Name = person1?.C_FullName,
                    person1?.Area,
                    vote = CurrentVotesForJs(GetCurrentBallot(), new List <Vote> {
                        vote
                    }).First()
                }.AsJsonResult());
            }

            // make a new Vote record
            var location = new LocationCacher(Db).AllForThisElection.Single(l => l.LocationGuid == ballot.LocationGuid);

            if (location.IsVirtual)
            {
                return(new { Updated = false, Error = "Cannot add votes to an online ballot" }.AsJsonResult());
            }

            var invalidReasonGuid = DetermineInvalidReasonGuid(invalidReason);

            var person = personCacher.AllForThisElection.SingleOrDefault(p => p.C_RowId == personId);

            var ok = person != null || (invalidReason != null && invalidReasonGuid != Guid.Empty);

            if (ok)
            {
                var nextVoteNum = 1 + voteCacher.AllForThisElection.Where(v => v.BallotGuid == ballot.BallotGuid)
                                  .OrderByDescending(v => v.PositionOnBallot)
                                  .Take(1)
                                  .Select(b => b.PositionOnBallot)
                                  .SingleOrDefault();

                var vote = new Vote
                {
                    BallotGuid              = ballot.BallotGuid,
                    PositionOnBallot        = nextVoteNum,
                    StatusCode              = VoteStatusCode.Ok,
                    SingleNameElectionCount = count
                };
                if (person != null)
                {
                    vote.PersonGuid         = person.PersonGuid;
                    vote.PersonCombinedInfo = person.CombinedInfo;
                    vote.InvalidReasonGuid  = person.CanReceiveVotes.AsBoolean(true) ? null : person.IneligibleReasonGuid;
                    //          VoteHelperLocal.IneligibleToReceiveVotes(person.IneligibleReasonGuid,
                    //            person.CanReceiveVotes);
                }
                vote.InvalidReasonGuid = invalidReasonGuid;
                Db.Vote.Add(vote);
                Db.SaveChanges();

                var votes = voteCacher.UpdateItemAndSaveCache(vote).AllForThisElection;

                var rawBallot        = CurrentRawBallot();
                var ballotStatusInfo = BallotAnalyzerLocal.UpdateBallotStatus(rawBallot, VoteInfosFor(rawBallot, votes), true);

                var sum = _helper.BallotCount(ballot.LocationGuid, isSingleName, null, votes);

                new BallotCacher(Db).UpdateItemAndSaveCache(rawBallot);
                Db.SaveChanges();

                var ballotCounts = isSingleName ? new VoteCacher().AllForThisElection
                                   .Where(v => v.BallotGuid == ballot.BallotGuid)
                                   .Sum(v => v.SingleNameElectionCount) : 0;
                var ballotCountNames = isSingleName ? new VoteCacher().AllForThisElection
                                       .Count(v => v.BallotGuid == ballot.BallotGuid) : 0;

                return(new
                {
                    Updated = true,
                    VoteId = vote.C_RowId,
                    pos = vote.PositionOnBallot,
                    BallotStatus = ballotStatusInfo.Status.Value,
                    BallotStatusText = ballotStatusInfo.Status.DisplayText,
                    ballotStatusInfo.SpoiledCount,
                    BallotId = ballot.C_RowId,
                    LocationBallotsEntered = sum,
                    SingleBallotCount = ballotCounts,
                    SingleBallotNames = ballotCountNames,
                    VoteUpdates = GetVoteUpdates(lastVid, voteCacher, isSingleName, personCacher),
                    LastVid = vote.C_RowId
                }.AsJsonResult());
            }

            // don't recognize person id
            return(new { Updated = false, Error = "Invalid person. Please try again." }.AsJsonResult());
        }
Example #11
0
        public object GetCurrentResults()
        {
            try
            {
                var resultSummaryFinal =
                    _analyzer.ResultSummaryFinal; // resultSummaries.SingleOrDefault(rs => rs.ResultType == ResultType.Final);

                //TODO build online checks into base analysis

                // don't show any details if review is needed or online ballots need to be processed
                var issues = new List <string>();
                if (_election.OnlineCurrentlyOpen)
                {
                    issues.Add("Online voting is still open. It must be Closed before analyzing ballots.");
                }

                var unprocessedOnlineBallots = _election.OnlineWhenOpen.HasValue
          ? Db.OnlineVotingInfo
                                               .Join(Db.Person.Where(p => p.VotingMethod == VotingMethodEnum.Online.Value), ovi => ovi.PersonGuid, p => p.PersonGuid, (ovi, p) => ovi)
                                               .Count(ovi => ovi.ElectionGuid == UserSession.CurrentElectionGuid && ovi.Status == OnlineBallotStatusEnum.Submitted)
          : 0;
                if (unprocessedOnlineBallots > 0)
                {
                    issues.Add($"Online ballots waiting to be accepted: {unprocessedOnlineBallots}");
                }

                if (resultSummaryFinal.BallotsNeedingReview != 0 || issues.Any())
                {
                    var locations         = new LocationCacher(Db).AllForThisElection;
                    var multipleLocations = locations.Count() > 1;

                    var needReview = _analyzer.VoteInfos.Where(VoteAnalyzer.VoteNeedReview)
                                     .Join(locations, vi => vi.LocationId, l => l.C_RowId,
                                           (vi, location) => new { vi, location })
                                     .Select(x => new
                    {
                        x.vi.LocationId,
                        x.vi.BallotId,
                        Status = BallotStatusEnum.TextFor(x.vi.BallotStatusCode),
                        Ballot = multipleLocations ? $"{x.vi.C_BallotCode} ({x.location.Name})" : x.vi.C_BallotCode,
                    })
                                     .Distinct()
                                     .OrderBy(x => x.Ballot);

                    var needReview2 = _analyzer.Ballots.Where(BallotAnalyzer.BallotNeedsReview)
                                      .Join(locations, b => b.LocationGuid, l => l.LocationGuid,
                                            (b, location) => new { b, location })
                                      .OrderBy(x => x.b.ComputerCode)
                                      .ThenBy(x => x.b.BallotNumAtComputer)
                                      .Select(x => new
                    {
                        LocationId = x.location.C_RowId,
                        BallotId   = x.b.C_RowId,
                        Status     = BallotStatusEnum.TextFor(x.b.StatusCode),
                        Ballot     = multipleLocations ? $"{x.b.C_BallotCode} ({x.location.Name})" : x.b.C_BallotCode
                    });

                    return(new
                    {
                        NeedReview = needReview.Concat(needReview2).Distinct(),
                        _election.VotingMethods,
                        ResultsFinal = _analyzer.ResultSummaryFinal
                                       .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                        ResultsCalc =
                            _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Calculated)
                            .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                        ResultsManual = (_analyzer.ResultSummaries.FirstOrDefault(rs => rs.ResultType == ResultType.Manual) ??
                                         new ResultSummary()).GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                        OnlineIssues = issues,
                        _election.OnlineCurrentlyOpen
                        //ResultsFinal =
                        //  resultSummaries.First(rs => rs.ResultType == ResultType.Final)
                        //    .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    });
                }

                // show vote totals

                var persons = new PersonCacher(Db).AllForThisElection;

                var vResultInfos =
                    // TODO 2012-01-21 Glen Little: Could return fewer columns for non-tied results
                    _analyzer.Results // new ResultCacher(Db).AllForThisElection
                    .OrderBy(r => r.Rank)
                    .ToList()
                    .Select(r => new
                {
                    rid = r.C_RowId,
                    r.CloseToNext,
                    r.CloseToPrev,
                    r.ForceShowInOther,
                    r.IsTied,
                    r.IsTieResolved,
                    PersonName = PersonNameFor(persons, r),
                    r.Rank,
                    //ri.RankInExtra,
                    r.Section,
                    r.TieBreakCount,
                    r.TieBreakGroup,
                    r.TieBreakRequired,
                    r.VoteCount
                }).ToList();

                var ties = _analyzer.ResultTies //  new ResultTieCacher(Db).AllForThisElection
                           .OrderBy(rt => rt.TieBreakGroup)
                           .Select(rt => new
                {
                    rt.TieBreakGroup,
                    rt.NumInTie,
                    rt.NumToElect,
                    rt.TieBreakRequired,
                    rt.IsResolved
                }).ToList();

                //var spoiledVotesSummary = Db.vVoteInfoes.where
                return(new
                {
                    Votes = vResultInfos,
                    UserSession.CurrentElectionStatus,
                    Ties = ties,
                    NumToElect = _election.NumberToElect,
                    NumExtra = _election.NumberExtra,
                    // ShowCalledIn = _election.UseCallInButton,
                    // _election.CustomMethods,
                    _election.VotingMethods,
                    ShowOnline = _election.OnlineWhenOpen.HasValue,
                    ResultsManual =
                        (_analyzer.ResultSummaries.FirstOrDefault(rs => rs.ResultType == ResultType.Manual) ?? new ResultSummary())
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    ResultsCalc =
                        _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Calculated)
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    ResultsFinal =
                        _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Final)
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                });
            }
            catch (Exception ex)
            {
                return(new
                {
                    Interrupted = true,
                    Msg = ex.GetAllMsgs("; ") + "\n" + ex.StackTrace
                });
            }
        }
Example #12
0
        public JsonResult EditLocation(int id, string text, bool allowModifyOnline = false)
        {
            if (text == OnlineLocationName && !allowModifyOnline)
            {
                return(new
                {
                    Success = false,
                    Status = $"Cannot name a location as \"{OnlineLocationName}\""
                }.AsJsonResult());
            }

            if (text == ImportedLocationName)
            {
                return(new
                {
                    Success = false,
                    Status = $"Cannot name a location as \"{ImportedLocationName}\""
                }.AsJsonResult());
            }

            var locationCacher = new LocationCacher(Db);

            var location = locationCacher.AllForThisElection.SingleOrDefault(l => l.C_RowId == id);
            var changed  = false;

            if (location == null)
            {
                location = new Location
                {
                    ElectionGuid = UserSession.CurrentElectionGuid,
                    LocationGuid = Guid.NewGuid()
                };
                Db.Location.Add(location);
                changed = true;
            }
            else
            {
                if (location.IsVirtual && !allowModifyOnline)
                {
                    return(new
                    {
                        Success = false,
                        Status = "Cannot edit Online location"
                    }.AsJsonResult());
                }

                Db.Location.Attach(location);
            }

            int    locationId;
            string locationText;
            string status;
            var    success = false;

            if (text.HasNoContent() && location.C_RowId > 0)
            {
                // deleting this location

                // don't delete last location
                if (location.IsTheOnlineLocation && allowModifyOnline ||
                    GetLocations_Physical().Count > 1)
                {
                    // delete existing if we can
                    if (!IsLocationInUse(location.LocationGuid))
                    {
                        Db.Location.Remove(location);
                        Db.SaveChanges();
                        locationCacher.RemoveItemAndSaveCache(location);

                        status       = "Deleted";
                        success      = true;
                        locationId   = 0;
                        locationText = "";
                    }
                    else
                    {
                        status       = "Cannot deleted this location because it has Ballots recorded in it";
                        locationId   = location.C_RowId;
                        locationText = location.Name;
                    }
                }
                else
                {
                    // only one
                    status       = "At least one location is required";
                    locationId   = location.C_RowId;
                    locationText = location.Name;
                }
            }
            else if (text.HasContent())
            {
                locationText = location.Name = text;
                locationId   = location.C_RowId; // may be 0 if new

                changed = true;
                status  = "Saved";
            }
            else
            {
                status       = "Nothing to save";
                locationId   = 0;
                locationText = "";
                success      = true;
                changed      = false;
            }

            if (changed)
            {
                Db.SaveChanges();

                locationId = location.C_RowId;
                locationCacher.UpdateItemAndSaveCache(location);
                success = true;
            }

            return(new
            {
                // returns 0 if deleted or not created
                Id = locationId,
                Text = locationText,
                Success = success,
                Status = status
            }.AsJsonResult());
        }
Example #13
0
        public object GetCurrentResults()
        {
            //var ready = _analyzer.IsResultAvailable;
            var dbContext = GetNewDbContext();

            try
            {
                var resultSummaryFinal = _analyzer.ResultSummaryFinal; // resultSummaries.SingleOrDefault(rs => rs.ResultType == ResultType.Final);


                // don't show any details if review is needed
                if (resultSummaryFinal.BallotsNeedingReview != 0)
                {
                    var locations         = new LocationCacher(dbContext).AllForThisElection;
                    var multipleLocations = locations.Count() > 1;

                    //TODO
                    var needReview = _analyzer.VoteInfos // .Where(VoteAnalyzer.VoteNeedReview)
                                     .Join(locations, vi => vi.LocationId, l => l.Id,
                                           (vi, location) => new { vi, location })
                                     .Select(x => new
                    {
                        x.vi.LocationId,
                        x.vi.BallotId,
                        Status =
                            x.vi.BallotStatusCode == "Review"
                            ? BallotStatusEnum.Review.DisplayText
                            : "Verification Needed",
                        Ballot = multipleLocations ?
                                 string.Format("{0} ({1})", x.vi.C_BallotCode, x.location.Name) : x.vi.C_BallotCode
                    })
                                     .Distinct()
                                     .OrderBy(x => x.Ballot);

                    var needReview2 = _analyzer.Ballots.Where(b => b.StatusCode == BallotStatusEnum.Review)
                                      .Join(locations, b => b.LocationGuid, l => l.LocationGuid,
                                            (b, location) => new { b, location })
                                      .Select(x => new
                    {
                        LocationId = x.location.Id,
                        BallotId   = x.b.Id,
                        Status     =
                            x.b.StatusCode == "Review"
                            ? BallotStatusEnum.Review.DisplayText
                            : "Verification Needed",
                        Ballot = multipleLocations ?
                                 string.Format("{0} ({1})", x.b.C_BallotCode, x.location.Name) : x.b.C_BallotCode
                    });

                    return(new
                    {
                        NeedReview = needReview.Concat(needReview2).Distinct(),
                        ResultsFinal = _analyzer.ResultSummaryFinal
                                       .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                        ResultsCalc =
                            _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Calculated)
                            .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                        ResultsManual = (_analyzer.ResultSummaries.FirstOrDefault(rs => rs.ResultType == ResultType.Manual) ??
                                         new ResultSummary()).GetPropertiesExcept(null, new[] { "ElectionGuid" }),

                        //ResultsFinal =
                        //  resultSummaries.First(rs => rs.ResultType == ResultType.Final)
                        //    .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    });
                }

                // show vote totals

                var persons = new PersonCacher(dbContext).AllForThisElection;

                var vResultInfos =
                    // TODO 2012-01-21 Glen Little: Could return fewer columns for non-tied results
                    _analyzer.Results // new ResultCacher(Db).AllForThisElection
                    .OrderBy(r => r.Rank)
                    .ToList()
                    .Select(r => new
                {
                    rid = r.Id,
                    r.CloseToNext,
                    r.CloseToPrev,
                    r.ForceShowInOther,
                    r.IsTied,
                    r.IsTieResolved,
                    PersonName = PersonNameFor(persons, r),
                    r.Rank,
                    //ri.RankInExtra,
                    r.Section,
                    r.TieBreakCount,
                    r.TieBreakGroup,
                    r.TieBreakRequired,
                    r.VoteCount
                }).ToList();

                var ties = _analyzer.ResultTies //  new ResultTieCacher(Db).AllForThisElection
                           .OrderBy(rt => rt.TieBreakGroup)
                           .Select(rt => new
                {
                    rt.TieBreakGroup,
                    rt.NumInTie,
                    rt.NumToElect,
                    rt.TieBreakRequired,
                    rt.IsResolved
                }).ToList();

                //var spoiledVotesSummary = Db.vVoteInfoes.where



                return(new
                {
                    Votes = vResultInfos,
                    UserSession.CurrentElectionStatus,
                    Ties = ties,
                    NumToElect = _election.NumberToElect,
                    NumExtra = _election.NumberExtra,
                    ShowCalledIn = _election.UseCallInButton,
                    ResultsManual =
                        (_analyzer.ResultSummaries.FirstOrDefault(rs => rs.ResultType == ResultType.Manual) ?? new ResultSummary())
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    ResultsCalc =
                        _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Calculated)
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                    ResultsFinal =
                        _analyzer.ResultSummaries.First(rs => rs.ResultType == ResultType.Final)
                        .GetPropertiesExcept(null, new[] { "ElectionGuid" }),
                });
            }
            catch (Exception ex)
            {
                return(new
                {
                    Interrupted = true,
                    Msg = ex.GetAllMsgs("; ") + "\n" + ex.StackTrace
                });
            }
        }
Example #14
0
        public JsonResult EditLocation(int id, string text)
        {
            var locationCacher = new LocationCacher(SharedDbContext);

            var location = locationCacher.AllForThisElection.SingleOrDefault(l => l.Id == id);
            var changed  = false;

            if (location == null)
            {
                location = new Location
                {
                    ElectionGuid = UserSession.CurrentElectionGuid,
                    LocationGuid = Guid.NewGuid()
                };
                SharedDbContext.Location.Add(location);
                changed = true;
            }
            else
            {
                SharedDbContext.Location.Attach(location);
            }

            int    locationId;
            string locationText;
            string status;
            var    success = false;

            if (text.HasNoContent() && location.Id > 0)
            {
                // don't delete last location
                if (AllLocations.Count() > 1)
                {
                    // delete existing if we can
                    var used = new BallotCacher(SharedDbContext).AllForThisElection.Any(b => b.LocationGuid == location.LocationGuid);
                    if (!used)
                    {
                        SharedDbContext.Location.Remove(location);
                        SharedDbContext.SaveChanges();
                        locationCacher.RemoveItemAndSaveCache(location);

                        status       = "Deleted";
                        success      = true;
                        locationId   = 0;
                        locationText = "";
                    }
                    else
                    {
                        status       = "Cannot deleted this location because it has Ballots recorded in it";
                        locationId   = location.Id;
                        locationText = location.Name;
                    }
                }
                else
                {
                    // only one
                    status       = "At least one location is required";
                    locationId   = location.Id;
                    locationText = location.Name;
                }
            }
            else if (text.HasContent())
            {
                locationText = location.Name = text;
                locationId   = location.Id; // may be 0 if new

                changed = true;
                status  = "Saved";
            }
            else
            {
                status       = "Nothing to save";
                locationId   = 0;
                locationText = "";
                success      = true;
                changed      = false;
            }

            if (changed)
            {
                SharedDbContext.SaveChanges();

                locationId = location.Id;
                locationCacher.UpdateItemAndSaveCache(location);
                success = true;
            }

            return(new
            {
                // returns 0 if deleted or not created
                Id = locationId,
                Text = locationText,
                Success = success,
                Status = status
            }.AsJsonResult());
        }