public ComputedTrainingAward(TrainingAward award)
     : this()
 {
     this.Member    = award.Member;
     this.Course    = award.Course;
     this.Roster    = award.Roster;
     this.Expiry    = award.Expiry;
     this.Completed = award.Completed;
 }
 public ComputedTrainingAward(TrainingAward award)
     : this()
 {
     this.Member = award.Member;
     this.Course = award.Course;
     this.Roster = award.Roster;
     this.Expiry = award.Expiry;
     this.Completed = award.Completed;
 }
Esempio n. 3
0
        static void Main(string[] args)
        {
            using (var db = new KcsarContext())
              {
            DateTime cutoff = DateTime.Today.AddYears(1);

            var course = db.TrainingCourses.Single(f => f.DisplayName == "HAM License");

            var hams = db.PersonContact.Where(f => f.Type == "hamcall")
              .Where(f => ! f.Person.ComputedAwards.Any(g => g.Expiry > cutoff && g.Course.Id == course.Id))
              .Select(f => new { Member = f.Person, Call = f.Value })
              .OrderBy(f => f.Member.LastName).ThenBy(f => f.Member.FirstName).ToArray();

            foreach (var ham in hams)
            {
              Console.WriteLine(ham.Call);
              var lic = GetLicense(ham.Call);

              if (lic == null)
              {
            Console.WriteLine("!! No license found");
            continue;
              }

              if (lic.Name.StartsWith(ham.Member.ReverseName, StringComparison.OrdinalIgnoreCase))
              {
            // probably a match
            Console.WriteLine("Grant HAM to {0}, effective {1:yyyy-MM-dd}, expires {2:yyyy-MM-dd}", ham.Member.FullName, lic.Issued, lic.Expires);
            TrainingAward ta = new TrainingAward { Completed = lic.Issued, Course = course, Expiry = lic.Expires, Member = ham.Member, metadata = "Via FCC: " + lic.Url, LastChanged = DateTime.Now, ChangedBy = "HamFromFCC" };
            db.TrainingAward.Add(ta);
            db.SaveChanges();
            db.RecalculateTrainingAwards(ham.Member.Id);
            db.SaveChanges();
              }
              else
              {
            Console.WriteLine("Can't match names: {0} :: {1}", lic.Name, ham.Member.ReverseName);
              }
            }
              }
        }
        private Member NewEsarTrainee_Internal(FormCollection fields)
        {
            Member m = new Member();
              TryUpdateModel(m, new[] { "FirstName", "LastName", "MiddleName", "BirthDate", "SheriffApp", "Gender" });
              this.db.Members.Add(m);

              SarUnit esar = (from u in this.db.Units where u.DisplayName == "ESAR" select u).First();
              UnitStatus status = (from s in this.db.UnitStatusTypes where s.Unit.Id == esar.Id && s.StatusName == "trainee" select s).First();

              if (!string.IsNullOrEmpty(fields["Street"]))
              {
            PersonAddress address = new PersonAddress { Person = m, Type = PersonAddressType.Mailing };
            TryUpdateModel(address, new[] { "Street", "City", "State" });

            GeographyServices.RefineAddressWithGeography(address);
            if (address.Quality < 8)
            {
              try
              {
            ModelState.SetModelValue("Zip", new ValueProviderResult(fields["Zip"], fields["Zip"], CultureInfo.CurrentUICulture));
            // This is supposed to be UpdateModel, not TryUpdate
            UpdateModel(address, new[] { "Zip" });
              }
              catch (Exception)
              {
            ModelState.AddModelError("Zip", "Can't locate address. ZIP is required");
              }
            }

            this.db.PersonAddress.Add(address);
              }

              foreach (string contact in new[] { "Home", "Work", "Cell" })
              {
            if (string.IsNullOrEmpty(fields[contact + "Phone"]))
            {
              continue;
            }

            ModelState.SetModelValue(contact + "Phone", new ValueProviderResult(fields[contact + "Phone"], fields[contact + "Phone"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "phone", Subtype = contact.ToLower(), Value = fields[contact + "Phone"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["HamCall"]))
              {
            ModelState.SetModelValue("HamCall", new ValueProviderResult(fields["HamCall"], fields["HamCall"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "hamcall", Value = fields["HamCall"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["Email"]))
              {
            ModelState.SetModelValue("Email", new ValueProviderResult(fields["Email"], fields["Email"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email"] };
            this.db.PersonContact.Add(pc);
              }

              if (!string.IsNullOrEmpty(fields["Email2"]))
              {
            ModelState.SetModelValue("Email2", new ValueProviderResult(fields["Email2"], fields["Email2"], CultureInfo.CurrentUICulture));
            PersonContact pc = new PersonContact { Person = m, Type = "email", Value = fields["Email2"] };
            this.db.PersonContact.Add(pc);
              }

              DateTime courseDate = new DateTime(1900, 1, 1);
              ModelState.SetModelValue("CourseDate", new ValueProviderResult(fields["CourseDate"], fields["CourseDate"], CultureInfo.CurrentUICulture));
              if (string.IsNullOrEmpty(fields["CourseDate"]))
              {
            ModelState.AddModelError("CourseDate", "Required");
            return null;
              }
              else if (!DateTime.TryParse(fields["CourseDate"], out courseDate))
              {
            ModelState.AddModelError("CourseDate", "Unknown format. Try yyyy-mm-dd");
            return null;
              }
              courseDate = courseDate.Date;

              UnitMembership um = new UnitMembership { Person = m, Status = status, Unit = esar, Activated = courseDate };
              this.db.UnitMemberships.Add(um);

              TrainingCourse courseA = (from tc in this.db.TrainingCourses where tc.DisplayName == "Course A" select tc).First();
              DateTime nextDate = courseDate.AddDays(1);

              Training t = (from trn in this.db.Trainings where trn.StartTime >= courseDate && trn.StartTime < nextDate && trn.Title == "Course A" select trn).FirstOrDefault();
              if (t == null)
              {
            t = new Training();
            t.OfferedCourses.Add(courseA);
            t.StartTime = courseDate.AddHours(19);
            t.StopTime = courseDate.AddHours(21);
            t.County = "King";
            t.Title = "Course A";
            t.Location = "Eastside Fire Headquarters";
            this.db.Trainings.Add(t);
              }

              TrainingRoster tr = new TrainingRoster { Person = m, TimeIn = courseDate.AddHours(18), TimeOut = courseDate.AddHours(22) };
              this.db.TrainingRosters.Add(tr);
              t.Roster.Add(tr);

              TrainingAward ta = new TrainingAward();
              ta.Completed = courseDate.AddHours(21);
              if ((courseA.ValidMonths ?? 0) > 0)
              {
            ta.Expiry = ta.Completed.AddMonths(courseA.ValidMonths.Value);
              }
              ta.Course = courseA;
              ta.Member = m;
              this.db.TrainingAward.Add(ta);
              tr.TrainingAwards.Add(ta);
              return m;
        }
        public TrainingAwardView Post([FromBody]TrainingAwardView view)
        {
            log.DebugFormat("POST {0} {1} {2}", Request.RequestUri, User.Identity.Name, JsonConvert.SerializeObject(view));
              if (!User.IsInRole("cdb.trainingeditors")) ThrowAuthError();
              //     if (!Permissions.IsAdmin && !Permissions.IsSelf(view.MemberId) && !Permissions.IsMembershipForPerson(view.MemberId)) return GetAjaxLoginError<MemberContactView>(null);
              List<SubmitError> errors = new List<SubmitError>();

              if (view.Member.Id == Guid.Empty)
              {
            ThrowSubmitErrors(new[] { new SubmitError { Error = Strings.API_Required, Property = "Member" } });
              }

              TrainingAward model;
              model = (from a in db.TrainingAward.Include("Member").Include("Course") where a.Id == view.ReferenceId select a).FirstOrDefault();

              if (model == null)
              {
            model = new TrainingAward();
            model.Member = db.Members.Where(f => f.Id == view.Member.Id).FirstOrDefault();
            if (model.Member == null)
            {
              errors.Add(new SubmitError { Property = "Member", Error = Strings.API_NotFound });
              ThrowSubmitErrors(errors);
            }
            db.TrainingAward.Add(model);
              }

             //     try
             //     {
            model.UploadsPending = (view.PendingUploads > 0);

            DateTime completed;
            if (string.IsNullOrWhiteSpace(view.Completed))
            {
              errors.Add(new SubmitError { Property = "Completed", Error = Strings.API_Required });
            }
            else if (!DateTime.TryParse(view.Completed, out completed))
            {
              errors.Add(new SubmitError { Error = Strings.API_InvalidDate, Property = "Completed" });
            }
            else
            {
              model.Completed = completed;
            }

            if (model.metadata != view.Comments) model.metadata = view.Comments;

            if (model.Member.Id != view.Member.Id)
            {
              throw new InvalidOperationException("Don't know how to change member yet");
            }

            if (view.Course.Id == null)
            {
              errors.Add(new SubmitError { Error = Strings.API_Required, Id = new[] { view.ReferenceId }, Property = "Course" });
            }
            else if (model.Course == null || model.Course.Id != view.Course.Id)
            {
              model.Course = (from c in db.TrainingCourses where c.Id == view.Course.Id select c).First();
            }

            switch (view.ExpirySrc)
            {
              case "default":
            model.Expiry = model.Course.ValidMonths.HasValue ? model.Completed.AddMonths(model.Course.ValidMonths.Value) : (DateTime?)null;
            break;
              case "custom":
            if (!string.IsNullOrWhiteSpace(view.Expires))
            {
              model.Expiry = DateTime.Parse(view.Expires);
            }
            else
            {
              errors.Add(new SubmitError { Error = Strings.API_TrainingRecord_CustomExpiryRequired, Property = "Expiry", Id = new[] { view.ReferenceId } });
            }
            break;
              case "never":
            model.Expiry = null;
            break;
            }

            // Documentation required.
            if (!model.UploadsPending && string.IsNullOrWhiteSpace(model.metadata))
            {
              errors.Add(new SubmitError { Error = Strings.API_TrainingRecord_DocumentationRequired, Property = BaseApiController.ModelRootNodeName });
            }

            // Prevent duplicate records
            if (db.TrainingAward.Where(f => f.Id != model.Id && f.Completed == model.Completed && f.Course.Id == model.Course.Id && f.Member.Id == model.Member.Id).Count() > 0)
            {
              ThrowSubmitErrors(new[] { new SubmitError { Error = Strings.API_TrainingRecord_Duplicate, Id = new[] { model.Id }, Property = BaseApiController.ModelRootNodeName } });
            }

            if (errors.Count == 0)
            {
              db.SaveChanges();
              db.RecalculateTrainingAwards(model.Member.Id);
              db.SaveChanges();
            }

            view.ReferenceId = model.Id;
            view.Course.Title = model.Course.DisplayName;
              //}
              //catch (RuleViolationsException ex)
              //{
              //  foreach (RuleViolation v in ex.Errors)
              //  {
              //    errors.Add(new SubmitError { Error = v.ErrorMessage, Property = v.PropertyName, Id = new[] { v.EntityKey } });
              //  }
              //  // throw new InvalidOperationException("TODO: report errors");
              //}

              //if (errors.Count > 0)
              //{
              //  ThrowSubmitErrors(errors);
              //}

              return view;
        }
        public TrainingRecord Post([FromBody] TrainingRecord view)
        {
            //TODO - Move validation errors to API way of doing things
            log.DebugFormat("POST {0} {1} {2}", Request.RequestUri, User.Identity.Name, JsonConvert.SerializeObject(view));
            if (!User.IsInRole("cdb.trainingeditors"))
            {
                ThrowAuthError();
            }
            //     if (!Permissions.IsAdmin && !Permissions.IsSelf(view.MemberId) && !Permissions.IsMembershipForPerson(view.MemberId)) return GetAjaxLoginError<MemberContactView>(null);
            //List<SubmitError> errors = new List<SubmitError>();

            //if (view.Member.Id == Guid.Empty)
            //{
            //    ThrowSubmitErrors(new [] { new SubmitError { Error = Strings.API_Required, Property = "Member" } });
            //}

            Data.TrainingAward model;
            model = (from a in db.TrainingAward.Include("Member").Include("Course") where a.Id == view.ReferenceId select a).FirstOrDefault();

            if (model == null)
            {
                model        = new Data.TrainingAward();
                model.Member = db.Members.Where(f => f.Id == view.Member.Id).FirstOrDefault();
                //if (model.Member == null)
                //{
                //    errors.Add(new SubmitError { Property = "Member", Error = Strings.API_NotFound });
                //    ThrowSubmitErrors(errors);
                //}
                db.TrainingAward.Add(model);
            }

            //try
            //{
            model.UploadsPending = (view.PendingUploads > 0);

            DateTime completed;

            if (string.IsNullOrWhiteSpace(view.Completed))
            {
                //                    errors.Add(new SubmitError { Property = "Completed", Error = Strings.API_Required });
            }
            else if (!DateTime.TryParse(view.Completed, out completed))
            {
                //                    errors.Add(new SubmitError { Error = Strings.API_InvalidDate, Property = "Completed" });
            }
            else
            {
                model.Completed = completed;
            }

            if (model.metadata != view.Comments)
            {
                model.metadata = view.Comments;
            }

            if (model.Member.Id != view.Member.Id)
            {
                throw new InvalidOperationException("Don't know how to change member yet");
            }

            if (view.Course.Id == null)
            {
                //                  errors.Add(new SubmitError { Error = Strings.API_Required, Id = new[] { view.ReferenceId }, Property = "Course" });
            }
            else if (model.Course == null || model.Course.Id != view.Course.Id)
            {
                model.Course = (from c in db.TrainingCourses where c.Id == view.Course.Id select c).First();
            }

            switch (view.ExpirySrc)
            {
            case "default":
                model.Expiry = model.Course.ValidMonths.HasValue ? model.Completed.AddMonths(model.Course.ValidMonths.Value) : (DateTime?)null;
                break;

            case "custom":
                if (!string.IsNullOrWhiteSpace(view.Expires))
                {
                    model.Expiry = DateTime.Parse(view.Expires);
                }
                else
                {
                    //                        errors.Add(new SubmitError { Error = Strings.API_TrainingRecord_CustomExpiryRequired, Property = "Expiry", Id = new[] { view.ReferenceId } });
                }
                break;

            case "never":
                model.Expiry = null;
                break;
            }

            // Documentation required.
            if (!model.UploadsPending && string.IsNullOrWhiteSpace(model.metadata))
            {
                //              errors.Add(new SubmitError { Error = Strings.API_TrainingRecord_DocumentationRequired, Property = BaseApiController.ModelRootNodeName });
            }

            // Prevent duplicate records
            if (db.TrainingAward.Where(f => f.Id != model.Id && f.Completed == model.Completed && f.Course.Id == model.Course.Id && f.Member.Id == model.Member.Id).Count() > 0)
            {
                //            ThrowSubmitErrors(new [] { new SubmitError { Error = Strings.API_TrainingRecord_Duplicate, Id = new[] { model.Id }, Property = BaseApiController.ModelRootNodeName }});
            }

            //if (errors.Count == 0)
            //{
            db.SaveChanges();
            Data.TrainingRecordCalculator calculator = new Data.TrainingRecordCalculator(db);
            calculator.Calculate(model.Member.Id);
            db.SaveChanges();
            //}

            view.ReferenceId  = model.Id;
            view.Course.Title = model.Course.DisplayName;
            //}
            //catch (RuleViolationsException ex)
            //{
            //  foreach (RuleViolation v in ex.Errors)
            //  {
            //    errors.Add(new SubmitError { Error = v.ErrorMessage, Property = v.PropertyName, Id = new[] { v.EntityKey } });
            //  }
            //  // throw new InvalidOperationException("TODO: report errors");
            //}

            //if (errors.Count > 0)
            //{
            //  ThrowSubmitErrors(errors);
            //}

            return(view);
        }