The todaytxn() function performs the following steps:
It gets the current date and time using the DateTime.now() function and creates a new DateTime object with only the year, month, and day parts.
It converts the DateTime object to a string in the format "yyyy-MM-dd" using the toString() function and the substring() method to extract the first 10 characters.
It queries the payment collection in Firestore using the where() method to filter the documents based on the txnDate field. It sets the minimum and maximum values of the txnDate field to be the start and end of the current day, respectively.
It retrieves the query results using the get() method and then uses the then() method to handle the asynchronous response.
It retrieves the total number of transactions by getting the length of the docs list in the QuerySnapshot object.
It retrieves the total transaction amount by using the fold() method to iterate over the docs list and accumulate the txnAmount field values. The fold() method takes an initial value of 0 and a callback function that takes two arguments: the accumulated value (starting with the initial value) and the current document being processed. The callback function returns the sum of the accumulated value and the current document's txnAmount field value. The toInt() method is used to convert the accumulated value to an integer.
It prints the total number of transactions and the total transaction amount to the console using the print() function. Code i used below
todaytxn() async {
DateTime now = DateTime.now();
DateTime today = DateTime(now.year, now.month, now.day);
print(today);
String todayString = today.toString().substring(0, 10); // convert DateTime to string in format "yyyy-MM-dd"
print(todayString);
FirebaseFirestore.instance.collection('payment')
.where('txnDate', isGreaterThanOrEqualTo: todayString)
.where('txnDate', isLessThan: todayString + 'T23:59:59') // add time part to create range
.get()
.then((QuerySnapshot querySnapshot) {
int numTransactions = querySnapshot.docs.length;
print('Total transactions for today: $numTransactions');
});
FirebaseFirestore.instance.collection('payment')
.where('txnDate', isGreaterThanOrEqualTo: todayString)
.where('txnDate', isLessThan: todayString + 'T23:59:59') // add time part to create range
.get()
.then((QuerySnapshot querySnapshot) {
int numTransactions = querySnapshot.docs.length;
print('Total transactions for today: $numTransactions');
int totalTxnAmt = querySnapshot.docs.fold(0, (acc, doc) => acc + (doc['txnAmount'] ?? 0)).toInt();
print('Total txnAmt for today: $totalTxnAmt');
});
}