@RequiresApi(Build.VERSION_CODES.O) @Composable fun ExpensesGraph(paddingValues:…
- User
@RequiresApi(Build.VERSION_CODES.O) @Composable fun ExpensesGraph(paddingValues: PaddingValues) { val db = FirebaseFirestore.getInstance()
// Define your timeframes val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly") val selectedIndex = remember { mutableStateOf(0) } // Fetch and process the expenses data val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) } var chartModelProducer = ChartEntryModelProducer(chartEntries.value) var xAxisLabels = remember { mutableStateOf(listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")) } var bottomAxisValueFormatter = AxisValueFormatter<AxisPosition.Horizontal.Bottom> { x, _ -> xAxisLabels.value[x.toInt() % xAxisLabels.value.size] } val expensesMap = mutableMapOf<String, Float>().apply { xAxisLabels.value.forEach { put(it, 0f) } } fun fetchExpensesData(timeFrame: String) { val startCalendar = Calendar.getInstance() val endCalendar = Calendar.getInstance() var dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault()) when (timeFrame) { "Daily" -> { // Daily: Showing 7 days in a week startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek) endCalendar.add(Calendar.DATE, 6) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault()) val c = Calendar.getInstance() c.time = startCalendar.time while (c.timeInMillis < endCalendar.timeInMillis) { val date = dateFormat.format(c.time) expensesMap[date] = 0f c.add(Calendar.DATE, 1) } xAxisLabels.value = listOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") bottomAxisValueFormatter = AxisValueFormatter { x, _ -> xAxisLabels.value[x.toInt() % xAxisLabels.value.size] } } "Weekly" -> { // Weekly: Showing 4 weeks in a month startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set( Calendar.DAY_OF_MONTH, startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH), ) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault()) xAxisLabels.value = (1..4).map { "Week $it" } println(xAxisLabels.value) bottomAxisValueFormatter = AxisValueFormatter { x, _ -> xAxisLabels.value[x.toInt() % xAxisLabels.value.size] } } "Monthly" -> { // Monthly: Showing 12 months in a year startCalendar.set(Calendar.MONTH, 0) startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.MONTH, 11) endCalendar.set( Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) ) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault()) xAxisLabels.value = listOf( "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec" ) bottomAxisValueFormatter = AxisValueFormatter { x, _ -> xAxisLabels.value[x.toInt() % xAxisLabels.value.size] } } "Yearly" -> { startCalendar.set(Calendar.MONTH, 0) startCalendar.set(Calendar.DAY_OF_MONTH, -1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.MONTH, 11) endCalendar.set(Calendar.DAY_OF_MONTH, 31) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("yyyy", Locale.getDefault()) } else -> { throw IllegalArgumentException("Unsupported time frame: $timeFrame") } } val expensesMap = mutableMapOf<String, Float>().apply { xAxisLabels.value.forEach { put(it, 0f) } } val query = db.collection("expenses") .document("Kantin") .collection(timeFrame.lowercase()) query.get().addOnSuccessListener { result -> val expenses = mutableListOf<Pair<Float, Date>>() for (document in result) { val total = document.getDouble("total")?.toFloat() ?: 0f val date = dateFormat.parse(document.id) ?: Date() expenses.add(total to date) } expenses.groupBy({ dateFormat.format(it.second) }, { it.first }).forEach { date, values -> values.sum().let { expenseSum -> expensesMap[date] = expensesMap.getOrDefault(date, 0f) + expenseSum } } for (expense in expenses) { val dateFormatted = dateFormat.format(expense.second) expensesMap[dateFormatted] = expense.first } chartEntries.value = entriesOf(*expensesMap.entries.mapIndexed { index, (_, expense) -> index.toFloat() to expense } .toTypedArray()) } } LaunchedEffect(Unit) { fetchExpensesData(timeFrames[0]) } Column(modifier = Modifier.padding(paddingValues)) { timeFrames.forEachIndexed { index, timeFrame -> Button( onClick = { selectedIndex.value = index fetchExpensesData(timeFrame) }, colors = ButtonDefaults.buttonColors( containerColor = if (selectedIndex.value == index) DarkGray else LightGray ) ) { Text(timeFrame) } } val AXIS_VALUE_OVERRIDER_Y_FRACTION = 1.2f val axisValueOverrider = AxisValuesOverrider.adaptiveYValues( yFraction = AXIS_VALUE_OVERRIDER_Y_FRACTION, round = true ) ProvideChartStyle(chartStyle = m3ChartStyle()) { Chart( chart = columnChart( axisValuesOverrider = axisValueOverrider ), chartModelProducer = chartModelProducer, startAxis = startAxis(), bottomAxis = bottomAxis( valueFormatter = bottomAxisValueFormatter ), marker = rememberMarker() ) } } - Assistant
- User
I use the documents name to store the date, for example Saturday_22_Apr_2023
- Assistant
In that case, you should modify the queries in the "Daily" and "Weekly" cases to use the proper field name, which in this case is "id" (since you're using the document name to store the date). You can achieve this by creating a range query on document IDs, which unfortunately is not directly supported in Firestore. However, you can use a workaround using a combination of
startAt()andendAt()query functions:To create this range query, you can modify the end of the "Daily" and "Weekly" cases like this:
when (timeFrame) { "Daily" -> { // Daily: Showing 7 days in a week ... // Add this at the end of the "Daily" case val startDocId = dateFormat.format(startCalendar.time) val endDocId = dateFormat.format(endCalendar.time) query = query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId) ... } "Weekly" -> { // Weekly: Showing 4 weeks in a month ... // Add this at the end of the "Weekly" case val startDocId = dateFormat.format(startCalendar.time) val endDocId = dateFormat.format(endCalendar.time) query = query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId) ... } ... } - User
Smart cast to 'MutableList' is impossible, because 'xAxisLabels.value' is a complex expression
- Assistant
My apologies for the confusion. You're right; directly assigning a new instance to
xAxisLabels.valueusing a complex expression might not work. Instead, you can create a new list first, populate it, and then assign it toxAxisLabels.value.Replace the code that updates
xAxisLabels.valuein the "Daily" case with the following:val c = Calendar.getInstance() c.time = startCalendar.time val newLabels = mutableListOf<String>() while (c.timeInMillis < endCalendar.timeInMillis) { newLabels.add(dateFormat.format(c.time)) c.add(Calendar.DATE, 1) } xAxisLabels.value = newLabelsThis code first creates a new list called
newLabels, populates it with the specific dates within the 7 days, and then assignsnewLabelstoxAxisLabels.value.Similarly, if you want to update the xAxisLabels for the "Weekly" graph, you can follow the same approach with a new list, populate it accordingly, and then assign it to
xAxisLabels.value. - User
now it is showing 10 days for the daily graph and sunday is missing
- Assistant
It seems like the number of days shown in the "Daily" graph is not correct. Let's fix the issue by making sure the start and end calendar values are correct and that the xAxisLabels are also being updated correctly.
To fix the issue with the "Daily" graph, first, update the start and end calendar values in the "Daily" case to fix their week starting and ending days. Here's the updated code:
"Daily" -> { // Daily: Showing 7 days in a week startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.time = startCalendar.time endCalendar.add(Calendar.DATE, 6) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) ... - User
- Assistant
Apologies for the confusion earlier. It appears that the logic to filter documents based on the date was placed inside the query's
addOnSuccessListenerblock. Instead, this logic should be moved outside the block to correctly build the query before fetching the data from Firestore. - User
- Assistant
I see that you moved the logic to calculate startCalendar and endCalendar values inside the
addOnSuccessListenerblock. Instead, the logic should be placed outside the block, before fetching the data from Firestore, which I recommended in one of my previous responses.The issue with the data not showing in the graph is the filtering logic that you added inside the
addOnSuccessListenerblock. Instead of manually filtering the data inside the block, we should build the query before fetching the data. The filtering will then automatically happen on the server-side. - User
the daily is perfect now, how to fix the weekly timeframe it is still showing 6 weeks
"Weekly" -> { // Weekly: Showing 4 weeks in a month startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set( Calendar.DAY_OF_MONTH, startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH), ) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault())
xAxisLabels.value = (1..4).map { "Week $it" } bottomAxisValueFormatter = AxisValueFormatter { x, _ -> xAxisLabels.value[x.toInt() % xAxisLabels.value.size] } val startDocId = dateFormat.format(startCalendar.time) val endDocId = dateFormat.format(endCalendar.time) query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId) } - Assistant
I'm glad the daily graph works as expected. To fix the "Weekly" timeframe, we need to adjust some logic inside the "Weekly" case.
First, update the start and end calendar values in the "Weekly" case to match the start and end weeks of the current month. You can compute the start and end of the weeks by getting the first week of the month and adding three weeks to it.
Here's the updated code inside the "Weekly" case for setting the start and end calendar values:
"Weekly" -> { // Weekly: Showing 4 weeks in a month startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) // Move to the first day of the week while (startCalendar.get(Calendar.DAY_OF_WEEK) != startCalendar.firstDayOfWeek) { startCalendar.add(Calendar.DATE, -1) } endCalendar.time = startCalendar.time endCalendar.add(Calendar.DATE, 3 * 7) // Move to the end of the fourth week endCalendar.set(Calendar.HOUR_OF_DAY, 23) endCalendar.set(Calendar.MINUTE, 59) endCalendar.set(Calendar.SECOND, 59) endCalendar.set(Calendar.MILLISECOND, 999) dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault()) val startDocId = dateFormat.format(startCalendar.time) val endDocId = dateFormat.format(endCalendar.time) query = query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId) ... } - User
I want to design my weekly timeframe as such, so for example April 2023 has 6 weeks, I want each month to only have 4 weeks, each week has to be clean so Monday to Sunday
- Assistant
Understood, you want to display the first 4 weeks of each month in the weekly timeframe.
To implement this, use the startCalendar to point to the first weekday of the first week of the month, then update the endCalendar to point to the last weekday of the fourth week of that month. Here's how to update the "Weekly" case:
"Weekly" -> { // Weekly: Showing 4 weeks in a month startCalendar.set(Calendar.DAY_OF_MONTH, 1) // Set to the first day of the month while (startCalendar.get(Calendar.DAY_OF_WEEK) != startCalendar.firstDayOfWeek) { startCalendar.add(Calendar.DATE, -1) // Move backward until reaching the first day of the week } startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.time = startCalendar.time endCalendar.add(Calendar.DATE, 4 * 7 - 1) // Move forward 4 weeks (minus 1 day to include the start day) endCalendar.set(Calendar.HOUR_OF_DAY, 23) end