-
Notifications
You must be signed in to change notification settings - Fork 10
/
study.dart
312 lines (260 loc) · 10.7 KB
/
study.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import 'package:csv/csv.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:studyu_core/src/env/env.dart' as env;
import 'package:studyu_core/src/models/models.dart';
import 'package:studyu_core/src/util/supabase_object.dart';
import 'package:supabase/supabase.dart';
import 'package:uuid/uuid.dart';
part 'study.g.dart';
enum StudyStatus {
draft,
running,
closed;
String toJson() => name;
static StudyStatus fromJson(String json) => values.byName(json);
}
enum Participation {
open,
invite;
String toJson() => name;
static Participation fromJson(String json) => values.byName(json);
}
enum ResultSharing {
public,
private,
organization;
String toJson() => name;
static ResultSharing fromJson(String json) => values.byName(json);
}
@JsonSerializable()
class Study extends SupabaseObjectFunctions<Study> implements Comparable<Study> {
static const String tableName = 'study';
@override
Map<String, Object> get primaryKeys => {'id': id};
static const String baselineID = '__baseline';
String id;
String? title;
String? description;
@JsonKey(name: 'user_id')
String userId;
Participation participation = Participation.invite;
@JsonKey(name: 'result_sharing')
ResultSharing resultSharing = ResultSharing.private;
@JsonKey(fromJson: _contactFromJson)
late Contact contact = Contact();
@JsonKey(name: 'icon_name', defaultValue: 'accountHeart')
late String iconName = 'accountHeart';
@Deprecated('Use status instead')
@JsonKey(defaultValue: false)
late bool published = false;
late StudyStatus status = StudyStatus.draft;
@JsonKey(fromJson: _questionnaireFromJson)
late StudyUQuestionnaire questionnaire = StudyUQuestionnaire();
@JsonKey(name: 'eligibility_criteria', fromJson: _eligibilityCriteriaFromJson)
late List<EligibilityCriterion> eligibilityCriteria = [];
@JsonKey(defaultValue: [])
late List<ConsentItem> consent = [];
@JsonKey(defaultValue: [])
late List<Intervention> interventions = [];
@JsonKey(defaultValue: [])
late List<Observation> observations = [];
@JsonKey(fromJson: _studyScheduleFromJson)
late StudySchedule schedule = StudySchedule();
@JsonKey(name: 'report_specification', fromJson: _reportSpecificationFromJson)
late ReportSpecification reportSpecification = ReportSpecification();
@JsonKey(defaultValue: [])
late List<StudyResult> results = [];
@JsonKey(name: 'collaborator_emails', defaultValue: [])
late List<String> collaboratorEmails = [];
@JsonKey(name: 'registry_published', defaultValue: false)
late bool registryPublished = false;
@JsonKey(includeToJson: false, includeFromJson: false)
int participantCount = 0;
@JsonKey(includeToJson: false, includeFromJson: false)
int endedCount = 0;
@JsonKey(includeToJson: false, includeFromJson: false)
int activeSubjectCount = 0;
@JsonKey(includeToJson: false, includeFromJson: false)
List<int> missedDays = [];
@JsonKey(includeToJson: false, includeFromJson: false)
Repo? repo;
@JsonKey(includeToJson: false, includeFromJson: false)
List<StudyInvite>? invites;
@JsonKey(includeToJson: false, includeFromJson: false)
List<StudySubject>? participants;
@JsonKey(includeToJson: false, includeFromJson: false)
List<SubjectProgress>? participantsProgress;
@JsonKey(includeToJson: false, includeFromJson: false)
DateTime? createdAt;
Study(this.id, this.userId);
Study.withId(this.userId) : id = const Uuid().v4();
static List<EligibilityCriterion> _eligibilityCriteriaFromJson(dynamic json) {
if (json == null) {
return [];
}
return (json as List).map((e) => EligibilityCriterion.fromJson(e as Map<String, dynamic>)).toList();
}
static Contact _contactFromJson(dynamic json) {
if (json is Map<String, dynamic>) {
return Contact.fromJson(json);
}
return Contact();
}
static StudySchedule _studyScheduleFromJson(dynamic json) {
if (json is Map<String, dynamic>) {
return StudySchedule.fromJson(json);
}
return StudySchedule();
}
static StudyUQuestionnaire _questionnaireFromJson(dynamic json) {
if (json is List<dynamic>) {
return StudyUQuestionnaire.fromJson(json);
}
return StudyUQuestionnaire();
}
static ReportSpecification _reportSpecificationFromJson(dynamic json) {
if (json is Map<String, dynamic>) {
return ReportSpecification.fromJson(json);
}
return ReportSpecification();
}
factory Study.fromJson(Map<String, dynamic> json) {
final study = _$StudyFromJson(json);
final List? repo = json['repo'] as List?;
if (repo != null && repo.isNotEmpty) {
study.repo = Repo.fromJson((json['repo'] as List)[0] as Map<String, dynamic>);
}
final List? invites = json['study_invite'] as List?;
if (invites != null) {
study.invites = invites.map((json) => StudyInvite.fromJson(json as Map<String, dynamic>)).toList();
}
final List? participants = json['study_subject'] as List?;
if (participants != null) {
study.participants = participants.map((json) => StudySubject.fromJson(json as Map<String, dynamic>)).toList();
}
List? participantsProgress = json['study_progress'] as List?;
participantsProgress = json['study_progress_export'] as List?;
participantsProgress ??= json['subject_progress'] as List?;
if (participantsProgress != null) {
study.participantsProgress =
participantsProgress.map((json) => SubjectProgress.fromJson(json as Map<String, dynamic>)).toList();
}
final int? participantCount = json['study_participant_count'] as int?;
if (participantCount != null) {
study.participantCount = participantCount;
}
final int? endedCount = json['study_ended_count'] as int?;
if (endedCount != null) {
study.endedCount = endedCount;
}
final int? activeSubjectCount = json['active_subject_count'] as int?;
if (activeSubjectCount != null) {
study.activeSubjectCount = activeSubjectCount;
}
final List? missedDays = json['study_missed_days'] as List?;
if (missedDays != null) {
study.missedDays = List<int>.from(json['study_missed_days'] as List);
}
final String? createdAt = json['created_at'] as String?;
if (createdAt != null && createdAt.isNotEmpty) {
study.createdAt = DateTime.parse(createdAt);
}
return study;
}
@override
Map<String, dynamic> toJson() => _$StudyToJson(this);
// TODO: Add null checks in fromJson to allow selecting columns
static Future<List<Study>> getResearcherDashboardStudies() async => SupabaseQuery.getAll<Study>(
selectedColumns: [
'*',
'repo(*)',
'study_participant_count',
'study_ended_count',
'active_subject_count',
'study_missed_days',
],
);
/*static Future<List<Study>> getDashboardDisplayStudies() async => SupabaseQuery.getAll<Study>(
selectedColumns: [
'id',
'title',
'description',
'user_id',
'participation',
'result_sharing',
'published',
'registry_published',
'study_participant_count',
'study_ended_count',
'active_subject_count',
],
);*/
// ['id', 'title', 'description', 'published', 'icon_name', 'results', 'schedule']
static Future<ExtractionResult<Study>> publishedPublicStudies() async {
ExtractionResult<Study> result;
try {
final response = await env.client.from(tableName).select().eq('participation', 'open').eq("closed", false);
final extracted = SupabaseQuery.extractSupabaseList<Study>(List<Map<String, dynamic>>.from(response));
result = ExtractionSuccess<Study>(extracted);
} on ExtractionFailedException<Study> catch (error) {
result = error;
} catch (error, stacktrace) {
SupabaseQuery.catchSupabaseException(error, stacktrace);
rethrow;
}
return result;
}
bool isOwner(User? user) => user != null && userId == user.id;
bool isEditor(User? user) => user != null && collaboratorEmails.contains(user.email);
bool canEdit(User? user) => user != null && (isOwner(user) || isEditor(user));
bool get hasEligibilityCheck => eligibilityCriteria.isNotEmpty && questionnaire.questions.isNotEmpty;
bool get hasConsentCheck => consent.isNotEmpty;
int get totalMissedDays => missedDays.isNotEmpty ? missedDays.reduce((total, days) => total += days) : 0;
double get percentageMissedDays => totalMissedDays / (participantCount * schedule.length);
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);
}
// - Status
bool get isDraft => status == StudyStatus.draft;
bool get isRunning => status == StudyStatus.running;
bool get isClosed => status == StudyStatus.closed;
bool isReadonly(User user) {
return status != StudyStatus.draft || !canEdit(user);
}
@override
String toString() {
return 'Study{id: $id, title: $title, description: $description, userId: $userId, participation: $participation, resultSharing: $resultSharing, contact: $contact, iconName: $iconName, published: <deprecated>, status: $status, questionnaire: $questionnaire, eligibilityCriteria: $eligibilityCriteria, consent: $consent, interventions: $interventions, observations: $observations, schedule: $schedule, reportSpecification: $reportSpecification, results: $results, collaboratorEmails: $collaboratorEmails, registryPublished: $registryPublished, participantCount: $participantCount, endedCount: $endedCount, activeSubjectCount: $activeSubjectCount, missedDays: $missedDays, repo: $repo, invites: $invites, participants: $participants, participantsProgress: $participantsProgress, createdAt: $createdAt}';
}
@override
int compareTo(Study other) {
return id.compareTo(other.id);
}
}