getActiveSubscriptions method

  1. @override
List<UserSubscription> getActiveSubscriptions({
  1. SubscriptionLevel? targetLevel,
  2. int? targetMonth,
  3. int? targetYear,
})
override

Implementation

@override
List<UserSubscription> getActiveSubscriptions({SubscriptionLevel? targetLevel, int? targetMonth, int? targetYear}) {
  AppConfig.logger.d("Checking ${targetLevel?.name} Active Subscriptions for: $targetMonth/$targetYear");

  List<UserSubscription> activeSubs = [];
  int month = targetMonth ?? DateTime.now().month;
  int year = targetYear ?? DateTime.now().year;

  _activeSubscriptions.forEach((level, subscriptions) {

    if(targetLevel != null && level != targetLevel) return;

    for(UserSubscription subscription in subscriptions) {

      int startDateMonth = 0;
      int startDateYear = 0;
      int endDateMonth = 0;
      int endDateYear = 0;
      bool isActive = true;

      if(subscription.startDate != 0) {
        startDateMonth = DateTime.fromMillisecondsSinceEpoch(subscription.startDate).month;
        startDateYear = DateTime.fromMillisecondsSinceEpoch(subscription.startDate).year;
      }

      bool startedOnOrBeforeTargetMonth = (startDateYear < year) ||
          (startDateYear == year && startDateMonth <= month);

      if(startedOnOrBeforeTargetMonth) {
        if(subscription.endDate != 0) {
          endDateMonth = DateTime.fromMillisecondsSinceEpoch(subscription.endDate).month;
          endDateYear = DateTime.fromMillisecondsSinceEpoch(subscription.endDate).year;
          bool endedBeforeTargetMonth = (endDateYear < year) || (endDateYear == year && endDateMonth < month);
          if(endedBeforeTargetMonth) isActive = false;
        }
      } else {
        isActive = false;
      }

      if(isActive) {
        AppConfig.logger.d("Subscription ${subscription.subscriptionId} of level ${subscription.level?.name} was active in $month/$year");
        activeSubs.add(subscription);
      }
    }
  });

  return activeSubs;
}