getAverageTasksPerDay function

Future<double> getAverageTasksPerDay(
  1. dynamic firestore,
  2. String userId
)

Returns the average number of tasks completed per day by the given userId.

Calculates the total number of completed tasks and divides it by the number of days between the first and last completion date. Returns 0.0 if no tasks have been completed.

Implementation

Future<double> getAverageTasksPerDay(
  FirebaseFirestore firestore,
  String userId,
) async {
  final snapshot =
      await firestore
          .collection(tasksCollectionFieldName)
          .where(ownerUserIdFieldName, isEqualTo: userId)
          .where(isCompletedFieldName, isEqualTo: true)
          .get();

  if (snapshot.docs.isEmpty) return 0.0;

  final dates =
      snapshot.docs
          .map(
            (doc) =>
                (doc.data()[taskCompletionDateTimeFieldName] as Timestamp)
                    .toDate(),
          )
          .toList();

  dates.sort();
  final first = dates.first;
  final last = dates.last;
  final days = last.difference(first).inDays + 1;

  return dates.length / days;
}