logNpsCsat static method
Implementation
static Future<String> logNpsCsat(
String type,
String id,
double rating) async {
try {
FirebaseApp app = Instadiv.getInstance().firebaseApp;
FirebaseFirestore firestore = FirebaseFirestore.instanceFor(app: app);
CollectionReference<Map<String, dynamic>> feedbackCollection = firestore
.collection(instaCollection)
.doc(Instadiv.getInstance().project)
.collection(type);
DocumentReference<Map<String, dynamic>> feedbackDocument = feedbackCollection.doc(id);
bool documentExists = await feedbackDocument.get().then((doc) => doc.exists);
if (documentExists) {
DocumentSnapshot<Map<String, dynamic>> snapshot = await feedbackDocument.get();
Map<String, dynamic> data = snapshot.data() as Map<String, dynamic>;
Map<String, dynamic> score = data['score'] ?? {};
if (score.isEmpty) {
Map<String, dynamic> newScore = {
'score': {
rating.toString(): 1
}
};
feedbackDocument.update(newScore);
} else {
int count = score[rating.toString()]??0;
score[rating.toString()] = count + 1;
Map<String, dynamic> updatedScore = {
'score': score
};
feedbackDocument.update(updatedScore);
}
} else {
// Document doesn't exist, create it
Map<String, dynamic> newScore = {
'score': {
rating.toString(): 1
}
};
await feedbackDocument.set(newScore);
}
// Specify the subcollection path
CollectionReference<Map<String, dynamic>> dataCollection =
feedbackDocument.collection('data');
// Create data to be stored in the subcollection
Map<String, dynamic> data = {
type: rating
};
// Add the document to the collection
DocumentReference documentReference = await dataCollection.add(data);
// Get the document ID
return documentReference.id;
} catch (e) {
print('Error $e');
return '';
}
}