Ejemplo n.º 1
0
        private static IReportingPeriod <UnitOfTime> MakeMoreGranular(
            this IReportingPeriod <UnitOfTime> reportingPeriod,
            UnitOfTimeGranularity granularity)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component."));
            }

            if (granularity == UnitOfTimeGranularity.Invalid)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Invalid)}"));
            }

            if (granularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Unbounded)}"));
            }

            if (reportingPeriod.GetUnitOfTimeGranularity().IsAsGranularOrMoreGranularThan(granularity))
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} is as granular or more granular than {nameof(granularity)}"));
            }

            var moreGranularStart = reportingPeriod.Start.MakeMoreGranular(granularity);
            var moreGranularEnd   = reportingPeriod.End.MakeMoreGranular(granularity);
            var result            = new ReportingPeriod <UnitOfTime>(moreGranularStart.Start, moreGranularEnd.End);

            return(result);
        }
        private static bool IsEqual(
            ReportingPeriod <T> left,
            IReportingPeriod <UnitOfTime> right)
        {
            if (ReferenceEquals(left, right))
            {
                return(true);
            }

            if (ReferenceEquals(left, null) || ReferenceEquals(right, null))
            {
                return(false);
            }

            if (right.GetType().GetGenericTypeDefinition() != typeof(ReportingPeriod <>))
            {
                return(false);
            }

            try
            {
                var result = (left.Start.CompareTo(right.Start) == 0) && (left.End.CompareTo(right.End) == 0);
                return(result);
            }
            catch (ArgumentException)
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets the matching datapoints from a timeseries.
        /// </summary>
        /// <typeparam name="T">The type of value of the datapoints.</typeparam>
        /// <param name="timeseries">The timeseries.</param>
        /// <param name="reportingPeriod">The reporting period to search for.</param>
        /// <param name="reportingPeriodComparison">OPTIONAL value that determines how the reporting period of the datapoints in <paramref name="timeseries"/> are compared to <paramref name="reportingPeriod"/>.  DEFAULT is to match when the reporting periods are equal, ignoring granularity.</param>
        /// <returns>
        /// The matching datapoints or an empty collection if there are none.
        /// If using <see cref="ReportingPeriodComparison.IsEqualToIgnoringGranularity"/> or <see cref="ReportingPeriodComparison.Contains"/>
        /// then a single datapoint will be returned at most.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="timeseries"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="NotSupportedException"><paramref name="reportingPeriodComparison"/> is not supported.</exception>
        public static IReadOnlyList <Datapoint <T> > GetMatchingDatapoints <T>(
            this Timeseries <T> timeseries,
            ReportingPeriod reportingPeriod,
            ReportingPeriodComparison reportingPeriodComparison = ReportingPeriodComparison.IsEqualToIgnoringGranularity)
        {
            if (timeseries == null)
            {
                throw new ArgumentNullException(nameof(timeseries));
            }

            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            IReadOnlyList <Datapoint <T> > result;

            if (reportingPeriodComparison == ReportingPeriodComparison.IsEqualToIgnoringGranularity)
            {
                var mostGranularReportingPeriod = reportingPeriod.ToMostGranular();

                result = timeseries.Datapoints.Where(_ => _.ReportingPeriod.ToMostGranular().Equals(mostGranularReportingPeriod)).ToList();
            }
            else if (reportingPeriodComparison == ReportingPeriodComparison.Contains)
            {
                result = timeseries.Datapoints.Where(_ => (_.ReportingPeriod.GetUnitOfTimeKind() == reportingPeriod.GetUnitOfTimeKind()) && _.ReportingPeriod.Contains(reportingPeriod)).ToList();
            }
            else
            {
                throw new NotSupportedException(Invariant($"This {nameof(ReportingPeriodComparison)} is not supported: {reportingPeriodComparison}."));
            }

            return(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Determines if two reporting periods overlap.
        /// For example, the following reporting periods have an overlap: 1Q2017-3Q2017 and 3Q2017-4Q2017.
        /// </summary>
        /// <remarks>
        /// If the endpoint of one reporting period is the same as the endpoint
        /// of the second reporting period, the reporting periods are deemed to overlap.
        /// </remarks>
        /// <param name="reportingPeriod1">A reporting period.</param>
        /// <param name="reportingPeriod2">A second reporting period to check for overlap against the first reporting period.</param>
        /// <returns>
        /// true if there is an overlap between the reporting periods; false otherwise.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod1"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod2"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod1"/> cannot be compared against <paramref name="reportingPeriod2"/> because they represent different <see cref="UnitOfTime.UnitOfTimeKind"/>.</exception>
        public static bool HasOverlapWith(
            this ReportingPeriod reportingPeriod1,
            ReportingPeriod reportingPeriod2)
        {
            if (reportingPeriod1 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod1));
            }

            if (reportingPeriod2 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod2));
            }

            if (reportingPeriod1.GetUnitOfTimeKind() != reportingPeriod2.GetUnitOfTimeKind())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod1)} cannot be compared against {nameof(reportingPeriod2)} because they represent different {nameof(UnitOfTimeKind)}"));
            }

            var result =
                reportingPeriod1.Contains(reportingPeriod2.Start) ||
                reportingPeriod1.Contains(reportingPeriod2.End) ||
                reportingPeriod2.Contains(reportingPeriod1.Start) ||
                reportingPeriod2.Contains(reportingPeriod1.End);

            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Determines if a reporting period is greater than and adjacent to a second reporting period.
        /// </summary>
        /// <remarks>
        /// For this method to return true, the first reporting period's Start must be greater than the
        /// second reporting period's End, and they must be adjacent (subtracting one unit in the same granularity
        /// to the first reporting period's Start should make it equal to the second reporting period's End)
        /// For example, 3Q2017-4Q2017 is greater than and adjacent to 1Q2017-2Q2017.
        /// For example, 3Q2017-4Q2017 is NOT greater than 1Q2017-3Q2017, because they overlap.
        /// For example, 4Q2017-4Q2017 is NOT adjacent to 1Q2017-2Q2017, because there's a gap of 3Q2017.
        /// </remarks>
        /// <param name="reportingPeriod1">A reporting period to check if greater than and adjacent to a second reporting period.</param>
        /// <param name="reportingPeriod2">The second reporting period.</param>
        /// <returns>
        /// true if the first reporting period is greater than and adjacent to the second reporting period; false, otherwise.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod1"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod2"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod1"/> cannot be compared against <paramref name="reportingPeriod2"/> because they represent different <see cref="UnitOfTime.UnitOfTimeKind"/>.</exception>
        public static bool IsGreaterThanAndAdjacentTo(
            this ReportingPeriod reportingPeriod1,
            ReportingPeriod reportingPeriod2)
        {
            if (reportingPeriod1 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod1));
            }

            if (reportingPeriod2 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod2));
            }

            if (reportingPeriod1.GetUnitOfTimeKind() != reportingPeriod2.GetUnitOfTimeKind())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod1)} cannot be compared against {nameof(reportingPeriod2)} because they represent different {nameof(UnitOfTimeKind)}."));
            }

            var mostGranularReportingPeriod1 = reportingPeriod1.ToMostGranular();
            var mostGranularReportingPeriod2 = reportingPeriod2.ToMostGranular();

            var result = mostGranularReportingPeriod1.Start.Plus(-1).Equals(mostGranularReportingPeriod2.End);

            return(result);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the distinct units-of-time contained within a specified reporting period.
        /// For example, a reporting period of 2Q2017-4Q2017, contains 2Q2017, 3Q2017, and 4Q2017.
        /// </summary>
        /// <remarks>
        /// The endpoints are considered units within the reporting period.
        /// </remarks>
        /// <param name="reportingPeriod">The reporting period.</param>
        /// <returns>
        /// The units-of-time contained within the specified reporting period.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod"/> <see cref="ReportingPeriod.Start"/> and/or <see cref="ReportingPeriod.End"/> is unbounded.</exception>
        public static IReadOnlyList <UnitOfTime> GetUnitsWithin(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} {nameof(reportingPeriod.Start)} and/or {nameof(reportingPeriod.End)} is unbounded."));
            }

            var allUnits    = new List <UnitOfTime>();
            var currentUnit = reportingPeriod.Start;

            do
            {
                allUnits.Add(currentUnit);

                currentUnit = currentUnit.Plus(1);
            }while (currentUnit <= reportingPeriod.End);

            return(allUnits);
        }
        public Datapoint <T> DeepCloneWithReportingPeriod(ReportingPeriod reportingPeriod)
        {
            var result = new Datapoint <T>(
                reportingPeriod,
                this.Value == null ? default : this.Value.DeepClone());

            return(result);
        }
        /// <inheritdoc />
        public IReportingPeriod <T> Clone()
        {
            var startClone = this.Start.Clone <T>();
            var endClone   = this.End.Clone <T>();
            var result     = new ReportingPeriod <T>(startClone, endClone);

            return(result);
        }
        /// <summary>
        /// Splits a reporting period into units-of-time by a specified granularity.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period to split.</param>
        /// <param name="granularity">The granularity to use when splitting.</param>
        /// <param name="overflowStrategy">
        /// OPTIONAL strategy to use when <paramref name="granularity"/> is less granular than
        /// the <paramref name="reportingPeriod"/> and, when splitting, the resulting units-of-time
        /// cannot be aligned with the start and end of the reporting period.
        /// For example, splitting March 2015 - February 2017 by year results in 2015,2016,2017,
        /// however only 2016 is fully contained within the reporting period.
        /// The reporting period is missing January 2015 - February 2015 and March 2017 to December 2017.
        /// DEFAULT is to throw when this happens.
        /// </param>
        /// <returns>
        /// Returns the units-of-time that split the specified reporting period by the specified granularity.
        /// The units-of-time will always be in the specified granularity, regardless of the granularity
        /// of the reporting period (e.g. splitting a fiscal month reporting period using yearly granularity
        /// will return <see cref="FiscalYear"/> objects).
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod"/> has an <see cref="UnitOfTimeGranularity.Unbounded"/> component.</exception>
        /// <exception cref="ArgumentException"><paramref name="granularity"/> is <see cref="UnitOfTimeGranularity.Invalid"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="granularity"/> is <see cref="UnitOfTimeGranularity.Unbounded"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="overflowStrategy"/> is not <see cref="OverflowStrategy.ThrowOnOverflow"/>.</exception>
        /// <exception cref="InvalidOperationException">There was some overflow when splitting.</exception>
        public static IReadOnlyList <UnitOfTime> Split(
            this ReportingPeriod reportingPeriod,
            UnitOfTimeGranularity granularity,
            OverflowStrategy overflowStrategy = OverflowStrategy.ThrowOnOverflow)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component."));
            }

            if (granularity == UnitOfTimeGranularity.Invalid)
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(granularity)}' == '{UnitOfTimeGranularity.Invalid}'"), (Exception)null);
            }

            if (granularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(granularity)}' == '{UnitOfTimeGranularity.Unbounded}'"), (Exception)null);
            }

            if ((overflowStrategy != OverflowStrategy.ThrowOnOverflow) && (overflowStrategy != OverflowStrategy.DiscardOverflow))
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(overflowStrategy)}' is not one of {{{OverflowStrategy.ThrowOnOverflow}, {OverflowStrategy.DiscardOverflow}}}."), (Exception)null);
            }

            var reportingPeriodGranularity = reportingPeriod.GetUnitOfTimeGranularity();

            IReadOnlyList <UnitOfTime> result;

            if (reportingPeriodGranularity == granularity)
            {
                result = reportingPeriod.GetUnitsWithin();
            }
            else if (reportingPeriodGranularity.IsLessGranularThan(granularity))
            {
                result = reportingPeriod.MakeMoreGranular(granularity).GetUnitsWithin();
            }
            else
            {
                var lessGranularReportingPeriod = reportingPeriod.MakeLessGranular(
                    granularity,
                    throwOnMisalignment: overflowStrategy == OverflowStrategy.ThrowOnOverflow);

                result = lessGranularReportingPeriod.GetUnitsWithin();

                if (overflowStrategy == OverflowStrategy.DiscardOverflow)
                {
                    result = result.Where(reportingPeriod.Contains).ToList();
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the kind of the unit-of-time used in a reporting period.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period.</param>
        /// <returns>
        /// The kind of the unit-of-time used in the specified reporting period.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        public static UnitOfTimeKind GetUnitOfTimeKind(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            var result = reportingPeriod.Start.UnitOfTimeKind;

            return(result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="Datapoint{T}"/> class.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period of the datapoint.</param>
        /// <param name="value">The value of the datapoint.</param>
        public Datapoint(
            ReportingPeriod reportingPeriod,
            T value)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            this.ReportingPeriod = reportingPeriod;
            this.Value           = value;
        }
        /// <summary>
        /// Creates a reporting period from a unit-of-time.
        /// </summary>
        /// <param name="unitOfTime">The unit-of-time to use in the reporting period.</param>
        /// <returns>
        /// A reporting period where the Start and End components are equal to the specified unit-of-time.
        /// </returns>
        public static ReportingPeriod ToReportingPeriod(
            this UnitOfTime unitOfTime)
        {
            if (unitOfTime == null)
            {
                throw new ArgumentNullException(nameof(unitOfTime));
            }

            var result = new ReportingPeriod(unitOfTime, unitOfTime);

            return(result);
        }
        /// <summary>
        /// Serializes a <see cref="ReportingPeriod"/> to a string.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period to serialize.</param>
        /// <returns>
        /// Gets a string representation of a reporting period that can be deserialized
        /// into the same reporting period.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        public static string SerializeToString(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            var result = Invariant($"{reportingPeriod.Start.SerializeToSortableString()},{reportingPeriod.End.SerializeToSortableString()}");

            return(result);
        }
        /// <summary>
        /// Deserializes a <see cref="ReportingPeriod"/> from a string.
        /// </summary>
        /// <param name="reportingPeriod">The serialized reporting period string to deserialize.</param>
        /// <returns>
        /// Gets a reporting period deserialized from it's string representation.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod"/> is whitespace.</exception>
        /// <exception cref="InvalidOperationException">Cannot deserialize string; it is not valid reporting period.</exception>
        public static ReportingPeriod DeserializeFromString(
            this string reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (string.IsNullOrWhiteSpace(reportingPeriod))
            {
                throw new ArgumentException(Invariant($"'{nameof(reportingPeriod)}' is white space"));
            }

            var errorMessage = Invariant($"Cannot deserialize reporting period; the specified string is malformed: {reportingPeriod}.");

            var tokens = reportingPeriod.Split(',');

            if (tokens.Length != 2)
            {
                throw new InvalidOperationException(errorMessage);
            }

            if (tokens.Any(string.IsNullOrWhiteSpace))
            {
                throw new InvalidOperationException(errorMessage);
            }

            UnitOfTime start, end;

            try
            {
                start = tokens[0].DeserializeFromSortableString <UnitOfTime>();
                end   = tokens[1].DeserializeFromSortableString <UnitOfTime>();
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException(errorMessage);
            }

            ReportingPeriod result;

            try
            {
                result = new ReportingPeriod(start, end);
            }
            catch (ArgumentException ex)
            {
                throw new InvalidOperationException(errorMessage, ex);
            }

            return(result);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Determines if the reporting period has a component with unbounded granularity.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period.</param>
        /// <returns>
        /// true if one or both components of the reporting period has unbounded granularity; otherwise false.
        /// </returns>
        public static bool HasComponentWithUnboundedGranularity(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            var result = (reportingPeriod.Start.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded) ||
                         (reportingPeriod.End.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded);

            return(result);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Converts the the specified reporting period into the most
        /// granular possible, but equivalent, reporting period.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period to operate on.</param>
        /// <returns>
        /// A reporting period that addresses the same set of time as <paramref name="reportingPeriod"/>,
        /// but is the most granular version possible of that reporting period.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        public static IReportingPeriod <UnitOfTime> ToMostGranular(
            this IReportingPeriod <UnitOfTime> reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            var mostGranularStart = reportingPeriod.Start.ToMostGranular();
            var mostGranularEnd   = reportingPeriod.End.ToMostGranular();
            var result            = new ReportingPeriod <UnitOfTime>(mostGranularStart.Start, mostGranularEnd.End);

            return(result);
        }
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException"><paramref name="fiscalYear"/> is null.</exception>
        public override ReportingPeriod <CalendarDay> GetReportingPeriodForFiscalYear(
            FiscalYear fiscalYear)
        {
            if (fiscalYear == null)
            {
                throw new ArgumentNullException(nameof(fiscalYear));
            }

            var januaryFirst        = new CalendarDay(fiscalYear.Year, MonthOfYear.January, DayOfMonth.One);
            var decemberThirtyFirst = new CalendarDay(fiscalYear.Year, MonthOfYear.December, DayOfMonth.ThirtyOne);
            var result = new ReportingPeriod <CalendarDay>(januaryFirst, decemberThirtyFirst);

            return(result);
        }
        public override ReportingPeriod <CalendarDay> GetReportingPeriodForFiscalYear(
            FiscalYear fiscalYear)
        {
            if (fiscalYear == null)
            {
                throw new ArgumentNullException(nameof(fiscalYear));
            }

            var firstDayInYear = this.GetAccountingYearEndDate(fiscalYear.Year - 1).AddDays(1).ToCalendarDay();
            var lastDayInYear  = this.GetAccountingYearEndDate(fiscalYear.Year).ToCalendarDay();
            var result         = new ReportingPeriod <CalendarDay>(firstDayInYear, lastDayInYear);

            return(result);
        }
        /// <inheritdoc />
        /// <exception cref="ArgumentNullException"><paramref name="fiscalYear"/> is null.</exception>
        public override ReportingPeriod <CalendarDay> GetReportingPeriodForFiscalYear(
            FiscalYear fiscalYear)
        {
            if (fiscalYear == null)
            {
                throw new ArgumentNullException(nameof(fiscalYear));
            }

            var lastDayInEndingMonth = DateTime.DaysInMonth(fiscalYear.Year, (int)this.LastMonthInFiscalYear);
            var lastDayInFiscalYear  = new DateTime(fiscalYear.Year, (int)this.LastMonthInFiscalYear, lastDayInEndingMonth);
            var firstDayInFiscalYear = lastDayInFiscalYear.AddDays(1).AddYears(-1);
            var result = new ReportingPeriod <CalendarDay>(firstDayInFiscalYear.ToCalendarDay(), lastDayInFiscalYear.ToCalendarDay());

            return(result);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the granularity of the unit-of-time used in a reporting period.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period.</param>
        /// <returns>
        /// The granularity of the unit-of-time used in the specified reporting period.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod"/> <see cref="ReportingPeriod.Start"/> and <see cref="ReportingPeriod.End"/> has different granularity.</exception>
        public static UnitOfTimeGranularity GetUnitOfTimeGranularity(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.Start.UnitOfTimeGranularity != reportingPeriod.End.UnitOfTimeGranularity)
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} Start and End has different granularity."));
            }

            var result = reportingPeriod.Start.UnitOfTimeGranularity;

            return(result);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Clones a reporting period while adjusting the start or end of the reporting period, or both.
        /// </summary>
        /// <typeparam name="TReportingPeriod">The type of reporting period to return.</typeparam>
        /// <param name="reportingPeriod">The reporting period to clone.</param>
        /// <param name="component">The component(s) of the reporting period to adjust.</param>
        /// <param name="unitsToAdd">The number of units to add when adjusting the reporting period component.  Use negative numbers to subtract units.</param>
        /// <param name="granularityOfUnitsToAdd">The granularity of the units to add to the specified reporting period component(s).  Must be as or less granular than the reporting period component (e.g. can add CalendarYear to a CalendarQuarter, but not vice-versa).</param>
        /// <returns>A clone of the specified reporting period with the specified adjustment made to the start or end of the reporting period, or both.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="component"/> is <see cref="ReportingPeriodComponent.Invalid"/>.</exception>
        /// <exception cref="ArgumentException">Cannot add or subtract from a unit-of-time whose granularity is <see cref="UnitOfTimeGranularity.Unbounded"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="granularityOfUnitsToAdd"/> is <see cref="UnitOfTimeGranularity.Invalid"/>.</exception>
        /// <exception cref="ArgumentException"><paramref name="granularityOfUnitsToAdd"/> is <see cref="UnitOfTimeGranularity.Unbounded"/>.  Cannot add units of that granularity.</exception>
        /// <exception cref="ArgumentException"><paramref name="granularityOfUnitsToAdd"/> is more granular than the reporting period component.  Only units that are as granular or less granular than a unit-of-time can be added to that unit-of-time.</exception>
        /// <exception cref="InvalidOperationException">The adjustment has caused the <see cref="ReportingPeriod{T}.Start"/> to be greater than <see cref="ReportingPeriod{T}.End"/>.</exception>
        /// <exception cref="InvalidOperationException">The adjusted reporting period cannot be converted into a <typeparamref name="TReportingPeriod"/>.</exception>
        public static TReportingPeriod CloneWithAdjustment <TReportingPeriod>(
            this IReportingPeriod <UnitOfTime> reportingPeriod,
            ReportingPeriodComponent component,
            int unitsToAdd,
            UnitOfTimeGranularity granularityOfUnitsToAdd)
            where TReportingPeriod : class, IReportingPeriod <UnitOfTime>
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (component == ReportingPeriodComponent.Invalid)
            {
                throw new ArgumentException(Invariant($"{nameof(component)} is {nameof(ReportingPeriodComponent.Invalid)}"));
            }

            var start = reportingPeriod.Start;
            var end   = reportingPeriod.End;

            if ((component == ReportingPeriodComponent.Start) || (component == ReportingPeriodComponent.Both))
            {
                start = start.Plus(unitsToAdd, granularityOfUnitsToAdd);
            }

            if ((component == ReportingPeriodComponent.End) || (component == ReportingPeriodComponent.Both))
            {
                end = end.Plus(unitsToAdd, granularityOfUnitsToAdd);
            }

            try
            {
                var result = new ReportingPeriod <UnitOfTime>(start, end).Clone <TReportingPeriod>();
                return(result);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw new InvalidOperationException("The adjustment has caused the Start of the reporting period to be greater than the End of the reporting period.", ex);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Determines if a unit-of-time is contained within a reporting period.
        /// For example, 2Q2017 is contained within a reporting period of 1Q2017-4Q2017.
        /// </summary>
        /// <remarks>
        /// If the unit-of-time is equal to one of the endpoints of the reporting period,
        /// that unit-of-time is considered to be within the reporting period.
        /// </remarks>
        /// <param name="reportingPeriod">The reporting period.</param>
        /// <param name="unitOfTime">The unit-of-time to check against a reporting period.</param>
        /// <returns>
        /// true if the unit-of-time is contained within the reporting period; false otherwise.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="unitOfTime"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="unitOfTime"/> cannot be compared against <paramref name="reportingPeriod"/> because they represent different <see cref="UnitOfTime.UnitOfTimeKind"/>.</exception>
        public static bool Contains(
            this ReportingPeriod reportingPeriod,
            UnitOfTime unitOfTime)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (unitOfTime == null)
            {
                throw new ArgumentNullException(nameof(unitOfTime));
            }

            if (unitOfTime.UnitOfTimeKind != reportingPeriod.GetUnitOfTimeKind())
            {
                throw new ArgumentException(Invariant($"{nameof(unitOfTime)} cannot be compared against {nameof(reportingPeriod)} because they represent different {nameof(UnitOfTimeKind)}."));
            }

            var result = reportingPeriod.Contains(new ReportingPeriod(unitOfTime, unitOfTime));

            return(result);
        }
Ejemplo n.º 23
0
        public static ICollection <IReportingPeriod <T> > CreatePermutations <T>(
            this IReportingPeriod <T> reportingPeriod,
            int maxUnitsInAnyReportingPeriod)
            where T : UnitOfTime
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component."));
            }

            if (maxUnitsInAnyReportingPeriod < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(maxUnitsInAnyReportingPeriod), "max units in any reporting period is <= 0");
            }

            var allUnits            = reportingPeriod.GetUnitsWithin();
            var allReportingPeriods = new List <IReportingPeriod <T> >();

            for (int unitOfTimeIndex = 0; unitOfTimeIndex < allUnits.Count; unitOfTimeIndex++)
            {
                for (int numberOfUnits = 1; numberOfUnits <= maxUnitsInAnyReportingPeriod; numberOfUnits++)
                {
                    if (unitOfTimeIndex + numberOfUnits - 1 < allUnits.Count)
                    {
                        var subReportingPeriod = new ReportingPeriod <T>(allUnits[unitOfTimeIndex], allUnits[unitOfTimeIndex + numberOfUnits - 1]);
                        allReportingPeriods.Add(subReportingPeriod);
                    }
                }
            }

            return(allReportingPeriods);
        }
        public static IReadOnlyCollection <ReportingPeriod> CreatePermutations(
            this ReportingPeriod reportingPeriod,
            int maxUnitsInAnyReportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component."));
            }

            if (maxUnitsInAnyReportingPeriod < 1)
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(maxUnitsInAnyReportingPeriod)}' < '{1}'"), (Exception)null);
            }

            var allUnits = reportingPeriod.GetUnitsWithin();

            var result = new List <ReportingPeriod>();

            for (int unitOfTimeIndex = 0; unitOfTimeIndex < allUnits.Count; unitOfTimeIndex++)
            {
                for (int numberOfUnits = 1; numberOfUnits <= maxUnitsInAnyReportingPeriod; numberOfUnits++)
                {
                    if (unitOfTimeIndex + numberOfUnits - 1 < allUnits.Count)
                    {
                        var subReportingPeriod = new ReportingPeriod(allUnits[unitOfTimeIndex], allUnits[unitOfTimeIndex + numberOfUnits - 1]);
                        result.Add(subReportingPeriod);
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Converts the the specified reporting period into the least
        /// granular possible, but equivalent, reporting period.
        /// </summary>
        /// <param name="reportingPeriod">The reporting period to operate on.</param>
        /// <returns>
        /// A reporting period that addresses the same set of time as <paramref name="reportingPeriod"/>,
        /// but is the least granular version possible of that reporting period.
        /// Any reporting period with one unbounded and one bounded component will be returned
        /// as-is (e.g. Unbounded to 12/31/2017 will not be converted to Unbounded to CalendarYear 2017).
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod"/> is null.</exception>
        public static ReportingPeriod ToLeastGranular(
            this ReportingPeriod reportingPeriod)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            ReportingPeriod result;

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                result = reportingPeriod.DeepClone();
            }
            else
            {
                var targetGranularity = reportingPeriod.GetUnitOfTimeGranularity().OneNotchLessGranular();
                if (targetGranularity == UnitOfTimeGranularity.Unbounded)
                {
                    result = reportingPeriod.DeepClone();
                }
                else
                {
                    try
                    {
                        result = reportingPeriod.MakeLessGranular(targetGranularity).ToLeastGranular();
                    }
                    catch (InvalidOperationException)
                    {
                        result = reportingPeriod.DeepClone();
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 26
0
        private static IReportingPeriod <UnitOfTime> MakeLessGranular(
            this IReportingPeriod <UnitOfTime> reportingPeriod,
            UnitOfTimeGranularity granularity)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component"));
            }

            if (granularity == UnitOfTimeGranularity.Invalid)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Invalid)}"));
            }

            if (granularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Unbounded)}"));
            }

            var reportingPeriodGranularity = reportingPeriod.GetUnitOfTimeGranularity();

            if (reportingPeriodGranularity.IsAsGranularOrLessGranularThan(granularity))
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} is as granular or less granular than {nameof(granularity)}"));
            }

            IReportingPeriod <UnitOfTime> lessGranularReportingPeriod;
            var unitOfTimeKind = reportingPeriod.GetUnitOfTimeKind();

            if (reportingPeriodGranularity == UnitOfTimeGranularity.Day)
            {
                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startAsCalendarDay = reportingPeriod.Start as CalendarDay;

                    // ReSharper disable once PossibleNullReferenceException
                    var startMonth = new CalendarMonth(startAsCalendarDay.Year, startAsCalendarDay.MonthOfYear);
                    if (startMonth.GetFirstCalendarDay() != startAsCalendarDay)
                    {
                        throw new InvalidOperationException("Cannot convert a calendar day reporting period to a calendar month reporting period when the reporting period start time is not the first day of a month.");
                    }

                    var endAsCalendarDay = reportingPeriod.End as CalendarDay;

                    // ReSharper disable once PossibleNullReferenceException
                    var endMonth = new CalendarMonth(endAsCalendarDay.Year, endAsCalendarDay.MonthOfYear);
                    if (endMonth.GetLastCalendarDay() != endAsCalendarDay)
                    {
                        throw new InvalidOperationException("Cannot convert a calendar day reporting period to a calendar month reporting period when the reporting period end time is not the last day of a month.");
                    }

                    lessGranularReportingPeriod = new ReportingPeriod <CalendarMonth>(startMonth, endMonth);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else if (reportingPeriodGranularity == UnitOfTimeGranularity.Month)
            {
                var startAsMonth = reportingPeriod.Start as IHaveAMonth;
                var endAsMonth   = reportingPeriod.End as IHaveAMonth;

                var quarterByStartMonth = new Dictionary <int, QuarterNumber>
                {
                    { 1, QuarterNumber.Q1 },
                    { 4, QuarterNumber.Q2 },
                    { 7, QuarterNumber.Q3 },
                    { 10, QuarterNumber.Q4 },
                };

                var quarterByEndMonth = new Dictionary <int, QuarterNumber>
                {
                    { 3, QuarterNumber.Q1 },
                    { 6, QuarterNumber.Q2 },
                    { 9, QuarterNumber.Q3 },
                    { 12, QuarterNumber.Q4 },
                };

                // ReSharper disable once PossibleNullReferenceException
                if (!quarterByStartMonth.ContainsKey((int)startAsMonth.MonthNumber))
                {
                    throw new InvalidOperationException("Cannot convert a monthly reporting period to a quarterly reporting period when the reporting period start time is not the first month of a recognized quarter.");
                }

                // ReSharper disable once PossibleNullReferenceException
                if (!quarterByEndMonth.ContainsKey((int)endAsMonth.MonthNumber))
                {
                    throw new InvalidOperationException("Cannot convert a monthly reporting period to a quarterly reporting period when the reporting period end time is not the last month of a recognized quarter.");
                }

                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startQuarter = new CalendarQuarter(startAsMonth.Year, quarterByStartMonth[(int)startAsMonth.MonthNumber]);
                    var endQuarter   = new CalendarQuarter(endAsMonth.Year, quarterByEndMonth[(int)endAsMonth.MonthNumber]);
                    lessGranularReportingPeriod = new ReportingPeriod <CalendarQuarter>(startQuarter, endQuarter);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    var startQuarter = new FiscalQuarter(startAsMonth.Year, quarterByStartMonth[(int)startAsMonth.MonthNumber]);
                    var endQuarter   = new FiscalQuarter(endAsMonth.Year, quarterByEndMonth[(int)endAsMonth.MonthNumber]);
                    lessGranularReportingPeriod = new ReportingPeriod <FiscalQuarter>(startQuarter, endQuarter);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    var startQuarter = new GenericQuarter(startAsMonth.Year, quarterByStartMonth[(int)startAsMonth.MonthNumber]);
                    var endQuarter   = new GenericQuarter(endAsMonth.Year, quarterByEndMonth[(int)endAsMonth.MonthNumber]);
                    lessGranularReportingPeriod = new ReportingPeriod <GenericQuarter>(startQuarter, endQuarter);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else if (reportingPeriodGranularity == UnitOfTimeGranularity.Quarter)
            {
                var startAsQuarter = reportingPeriod.Start as IHaveAQuarter;
                var endAsQuarter   = reportingPeriod.End as IHaveAQuarter;

                // ReSharper disable once PossibleNullReferenceException
                if (startAsQuarter.QuarterNumber != QuarterNumber.Q1)
                {
                    throw new InvalidOperationException(
                              "Cannot convert a quarterly reporting period to a yearly reporting period when the reporting period start time is not Q1.");
                }

                // ReSharper disable once PossibleNullReferenceException
                if (endAsQuarter.QuarterNumber != QuarterNumber.Q4)
                {
                    throw new InvalidOperationException(
                              "Cannot convert a quarterly reporting period to a yearly reporting period when the reporting period end is not Q4.");
                }

                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startYear = new CalendarYear(startAsQuarter.Year);
                    var endYear   = new CalendarYear(endAsQuarter.Year);
                    lessGranularReportingPeriod = new ReportingPeriod <CalendarYear>(startYear, endYear);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    var startYear = new FiscalYear(startAsQuarter.Year);
                    var endYear   = new FiscalYear(endAsQuarter.Year);
                    lessGranularReportingPeriod = new ReportingPeriod <FiscalYear>(startYear, endYear);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    var startYear = new GenericYear(startAsQuarter.Year);
                    var endYear   = new GenericYear(endAsQuarter.Year);
                    lessGranularReportingPeriod = new ReportingPeriod <GenericYear>(startYear, endYear);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else
            {
                throw new NotSupportedException("This granularity is not supported: " + reportingPeriodGranularity);
            }

            if (lessGranularReportingPeriod.GetUnitOfTimeGranularity() == granularity)
            {
                return(lessGranularReportingPeriod);
            }

            var result = MakeLessGranular(lessGranularReportingPeriod, granularity);

            return(result);
        }
Ejemplo n.º 27
0
        private static IReportingPeriod <UnitOfTime> MakeMoreGranular(
            this UnitOfTime unitOfTime,
            UnitOfTimeGranularity granularity)
        {
            if (unitOfTime == null)
            {
                throw new ArgumentNullException(nameof(unitOfTime));
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentException(Invariant($"{nameof(unitOfTime)} granularity is {nameof(UnitOfTimeGranularity.Unbounded)}"));
            }

            if (granularity == UnitOfTimeGranularity.Invalid)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Invalid)}"));
            }

            if (granularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentException(Invariant($"{nameof(granularity)} is {nameof(UnitOfTimeGranularity.Unbounded)}"));
            }

            if (unitOfTime.UnitOfTimeGranularity.IsAsGranularOrMoreGranularThan(granularity))
            {
                throw new ArgumentException(Invariant($"{nameof(unitOfTime)} is as granular or more granular than {nameof(granularity)}"));
            }

            IReportingPeriod <UnitOfTime> moreGranularReportingPeriod;

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Year)
            {
                var unitOfTimeAsYear = unitOfTime as IHaveAYear;
                var startQuarter     = QuarterNumber.Q1;
                var endQuarter       = QuarterNumber.Q4;

                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new CalendarQuarter(unitOfTimeAsYear.Year, startQuarter), new CalendarQuarter(unitOfTimeAsYear.Year, endQuarter));
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new FiscalQuarter(unitOfTimeAsYear.Year, startQuarter), new FiscalQuarter(unitOfTimeAsYear.Year, endQuarter));
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new GenericQuarter(unitOfTimeAsYear.Year, startQuarter), new GenericQuarter(unitOfTimeAsYear.Year, endQuarter));
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
                }
            }
            else if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Quarter)
            {
                var unitOfTimeAsQuarter = unitOfTime as IHaveAQuarter;

                // ReSharper disable once PossibleNullReferenceException
                var startMonth = ((((int)unitOfTimeAsQuarter.QuarterNumber) - 1) * 3) + 1;
                var endMonth   = ((int)unitOfTimeAsQuarter.QuarterNumber) * 3;

                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new CalendarMonth(unitOfTimeAsQuarter.Year, (MonthOfYear)startMonth), new CalendarMonth(unitOfTimeAsQuarter.Year, (MonthOfYear)endMonth));
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new FiscalMonth(unitOfTimeAsQuarter.Year, (MonthNumber)startMonth), new FiscalMonth(unitOfTimeAsQuarter.Year, (MonthNumber)endMonth));
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(new GenericMonth(unitOfTimeAsQuarter.Year, (MonthNumber)startMonth), new GenericMonth(unitOfTimeAsQuarter.Year, (MonthNumber)endMonth));
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
                }
            }
            else if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Month)
            {
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var calendarUnitOfTime = unitOfTime as CalendarUnitOfTime;
                    moreGranularReportingPeriod = new ReportingPeriod <UnitOfTime>(calendarUnitOfTime.GetFirstCalendarDay(), calendarUnitOfTime.GetLastCalendarDay());
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    throw new NotSupportedException("The Fiscal kind cannot be made more granular than Month.");
                }
                else if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    throw new NotSupportedException("The Generic kind cannot be made more granular than Month.");
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
                }
            }
            else
            {
                throw new NotSupportedException("This granularity is not supported: " + unitOfTime.UnitOfTimeGranularity);
            }

            if (moreGranularReportingPeriod.GetUnitOfTimeGranularity() == granularity)
            {
                return(moreGranularReportingPeriod);
            }

            var result = moreGranularReportingPeriod.MakeMoreGranular(granularity);

            return(result);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Determines if a reporting period is contained within another reporting period.
        /// For example, 1Q2017-3Q2017 contains 2Q2017-3Q2017.
        /// </summary>
        /// <remarks>
        /// If an endpoint in the second reporting period equals an endpoint in the first reporting period, that endpoint
        /// is considered to be contained within the first reporting period.  Of course, both endpoints must be contained
        /// within the reporting period for this method to return true.
        /// </remarks>
        /// <param name="reportingPeriod1">A reporting period.</param>
        /// <param name="reportingPeriod2">A second reporting period to check for containment within the first reporting period.</param>
        /// <returns>
        /// true if the first reporting period contains the second one; false if not.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod1"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="reportingPeriod2"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="reportingPeriod1"/> cannot be compared against <paramref name="reportingPeriod2"/> because they represent different <see cref="UnitOfTime.UnitOfTimeKind"/>.</exception>
        public static bool Contains(
            this ReportingPeriod reportingPeriod1,
            ReportingPeriod reportingPeriod2)
        {
            if (reportingPeriod1 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod1));
            }

            if (reportingPeriod2 == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod2));
            }

            if (reportingPeriod1.GetUnitOfTimeKind() != reportingPeriod2.GetUnitOfTimeKind())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod1)} cannot be compared against {nameof(reportingPeriod2)} because they represent different {nameof(UnitOfTimeKind)}."));
            }

            reportingPeriod1 = reportingPeriod1.ToMostGranular();
            reportingPeriod2 = reportingPeriod2.ToMostGranular();

            bool startIsContained;

            if (reportingPeriod1.Start.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
            {
                startIsContained = true;
            }
            else
            {
                if (reportingPeriod2.Start.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
                {
                    startIsContained = false;
                }
                else
                {
                    startIsContained = reportingPeriod1.Start.CompareTo(reportingPeriod2.Start) <= 0;
                }
            }

            bool endIsContained;

            if (reportingPeriod1.End.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
            {
                endIsContained = true;
            }
            else
            {
                if (reportingPeriod2.End.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
                {
                    endIsContained = false;
                }
                else
                {
                    endIsContained = reportingPeriod1.End.CompareTo(reportingPeriod2.End) >= 0;
                }
            }

            var result = startIsContained && endIsContained;

            return(result);
        }
        /// <summary>
        /// Converts the the specified unit-of-time into the most
        /// granular possible, but equivalent, reporting period.
        /// </summary>
        /// <param name="unitOfTime">The unit-of-time to operate on.</param>
        /// <returns>
        /// A reporting period that addresses the same set of time as <paramref name="unitOfTime"/>,
        /// but is the most granular version possible of that unit-of-time.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="unitOfTime"/> is null.</exception>
        public static ReportingPeriod ToMostGranular(
            this UnitOfTime unitOfTime)
        {
            if (unitOfTime == null)
            {
                throw new ArgumentNullException(nameof(unitOfTime));
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Unbounded)
            {
                var result = new ReportingPeriod(unitOfTime, unitOfTime);

                return(result);
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Year)
            {
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var calendarYear = unitOfTime as CalendarYear;

                    var result = new ReportingPeriod(calendarYear.GetFirstCalendarDay(), calendarYear.GetLastCalendarDay());

                    return(result);
                }

                var year = unitOfTime as IHaveAYear;
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    var result = new ReportingPeriod(new FiscalMonth(year.Year, MonthNumber.One), new FiscalMonth(year.Year, MonthNumber.Twelve));

                    return(result);
                }

                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    // ReSharper disable once PossibleNullReferenceException
                    var result = new ReportingPeriod(new GenericMonth(year.Year, MonthNumber.One), new GenericMonth(year.Year, MonthNumber.Twelve));

                    return(result);
                }

                throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Quarter)
            {
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var calendarQuarter = unitOfTime as CalendarQuarter;

                    var result = new ReportingPeriod(calendarQuarter.GetFirstCalendarDay(), calendarQuarter.GetLastCalendarDay());

                    return(result);
                }

                var quarter = unitOfTime as IHaveAQuarter;

                // ReSharper disable once PossibleNullReferenceException
                var startMonth = (((int)quarter.QuarterNumber - 1) * 3) + 1;
                var endMonth   = (int)quarter.QuarterNumber * 3;

                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    var result = new ReportingPeriod(new FiscalMonth(quarter.Year, (MonthNumber)startMonth), new FiscalMonth(quarter.Year, (MonthNumber)endMonth));

                    return(result);
                }

                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    var result = new ReportingPeriod(new GenericMonth(quarter.Year, (MonthNumber)startMonth), new GenericMonth(quarter.Year, (MonthNumber)endMonth));

                    return(result);
                }

                throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Month)
            {
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var calendarMonth = unitOfTime as CalendarMonth;

                    var result = new ReportingPeriod(calendarMonth.GetFirstCalendarDay(), calendarMonth.GetLastCalendarDay());

                    return(result);
                }

                if ((unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Fiscal) || (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Generic))
                {
                    var result = new ReportingPeriod(unitOfTime, unitOfTime);

                    return(result);
                }

                throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
            }

            if (unitOfTime.UnitOfTimeGranularity == UnitOfTimeGranularity.Day)
            {
                if (unitOfTime.UnitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var result = new ReportingPeriod(unitOfTime, unitOfTime);

                    return(result);
                }

                throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTime.UnitOfTimeKind);
            }

            throw new NotSupportedException("This granularity is not supported: " + unitOfTime.UnitOfTimeGranularity);
        }
        private static ReportingPeriod MakeLessGranular(
            this ReportingPeriod reportingPeriod,
            UnitOfTimeGranularity granularity,
            bool throwOnMisalignment = true)
        {
            if (reportingPeriod == null)
            {
                throw new ArgumentNullException(nameof(reportingPeriod));
            }

            if (reportingPeriod.HasComponentWithUnboundedGranularity())
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} has an {nameof(UnitOfTimeGranularity.Unbounded)} component."));
            }

            if (granularity == UnitOfTimeGranularity.Invalid)
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(granularity)}' == '{UnitOfTimeGranularity.Invalid}'"), (Exception)null);
            }

            if (granularity == UnitOfTimeGranularity.Unbounded)
            {
                throw new ArgumentOutOfRangeException(Invariant($"'{nameof(granularity)}' == '{UnitOfTimeGranularity.Unbounded}'"), (Exception)null);
            }

            var reportingPeriodGranularity = reportingPeriod.GetUnitOfTimeGranularity();

            if (reportingPeriodGranularity.IsAsGranularOrLessGranularThan(granularity))
            {
                throw new ArgumentException(Invariant($"{nameof(reportingPeriod)} is as granular or less granular than {nameof(granularity)}."));
            }

            ReportingPeriod lessGranularReportingPeriod;
            var             unitOfTimeKind = reportingPeriod.GetUnitOfTimeKind();

            if (reportingPeriodGranularity == UnitOfTimeGranularity.Day)
            {
                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startAsCalendarDay = reportingPeriod.Start as CalendarDay;

                    // ReSharper disable once PossibleNullReferenceException
                    var startMonth = new CalendarMonth(startAsCalendarDay.Year, startAsCalendarDay.MonthOfYear);
                    if ((startMonth.GetFirstCalendarDay() != startAsCalendarDay) && throwOnMisalignment)
                    {
                        throw new InvalidOperationException("Cannot convert a calendar day reporting period to a calendar month reporting period when the reporting period start time is not the first day of a month.");
                    }

                    var endAsCalendarDay = reportingPeriod.End as CalendarDay;

                    // ReSharper disable once PossibleNullReferenceException
                    var endMonth = new CalendarMonth(endAsCalendarDay.Year, endAsCalendarDay.MonthOfYear);
                    if ((endMonth.GetLastCalendarDay() != endAsCalendarDay) && throwOnMisalignment)
                    {
                        throw new InvalidOperationException("Cannot convert a calendar day reporting period to a calendar month reporting period when the reporting period end time is not the last day of a month.");
                    }

                    lessGranularReportingPeriod = new ReportingPeriod(startMonth, endMonth);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else if (reportingPeriodGranularity == UnitOfTimeGranularity.Month)
            {
                var startAsMonth = reportingPeriod.Start as IHaveAMonth;
                var endAsMonth   = reportingPeriod.End as IHaveAMonth;

                var validStartMonths = new HashSet <int> {
                    1, 4, 7, 10
                };

                // ReSharper disable once PossibleNullReferenceException
                if ((!validStartMonths.Contains((int)startAsMonth.MonthNumber)) && throwOnMisalignment)
                {
                    throw new InvalidOperationException("Cannot convert a monthly reporting period to a quarterly reporting period when the reporting period start time is not the first month of a recognized quarter.");
                }

                var validEndMonths = new HashSet <int> {
                    3, 6, 9, 12
                };

                // ReSharper disable once PossibleNullReferenceException
                if ((!validEndMonths.Contains((int)endAsMonth.MonthNumber)) && throwOnMisalignment)
                {
                    throw new InvalidOperationException("Cannot convert a monthly reporting period to a quarterly reporting period when the reporting period end time is not the last month of a recognized quarter.");
                }

                var monthNumberToQuarterMap = new Dictionary <int, QuarterNumber>
                {
                    { 1, QuarterNumber.Q1 },
                    { 2, QuarterNumber.Q1 },
                    { 3, QuarterNumber.Q1 },
                    { 4, QuarterNumber.Q2 },
                    { 5, QuarterNumber.Q2 },
                    { 6, QuarterNumber.Q2 },
                    { 7, QuarterNumber.Q3 },
                    { 8, QuarterNumber.Q3 },
                    { 9, QuarterNumber.Q3 },
                    { 10, QuarterNumber.Q4 },
                    { 11, QuarterNumber.Q4 },
                    { 12, QuarterNumber.Q4 },
                };

                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startQuarter = new CalendarQuarter(startAsMonth.Year, monthNumberToQuarterMap[(int)startAsMonth.MonthNumber]);

                    var endQuarter = new CalendarQuarter(endAsMonth.Year, monthNumberToQuarterMap[(int)endAsMonth.MonthNumber]);

                    lessGranularReportingPeriod = new ReportingPeriod(startQuarter, endQuarter);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    var startQuarter = new FiscalQuarter(startAsMonth.Year, monthNumberToQuarterMap[(int)startAsMonth.MonthNumber]);

                    var endQuarter = new FiscalQuarter(endAsMonth.Year, monthNumberToQuarterMap[(int)endAsMonth.MonthNumber]);

                    lessGranularReportingPeriod = new ReportingPeriod(startQuarter, endQuarter);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    var startQuarter = new GenericQuarter(startAsMonth.Year, monthNumberToQuarterMap[(int)startAsMonth.MonthNumber]);

                    var endQuarter = new GenericQuarter(endAsMonth.Year, monthNumberToQuarterMap[(int)endAsMonth.MonthNumber]);

                    lessGranularReportingPeriod = new ReportingPeriod(startQuarter, endQuarter);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else if (reportingPeriodGranularity == UnitOfTimeGranularity.Quarter)
            {
                var startAsQuarter = reportingPeriod.Start as IHaveAQuarter;
                var endAsQuarter   = reportingPeriod.End as IHaveAQuarter;

                // ReSharper disable once PossibleNullReferenceException
                if ((startAsQuarter.QuarterNumber != QuarterNumber.Q1) && throwOnMisalignment)
                {
                    throw new InvalidOperationException("Cannot convert a quarterly reporting period to a yearly reporting period when the reporting period start time is not Q1.");
                }

                // ReSharper disable once PossibleNullReferenceException
                if ((endAsQuarter.QuarterNumber != QuarterNumber.Q4) && throwOnMisalignment)
                {
                    throw new InvalidOperationException("Cannot convert a quarterly reporting period to a yearly reporting period when the reporting period end is not Q4.");
                }

                if (unitOfTimeKind == UnitOfTimeKind.Calendar)
                {
                    var startYear = new CalendarYear(startAsQuarter.Year);

                    var endYear = new CalendarYear(endAsQuarter.Year);

                    lessGranularReportingPeriod = new ReportingPeriod(startYear, endYear);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Fiscal)
                {
                    var startYear = new FiscalYear(startAsQuarter.Year);

                    var endYear = new FiscalYear(endAsQuarter.Year);

                    lessGranularReportingPeriod = new ReportingPeriod(startYear, endYear);
                }
                else if (unitOfTimeKind == UnitOfTimeKind.Generic)
                {
                    var startYear = new GenericYear(startAsQuarter.Year);

                    var endYear = new GenericYear(endAsQuarter.Year);

                    lessGranularReportingPeriod = new ReportingPeriod(startYear, endYear);
                }
                else
                {
                    throw new NotSupportedException("This kind of unit-of-time is not supported: " + unitOfTimeKind);
                }
            }
            else
            {
                throw new NotSupportedException("This granularity is not supported: " + reportingPeriodGranularity);
            }

            if (lessGranularReportingPeriod.GetUnitOfTimeGranularity() == granularity)
            {
                return(lessGranularReportingPeriod);
            }

            var result = MakeLessGranular(lessGranularReportingPeriod, granularity, throwOnMisalignment);

            return(result);
        }