Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

fun ExpensesGraph(paddingValues: PaddingValues) { val db =…

  1. User

    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
    
        val query = db.collection("expenses")
            .document("Kantin")
            .collection(timeFrame.lowercase())
    
        startCalendar.firstDayOfWeek = Calendar.MONDAY
        endCalendar.firstDayOfWeek = Calendar.MONDAY
    
            when (timeFrame) {
                "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.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 2) endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 6) endCalendar.set(Calendar.HOUR_OF_DAY, 23) endCalendar.set(Calendar.MINUTE, 59) endCalendar.set(Calendar.SECOND, 59) endCalendar.set(Calendar.MILLISECOND, 999) dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault())

                    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 = newLabels
    
                    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)
                }
    
                "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)
    
                    while (startCalendar.get(Calendar.DAY_OF_WEEK) != startCalendar.firstDayOfWeek) {
                        startCalendar.add(Calendar.DATE, +1)
                    }
    
                    endCalendar.time = startCalendar.time
                    endCalendar.add(Calendar.DATE, 3 * 7)
                    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 weekDateFormat = SimpleDateFormat("d_MMM_yyyy", Locale.getDefault())
    
                    val c = Calendar.getInstance()
                    c.time = startCalendar.time
                    val newLabels = mutableListOf<String>()
    
                    var weekCounter = 1
                    while (c.timeInMillis <= endCalendar.timeInMillis) {
                        newLabels.add("Week $weekCounter")
                        weekCounter += 1
                    }
                    xAxisLabels.value = newLabels
    

    // 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)
                }
    
                "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())
    
                    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 = newLabels
    

    // 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] }

                    val startDocId = dateFormat.format(startCalendar.time)
                    val endDocId = dateFormat.format(endCalendar.time)
                    query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId)
                }
    
                "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())
    
                    val startDocId = dateFormat.format(startCalendar.time)
                    val endDocId = dateFormat.format(endCalendar.time)
                    query.orderBy(FieldPath.documentId()).startAt(startDocId).endAt(endDocId)
                }
    
                else -> {
                    throw IllegalArgumentException("Unsupported time frame: $timeFrame")
                }
            }
    
        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()
                if (date.time >= startCalendar.timeInMillis && date.time <= endCalendar.timeInMillis) {
                    expenses.add(total to date)
                }
            }
    
            val expensesMap = mutableMapOf<String, Float>().apply {
                xAxisLabels.value.forEach { put(it, 0f) }
            }
    
            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()
            )
        }
    }
    

    }

    why is my weekly graph showing Week1, Week2, Week3, Week4 and Week1, I only have 3_Apr_2023 in my firestore weekly timeframe, I want it to be mapped to Week1, Week2, Week3, and Week4 and only that

  2. Assistant

    It looks like you have an issue in your fetchExpensesData function when handling the "Weekly" timeFrame. After creating the newLabels list with only four weeks, you overwrite it with a new list that contains five weeks - this is why you see Week1 again at the end.

    Here's how you can fix this issue:

    1. Remove the line weekCounter += 1, which is incrementing the weekCounter variable one extra time, causing the fifth week to be added to the list.

    2. Also, update the while loop condition to run a maximum of 4 times, ensuring that only 4 weeks are added to the newLabels list.

    You can achieve this by adjusting your "Weekly" case in the fetchExpensesData function as follows:

    "Weekly" -> {
        // ... other code isn't changed ...
    
        val c = Calendar.getInstance()
        c.time = startCalendar.time
        val newLabels = mutableListOf<String>()
    
        var weekCounter = 1
        while (c.timeInMillis <= endCalendar.timeInMillis && weekCounter <= 4) {
            newLabels.add("Week $weekCounter")
            weekCounter += 1
            c.add(Calendar.DATE, 7) // increment c by 7 days
        }
        xAxisLabels.value = newLabels
    
        // ... other code isn't changed ...
    }
    

    With these changes, your weekly graph should only display Week1, Week2, Week3, and Week4.

  3. User

    thats not the problem because the fifth week is Week1

  4. Assistant

    I see. I misunderstood the issue previously. It appears the problem lies in how the data is being processed while creating the list newLabels in the "Weekly" case.

    Update the "Weekly" case in the fetchExpensesData function as follows:

    "Weekly" -> {
        // ... other code isn't changed ...
    
        val c = Calendar.getInstance()
        c.time = startCalendar.time
        val newLabels = mutableListOf<String>()
    
        var weekCounter = 1
        while (c.timeInMillis <= endCalendar.timeInMillis && weekCounter <= 4) {
            newLabels.add("Week $weekCounter")
            weekCounter += 1
            c.add(Calendar.DATE, 7) // Change this line to increment c by 7 days
        }
        xAxisLabels.value = newLabels
    
        // ... other code isn't changed ...
    }
    

    This change should fix the issue with the weekly graph labels.

  5. User

    still the same

  6. Assistant

    I apologize for the confusion. Let's investigate the issue step by step.

    First, let's make sure we are handling the calendar objects correctly. We'll add some log statements to gather more information:

    "Weekly" -> {
        // ... other code isn't changed ...
    
        val c = Calendar.getInstance()
        c.time = startCalendar.time
        
        // Add log statements to display startCalendar and endCalendar
        Log.d("Weekly", "Start Calendar: ${startCalendar.time}")
        Log.d("Weekly", "End Calendar: ${endCalendar.time}")
    
        val newLabels = mutableListOf<String>()
    
        var weekCounter = 1
        while (c.timeInMillis <= endCalendar.timeInMillis && weekCounter <= 4) {
            newLabels.add("Week $weekCounter")
            // Add log statement to display c and the corresponding label
            Log.d("Weekly", "Calendar c: ${c.time}, Label: Week $weekCounter")
            
            weekCounter += 1
            c.add(Calendar.DATE, 7) // Increment c by 7 days
        }
        xAxisLabels.value = newLabels
    
        // ... other code isn't changed ...
    }```
    
    Run the app and check the log output. This will give us more information about the issue.
    
  7. User

    Start Calendar: Mon Apr 03 00:00:00 GMT+08:00 2023 End Calendar: Mon Apr 24 23:59:59 GMT+08:00 2023

  8. Assistant

    The log shows that your startCalendar and endCalendar are set correctly for the Weekly time frame. The weeks in this range should be labeled Week1, Week2, Week3, and Week4.

    Now, let's move on to the next part of the code, where we process the data and create chartEntries for the graph. We'll add some logging inside the addOnSuccessListener and display the contents of expenses, expensesMap, and chartEntries:

    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()
            if (date.time >= startCalendar.timeInMillis && date.time <= endCalendar.timeInMillis) {
                expenses.add(total to date)
            }
        }
        
        // Add log statement to display expenses
        Log.d("Expenses", "Expenses: $expenses")
    
        val expensesMap = mutableMapOf<String, Float>().apply {
            xAxisLabels.value.forEach { put(it, 0f) }
        }
    
        expenses.groupBy({ dateFormat.format(it.second) }, { it.first })
            .forEach { date, values ->
                values.sum().let { expenseSum ->
                    expensesMap[date] = expensesMap.getOrDefault(date, 0f) + expenseSum
                }
            }
        
        // Add log statement to display expensesMap
        Log.d("ExpensesMap", "Expenses Map: $expensesMap")
    
        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())
        
        // Add log statement to display chartEntries
        Log.d("ChartEntries", "Chart Entries: ${chartEntries.value}")
    }
    

    Run the app and share the new log output with me. This will help us further investigate the issue.

  9. User

    Expenses: [(32131.0, Sun Apr 09 00:00:00 GMT+08:00 2023)] Expenses Map: {Week 1=0.0, Week 2=0.0, Week 3=0.0, Week 4=0.0, 3_Apr_2023=32131.0}

  10. Assistant

    Thank you for providing the log output. It appears there is an issue with the processing of the expenses list and the creation of the chartEntries.

    The problem lies in these lines of code:

    expenses.groupBy({ dateFormat.format(it.second) }, { it.first })
        .forEach { date, values ->
            values.sum().let { expenseSum ->
                expensesMap[date] = expensesMap.getOrDefault(date, 0f) + expenseSum
            }
        }
    

    The groupBy function creates a map, but its keys are generated by dateFormat.format(it.second), which creates a date string like "3_Apr_2023". However, the keys in the expensesMap are of the format "Week X". So, the expensesMap doesn't get properly updated, resulting in the wrong data being displayed on the graph.

    Instead, we need to update the expenses.groupBy function to group based on the week number, not the date string.

    Update your "Weekly" case in the fetchExpensesData function with the following changes in addOnSuccessListener:

    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()
            if (date.time >= startCalendar.timeInMillis && date.time <= endCalendar.timeInMillis) {
                expenses.add(total to date)
            }
        }
    
        val expensesMap = mutableMapOf<String, Float>().apply {
            xAxisLabels.value.forEach { put(it, 0f) }
        }
    
        // Get the start date for the first week to calculate week numbers
        val firstWeekStartDate = startCalendar.time
    
        // Update the groupBy function to group by week number
        expenses.groupBy({ (it.second.time - firstWeekStartDate.time) / (7 * 24 * 60 * 60 * 1000) }, { it.first })
           .forEach { weekNumber, values ->
                values.sum().let { expenseSum ->
                    // Update weekNumber to 1-based instead of 0-based
                    val weekLabel = "Week ${weekNumber + 1}"
                    expensesMap[weekLabel] = expensesMap.getOrDefault(weekLabel, 0f) + expenseSum
                }
            }
    
        chartEntries.value =
            entriesOf(*expensesMap.entries.mapIndexed { index, (_, expense) -> index.toFloat() to expense }
                .toTypedArray())
    }
    

    These changes should fix the issue, and your weekly graph should display the correct data for each week.

  11. User

    so based on your code Week 1 would not get inputted because it only has Saturday, and Week 6 would not be inputted because it only has Sunday, so the code will search for Week 2 - Week 5, right?

  12. Assistant

    Apologies for the confusion earlier. Based on the code I provided, it will search for Week 1 to Week 4. I misunderstood your requirement. You would like to have the graph show Week 1 as just Saturday and Week 6 as only Sunday while showing Week 2 to Week 5 as complete weeks in between. Here is the updated code to achieve your desired result:

    In your query part for the "Weekly" case, update the end week calculation as follows:

    // Weekly: Showing 4 weeks in a month
    // ...
    endCalendar.time = startCalendar.time
    endCalendar.add(Calendar.DATE, 4 * 7 - 1) // Changed from 3 * 7 to (4 * 7 - 1)
    endCalendar.set(Calendar.HOUR_OF_DAY, 23)
    endCalendar.set(Calendar.MINUTE, 59)
    endCalendar.set(Calendar.SECOND, 59)
    endCalendar.set(Calendar.MILLISECOND, 999)
    

    Next, update the addOnSuccessListener part as follows:

    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()
            if (date.time >= startCalendar.timeInMillis && date.time <= endCalendar.timeInMillis) {
                expenses.add(total to date)
            }
        }
    
        val expensesMap = mutableMapOf<String, Float>().apply {
            xAxisLabels.value.forEach { put(it, 0f) }
        }
    
        // Get the start date for the first week to calculate week numbers
        val firstWeekStartDate = startCalendar.time
    
        // Update the groupBy function to group by week number
        expenses.groupBy({ (it.second.time - firstWeekStartDate.time) / (7 * 24 * 60 * 60 * 1000) }, { it.first })
           .forEach { weekNumber, values ->
                values.sum().let { expenseSum ->
                    // Update weekNumber to 1-based and add 1
                    val weekLabel = "Week ${weekNumber + 2}" // Instead of weekNumber + 1, use weekNumber + 2
                    expensesMap[weekLabel] = expensesMap.getOrDefault(weekLabel, 0f) + expenseSum
                }
            }
    
        chartEntries.value =
            entriesOf(*expensesMap.entries.mapIndexed { index, (_, expense) -> index.toFloat() to expense }
                .toTypedArray())
    }
    

    Now, the code will search for Week 1 with just Saturday and Week 6 with only Sunday and also show Week 2 to Week 5 with normal weekdays in between.