/// <summary>
        /// Create a New PlanCycle and attach it to the given plan year.
        /// </summary>
        /// <param name="cycle">with Name and Description</param>
        /// <param name="rtpYearId">ID of plan year</param>
        /// <returns>ID of created Plan Cycle</returns>
        public int CreateRtpPlanCycle(DRCOG.Domain.ViewModels.RTP.PlanCycle cycle, int rtpYearId)
        {
            using (var db = new Models.TRIPSEntities())
            {
                // there can be only one cycle in this plan year with a status of New
                var stId = db.StatusTypes.First(st => st.StatusType1 == "Cycle Status").StatusTypeID;
                var newId = db.Status.First(s => s.StatusTypeID == stId && s.Status1 == "New").StatusID;

                // see if there is already a new plan cycle for this RTP Year
                var previousNew = db.TimePeriodCycles.FirstOrDefault(tpc => tpc.TimePeriodId == rtpYearId && tpc.Cycle.statusId == newId);
                if (previousNew != null)
                {
                    throw new Exception("There is already a New Plan Cycle");
                }

                byte listOrder = 0;
                int? priorCycleId = null;

                // if this is not the first cycle in the time period, attach it to the end
                // of the two lists - ListOrder and priorCycleId
                var planCycles = db.TimePeriodCycles.Where(tpc => tpc.TimePeriodId == rtpYearId);
                if (planCycles.Count() > 0)
                {
                    // find last cycle in this time period. "last" means highest ListOrder.
                    var lo = planCycles.Max(tpc => tpc.ListOrder);
                    var prior = planCycles.First(tpc => tpc.ListOrder == lo);
                    priorCycleId = prior.CycleId;
                    listOrder = lo ?? 0;
                }

                // find largest ListOrder in these cycles and add 1
                ++listOrder;

                var mcycle = new Models.Cycle()
                {
                    cycle1 = cycle.Name,
                    Description = cycle.Description,
                    statusId = newId,
                    priorCycleId = priorCycleId
                };
                db.Cycles.AddObject(mcycle);

                var mtpc = new Models.TimePeriodCycle()
                {
                    Cycle = mcycle,
                    TimePeriodId = (short)rtpYearId,
                    ListOrder = listOrder
                };
                db.TimePeriodCycles.AddObject(mtpc);

                db.SaveChanges();

                return mcycle.id;
            }
        }
 /// <summary>
 /// Delete RTP Plan Cycle from RTP Year and then from Cycles. Not currently used in production,
 /// but useful for testing.
 /// </summary>
 /// <param name="id"></param>
 public void DeleteRtpPlanCycle(int id)
 {
     using (var db = new Models.TRIPSEntities())
     {
         var cycle = db.Cycles.FirstOrDefault(c => c.id == id);
         if (cycle == null)
         {
             throw new Exception("No such RTP Plan Cycle");
         }
         var refs = db.TimePeriodCycles.Where(tpc => tpc.CycleId == id);
         foreach (var t in refs)
         {
             db.TimePeriodCycles.DeleteObject(t);
         }
         db.Cycles.DeleteObject(cycle);
         db.SaveChanges();
     }
 }
        public int RtpCreatePlan(RtpCreatePlanRequest request)
        {
            using (var db = new Models.TRIPSEntities())
            {
                // create a time period for the plan
                var tp = new Models.TimePeriod()
                {
                    TimePeriodTypeID = (int)Enums.TimePeriodType.PlanYear,
                    TimePeriod1 = request.PlanName
                };
                db.TimePeriods.AddObject(tp);

                // create pieces of the plan, with a status of Pending
                var pi = new Models.ProgramInstance()
                {
                    StatusId = (int)Enums.RtpTimePeriodStatus.Pending,
                    ProgramID = 2,
                    TimePeriod = tp
                };
                db.ProgramInstances.AddObject(pi);

                var rtpi = new Models.RTPProgramInstance()
                {
                    ProgramInstance = pi,
                    TimePeriod = tp
                };
                db.RTPProgramInstances.AddObject(rtpi);

                db.SaveChanges();
                Logger.Debug("created RTP Program Instance " + rtpi.RTPProgramID.ToString() + ", " + rtpi.TimePeriodID.ToString());

                // we had to save the changes to get IDs for the created objects,
                // since the TimePeriodID is part of a compound key.

                // TODO: get active plan
                int activePlan = 78;

                // copy the sponsors from the current plan
                foreach (var sponsor in db.RTPProgramInstanceSponsors.Where(r => r.TimePeriodID == activePlan))
                {
                    // first create a base ProgramInstanceSponsor
                    var pis = new Models.ProgramInstanceSponsor()
                    {
                        ProgramID = sponsor.RTPProgramID,
                        SponsorID = sponsor.SponsorID,
                        TimePeriodID = tp.TimePeriodID
                    };
                    db.ProgramInstanceSponsors.AddObject(pis);

                    var copy = new Models.RTPProgramInstanceSponsor()
                    {
                        EmailDate = sponsor.EmailDate,
                        FormPrintedDate = sponsor.FormPrintedDate,
                        ReadyDate = sponsor.ReadyDate,
                        RTPProgramID = sponsor.RTPProgramID,
                        SponsorID = sponsor.SponsorID,
                        TimePeriodID = tp.TimePeriodID
                    };
                    db.RTPProgramInstanceSponsors.AddObject(copy);
                }

                // create a pending cycle
                var mcycle = new Models.Cycle()
                {
                    cycle1 = request.CycleName,
                    Description = request.CycleDescription,
                    statusId = (int)Enums.RTPCycleStatus.Pending,
                    priorCycleId = null
                };
                db.Cycles.AddObject(mcycle);

                var mtpc = new Models.TimePeriodCycle()
                {
                    Cycle = mcycle,
                    TimePeriodId = tp.TimePeriodID,
                    ListOrder = 1
                };
                db.TimePeriodCycles.AddObject(mtpc);
                db.SaveChanges();
                Logger.Debug("copied sponsors from RTP Plan " + activePlan.ToString());
                Logger.Debug("created RTP Plan Cycle " + mcycle.id.ToString());

                return tp.TimePeriodID;
            }
        }
        /// <summary>
        /// Update the TIP status.
        /// </summary>
        /// <param name="model"></param>
        public void UpdateTipStatus(DRCOG.Domain.Models.TipStatusModel model)
        {
            using (var db = new Models.TRIPSEntities())
            {
                var p = db.ProgramInstances.Single(pi => pi.TimePeriodID == model.TimePeriodId);
                var tp = db.TimePeriods.Single(t => t.TimePeriodID == model.TimePeriodId);
                var tpi = db.TIPProgramInstances.Single(pi => pi.TimePeriodID == model.TimePeriodId && pi.TIPProgramID == p.ProgramID);
                //p.ClosingDate = ?
                p.Current = model.IsCurrent;
                p.Notes = model.Notes;
                p.Pending = model.IsPending;
                p.Previous = model.IsPrevious;

                tpi.AdoptionDate = model.Adoption;
                tpi.GovernorApprovalDate = model.GovernorApproval;
                tpi.PublicHearingDate = model.PublicHearing;
                tpi.ShowDelayDate = model.ShowDelayDate;
                tpi.USDOTApprovalDate = model.USDOTApproval;
                tpi.USEPAApprovalDate = model.EPAApproval;

                var fs = new FundingIncrementSetter(db, tp);
                fs.SetFundingIncrement(model.FundingIncrement_Year_1, "Year 1");
                fs.SetFundingIncrement(model.FundingIncrement_Year_2, "Year 2");
                fs.SetFundingIncrement(model.FundingIncrement_Year_3, "Year 3");
                fs.SetFundingIncrement(model.FundingIncrement_Year_4, "Year 4");
                fs.SetFundingIncrement(model.FundingIncrement_Year_5, "Year 5");
                fs.SetFundingIncrement(model.FundingIncrement_Year_6, "Year 6");
                fs.SetFundingIncrement(model.FundingIncrement_Years_4_6, "Years 4-6");
                fs.SetFundingIncrement(model.FundingIncrement_Years_5_6, "Years 5-6");

                db.SaveChanges();
            }
        }
 public void UpdateRtpPlanCycle(DRCOG.Domain.ViewModels.RTP.PlanCycle cycle)
 {
     using (var db = new Models.TRIPSEntities())
     {
         var found = db.Cycles.FirstOrDefault(c => c.id == cycle.Id);
         if (found == null)
         {
             throw new Exception("No such RTP Plan Cycle");
         }
         found.cycle1 = cycle.Name;
         found.Description = cycle.Description;
         db.SaveChanges();
     }
 }
 /// <summary>
 /// Add projects to given Survey. Currently, this must be the latest Survey and must be in 
 /// a New status. 
 /// </summary>
 /// <param name="surveyId"></param>
 /// <param name="projects"></param>
 public void SurveyAmendProjects(int surveyId, IEnumerable<int> projects)
 {
     using (var db = new Models.TRIPSEntities())
     {
         foreach (var pid in projects)
         {
             // Due to crappy data, we expect some operations to fail, but we
             // want to do as much as possible.
             try
             {
                 Logger.Debug("Copy SurveyProjectVersion " + pid.ToString());
                 var ov = new System.Data.Objects.ObjectParameter("NewProjectVersionId", typeof(int));
                 var result = db.SurveyCopyProject(pid, surveyId, null, ov);
                 var npid = ov.Value;
                 Logger.Debug("created SurveyProjectVersion " + npid.ToString());
             }
             catch (Exception ex)
             {
                 var message = string.Format("SurveyAmendProjects failed for id {0}", pid);
                 Logger.WarnException(message, ex);
             }
         }
         db.SaveChanges();
     }
 }
 /// <summary>
 /// Update the XML data in an RTP Project LRS record.
 /// </summary>
 /// <param name="lrs">data</param>
 public void RtpUpdateLrs(DRCOG.Domain.Models.LRS lrs)
 {
     var model = CompileLrs(lrs);
     using (var db = new Models.TRIPSEntities())
     {
         var record = db.LRS.First(l => l.Id == lrs.Id);
         record.Data = model.Data;
         db.SaveChanges();
     }
 }
        /// <summary>
        /// Copy the given projects into the given RTP Plan Year and mark them Pending.
        /// </summary>
        /// <remarks>seems identical to RtpAmendProjects. question the VersionStatus.</remarks>
        /// <param name="rtpPlanYearId">ID of the RTP Plan Year</param>
        /// <param name="projects">list of RTP ProjectVersion IDs</param>
        public void RtpRestoreProjects(int rtpPlanYearId, IEnumerable<int> projects)
        {
            using (var db = new Models.TRIPSEntities())
            {
                var pc = RtpAssurePendingCycle(db, rtpPlanYearId);
                Logger.Debug("RTP Pending Cycle is " + pc.id.ToString());
                db.SaveChanges();

                foreach (var pid in projects)
                {
                    // Due to crappy data, we expect some operations to fail, but we
                    // want to do as much as possible.
                    try
                    {
                        Logger.Debug("Copy RTPProjectVersion " + pid.ToString());
                        var result = db.RtpCopyProject(pid, null, rtpPlanYearId, pc.id);
                        var npid = result.First().RTPProjectVersionID;
                        Logger.Debug("created RTPProjectVersion " + npid.ToString());

                        // get the newly created RTPProjectVersion
                        var npv = db.RTPProjectVersions.First(p => p.RTPProjectVersionID == npid);

                        // set status to Pending
                        npv.AmendmentStatusID = (int)Enums.RTPAmendmentStatus.Pending;

                        // TODO: this seems to be the only difference
                        npv.VersionStatusID = (int)Enums.RTPVersionStatus.Pending;
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format("RtpRestoreProjects failed for id {0}", pid);
                        Logger.WarnException(message, ex);
                    }
                }

                db.SaveChanges();
            }
        }
 public void RtpDeleteLrs(int id)
 {
     using (var db = new Models.TRIPSEntities())
     {
         var lrs = db.LRS.FirstOrDefault(l => id == l.Id);
         if (lrs != null)
         {
             db.LRS.DeleteObject(lrs);
             db.SaveChanges();
         }
     }
 }
 public int RtpCreateLrs(DRCOG.Domain.Models.LRS lrs)
 {
     var model = CompileLrs(lrs);
     using (var db = new Models.TRIPSEntities())
     {
         db.LRS.AddObject(model);
         db.SaveChanges();
         return model.Id;
     }
 }
        /// <summary>
        /// Mark the projects Adopted, mark the Pending Cycle Active, and
        /// mark the Active Cycle Inactive.
        /// </summary>
        /// <param name="rtpPlanYearId">ID of the RTP Plan Year</param>
        /// <param name="projects">list of RTP ProjectVersion IDs</param>
        public void RtpAdoptProjects(int rtpPlanYearId, IEnumerable<int> projects)
        {
            using (var db = new Models.TRIPSEntities())
            {
                var pc = RtpAssurePendingCycle(db, rtpPlanYearId);
                Logger.Debug("RTP Pending Cycle is " + pc.id.ToString());
                var tp = db.TimePeriods.First(t => t.TimePeriodID == rtpPlanYearId);

                foreach (var pid in projects)
                {
                    // Due to crappy data, we expect some operations to fail, but we
                    // want to do as much as possible.
                    try
                    {
                        var npv = db.RTPProjectVersions.First(p => p.RTPProjectVersionID == pid);

                        // set statuses (stati?)
                        npv.AmendmentStatusID = (int)Enums.RTPAmendmentStatus.Amended;
                        npv.VersionStatusID = (int)Enums.RTPVersionStatus.Active;

                        // TODO: set status of previous version, if any
                        //var ppv = db.RTPProjectVersions.First(p => p.RTPProjectVersionID == npv.Pre);
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format("RtpAdoptProjects failed for id {0}", pid);
                        Logger.WarnException(message, ex);
                    }
                }

                /// Set the current Active Cycle (if any) to Inactive.
                /// Set the current Pending Cycle to Active.
                var ac = tp.TimePeriodCycles.FirstOrDefault(tpc => tpc.Cycle.statusId == (int)Enums.RTPCycleStatus.Active);
                if (ac != null)
                {
                    ac.Cycle.statusId = (int)Enums.RTPCycleStatus.Inactive;
                }
                pc.statusId = (int)Enums.RTPCycleStatus.Active;

                db.SaveChanges();
            }
        }