firstOccurrence property

DateTime get firstOccurrence

The date and time of the first occurrence of this trigger.

Implementation

DateTime get firstOccurrence {
  late DateTime firstDay;
  DateTime now = DateTime.now();
  DateTime start = DateTime(
      now.year, now.month, now.day, time.hour, time.minute, time.second);

  switch (type) {
    case RecurrentType.daily:
      firstDay =
          (start.isAfter(now)) ? start : start.add(Duration(hours: 24));
      break;
    case RecurrentType.weekly:
      int days = dayOfWeek! - now.weekday;
      days = (days < 0) ? days + daysPerWeek : days;
      firstDay = start.add(Duration(days: days));
      // check if this is the same day, but a time slot earlier this day
      firstDay = (firstDay.isBefore(now))
          ? firstDay.add(Duration(days: daysPerWeek))
          : firstDay;
      break;
    case RecurrentType.monthly:
      if (dayOfMonth != null) {
        // we have a trigger of the following type: collect quarterly on the 11th day of the first month in each quarter at 21:30
        //   RecurrentScheduledTrigger(type: RecurrentType.monthly, dayOfMonth: 11, separationCount: 2, time: Time(hour: 21, minute: 30));
        int days = dayOfMonth! - now.day;
        int month = (days > 0)
            ? now.month + separationCount
            : now.month + separationCount + 1;
        int year = now.year;
        if (month > 12) {
          year = now.year + 1;
          month = month - DateTime.monthsPerYear;
        }
        firstDay = DateTime(year, month, dayOfMonth!);
      } else {
        // we have a trigger of the following type: collect monthly in the second week on a monday at 14:30
        //   RecurrentScheduledTrigger(type: RecurrentType.monthly, weekOfMonth: 2, dayOfWeek: DateTime.monday, time: Time(hour: 14, minute: 30));
        firstDay = nextMonthlyDay(DateTime(now.year, now.month, 1));
        // check if this day is in the past - if so, move one month forward
        if (firstDay.isBefore(now)) {
          firstDay = nextMonthlyDay(DateTime(now.year, now.month + 1, 1));
        }
      }
      break;
  }

  return DateTime(firstDay.year, firstDay.month, firstDay.day, time.hour,
      time.minute, time.second);
}