From c677866f6ea134ed625ce45b366081edae366c58 Mon Sep 17 00:00:00 2001 From: NG WEI HEN Date: Tue, 13 Aug 2024 21:54:12 +0800 Subject: [PATCH] Updates --- .../Heart Beat/Pulse Dashboard.dart | 512 +++++++++++++----- .../Body Status/Heart Beat/Pulse History.dart | 27 +- .../Temperature/Temperature Dashboard.dart | 85 ++- .../Temperature/Temperature History.dart | 26 +- 4 files changed, 485 insertions(+), 165 deletions(-) diff --git a/lib/View/Patient/Body Status/Heart Beat/Pulse Dashboard.dart b/lib/View/Patient/Body Status/Heart Beat/Pulse Dashboard.dart index 8b9d3d1..6a442f7 100644 --- a/lib/View/Patient/Body Status/Heart Beat/Pulse Dashboard.dart +++ b/lib/View/Patient/Body Status/Heart Beat/Pulse Dashboard.dart @@ -47,40 +47,231 @@ class _PulseDashboardState extends State { } Future getAllPulseRecordsByToday() async { - setState(() { - graphTitle = "Today records"; - }); + // Get today's date DateTime now = DateTime.now(); DateTime today = DateTime(now.year, now.month, now.day); + try { - var pulseRecord = await MongoDatabase().getByQuery("Heart_Pulse", { - "PatientID": 'P-${widget.id}', - "MeasureDate": { - "\$gte": today, - "\$lt": today.add(Duration(days: 1)), + // Assuming 'MongoDatabase' instance is accessible here + var pulseRecord = await MongoDatabase().getByQuery("Heart_Pulse", + { + "PatientID" : 'P-${widget.id}', + "MeasureDate": { + "\$gte": today, //change to today + "\$lt": today.add(Duration(days: 1)), + } } - }); - - if (pulseRecord.isNotEmpty) { - setState(() { + ); + print("All Temperature: $pulseRecord"); + print("Total: ${pulseRecord.length}"); + + if(pulseRecord.isNotEmpty){ + setState((){ pulses = pulseRecord.map((json) => Pulse.fromJson(json)).toList(); pulsesData = pulses.map((rate) => GraphData(day: formatTime(rate.MeasureTime.toString()), value: rate.pulseRate.toDouble()) ).toList(); }); - } else { - setState(() { - pulses = []; - pulsesData = []; + } + else{ + setState((){ + pulses = pulseRecord.map((json) => Pulse.fromJson(json)).toList(); + pulsesData = pulses.map((rate) => + GraphData(day: formatTime(rate.MeasureTime.toString()), value: rate.pulseRate.toDouble()) + ).toList(); }); } + + } catch (e, printStack) { + print('Error fetching other doctors : $e'); + print(printStack); + // Handle the exception as needed, for example, show an error message to the user + } + + } + + Future getPulseRecordsByDateRange(DateTime startDate, DateTime endDate) async { + try { + var pulseRecords = await MongoDatabase().getByQuery( + "Heart_Pulse", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": startDate, + "\$lt": endDate.add(Duration(days: 1)), + } + }, + ); + + setState(() { + pulses = pulseRecords.map((json) => Pulse.fromJson(json)).toList(); + + print("Records between ${startDate} and ${endDate}: ${pulses}"); + pulsesData = pulses.map((rate) => GraphData(day: "${formatDate(rate.MeasureDate.toString())} ${formatTime(rate.MeasureTime.toString())}", value: rate.pulseRate.toDouble())).toList(); + }); } catch (e, printStack) { print('Error fetching pulse records: $e'); print(printStack); } } + + Future getHighestPulseRecordsForRecentDays() async { + setState(() { + graphTitle = "Highest Pulse records for Recent 5 days"; + }); + DateTime now = DateTime.now(); + DateTime today = DateTime(now.year, now.month, now.day); + DateTime fiveDaysAgo = today.subtract(Duration(days: 5)); + + try { + var pulseRecords = await MongoDatabase().getByQuery( + "Heart_Pulse", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": fiveDaysAgo, + "\$lt": today.add(Duration(days: 1)), + } + }, + ); + + List rates = pulseRecords.map((json) => Pulse.fromJson(json)).toList(); + Map highestRates = {}; + + for (var rate in rates) { + DateTime date = DateTime(rate.MeasureDate!.year, rate.MeasureDate!.month, rate.MeasureDate!.day); + if (!highestRates.containsKey(date) || highestRates[date]!.pulseRate < rate.pulseRate) { + highestRates[date] = rate; + + print("Highest: ${highestRates[date]}"); + } + } + + setState(() { + pulses = highestRates.values.toList(); + pulsesData = pulses.map((rate) => GraphData(day: formatDate(rate.MeasureDate.toString()), value: rate.pulseRate.toDouble())).toList(); + }); + } catch (e, printStack) { + print('Error fetching temperature records: $e'); + print(printStack); + } + } + + String? avg, max, min; + // Get records for a specific date and calculate the average, minimum, and maximum pulse rates + Future getPulseRecordsBySpecificDate(DateTime date) async { + setState(() { + graphTitle = "Records for ${date.day} ${monthNames[date.month - 1]} ${date.year}"; + }); + try { + var pulseRecords = await MongoDatabase().getByQuery( + "Heart_Pulse", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": DateTime(date.year, date.month, date.day), + "\$lt": DateTime(date.year, date.month, date.day).add(Duration(days: 1)), + } + }, + ); + + if (pulseRecords.isNotEmpty) { + // Map records to Pulse objects + pulses = pulseRecords.map((json) => Pulse.fromJson(json)).toList(); + + // Calculate average, minimum, and maximum pulse rates + double totalPulseRate = pulses.fold(0.0, (sum, rate) => sum + rate.pulseRate.toDouble()); + double averagePulseRate = totalPulseRate / pulses.length; + double minPulseRate = pulses.map((rate) => rate.pulseRate.toDouble()).reduce((a, b) => a < b ? a : b); + double maxPulseRate = pulses.map((rate) => rate.pulseRate.toDouble()).reduce((a, b) => a > b ? a : b); + + // Update the graph data + pulsesData = pulses.map((rate) => + GraphData(day: "${formatDate(rate.MeasureDate.toString())} ${formatTime(rate.MeasureTime.toString())}", value: rate.pulseRate.toDouble()) + ).toList(); + + print("Average Pulse Rate: $averagePulseRate"); + print("Minimum Pulse Rate: $minPulseRate"); + print("Maximum Pulse Rate: $maxPulseRate"); + + setState(() { + + + avg = "${averagePulseRate.toStringAsFixed(2)}"; + max = "${minPulseRate.toStringAsFixed(2)}"; + min = "${maxPulseRate.toStringAsFixed(2)}"; + }); + } else { + print("No pulse records found for the selected date."); + // Handle the case where no records are found + } + } catch (e, printStack) { + print('Error fetching pulse records for specific date: $e'); + print(printStack); + } + } + + + Future getPulseRecordsForWeek(DateTime date) async { + DateTime startOfWeek = date.subtract(Duration(days: date.weekday - 1)); // Start of the week (Monday) + DateTime endOfWeek = startOfWeek.add(Duration(days: 6)); // End of the week (Sunday) + + try { + var pulseRecords = await MongoDatabase().getByQuery( + "Heart_Pulse", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": startOfWeek, + "\$lt": endOfWeek.add(Duration(days: 1)), + } + }, + ); + + setState(() { + pulses = pulseRecords.map((json) => Pulse.fromJson(json)).toList(); + pulsesData = pulses.map((rate) => GraphData(day: "${formatDate(rate.MeasureDate.toString())} ${formatTime(rate.MeasureTime.toString())}", value: rate.pulseRate.toDouble())).toList(); + graphTitle = "Pulse Records for Week of ${formatDate(startOfWeek.toString())} to ${formatDate(endOfWeek.toString())}"; + }); + } catch (e, printStack) { + print('Error fetching pulse records for the week: $e'); + print(printStack); + } + } + + Future getPulseRecordsForMonth(DateTime date) async { + DateTime startOfMonth = DateTime(date.year, date.month, 1); // Start of the month + DateTime endOfMonth = DateTime(date.year, date.month + 1, 0); // End of the month + + try { + var pulseRecords = await MongoDatabase().getByQuery( + "Heart_Pulse", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": startOfMonth, + "\$lt": endOfMonth.add(Duration(days: 1)), + } + }, + ); + + setState(() { + pulses = pulseRecords.map((json) => Pulse.fromJson(json)).toList(); + pulsesData = pulses.map((rate) => GraphData(day: "${formatDate(rate.MeasureDate.toString())} ${formatTime(rate.MeasureTime.toString())}", value: rate.pulseRate.toDouble())).toList(); + graphTitle = "Pulse Records for ${monthNames[date.month - 1]} ${date.year}"; + }); + } catch (e, printStack) { + print('Error fetching pulse records for the month: $e'); + print(printStack); + } + } + + + + + @override void initState() { // TODO: implement initState @@ -188,6 +379,7 @@ class _PulseDashboardState extends State { if (date_result != null) { setState(() { selectedDate = date_result.last; // Update selected date to the first (and only) selected date + getPulseRecordsBySpecificDate(selectedDate!); }); print("Selected Date: ${selectedDate.toString()}"); // Print the selected date @@ -223,11 +415,18 @@ class _PulseDashboardState extends State { ), child: Column( children: [ - Text("Average", style: GoogleFonts.poppins( + Text("Average BPM", style: GoogleFonts.poppins( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12.0 ),), + + Spacer(), + + Text("${avg == null ? "-" : avg}", style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 25.0 + ),), ], ), ), @@ -244,11 +443,18 @@ class _PulseDashboardState extends State { ), child: Column( children: [ - Text("Minimum", style: GoogleFonts.poppins( + Text("Minimum BPM", style: GoogleFonts.poppins( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12.0 ),), + + Spacer(), + + Text("${min == null ? "-" : min}", style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 25.0 + ),), ], ), ), @@ -266,11 +472,18 @@ class _PulseDashboardState extends State { child: Column( children: [ - Text("Maximum", style: GoogleFonts.poppins( + Text("Maximum BPM", style: GoogleFonts.poppins( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12.0 ),), + + Spacer(), + + Text("${max == null ? "-" : max}", style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 25.0 + ),), ], ), ), @@ -292,6 +505,13 @@ class _PulseDashboardState extends State { for (int i = 0; i < _selectedDays.length; i++) { _selectedDays[i] = i == index; } + if (_selectedDays[0]) { + getPulseRecordsBySpecificDate(selectedDate!); + } else if (_selectedDays[1]) { + getPulseRecordsForWeek(selectedDate!); + } else if (_selectedDays[2]) { + getPulseRecordsForMonth(selectedDate!); + } }); }, borderRadius: const BorderRadius.all(Radius.circular(8)), @@ -325,141 +545,128 @@ class _PulseDashboardState extends State { SizedBox(height: 40), - Container( - height: 200, + Padding( + padding: const EdgeInsets.all(5.0), child: SfCartesianChart( - // Initialize category axis - plotAreaBorderWidth: 0.0, - primaryXAxis: CategoryAxis( - // For days view - labelStyle: GoogleFonts.poppins( - color: Color(0xFFFFFFFF), - fontWeight: FontWeight.w600, - fontSize: 10.0), - /* title: AxisTitle( - text: 'Day', - textStyle: GoogleFonts.poppins( - color: Colors.black, - fontWeight: FontWeight.w600, - fontSize: 15.0), - ), */ - ), - - primaryYAxis: NumericAxis( - labelStyle: GoogleFonts.poppins( - color: Color(0xFFFFFFFF), fontWeight: FontWeight.w600, - fontSize: 15.0 - ), - title: AxisTitle( - text: 'Pulse(BPM)', // Set the label for X axis - textStyle: GoogleFonts.poppins( - color: Colors.white, fontWeight: FontWeight.w600, - fontSize: 15.0 - ), - ), - /* title: AxisTitle( - text: 'Celsius', // Set the label for X axis - textStyle: GoogleFonts.poppins( - color: Colors.black, fontWeight: FontWeight.w600, - fontSize: 15.0 - ), - ), */ - ), - - - - - series: [ - - /* - ColumnSeries: Displays data as vertical columns, with height representing the data value. - BarSeries: Similar to ColumnSeries, but the columns are horizontal. - AreaSeries: Displays data as a filled area, with the area under the curve filled with color. - SplineSeries: Similar to LineSeries, but the curve is smoothed out. - ScatterSeries: Represents individual data points as symbols without connecting them. - BubbleSeries: Represents data points as bubbles, with the size of the bubble representing the data value. - PieSeries: Displays data as slices of a pie, with each slice representing a category and its size representing the data value. - DoughnutSeries: Similar to PieSeries, but with a hole in the center. - */ - - pulsesData.length > 1 - // Temperature Series - ? SplineSeries( - xAxisName: "BPM", - yAxisName: "Month", - color: Color(0xFFFFFFFF), - dataSource: pulsesData, - xValueMapper: (GraphData value, _) => value.day, - yValueMapper: (GraphData value, _) => value.value, - enableTooltip: true, - name: 'Heart rate (BPM)', // Name of the series - /* dataLabelSettings: DataLabelSettings( - isVisible: true, textStyle: GoogleFonts.poppins( - color: Colors.black, - fontSize: 8.0 - ),) */ - ) - - : ColumnSeries( - - color: Color(0xFFFFFFFF), - dataSource: pulsesData, - xValueMapper: (GraphData value, _) => value.day, - yValueMapper: (GraphData value, _) => value.value, - enableTooltip: true, - name: 'Heart rate (BPM)', // Name of the series - dataLabelSettings: DataLabelSettings( - isVisible: true, textStyle: GoogleFonts.poppins( - color: Color(0xFFFFFFFF), - fontSize: 8.0 - ),) - ), - - - - - - - - ], - // Enable legend - - // Custom legend position - legend: Legend( - isVisible: false, - position: LegendPosition.auto, // Adjust the position here - textStyle: GoogleFonts.poppins( - color: Color(0xFFFFFFFF), - fontSize: 10.0 - ), - ), - - // Enable zooming and panning - zoomPanBehavior: ZoomPanBehavior( - enableSelectionZooming: true, - enableMouseWheelZooming: true, - enablePanning: true, - enablePinching: true, - zoomMode: ZoomMode.x, - ), - - // Add tooltip - tooltipBehavior: TooltipBehavior( - textStyle: GoogleFonts.poppins( - color: Colors.white, - fontSize: 8.0 - ), - enable: true, - + // Initialize category axis + primaryXAxis: CategoryAxis( + // For days view + labelStyle: GoogleFonts.poppins( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 10.0), + /* title: AxisTitle( + text: 'Day', + textStyle: GoogleFonts.poppins( + color: Colors.black, + fontWeight: FontWeight.w600, + fontSize: 15.0), + ), */ + ), + + primaryYAxis: NumericAxis( + labelStyle: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.w600, + fontSize: 15.0 + ), + /* title: AxisTitle( + text: 'Celsius', // Set the label for X axis + textStyle: GoogleFonts.poppins( + color: Colors.black, fontWeight: FontWeight.w600, + fontSize: 15.0 ), - - + ), */ + ), + + + title: ChartTitle( + text: '${graphTitle}', + textStyle: GoogleFonts.poppins( + color: Colors.white, fontWeight: FontWeight.w600, + fontSize: 15.0 + ), + ), + + series: [ + + /* + ColumnSeries: Displays data as vertical columns, with height representing the data value. + BarSeries: Similar to ColumnSeries, but the columns are horizontal. + AreaSeries: Displays data as a filled area, with the area under the curve filled with color. + SplineSeries: Similar to LineSeries, but the curve is smoothed out. + ScatterSeries: Represents individual data points as symbols without connecting them. + BubbleSeries: Represents data points as bubbles, with the size of the bubble representing the data value. + PieSeries: Displays data as slices of a pie, with each slice representing a category and its size representing the data value. + DoughnutSeries: Similar to PieSeries, but with a hole in the center. + */ + + pulsesData.length > 1 + // Temperature Series + ? SplineSeries( + color: Color(0xFFFF4081), + dataSource: pulsesData, + xValueMapper: (GraphData value, _) => value.day, + yValueMapper: (GraphData value, _) => value.value, + enableTooltip: true, + name: 'Heart rate (BPM)', // Name of the series + /* dataLabelSettings: DataLabelSettings( + isVisible: true, textStyle: GoogleFonts.poppins( + color: Colors.black, + fontSize: 8.0 + ),) */ + ) + + : ColumnSeries( + color: Color(0xFFFF4081), + dataSource: pulsesData, + xValueMapper: (GraphData value, _) => value.day, + yValueMapper: (GraphData value, _) => value.value, + enableTooltip: true, + name: 'Heart rate (BPM)', // Name of the series + /* dataLabelSettings: DataLabelSettings( + isVisible: true, textStyle: GoogleFonts.poppins( + color: Colors.black, + fontSize: 8.0 + ),) */ + ), + + + ], + // Enable legend + + // Custom legend position + legend: Legend( + isVisible: true, + position: LegendPosition.auto, // Adjust the position here + textStyle: GoogleFonts.poppins( + color: Colors.white, + fontSize: 10.0 + ), ), + + // Enable zooming and panning + zoomPanBehavior: ZoomPanBehavior( + enableSelectionZooming: true, + enableMouseWheelZooming: true, + enablePanning: true, + enablePinching: true, + zoomMode: ZoomMode.x, + ), + + // Add tooltip + tooltipBehavior: TooltipBehavior( + textStyle: GoogleFonts.poppins( + color: Colors.white, + fontSize: 8.0 + ), + enable: true, + + ), + + + ), ), - - - - SizedBox(height: 20), + Padding( padding: const EdgeInsets.all(8.0), @@ -495,6 +702,7 @@ class _PulseDashboardState extends State { setState(() { graphTitle = "Today Pulse"; dateRange = null; + selectedDate = DateTime.now(); }); }, child: Card( @@ -564,9 +772,12 @@ class _PulseDashboardState extends State { // If results are not null and contain at least one date, update the selected date if (date_result != null) { setState(() { + startRange = date_result.first; // Update selected date to the first (and only) selected date endRange = date_result.last; + getPulseRecordsByDateRange(startRange!, endRange!); dateRange = "Date Selected: ${startRange!.day} ${monthNames[startRange!.month - 1]} ${startRange!.year} - ${endRange!.day} ${monthNames[endRange!.month - 1]} ${endRange!.year} "; + graphTitle = "Pulse records between ${startRange!.day} ${monthNames[startRange!.month - 1]} ${startRange!.year} and ${endRange!.day} ${monthNames[endRange!.month - 1]} ${endRange!.year} "; }); @@ -610,6 +821,7 @@ class _PulseDashboardState extends State { InkWell( onTap: (){ + getHighestPulseRecordsForRecentDays(); setState(() { graphTitle = "Highest pulse records for Recent 5 days"; }); diff --git a/lib/View/Patient/Body Status/Heart Beat/Pulse History.dart b/lib/View/Patient/Body Status/Heart Beat/Pulse History.dart index ee77efa..ed32eb9 100644 --- a/lib/View/Patient/Body Status/Heart Beat/Pulse History.dart +++ b/lib/View/Patient/Body Status/Heart Beat/Pulse History.dart @@ -16,6 +16,7 @@ class PulseHistory extends StatefulWidget { class _PulseHistoryState extends State { late List pulses = []; + late List filteredPulses = []; // Added filtered pulses list Future getAllPulseRecords() async { try { // Assuming 'MongoDatabase' instance is accessible here @@ -25,6 +26,7 @@ class _PulseHistoryState extends State { if(pulse.isNotEmpty){ setState((){ pulses = pulse.map((json) => Pulse.fromJson(json)).toList(); + filteredPulses = List.from(pulses); }); } @@ -36,6 +38,23 @@ class _PulseHistoryState extends State { } + + // add function to display list based on certain day + void filterPulsesByDate(DateTime? date) { + setState(() { + if (date != null) { + filteredPulses = pulses.where((record) { + final recordDate = DateTime.parse(record.MeasureDate.toString()); + return recordDate.year == date.year && + recordDate.month == date.month && + recordDate.day == date.day; + }).toList(); + } else { + filteredPulses = List.from(pulses); // Reset to all records if no date is selected + } + }); + } + @override void initState() { // TODO: implement initState @@ -184,7 +203,9 @@ class _PulseHistoryState extends State { // If results are not null and contain at least one date, update the selected date if (date_result != null) { setState(() { + selectedDate = date_result.last; // Update selected date to the first (and only) selected date + filterPulsesByDate(selectedDate!); }); print("Selected Date: ${selectedDate.toString()}"); // Print the selected date @@ -218,10 +239,10 @@ class _PulseHistoryState extends State { return SizedBox(height: 15); // Adjust the height as needed }, reverse: false, - itemCount: pulses.length, + itemCount: filteredPulses.length, itemBuilder: (context, index){ - final records = pulses[index]; + final records = filteredPulses[index]; return Card( @@ -234,7 +255,7 @@ class _PulseHistoryState extends State { "${formatDate(records.MeasureDate.toString())}", style: GoogleFonts.poppins( color: Colors.black, - fontSize: 13.0, + fontSize: 13.0, fontWeight: FontWeight.bold, ), ), diff --git a/lib/View/Patient/Body Status/Temperature/Temperature Dashboard.dart b/lib/View/Patient/Body Status/Temperature/Temperature Dashboard.dart index 49f582c..11d5b4d 100644 --- a/lib/View/Patient/Body Status/Temperature/Temperature Dashboard.dart +++ b/lib/View/Patient/Body Status/Temperature/Temperature Dashboard.dart @@ -64,9 +64,7 @@ class _TempDashboardState extends State { // get today records Future getAllTempRecordsByToday() async { - setState(() { - graphTitle = "Today records"; - }); + // Get today's date DateTime now = DateTime.now(); DateTime today = DateTime(now.year, now.month, now.day); @@ -104,7 +102,7 @@ class _TempDashboardState extends State { } - // Get records for a specific date + /* // Get records for a specific date Future getTempRecordsByDate(DateTime selectedDate) async { setState(() { graphTitle = "Records for ${selectedDate.day} ${monthNames[selectedDate.month - 1]} ${selectedDate.year}"; @@ -130,10 +128,65 @@ class _TempDashboardState extends State { print('Error fetching temperature records for the specific date: $e'); print(printStack); } + } */ + + String? avg, fahren; + + // Get records for a specific date and calculate the average temperature + Future getTempRecordsByDate(DateTime selectedDate) async { + setState(() { + graphTitle = "Records for ${selectedDate.day} ${monthNames[selectedDate.month - 1]} ${selectedDate.year}"; + }); + + try { + var tempRecords = await MongoDatabase().getByQuery( + "Temperature", + { + "PatientID": 'P-${widget.id}', + "MeasureDate": { + "\$gte": DateTime(selectedDate.year, selectedDate.month, selectedDate.day), + "\$lt": DateTime(selectedDate.year, selectedDate.month, selectedDate.day).add(Duration(days: 1)), + } + }, + ); + + if (tempRecords.isNotEmpty) { + // Map records to Temperature objects + temperatures = tempRecords.map((json) => Temperature.fromJson(json)).toList(); + + // Calculate the average temperature + double totalTemperature = temperatures.fold(0.0, (sum, temp) => sum + temp.temperature.toDouble()); + double averageTemperature = totalTemperature / temperatures.length; + + double avgFahrenheit = (averageTemperature * 9 / 5) + 32; + + // Update the graph data + temperatureData = temperatures.map((temp) => + GraphData(day: formatTime(temp.measureTime.toString()), value: temp.temperature.toDouble()) + ).toList(); + + print("Average Temperature: $averageTemperature"); + + setState(() { + // You can update the UI with the average temperature here if needed + // For example, you could display it in a widget or add it to the graphTitle + avg = "${averageTemperature.toStringAsFixed(2)}"; + fahren = "${avgFahrenheit.toStringAsFixed(2)}"; + + }); + } else { + print("No records found for the selected date."); + // Handle the case where no records are found + } + } catch (e, printStack) { + print('Error fetching temperature records for the specific date: $e'); + print(printStack); + } } + // get highest records for recent 5 days Future getHighestTempRecordsForRecentDays() async { setState(() { @@ -205,9 +258,7 @@ class _TempDashboardState extends State { // Get records for the week based on the specific date Future getTempRecordsForWeek(DateTime selectedDate) async { - setState(() { - graphTitle = "Records for the week of ${selectedDate.day} ${monthNames[selectedDate.month - 1]} ${selectedDate.year}"; - }); + DateTime startOfWeek = selectedDate.subtract(Duration(days: selectedDate.weekday - 1)); DateTime endOfWeek = startOfWeek.add(Duration(days: 6)); @@ -227,6 +278,7 @@ class _TempDashboardState extends State { setState(() { temperatures = tempRecords.map((json) => Temperature.fromJson(json)).toList(); temperatureData = temperatures.map((temp) => GraphData(day: formatDate(temp.measureDate.toString()), value: temp.temperature.toDouble())).toList(); + graphTitle = "Temperature Records for Week of ${formatDate(startOfWeek.toString())} to ${formatDate(endOfWeek.toString())}"; }); } catch (e, printStack) { print('Error fetching temperature records for the week: $e'); @@ -410,6 +462,13 @@ class _TempDashboardState extends State { fontWeight: FontWeight.bold, fontSize: 15.0 ),), + + Spacer(), + + Text("${avg == null ? "-" : avg}", style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 35.0 + ),), ], ), ), @@ -434,6 +493,15 @@ class _TempDashboardState extends State { fontWeight: FontWeight.bold, fontSize: 15.0 ),), + + Spacer(), + + Text("${fahren == null ? "-" : fahren}", style: GoogleFonts.poppins( + color: Colors.white, + fontSize: 35.0 + ),), + + ], ), ), @@ -660,9 +728,10 @@ class _TempDashboardState extends State { InkWell( onTap: (){ + getAllTempRecordsByToday(); setState(() { + graphTitle = "Today Temperature"; dateRange = null; - getAllTempRecordsByToday(); selectedDate = DateTime.now(); }); }, diff --git a/lib/View/Patient/Body Status/Temperature/Temperature History.dart b/lib/View/Patient/Body Status/Temperature/Temperature History.dart index 43ef3fc..a5237fa 100644 --- a/lib/View/Patient/Body Status/Temperature/Temperature History.dart +++ b/lib/View/Patient/Body Status/Temperature/Temperature History.dart @@ -15,6 +15,7 @@ class TempHistory extends StatefulWidget { class _TempHistoryState extends State { late List temperatures = []; + late List filteredTemperatures = []; // To hold filtered temperatures Future getAllTempRecords() async { try { // Assuming 'MongoDatabase' instance is accessible here @@ -24,7 +25,7 @@ class _TempHistoryState extends State { if(temp.isNotEmpty){ setState((){ temperatures = temp.map((json) => Temperature.fromJson(json)).toList(); - + filteredTemperatures = List.from(temperatures); // Initialize filtered temperatures to all records }); } @@ -36,6 +37,21 @@ class _TempHistoryState extends State { } + void filterTemperaturesByDate(DateTime? date) { + setState(() { + if (date != null) { + filteredTemperatures = temperatures.where((record) { + final recordDate = DateTime.parse(record.measureDate.toString()); + return recordDate.year == date.year && + recordDate.month == date.month && + recordDate.day == date.day; + }).toList(); + } else { + filteredTemperatures = List.from(temperatures); // Reset to all records if no date is selected + } + }); + } + @override void initState() { // TODO: implement initState @@ -185,12 +201,14 @@ class _TempHistoryState extends State { if (date_result != null) { setState(() { selectedDate = date_result.last; // Update selected date to the first (and only) selected date + filterTemperaturesByDate(selectedDate); }); print("Selected Date: ${selectedDate.toString()}"); // Print the selected date } else{ selectedDate = null; + filterTemperaturesByDate(null); } }, @@ -217,9 +235,9 @@ class _TempHistoryState extends State { return SizedBox(height: 15); // Adjust the height as needed }, reverse: false, - itemCount: temperatures.length, + itemCount: filteredTemperatures.length, itemBuilder: (context, index){ - final records = temperatures[index]; + final records = filteredTemperatures[index]; return Card( @@ -232,7 +250,7 @@ class _TempHistoryState extends State { "${formatDate(records.measureTime.toString())}", style: GoogleFonts.poppins( color: Colors.black, - fontSize: 13.0, + fontSize: 13.0, fontWeight: FontWeight.bold ), ),