// 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>())) }
val chartModelProducer = ChartEntryModelProducer(chartEntries.value)
val markers = remember { mutableStateOf<Map<Float, Marker>>(emptyMap()) }
fun fetchExpensesData(timeFrame: String) {
val startCalendar = Calendar.getInstance()
val endCalendar = Calendar.getInstance()
var dateFormat: SimpleDateFormat
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 + 1)
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())
}
"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())
}
"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())
}
"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 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)
println("Document: ${document.id}, Total: $total, Date: $date")
}
println(startCalendar.time)
println(endCalendar.time)
expenses.retainAll { it.second >= startCalendar.time && it.second <= endCalendar.time }
// Sort the expenses by date
expenses.sortBy { it.second }
chartEntries.value =
entriesOf(*expenses.mapIndexed { index, expense -> index.toFloat() to expense.first }
.toTypedArray())
}
}
LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) }
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)
}
}
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(),
)
}
}
}
this is my expenses graph screen, right now the amount of x axis will be dependent to the amount of document in the firestore, I want it to be persistent so for example in my daily timeframe it will always show Monday to Sunday in the x axis even though there is still no data for Wednesday to Sunday
Added axisLabels state to track x-axis labels for each timeframe
Predefined expected dates and labels for each timeframe
Created a date-to-value map from Firestore data
Generated entries for all expected dates, filling 0 when no data exists
Modified bottom axis formatter to use the predefined labels
Used proper date formatting and calendar calculations for each timeframe
Added automatic label generation for days/weeks/months/years
Added chart update on data change with chartModelProducer.updateEntries()
This implementation will:
Show all days of the week for Daily view (Mon-Sun)
Show all weeks of the month for Weekly view
Show all months for Monthly view
Show 5-year span for Yearly view
Display 0 values for missing data points
Maintain consistent x-axis labels regardless of data availability
Here's a comprehensive solution implementing swipe navigation with consistent axis labels:
kotlin
@Composable
fun ExpensesGraph(paddingValues: PaddingValues) {
val db = FirebaseFirestore.getInstance()
val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly")
val selectedIndex = remember { mutableStateOf(0) }
val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) }
val chartModelProducer = remember { ChartEntryModelProducer(chartEntries.value) }
val axisLabels = remember { mutableStateOf<List<String>>(emptyList()) }
val currentOffset = remember { mutableStateOf(0) }
val currentBaseDate = remember { mutableStateOf(Calendar.getInstance()) }
fun updateTimeFrame(offsetDelta: Int) {
currentOffset.value += offsetDelta
fetchExpensesData(timeFrames[selectedIndex.value])
}
fun calculateDateRange(timeFrame: String): Pair<Date, Date> {
val calendar = currentBaseDate.value.clone() as Calendar
return when (timeFrame) {
"Daily" -> {
calendar.add(Calendar.DATE, currentOffset.value * 7)
calendar.set(Calendar.DAY_OF_WEEK, calendar.firstDayOfWeek)
val start = calendar.time
calendar.add(Calendar.DATE, 6)
val end = calendar.time
start to end
}
"Weekly" -> {
calendar.add(Calendar.WEEK_OF_YEAR, currentOffset.value)
calendar.set(Calendar.DAY_OF_WEEK, calendar.firstDayOfWeek)
val start = calendar.time
calendar.add(Calendar.DATE, 6)
val end = calendar.time
start to end
}
"Monthly" -> {
calendar.add(Calendar.MONTH, currentOffset.value)
calendar.set(Calendar.DAY_OF_MONTH, 1)
val start = calendar.time
calendar.add(Calendar.MONTH, 1)
calendar.add(Calendar.DATE, -1)
val end = calendar.time
start to end
}
"Yearly" -> {
calendar.add(Calendar.YEAR, currentOffset.value)
calendar.set(Calendar.DAY_OF_YEAR, 1)
val start = calendar.time
calendar.add(Calendar.YEAR, 1)
calendar.add(Calendar.DATE, -1)
val end = calendar.time
start to end
}
else -> throw IllegalArgumentException("Invalid timeframe")
}
}
fun fetchExpensesData(timeFrame: String) {
val (startDate, endDate) = calculateDateRange(timeFrame)
val dateFormat = when (timeFrame) {
"Daily" -> SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault())
"Weekly" -> SimpleDateFormat("w_MMM_yyyy", Locale.getDefault())
"Monthly" -> SimpleDateFormat("MMM_yyyy", Locale.getDefault())
"Yearly" -> SimpleDateFormat("yyyy", Locale.getDefault())
else -> throw IllegalArgumentException("Invalid timeframe")
}
// Generate axis labels
axisLabels.value = when (timeFrame) {
"Daily" -> List(7) { idx ->
val cal = Calendar.getInstance().apply { time = startDate }
cal.add(Calendar.DATE, idx)
SimpleDateFormat("EEE", Locale.getDefault()).format(cal.time)
}
"Weekly" -> listOf("Week ${currentOffset.value + 1}")
"Monthly" -> List(12) { idx ->
val cal = Calendar.getInstance().apply { time = startDate }
cal.add(Calendar.MONTH, idx)
SimpleDateFormat("MMM", Locale.getDefault()).format(cal.time)
}
"Yearly" -> List(5) { idx ->
(Calendar.getInstance().get(Calendar.YEAR) - 2 + idx).toString()
}
else -> emptyList()
}
db.collection("expenses")
.document("Kantin")
.collection(timeFrame.lowercase())
.whereGreaterThanOrEqualTo("date", startDate)
.whereLessThanOrEqualTo("date", endDate)
.get()
.addOnSuccessListener { result ->
val dataPoints = mutableMapOf<String, Float>()
result.forEach { document ->
val total = document.getDouble("total")?.toFloat() ?: 0f
val date = document.getDate("date") ?: Date()
dataPoints[dateFormat.format(date)] = total
}
val entries = when (timeFrame) {
"Daily" -> List(7) { idx ->
val cal = Calendar.getInstance().apply { time = startDate }
cal.add(Calendar.DATE, idx)
idx.toFloat() to (dataPoints[dateFormat.format(cal.time)] ?: 0f)
}
"Weekly" -> listOf(0f to (dataPoints.values.sum() ?: 0f))
"Monthly" -> List(12) { idx ->
idx.toFloat() to (dataPoints.values.sum() ?: 0f)
}
"Yearly" -> List(5) { idx ->
idx.toFloat() to (dataPoints.values.sum() ?: 0f)
}
else -> emptyList()
}
chartEntries.value = entriesOf(*entries.toTypedArray())
chartModelProducer.updateEntries(chartEntries.value)
}
}
LaunchedEffect(selectedIndex.value) {
currentOffset.value = 0
currentBaseDate.value = Calendar.getInstance()
fetchExpensesData(timeFrames[selectedIndex.value])
}
Column(
modifier = Modifier
.padding(paddingValues)
.pointerInput(Unit) {
detectSwipeGestures(
onSwipeLeft = { updateTimeFrame(1) },
onSwipeRight = { updateTimeFrame(-1) }
)
}
) {
// Timeframe selector buttons
Row {
timeFrames.forEachIndexed { index, timeFrame ->
Button(
onClick = {
selectedIndex.value = index
currentOffset.value = 0
currentBaseDate.value = Calendar.getInstance()
},
colors = ButtonDefaults.buttonColors(
containerColor = if (selectedIndex.value == index) Color.DarkGray else Color.LightGray
)
) {
Text(timeFrame)
}
}
}
// Navigation header
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(onClick = { updateTimeFrame(-1) }) {
Icon(Icons.Default.ArrowBack, "Previous")
}
Text(
text = when (timeFrames[selectedIndex.value]) {
"Daily" -> SimpleDateFormat("MMM yyyy", Locale.getDefault())
.format(currentBaseDate.value.time)
"Weekly" -> "Week ${currentOffset.value + 1}"
"Monthly" -> SimpleDateFormat("yyyy", Locale.getDefault())
.format(currentBaseDate.value.time)
"Yearly" -> "Year Range"
else -> ""
},
modifier = Modifier.align(Alignment.CenterVertically)
)
IconButton(onClick = { updateTimeFrame(1) }) {
Icon(Icons.Default.ArrowForward, "Next")
}
}
// Chart
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(
valueFormatter = { value, _ ->
axisLabels.value.getOrNull(value.toInt()) ?: ""
}
),
modifier = Modifier
.height(300.dp)
.fillMaxWidth()
)
}
}
}
Key features implemented:
Swipe Gestures:
Added pointerInput with detectSwipeGestures for left/right navigation
Arrow buttons for explicit navigation
Smooth transitions between time periods
Dynamic Date Ranges:
calculateDateRange function handles date math for different timeframes
currentOffset state tracks navigation position
Query filters using Firestore's whereGreaterThanOrEqualTo and whereLessThanOrEqualTo
Consistent Axis Labels:
Pre-generated labels based on timeframe
Dynamic label formatting for different ranges
Empty values filled with 0 to maintain chart structure
State Management:
Separate states for timeframe selection and navigation offset
Automatic reset when changing timeframes
Base date tracking for relative navigation
Visual Feedback:
Navigation header shows current period
Buttons indicate active timeframe
Smooth chart updates with updateEntries
Usage instructions:
Swipe left/right or use arrow buttons to navigate between periods
Click timeframe buttons to switch between daily/weekly/monthly views
Chart automatically fills missing data points with zero values
Labels remain consistent regardless of data availability
This implementation provides a smooth user experience while maintaining data integrity and consistent visualization across different time ranges.
Handling timezone differences is crucial when dealing with date-based data in a global application. Here's a comprehensive approach to ensure consistent chart display across different regions:
1. Store dates in a standardized timezone:
Use UTC (Coordinated Universal Time): Store all dates in UTC format in your Firestore database. This provides a single, unambiguous timezone for all date-related operations.
Convert to UTC upon insertion: When storing dates, convert them to UTC using the client's local timezone offset (e.g., using JavaScript's getTimezoneOffset() or equivalent in your client-side language).
Firestore Example (JavaScript):
javascript
const clientDate = new Date(); // Client's local date
const utcDate = new Date(clientDate.getTime() + (clientDate.getTimezoneOffset() * 60 * 1000));
await db.collection('expenses').add({
date: utcDate, // Store UTC date in Firestore
// ...
});
2. Query dates in UTC:
No conversion needed: Since dates are stored in UTC, your queries can directly use these values without worrying about timezone conversions.
Firestore Example (JavaScript):
javascript
const startDate = new Date('2023-03-01T00:00:00.000Z'); // UTC date
const endDate = new Date('2023-03-31T23:59:59.999Z'); // UTC date
db.collection('expenses')
.where('date', '>=', startDate)
.where('date', '<=', endDate)
.get()
.then((querySnapshot) => {
// Process results
});
3. Display dates in the user's local timezone:
Convert UTC to local timezone on the client-side: When fetching dates from Firestore, convert them to the user's local timezone for display purposes.
Use client-side libraries or functions: Utilize libraries like Moment.js (with Moment-Timezone) or Date libraries in your framework (e.g., Java's ZoneDateTime) to perform timezone conversions.
Client-side Example (JavaScript with Moment.js):
javascript
import moment from 'moment-timezone';
const utcDate = doc.data().date; // UTC date from Firestore
const localDate = moment.utc(utcDate).local().format('YYYY-MM-DD HH:mm:ss');
// Display localDate in your chart
4. Considerations for Charting Libraries:
Inform your charting library about the timezone: If your charting library supports timezone settings, configure it to work with the user's local timezone.
Format dates according to the user's locale: Use the Intl.DateTimeFormat API or equivalent to format dates and times according to the user's locale settings.
Additional Tips:
Test thoroughly: Verify your implementation across different timezones and daylight saving transitions.
Document timezone assumptions: Clearly document your timezone handling approach for future maintainers and contributors.
Be mindful of historical data: If dealing with existing data, ensure to convert historical dates to UTC if they were stored in a different timezone.
By following these steps, you'll ensure that your chart displays dates consistently across different regions, respecting each user's local timezone.