fetchAnalyticsData method

Future<void> fetchAnalyticsData()

Fetches doctor registration data from Appwrite and prepares data for both weekly and monthly charts.

Implementation

Future<void> fetchAnalyticsData() async {
  final userData = prefs.getUser();
  if (userData == null) return;
  final isRestricted = userData.role != UserRoles.superAdmin;

  List<String> buildQueries(String type) {
    final queries = <String>[];
    if (type.isNotEmpty) queries.add(Query.equal('type', type));
    if (isRestricted) {
      queries.add(Query.equal('organizationId', userData.organizationId));
    }
    return queries;
  }

  try {
    final response = await database.listDocuments(
      databaseId: AppConstants.appwriteDatabaseId,
      collectionId: AppConstants.userCollectionId,
      queries: buildQueries('doctor'),
    );

    final docs = response.documents;
    if (docs.isEmpty) {
      setState(() => isLoading = false);
      return;
    }

    final weeklyTrend = prepareTrend(docs, 'weekly');
    final monthlyTrend = prepareTrend(docs, 'monthly');

    setState(() {
      weeklySpots = buildSpots(weeklyTrend);
      weeklyLabels =
          weeklyTrend.map((e) => e['createdOn'] as String).toList();

      monthlySpots = buildSpots(monthlyTrend);
      monthlyLabels =
          monthlyTrend.map((e) => e['createdOn'] as String).toList();

      isChartDataAvailable = true;
      isLoading = false;
    });
  } catch (e) {
    debugPrint("Error fetching data: $e");
    setState(() => isLoading = false);
  }
}