fetchResultsCSVTable static method

Future<String> fetchResultsCSVTable(
  1. String studyId
)

Implementation

static Future<String> fetchResultsCSVTable(String studyId) async {
  final List res;
  try {
    res = await env.client
        .from('study_progress')
        .select()
        .eq('study_id', studyId);
  } catch (error, stacktrace) {
    SupabaseQuery.catchSupabaseException(error, stacktrace);
    rethrow;
  }

  final jsonList = List<Map<String, dynamic>>.from(res);
  if (jsonList.isEmpty) return '';
  final tableHeadersSet = jsonList[0].keys.toSet();
  final flattenedQuestions = jsonList.map((progress) {
    if (progress['result_type'] == 'QuestionnaireState') {
      for (final result
          in List<Map<String, dynamic>>.from(progress['result'] as List)) {
        progress[result['question'] as String] = result['response'];
        tableHeadersSet.add(result['question'] as String);
      }
      // progress.remove('result');
    }
    return progress;
  }).toList(growable: false);
  final tableHeaders = tableHeadersSet.toList();
  // Convert to List and fill empty cells with empty string
  final resultsTable = [
    tableHeaders,
    ...flattenedQuestions.map(
      (progress) => tableHeaders
          .map((header) => progress[header] ?? '')
          .toList(growable: false),
    ),
  ];
  return const ListToCsvConverter().convert(resultsTable);
}