Exemple #1
0
        public Period Add(Period period)
        {
            if (period.StartDate.Date <= DateTime.Now.Date)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(period.StartDate),
                          period.StartDate.Date,
                          "Cannot start a period that is less than or equal to the current date.");
            }

            if (period.EndDate.Date <= period.StartDate.Date)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(period.EndDate),
                          period.StartDate.Date,
                          "Period cannot have an end date that is less than or equal to the start date.");
            }

            using (IUnitOfWork unitOfWork = context.CreateUnitOfWork())
            {
                int newPeriodId = periodRepo.Insert(period);
                if (newPeriodId <= 0)
                {
                    throw new FailedOperationException("Failed to insert Period.", period);
                }

                if (period.IsOpen)
                {
                    Period oldPeriod = periodRepo
                                       .Find(x => x.IsOpen)
                                       .FirstOrDefault(y => y.PeriodId != newPeriodId);

                    if (oldPeriod != null)
                    {
                        oldPeriod.IsOpen = false;
                        if (!periodRepo.Update(oldPeriod))
                        {
                            throw new FailedOperationException("Failed to update Period.", oldPeriod);
                        }
                    }

                    IEnumerable <Assignment> assignments = assignmentRepo.Get(null, null, oldPeriod.PeriodId);
                    foreach (Assignment assignment in assignments)
                    {
                        assignment.PeriodId          = newPeriodId;
                        assignment.AttemptCount      = 0;
                        assignment.LastAttemptedBy   = null;
                        assignment.LastAttemptedDate = DateTime.MinValue;
                        assignment.Status            = "Not Called";
                        assignment.Notes             = null;

                        if (assignmentRepo.Insert(assignment) <= 0)
                        {
                            throw new FailedOperationException("Failed to insert Assignment.", assignment);
                        }
                    }
                }

                unitOfWork.SaveChanges();
                return(periodRepo.GetById(newPeriodId));
            }
        }