示例#1
0
    private bool IsValidMove(Constituent constituent, District newDistrict)
    {
        //make sure this constituent isn't locked
        if (LockedConstituents.Contains(constituent))
        {
            return(false);
        }

        if (constituent.party != Constituent.Party.None)
        {
            //make sure the size of the old district will be within size constraints
            if (constituent.District.VotingMemberCount - 1 < cityGenerator.MinDistrictSize)
            {
                return(false);
            }
        }

        //check if this constituent is a cut vertex for the old district. if it is, return false
        if (constituent.District.ArticulationPoints.Contains(constituent))
        {
            return(false);
        }

        //verify that this constituent is actually adjacent to the new district
        if (!newDistrict.NeighborConstituents.Contains(constituent))
        {
            return(false);
        }

        //return true
        return(true);
    }
        /// <summary>
        /// Sends a 'thank you' email to the given Constituent.
        /// </summary>
        /// <param name="constituent">The Constituent to send the email to.</param>
        /// <returns>The task, whether it succeeded or failed.</returns>
        public virtual Task SendThankYouEmail(ApplicationUser user, Constituent constituent)
        {
            return(Task.Run(() =>
            {
                if (constituent != null)
                {
                    var userProfile = unitOfWork.Profiles.Find(x => x.UserID == user.Id).FirstOrDefault();

                    string apiKey = WebConfigurationManager.AppSettings["SENDGRID_API_KEY"];
                    var client = new SendGridClient(apiKey);
                    var msg = new SendGridMessage()
                    {
                        From = new EmailAddress(userProfile.Email, userProfile.FullName),
                        Subject = "Thank you for your recent gift!",
                        PlainTextContent = "Thank you taking the time to speak with us over the phone, and for your recent gift!" +
                                           "                                                       " +
                                           "You did a good thing, and should feel good. Good? Good.",
                        HtmlContent = "<h4>Thank you taking the time to speak with us over the phone, and for your recent gift!</h4>" +
                                      "<p>You did a good thing, and should feel good. Good? Good.</p>"
                    };

                    msg.AddTo(new EmailAddress("*****@*****.**", "Mr. Brock Vance"));
                    Task <Response> response = client.SendEmailAsync(msg);
                }
            }));
        }
示例#3
0
        public static void InitialiseModelsForConstituent(RiverSystemScenario s, Constituent c)
        {
            ConstituentsManagement cm = s.Network.ConstituentsManagement;

            cm.Elements.OfType <NetworkElementConstituentData>().ForEachItem(d =>
            {
                if (d.Data == null)
                {
                    d.Data = new ConstituentsModel();
                }

                d.Data.GetModel(c, DefaultSourceSinkType(d));
                if (!d.Data.ConstituentPlayedValues.Any(cpv => cpv.Constituent == c))
                {
                    d.Data.ConstituentPlayedValues.Add(new ConstituentPlayedValue(c)
                    {
                        PlayedType = ConstituentPlayedValue.ConstituentPlayedType.varConcentration
                    });
                }
                d.Reset(cm, false, null, ScenarioType.RiverManager);
            });

            foreach (var catchment in s.Network.Catchments.OfType <Catchment>())
            {
                foreach (var functionalUnit in catchment.FunctionalUnits.OfType <StandardFunctionalUnit>())
                {
                    InitialiseConstituentSources(s, catchment, functionalUnit, c);
                }
            }
        }
        public ActionResult ReviewProposedConstituentChanges()
        {
            // Get a list of all the entries in both the Constituents and ProposedConstituentChanges tables
            ReviewChangesModel reviewChanges = new ReviewChangesModel
            {
                Constituents       = new List <Constituent>(),
                ConstituentChanges = new List <ProposedConstituentsChanges>()
            };

            // Create a list of all entries in the table of proposed changes
            List <ProposedConstituentsChanges> proposedChanges = unitOfWork.Changes.GetProposedChanges().ToList();

            //List<Constituent> constituents = new List<Constituent>();

            // Only proceed if there are entries in the table
            if (proposedChanges != null)
            {
                // Grab the original entry for each Constituent
                foreach (var changed in proposedChanges)
                {
                    Constituent original = unitOfWork.Constituents.Find(x => x.ConstituentID == changed.ConstituentID).FirstOrDefault();
                    //constituents.Add(selectedConstituent);
                    reviewChanges.Constituents.Add(original);
                    reviewChanges.ConstituentChanges.Add(changed);
                }

                // Send the list to the view
                return(View(reviewChanges));
            }

            // Send the list to the view
            return(View());
        }
示例#5
0
        public void Update(Constituent entity)
        {
            var isValid = Validate(entity);

            if (!isValid)
            {
                return;
            }

            using (var db = new DataContext())
            {
                var existing = db.Constituents.Find(entity.Id);
                if (entity.Equals(existing))
                {
                    return;
                }

                var demoChange = Mapper.Map <DemographicChange>(entity);
                demoChange.Source = Source.Tax;

                demoChange.UpdatedBy = "donor";
                demoChange.Source    = Source.Tax;

                db.DemographicChanges.Add(demoChange);
                db.Constituents.AddOrUpdate(entity);
                db.SaveChanges();
            }
        }
        public bool Delete(int id)
        {
            // If this constituent is in the call assignments, remove them from there before deleting
            CallAssignment callAssignment = unitOfWork.Assignments.Get(id);

            if (callAssignment != null)
            {
                unitOfWork.Assignments.Remove(callAssignment);

                // Remove the constituent from the database
                Constituent constituent = unitOfWork.Constituents.Find(x => x.ConstituentID == id).FirstOrDefault();
                if (constituent != null)
                {
                    unitOfWork.Constituents.Remove(constituent);
                    unitOfWork.Complete();
                }
                return(true);
            }
            else
            {
                // Remove the constituent from the database
                Constituent constituent = unitOfWork.Constituents.Find(x => x.ConstituentID == id).FirstOrDefault();
                if (constituent != null)
                {
                    unitOfWork.Constituents.Remove(constituent);
                    unitOfWork.Complete();
                }
                return(true);
            }
        }
        private IList <Constituent> Map(IDictionary <string, decimal> weights, IDictionary <string, decimal> prices, IReadOnlyList <AssetMarketCap> marketCaps)
        {
            if (weights.Count != prices.Count || prices.Count != marketCaps.Count)
            {
                throw new ValidationException($"Count of weights ({weights.Count})," +
                                              $"count of prices ({prices.Count})," +
                                              $"count of market caps ({marketCaps.Count}) are not equals.");
            }

            var result = new List <Constituent>();

            foreach (var assetWeight in weights)
            {
                var asset     = assetWeight.Key;
                var weight    = assetWeight.Value;
                var price     = prices[asset];
                var marketCap = marketCaps.Single(x => x.Asset == asset).MarketCap.Value;

                var constituent = new Constituent
                {
                    AssetId   = asset,
                    Weight    = weight,
                    Price     = price,
                    MarketCap = marketCap
                };

                result.Add(constituent);
            }

            return(result);
        }
        public ActionResult Index(int?id)
        {
            // If id is null, return to this user's Call List
            if (id == null)
            {
                return(RedirectToAction("ViewCallList", "StandardUsers"));
            }

            // It wasn't null, so try and find a Constituent associated with it
            Constituent constituent = db.Constituents.Find(id);

            Session["constituentID"] = id;

            // If we can't find a Constituent with this id, return an error
            if (constituent == null)
            {
                return(View("Error"));
            }

            // Build lists of Call Logs and Gifts to display in the view
            ViewBag.CallLog = db.CallLogs.Where(x => x.ConstituentID == id).OrderBy(x => x.DateOfCall).ToList();
            ViewBag.Gifts   = db.Gifts.Where(x => x.ConstituentID == id).OrderBy(x => x.CallLog.DateOfCall).ToList();

            // Return the view with the Consituent's information
            return(View(constituent));
        }
示例#9
0
 protected override void afterWriteNodeLogic()
 {
     if (Mixture.wasAnySubFieldModified() || Constituent.wasAnySubFieldModified())
     {
         _recalculateRegListMembership();
     }
 }
示例#10
0
        public ActionResult DeleteConfirmed(int id)
        {
            Constituent constituent = db.Constituents.Find(id);

            db.Constituents.Remove(constituent);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
示例#11
0
 // PUT api/values/5
 public void Put(int id, [FromBody] Constituent value)
 {
     if (value.Id == id)
     {
         db.Entry(value).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
示例#12
0
 // POST api/values
 public void Post([FromBody] Constituent value)
 {
     if (ModelState.IsValid)
     {
         db.Constituents.Add(value);
         db.SaveChanges();
     }
 }
示例#13
0
    private void BalanceConstituentCounts()
    {
        var RedConstituents  = Constituents.Where((c) => c.party == Constituent.Party.Red);
        var BlueConstituents = Constituents.Where((c) => c.party == Constituent.Party.Blue);

        var RedCount  = RedConstituents.Count();
        var BlueCount = BlueConstituents.Count();

        HashSet <District> changedDistricts = new HashSet <District>();

        if (RedCount > BlueConstituents.Count())
        {
            //find the disparity, and convert half that many to blue
            int diff = RedCount - BlueCount;

            //if diff is odd, convert one red to brown
            if ((diff % 2) == 1)
            {
                Constituent c = Utils.ChooseRandom(RedConstituents.ToList());
                c.party = Constituent.Party.Yellow;
                changedDistricts.Add(c.District);
            }

            //choose enough constituents randomly to even things out, and convert them to the other party
            foreach (Constituent c in Utils.ChooseKRandom(RedConstituents.ToList(), diff / 2))
            {
                c.party = Constituent.Party.Blue;
                changedDistricts.Add(c.District);
            }
        }
        else if (RedCount < BlueCount)
        {
            //find the disparity, and convert half that many to red
            int diff = BlueCount - RedCount;

            //if diff is odd, convert one red to brown
            if ((diff % 2) == 1)
            {
                Constituent c = Utils.ChooseRandom(RedConstituents.ToList());
                c.party = Constituent.Party.Yellow;
                changedDistricts.Add(c.District);
            }

            //choose enough constituents randomly to even things out, and convert them to the other party

            foreach (Constituent c in Utils.ChooseKRandom(BlueConstituents.ToList(), diff / 2))
            {
                c.party = Constituent.Party.Red;
                changedDistricts.Add(c.District);
            }
        }

        //update the member counts of every district we changed
        foreach (District d in changedDistricts)
        {
            d.UpdateMemberData();
        }
    }
示例#14
0
 public void MoveConstituent(Constituent c, District newDistrict)
 {
     if (IsValidMove(c, newDistrict))
     {
         MoveConstituents(new Dictionary <Constituent, District> {
             { c, newDistrict }
         });
     }
 }
        public ActionResult Import(HttpPostedFileBase file)
        {
            // Only proceed if the file isn't null and has content
            if (file != null && file.ContentLength > 0)
            {
                // Restrict accepted file types to csv and CSV
                var supportedTypes = new[] { "csv", "CSV" };

                // Reject the file if it doesn't match the required type defined above
                var fileExt = Path.GetExtension(file.FileName).Substring(1);
                if (!supportedTypes.Contains(fileExt))
                {
                    ViewBag.Message = "Invalid file type. Please select a CSV file.";
                    return(View());
                }

                // Set up the requirements for reading in the CSV file
                CsvFileDescription csvFileDescription = new CsvFileDescription
                {
                    SeparatorChar           = ',',
                    FirstLineHasColumnNames = true
                };

                // Read the file into a stream reader, and then convert each entry into our Constituent model
                CsvContext   csvContext              = new CsvContext();
                StreamReader streamReader            = new StreamReader(file.InputStream);
                IEnumerable <Constituent> importList = csvContext.Read <Constituent>(streamReader, csvFileDescription);

                // This loop iterates through each item in the importList object
                // and either updates an existing record, or creates a new one
                foreach (var constituent in importList)
                {
                    // Check for an existing record with this ID
                    Constituent original = db.Constituents.Find(constituent.ConstituentID);
                    if (original != null)
                    {
                        // If we found one, update the values
                        db.Entry(original).CurrentValues.SetValues(constituent);
                    }
                    else
                    {
                        // Otherwise, create a new entry
                        constituent.ConstituentID = constituent.ConstituentID;
                        db.Constituents.Add(constituent);
                    }
                }

                // Saves the changes to the database and additions to the Constituents table
                db.SaveChanges();

                // Redirects the user to the Constituents index page
                return(RedirectToAction("Index", "Constituents"));
            }

            // If we got this far, something went wrong -- return the view
            return(View());
        }
示例#16
0
        public async Task <IActionResult> Constituents([FromBody] Constituent constituent)
        {
            if (constituent.ConstituentId == 0)
            {
                constituent.ConstituentId = 1;
            }
            var task = Task.FromResult(constituent);

            return(Ok(await task));
        }
示例#17
0
        private bool Validate(Constituent entity)
        {
            ValidationErrors.Clear();
            if (string.IsNullOrWhiteSpace(entity.Name))
            {
                ValidationErrors.Add(new KeyValuePair <string, string>("Name", "Name is required"));
            }

            return(ValidationErrors.Count == 0);
        }
示例#18
0
 public TaxViewModel()
 {
     Entity           = new Constituent();
     SearchEntity     = new Constituent();
     TaxItems         = new List <TaxItem>();
     EventCommand     = "Search";
     IsDetailsVisible = false;
     SelectedTaxYear  = DateTime.Now.Year - 1;
     AcceptTerms      = false;
 }
示例#19
0
 public ActionResult Edit([Bind(Include = "ConstituentID,IsPerson,FirstName,LastName,Address,City,State,ZipCode,Country,Email,PhoneNumber,ReferralMethod,ActiveSince,AgeRange,Notes")] Constituent constituent)
 {
     if (ModelState.IsValid)
     {
         db.Entry(constituent).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(constituent));
 }
示例#20
0
        // DELETE api/values/5
        public void Delete(int id)
        {
            Constituent constituent = db.Constituents.Find(id);

            if (constituent != null)
            {
                db.Constituents.Remove(constituent);
                db.SaveChanges();
            }
        }
        public ActionResult UpdateConstituent(Constituent model)
        {
            if (ModelState.IsValid)
            {
                unitOfWork.Entry(model).State = EntityState.Modified;
                unitOfWork.Complete();
                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Index", "Constituents"));
        }
示例#22
0
        private bool ValidateSearch(Constituent entity)
        {
            ValidationErrors.Clear();

            if (entity.FinderNumber == null)
            {
                ValidationErrors.Add(new KeyValuePair <string, string>("Supporter Id", "Supporter Id is required."));
            }

            return(ValidationErrors.Count == 0);
        }
        public ActionResult CreateConstituent(Constituent constituent)
        {
            if (ModelState.IsValid)
            {
                unitOfWork.Constituents.Add(constituent);
                unitOfWork.Complete();

                return(RedirectToAction("Dashboard", "Admins"));
            }

            return(View(constituent));
        }
示例#24
0
    public Constituent GetPrimaryConstituent()
    {
        Constituent primaryConstituent = null;

        foreach (var constituent in Constituents)
        {
            if (primaryConstituent == null || constituent.Amount > primaryConstituent.Amount)
            {
                primaryConstituent = constituent;
            }
        }
        return(primaryConstituent);
    }
示例#25
0
        public Constituent Search(Constituent entity)
        {
            using (var db = new AppContext())
            {
                var ret = db.Constituents.Include(t => t.TaxItems).FirstOrDefault(c => c.LookupId == entity.LookupId && c.Zipcode.Substring(0, 5).Equals(entity.Zipcode.Substring(0, 5)));
                ValidateSearch(entity);
                if (ret == null)
                {
                    ValidationErrors.Add(new KeyValuePair <string, string>("Not Found", "No tax records found for given supporter."));
                }

                return(ret);
            }
        }
示例#26
0
        // GET: /Constituent/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Constituent constituent = db.Constituents.Find(id);

            if (constituent == null)
            {
                return(HttpNotFound());
            }
            return(View(constituent));
        }
示例#27
0
        public Constituent Search(Constituent entity)
        {
            using (var db = new DataContext())
            {
                var ret = db.Constituents.Include("TaxItems").FirstOrDefault(c => c.FinderNumber == entity.FinderNumber);
                ValidateSearch(entity);
                if (ret == null)
                {
                    ValidationErrors.Add(new KeyValuePair <string, string>("Not Found", "No tax records found for given supporter."));
                }

                return(ret);
            }
        }
示例#28
0
        private double LoadFromSurfaceWater(Constituent c, List <FunctionalUnitConstituentProvider> functionalUnitProviders)
        {
            double total = 0.0;

            foreach (FunctionalUnitConstituentProvider fup in functionalUnitProviders)
            {
                FunctionalUnitConstituentOutput relevantOutput =
                    fup.RecordedData.List
                    .FirstOrDefault(co => co.Constituent == c) as FunctionalUnitConstituentOutput;

                total += relevantOutput.TotalFlowMass;
            }
            return(total * UnitConversion.SECONDS_IN_ONE_DAY);
        }
        public string CheckStatus(Constituent constituent)
        {
            string   status;
            int      timeLapsed;
            DateTime current = DateTime.Now;

            if (constituent.DonationStatus == null)
            {
                var logs = unitOfWork.Logs.GetCallLogs().Where(x => x.ConstituentID == constituent.ConstituentID);

                if (logs != null && logs.Count() > 0)
                {
                    var      lastGift     = logs.Last();
                    DateTime lastGiftDate = (DateTime)lastGift.DateOfCall;
                    timeLapsed = ((current.Year - lastGiftDate.Year) * 12) + current.Month - lastGiftDate.Month;

                    if (timeLapsed >= 12 && timeLapsed <= 15)
                    {
                        status = "At Risk";
                    }
                    else if (timeLapsed > 15 && timeLapsed <= 24)
                    {
                        status = "Lapsing";
                    }
                    else if (timeLapsed > 24 && timeLapsed <= 60)
                    {
                        status = "Lapsed";
                    }
                    else if (timeLapsed > 60)
                    {
                        status = "Lost";
                    }
                    else
                    {
                        status = "Retained";
                    }
                }
                else
                {
                    status = "Never Donor";
                }
            }
            else
            {
                status = constituent.DonationStatus;
            }

            return(status);
        }
        public ActionResult ProposeConstituentChanges(int?id)
        {
            // If the id parameter is null, give a "bad request" error
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            // The parameter wasn't null -- try and find the associated Constituent in the proposed changes table first
            ProposedConstituentsChanges changes = unitOfWork.Changes.Find(x => x.ConstituentID == id).FirstOrDefault();

            if (changes == null)
            {
                // Nothing in the proposed changes table yet -- look them up in the main Constituents table
                Constituent constituent = unitOfWork.Constituents.Find(x => x.ConstituentID == id).FirstOrDefault();

                // If there wasn't a match with this id, give a "not found" error
                if (constituent == null)
                {
                    return(HttpNotFound());
                }

                // Found a match in the main Constituents table -- return the view with the Constituent
                return(PartialView("_ProposeChanges", constituent));
            }

            // If we got this far, we found a match in the proposed changes table -- copy values over to send to the view
            var existingConstituent = new Constituent
            {
                ConstituentID         = changes.ConstituentID,
                PrimaryAddressee      = changes.PrimaryAddressee,
                PreferredAddressLine1 = changes.PreferredAddressLine1,
                PreferredAddressLine2 = changes.PreferredAddressLine2,
                PreferredAddressLine3 = changes.PreferredAddressLine3,
                PreferredCity         = changes.PreferredCity,
                PreferredState        = changes.PreferredState,
                PreferredZIP          = changes.PreferredZIP,
                PhoneNumber           = changes.PhoneNumber,
                MobilePhoneNumber     = changes.MobilePhoneNumber,
                AlternatePhoneNumber  = changes.AlternatePhoneNumber,
                Deceased               = changes.Deceased,
                DonationStatus         = changes.DonationStatus,
                UniversityRelationship = changes.UniversityRelationship,
                CallPriority           = changes.CallPriority
            };

            // Return the view with the Constituent
            return(PartialView("_ProposeChanges", existingConstituent));
        }
        public ActionResult Save(ConstituentInputModel constituent)
        {
            var constituentToSave = new Constituent();

            constituentToSave.Name = new ConstituentName()
            {
                Id = constituent.NameId,
                FirstName = constituent.FirstName,
                MiddleName = constituent.MiddleName,
                LastName = constituent.LastName,
                CreatedBy = constituent.CreatedBy,
                CreatedDateTime = constituent.CreatedDateTime,
                PreferedName = "temp",
                Salutation = new SalutationType() { Id = 1 }

            };
            constituentToSave.HouseName = constituent.HouseName;
            constituentToSave.BranchName = new BranchType { Id = constituent.BranchName };
            constituentToSave.Gender = constituent.Gender;
            constituentToSave.MaritialStatus = constituent.MaritalStatus;
            constituentToSave.HasExpired = constituent.HasExpired;
            constituentToSave.IsRegistered = constituent.IsRegistered;
            constituentToSave.CreatedDateTime = constituent.CreatedDateTime;
            constituentToSave.CreatedBy = constituent.CreatedBy;
            constituentToSave.BornOn = constituent.BornOn;
            constituentToSave.Id =  Convert.ToInt32(Session["constituentId"]);

            var mapper = new AutoDataContractMapper();
            var constituentData = new ConstituentData();
            mapper.Map(constituentToSave, constituentData);

            ConstituentData data = HttpHelper.Put(string.Format(serviceBaseUri + "/Constituents/{0}", Session["constituentId"]), constituentData);
            var savedConstituent = new Constituent();
            mapper.Map(data, savedConstituent);
            return PartialView(GetConstituent());
        }
 private Constituent GetConstituent(string id)
 {
     var data = HttpHelper.Get<ConstituentData>(serviceBaseUri + "/Constituents/"+id);
     var constituent = new Constituent();
     mapper.Map(data, constituent);
     return constituent;
 }
示例#33
0
        public static void InitialiseModelsForConstituent(RiverSystemScenario s, Constituent c)
        {
            ConstituentsManagement cm = s.Network.ConstituentsManagement;
            
            cm.Elements.OfType<NetworkElementConstituentData>().ForEachItem(d =>
            {
                if (d.Data == null)
                    d.Data = new ConstituentsModel();

                d.Data.GetModel(c, DefaultSourceSinkType(d));
            });

            foreach (var catchment in s.Network.Catchments.OfType<Catchment>())
            {
                foreach (var functionalUnit in catchment.FunctionalUnits.OfType<StandardFunctionalUnit>())
                {
                    InitialiseConstituentSources(s,catchment, functionalUnit,c);
                }
            }
        }
示例#34
0
        private static void InitialiseConstituentSources(RiverSystemScenario scenario, Catchment catchment, StandardFunctionalUnit fu, Constituent constituent)
        {
            ConstituentsManagement cm = scenario.Network.ConstituentsManagement;
            FunctionalUnitConstituentData model = cm.GetConstituentData<CatchmentElementConstituentData>(catchment).GetFunctionalUnitData(fu);
            ConstituentContainer constituentModel = model.ConstituentModels.SingleOrDefault(f => f.Constituent.Equals(constituent));
            if (constituentModel == null)
            {
                constituentModel = new ConstituentContainer(constituent);
                model.ConstituentModels.Add(constituentModel);
            }

            if (constituentModel.ConstituentSources.Count > 0) return;

            var defaultConstituentSource = scenario.SystemConfiguration.ConstituentSources.First(cs => cs.IsDefault);
            constituentModel.ConstituentSources.Add(new ConstituentSourceContainer(defaultConstituentSource, new NilConstituent(), new PassThroughFilter()));
        }
        private Constituent GetConstituent()
        {
            var constituentId = Convert.ToInt32(Session["constituentId"]);
            var constituentData = HttpHelper.Get<ConstituentData>(string.Format(serviceBaseUri+"/Constituents/{0}", constituentId));

            mapper = new AutoDataContractMapper();
            var constituent = new Constituent();
            mapper.Map(constituentData, constituent);
            constituent.MaritialStatusString = constituent.MaritialStatus == 1 ? "Married" : "Single";
            return constituent;
        }