getAverageCompletionTime function

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

Returns the average completion time (in hours) for all completed tasks by the given userId.

For each completed task, calculates the time difference between creation and completion. Returns the average of those durations. Returns 0.0 if no tasks have been completed.

Implementation

Future<double> getAverageCompletionTime(
  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;

  double totalHours = 0;

  for (final doc in snapshot.docs) {
    final data = doc.data();
    final creation = (data[creationDateFieldName] as Timestamp).toDate();
    final completion =
        (data[taskCompletionDateTimeFieldName] as Timestamp).toDate();
    totalHours += completion.difference(creation).inMinutes / 60.0;
  }

  return double.parse((totalHours / snapshot.docs.length).toStringAsFixed(1));
}