lastRenewal method

DateTime lastRenewal({
  1. DateTime? from,
})

Returns the last renewal starting from from date. If from is not provided, DateTime.now() date is taken.

Implementation

DateTime lastRenewal({
  DateTime? from,
}) {
  from ??= DateTime.now();

  switch (renewal) {
    case Renewal.annual:
      final DateTime thisYearRenewal = DateTime(
        from.year,
        start.month,
        start.day,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );
      final DateTime lastYearRenewal = DateTime(
        from.year - 1,
        start.month,
        start.day,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );

      return from.isAtSameMomentAs(thisYearRenewal) ||
              from.isAfter(thisYearRenewal)
          ? thisYearRenewal
          : lastYearRenewal;
    case Renewal.daily:
      final DateTime todayRenewal = DateTime(
        from.year,
        from.month,
        from.day,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );
      final DateTime yesterdayRenewal = DateTime(
        from.year,
        from.month,
        from.day - 1,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );

      return from.isAtSameMomentAs(todayRenewal) || from.isAfter(todayRenewal)
          ? todayRenewal
          : yesterdayRenewal;
    case Renewal.monthly:
      final DateTime thisMonthRenewal = DateTime(
        from.year,
        from.month,
        start.day,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );
      final DateTime lastMonthRenewal = DateTime(
        from.year,
        from.month - 1,
        start.day,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );

      return from.isAtSameMomentAs(thisMonthRenewal) ||
              from.isAfter(thisMonthRenewal)
          ? thisMonthRenewal
          : lastMonthRenewal;
    case Renewal.weekly:
      final int startWeekDay = start.weekday;
      final int fromWeekDay = from.weekday;

      return DateTime(
        from.year,
        from.month,
        from.day - (fromWeekDay - startWeekDay) % 7,
        start.hour,
        start.minute,
        start.second,
        start.millisecond,
        start.microsecond,
      );
  }
}