@@ -150,26 +150,39 @@ class MeasurementFacade @Inject constructor(
150150 val enriched = enrichedFlowForUser(userId, measurementTypesFlow)
151151
152152 @OptIn(ExperimentalCoroutinesApi ::class )
153- val timeFiltered: Flow <List <EnrichedMeasurement >> =
154- combine(enriched, startTimeMillisFlow, endTimeMillisFlow) { list, startMs, endMs ->
155- filter.getTimeFiltered(flowOf(list), startMs, endMs)
156- }.flatMapLatest { it }
157-
158- // 1. Aggregate first — smoothing then operates on fewer, more meaningful points
159- val aggregated: Flow <List <AggregatedMeasurement >> =
160- combine(timeFiltered, aggregationLevelFlow) { list, level ->
161- aggregation.aggregate(list, level)
162- }
153+ val timeFiltered = combine(enriched, startTimeMillisFlow, endTimeMillisFlow) { list, startMs, endMs ->
154+ filter.getTimeFiltered(flowOf(list), startMs, endMs)
155+ }.flatMapLatest { it }
156+
157+ val aggregated = combine(timeFiltered, aggregationLevelFlow) { list, level ->
158+ aggregation.aggregate(list, level)
159+ }
163160
164- // 2. Smooth after aggregation
165- return smooth.applySmoothing(
161+ val smoothed = smooth.applySmoothing(
166162 baseAggregatedFlow = aggregated,
167163 typesToSmoothFlow = typesToSmoothFlow,
168164 algorithmFlow = algorithmFlow,
169165 alphaFlow = alphaFlow,
170166 windowFlow = windowFlow,
171167 maxGapDaysFlow = maxGapDaysFlow,
172168 )
169+
170+ return combine(smoothed, measurementTypesFlow, aggregationLevelFlow) { list, types, level ->
171+ if (list.isEmpty() || level == AggregationLevel .NONE ) return @combine list
172+
173+ val newest = list.first()
174+ val aggregatedAsMwv = list.map { it.enriched.measurementWithValues }
175+ val projection = enricher.enrichWithProjection(aggregatedAsMwv, types)
176+
177+ if (projection.isEmpty()) return @combine list
178+
179+ val withProjection = newest.copy(
180+ enriched = newest.enriched.copy(
181+ measurementWithValuesProjected = projection
182+ )
183+ )
184+ listOf (withProjection) + list.drop(1 )
185+ }
173186 }
174187
175188 // -------------------------------------------------------------------------
0 commit comments