amoriai/lib/models/daily_question_model.dart

99 lines
2.7 KiB
Dart

class DailyQuestion {
final String id;
final String question;
final QuestionType type;
final List<String>? options;
final int? minValue;
final int? maxValue;
final int? step;
/// If set, this question only shows when the question with [dependsOn] ID
/// has been answered with one of the values in [showWhenAnswers].
final String? dependsOn;
final List<String>? showWhenAnswers;
DailyQuestion({
required this.id,
required this.question,
required this.type,
this.options,
this.minValue,
this.maxValue,
this.step,
this.dependsOn,
this.showWhenAnswers,
});
factory DailyQuestion.fromJson(Map<String, dynamic> json) {
return DailyQuestion(
id: json['id'] as String,
question: json['question'] as String,
type: QuestionType.values.firstWhere(
(e) => e.name == json['type'],
orElse: () => QuestionType.choice,
),
options: json['options'] != null
? List<String>.from(json['options'])
: null,
minValue: json['minValue'] as int?,
maxValue: json['maxValue'] as int?,
step: json['step'] as int?,
dependsOn: json['dependsOn'] as String?,
showWhenAnswers: json['showWhenAnswers'] != null
? List<String>.from(json['showWhenAnswers'])
: null,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'question': question,
'type': type.name,
'options': options,
'minValue': minValue,
'maxValue': maxValue,
'step': step,
'dependsOn': dependsOn,
'showWhenAnswers': showWhenAnswers,
};
}
/// Whether this question should be visible given current answers
bool isVisible(Map<String, dynamic> currentAnswers) {
if (dependsOn == null || showWhenAnswers == null) return true;
final parentAnswer = currentAnswers[dependsOn];
if (parentAnswer == null) return false;
return showWhenAnswers!.contains(parentAnswer.toString());
}
}
enum QuestionType {
choice, // Multiple choice chips
slider, // Slider for numeric values
text, // Free text input
}
class DailyQuestionsResponse {
final List<DailyQuestion> questions;
final DateTime generatedAt;
DailyQuestionsResponse({required this.questions, required this.generatedAt});
factory DailyQuestionsResponse.fromJson(Map<String, dynamic> json) {
return DailyQuestionsResponse(
questions: (json['questions'] as List)
.map((q) => DailyQuestion.fromJson(q))
.toList(),
generatedAt: DateTime.parse(json['generatedAt'] as String),
);
}
Map<String, dynamic> toJson() {
return {
'questions': questions.map((q) => q.toJson()).toList(),
'generatedAt': generatedAt.toIso8601String(),
};
}
}