Address review of repeat from completion (#79)

This commit is contained in:
makiolaj committed 2026-11-17 11:08:49 +01:00
1 parent 70df9c8a4d
commit b0885169e7
11 files changed
+175 -61

No files matched your search

@@ -297,6 +297,63 @@ class RoomTasksDataSourceTest {
assertThat(copy.title).isEqualTo("Water the plants")
}
private fun fromCompletion(at: Instant, rule: String): Long = source.insertTask(
TaskForm(title = "Water the plants", listId = listId, start = at, due = at + 1.hours, rrule = rule, repeatFromCompletion = true),
)
@Test
fun aLateTickOfAFromCompletionSeriesCountsFromToday() {
val at = now - 10.days
val id = fromCompletion(at, "FREQ=DAILY;INTERVAL=7;COUNT=5")
source.setCompletedInstance(id, at, completed = true)
val master = db.tasks().entity(id)!!
assertThat(master.dtstart!!).isGreaterThan(now)
assertThat(master.dtstart!!).isLessThan(now + 8.days)
assertThat(master.due).isEqualTo(master.dtstart!! + 1.hours)
assertThat(master.rrule).isEqualTo("FREQ=DAILY;INTERVAL=7;COUNT=4")
assertThat(master.repeatsFromCompletion).isTrue()
val copy = db.tasks().allIn(listId).single { it.id != id }
assertThat(copy.status).isEqualTo(TaskStatus.COMPLETED)
assertThat(copy.dtstart).isEqualTo(at)
assertThat(copy.repeatsFromCompletion).isFalse()
}
@Test
fun anEarlyTickOfAFromCompletionSeriesStillMovesItOn() {
val at = now + 1.days
val id = fromCompletion(at, "FREQ=DAILY")
source.setCompletedInstance(id, at, completed = true)
assertThat(db.tasks().entity(id)!!.dtstart!!).isGreaterThan(at)
}
@Test
fun reopeningAFromCompletionTickMovesTheSeriesBack() {
val at = now - 10.days
val id = fromCompletion(at, "FREQ=DAILY;INTERVAL=7;COUNT=5")
source.setCompletedInstance(id, at, completed = true)
source.setCompletedInstance(id, at, completed = false)
val master = db.tasks().entity(id)!!
assertThat(master.dtstart).isEqualTo(at)
assertThat(master.rrule).isEqualTo("FREQ=DAILY;INTERVAL=7;COUNT=5")
assertThat(db.tasks().allIn(listId).filter { !it.isDeleted }.map { it.id }).containsExactly(id)
}
@Test
fun theLastTickOfAFromCompletionSeriesClosesIt() {
val at = now - 1.days
val id = fromCompletion(at, "FREQ=DAILY;COUNT=1")
source.setCompletedInstance(id, at, completed = true)
assertThat(db.tasks().entity(id)!!.status).isEqualTo(TaskStatus.COMPLETED)
}
@Test
fun reopeningTheOccurrenceMovesTheSeriesBack() {
val at = now
@@ -73,7 +73,7 @@ object RoomTaskMapper {
lastModified = row.task.lastModified,
seriesId = seriesId,
recurrenceRule = recurrenceRule,
repeatFromCompletion = recurrenceRule != null && repeatFromCompletion,
repeatFromCompletion = repeatFromCompletion,
isReadOnly = row.listReadOnly,
)
@@ -104,9 +104,14 @@ object RoomTaskMapper {
val TaskEntity.isRecurring: Boolean
get() = !rrule.isNullOrBlank() || !rdate.isNullOrBlank()
/** The series moves on from its completion rather than its schedule (#79). */
/**
* The series moves on from its completion rather than its schedule (#79).
* Only where a tick moves the series at all: not with `RDATE`s, nor for a
* recurring sub-task, which keep the override model.
*/
val TaskEntity.repeatsFromCompletion: Boolean
get() = !rrule.isNullOrBlank() && RepeatFromCompletion.isSet(unknownProperties)
get() = !rrule.isNullOrBlank() && rdate.isNullOrBlank() && parentId == null &&
RepeatFromCompletion.isSet(unknownProperties)
/** Completed or cancelled. */
val TaskEntity.isClosed: Boolean
@@ -33,6 +33,7 @@ import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/** How far either side of now a series is expanded. */
@@ -215,6 +216,7 @@ class RoomTasksDataSource @Inject constructor(
*/
private fun occurrencesOf(row: TaskRow, overrides: List<TaskEntity>, now: Instant): List<Task> {
val occurrences = seriesOccurrences(row.task, overrides, now) ?: return listOf(RoomTaskMapper.task(row))
val fromCompletion = row.task.repeatsFromCompletion
return occurrences.map { occurrence ->
val override = occurrence.override
if (override != null) {
@@ -226,7 +228,7 @@ class RoomTasksDataSource @Inject constructor(
distanceFromCurrent = occurrence.distance,
seriesId = row.task.id,
recurrenceRule = row.task.rrule,
repeatFromCompletion = row.task.repeatsFromCompletion,
repeatFromCompletion = fromCompletion,
)
} else {
RoomTaskMapper.task(
@@ -235,6 +237,7 @@ class RoomTasksDataSource @Inject constructor(
start = occurrence.start,
due = occurrence.due,
distanceFromCurrent = occurrence.distance,
repeatFromCompletion = fromCompletion,
)
}
}
@@ -619,9 +622,10 @@ class RoomTasksDataSource @Inject constructor(
* recurring subtasks, whose copies would pile up under the parent.
*
* A series repeating from completion (#79) moves to the first occurrence of
* its rule after the day it was ticked instead. That leaves the old
* schedule behind, so every other override becomes a task of its own, and
* comes back with the rest should the tick be undone.
* its rule after the day it was ticked instead, and always past [anchor].
* That leaves the old schedule behind: its `EXDATE`s go, and an override
* the new one does not generate becomes a task of its own. Undoing the tick
* brings both back.
*/
private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, close: (TaskEntity) -> TaskEntity): Boolean {
val rule = master.rrule?.takeIf { it.isNotBlank() } ?: return false
@@ -635,17 +639,29 @@ class RoomTasksDataSource @Inject constructor(
val now = clock.now()
val zone = master.timezone ?: zone()
val fromCompletion = master.repeatsFromCompletion
val newAnchor: Instant
val spent: Int
val toDetach: List<Pair<Instant, TaskEntity>>
if (master.repeatsFromCompletion) {
// Where the cycle the tick closes ends on the schedule, which measures it for the sub-tasks.
var cycleEnd: Instant? = null
if (fromCompletion) {
spent = spentBefore(spec, wholeSecond(anchor)) + 1
val left = TaskFormWriter.countOf(rule)?.let { it - spent }
val next = RepeatFromCompletion.nextAnchor(spec, now, ZoneId.of(zone()))
val next = RepeatFromCompletion.nextAnchor(spec, now, ZoneId.of(zone()), after = anchor)
if (next == null || (left != null && left < 1)) return true.also { closeSeries(master, override, close) }
newAnchor = next
toDetach = overrides.values.filter { it.id != override?.id }
.mapNotNull { row -> row.recurrenceId?.let { it to row } }
cycleEnd = leading.getOrNull(index + 1)
// The old schedule's exceptions go; overrides the new one still generates stay.
val others = overrides.values.filter { it.id != override?.id && it.recurrenceId != null }
val generated = others.maxOfOrNull { it.recurrenceId!! }?.takeIf { it >= newAnchor }?.let { last ->
val moved = spec.copy(rrule = TaskFormWriter.remainingCount(rule, spent), exdate = null, anchor = newAnchor)
RecurrenceExpander.expand(
moved,
ExpansionWindow(from = newAnchor, until = last + 1.seconds, maxOccurrences = SPLIT_COUNT_CEILING),
).mapTo(HashSet()) { it.epochSeconds }
}.orEmpty()
toDetach = others.filter { it.recurrenceId!!.epochSeconds !in generated }.map { it.recurrenceId!! to it }
} else {
var nextIndex = index + 1
while (nextIndex < leading.size && closedAt(leading[nextIndex])) nextIndex++
@@ -665,7 +681,7 @@ class RoomTasksDataSource @Inject constructor(
dtstart = start,
due = due,
rrule = ruleAfter,
exdate = TaskFormWriter.valuesFrom(master.exdate, newAnchor, zone),
exdate = if (fromCompletion) null else TaskFormWriter.valuesFrom(master.exdate, newAnchor, zone),
status = TaskStatus.NEEDS_ACTION,
percentComplete = null,
completedAt = null,
@@ -673,7 +689,8 @@ class RoomTasksDataSource @Inject constructor(
isDirty = true,
),
)
val (reset, resetLists) = resetSubtasks(master, newAnchor, now)
val (reset, resetLists) = resetSubtasks(master, newAnchor, now, cycleEnd ?: newAnchor)
val dropped = TaskFormWriter.instantsBefore(master.exdate, if (fromCompletion) Instant.DISTANT_FUTURE else newAnchor, zone)
val copyId = if (override != null) {
detach(override, now, close)
} else {
@@ -697,7 +714,7 @@ class RoomTasksDataSource @Inject constructor(
priorCompletedAt = master.completedAt,
spent = spent,
ruleAfter = ruleAfter,
droppedExdates = AdvancedOccurrenceEntity.encode(TaskFormWriter.instantsBefore(master.exdate, newAnchor, zone)),
droppedExdates = AdvancedOccurrenceEntity.encode(dropped),
fromOverride = override != null,
resetSubtasks = SubtaskReset.encode(reset),
),
@@ -710,16 +727,21 @@ class RoomTasksDataSource @Inject constructor(
/**
* Resets what [SubtaskReset] picks under [master] for the series' next
* occurrence at [newAnchor], dated ones moved along; the lists it wrote to.
* The cycle the tick closes is one step of the schedule, to [cycleEnd].
* A copy a provider tick of a recurring sub-task left, synced in, is known by
* its marker while it stays under the parent the marker names.
*/
private fun resetSubtasks(master: TaskEntity, newAnchor: Instant, now: Instant): Pair<List<ResetSubtask>, Set<Long>> {
private fun resetSubtasks(
master: TaskEntity,
newAnchor: Instant,
now: Instant,
cycleEnd: Instant,
): Pair<List<ResetSubtask>, Set<Long>> {
val from = master.recurrenceAnchor?.toEpochMilliseconds()
val to = newAnchor.toEpochMilliseconds()
val shift = from?.let { SeriesShift(it, to, dateZone(master.isAllDay, master.timezone, ZoneId.of(zone()))) }
val loaded = HashMap<Long, TaskEntity>().apply { put(master.id, master) }
// A series repeating from completion can move back, ticked early; there is no cycle to measure then.
val since = from?.takeIf { to > it }?.let { SubtaskReset.cycleStart(it, to) }
val since = from?.let { SubtaskReset.cycleStart(it, cycleEnd.toEpochMilliseconds()) }
val reset = SubtaskReset.toReset(master.id, shift, since = since) { id ->
val parentUid = loaded[id]?.uid
tasks.subtasks(id).map { row ->
@@ -72,8 +72,8 @@ object TaskFormWriter {
/**
* [current] with its rule set to [rrule], repeating from completion when
* [fromCompletion] (#79). Only ever a master or a plain task: an override
* carries no rule of its own.
* [fromCompletion] (#79), which a sub-task cannot. Only ever a master or a
* plain task: an override carries no rule of its own.
*/
fun withRule(current: TaskEntity, rrule: String?, fromCompletion: Boolean = false): TaskEntity {
val rule = rrule?.trim()?.removePrefix("RRULE:")?.ifEmpty { null }
@@ -84,7 +84,7 @@ object TaskFormWriter {
rule == null -> current.copy(rrule = null, rdate = null, exdate = null)
else -> current.copy(rrule = rule)
}
val flagged = rule != null && fromCompletion
val flagged = rule != null && fromCompletion && ruled.parentId == null
if (RepeatFromCompletion.isSet(ruled.unknownProperties) == flagged) return ruled
return ruled.copy(unknownProperties = RepeatFromCompletion.applied(ruled.unknownProperties, flagged))
}
@@ -214,14 +214,15 @@ object TaskFormWriter {
/** [rrule] with its `COUNT` lowered by [spent] occurrences, or unchanged without one. */
fun remainingCount(rrule: String, spent: Int): String = rrule.split(';').joinToString(";") { part ->
if (part.substringBefore('=').trim().uppercase() != "COUNT") part
if (!isCount(part)) part
else "COUNT=${((part.substringAfter('=').trim().toIntOrNull() ?: 1) - spent).coerceAtLeast(1)}"
}
/** [rrule]'s `COUNT`, or null without a readable one. */
fun countOf(rrule: String): Int? = rrule.split(';')
.firstOrNull { it.substringBefore('=').trim().equals("COUNT", ignoreCase = true) }
?.substringAfter('=')?.trim()?.toIntOrNull()
fun countOf(rrule: String): Int? =
rrule.split(';').firstOrNull(::isCount)?.substringAfter('=')?.trim()?.toIntOrNull()
private fun isCount(part: String) = part.substringBefore('=').trim().equals("COUNT", ignoreCase = true)
/** Cancelled, or back to needs-action; either way no longer complete. */
fun cancelled(current: TaskEntity, cancelled: Boolean, now: Instant): TaskEntity = current.copy(
@@ -64,35 +64,38 @@ object RepeatFromCompletion {
* The anchor [spec]'s series moves to once completed at [completedAt]: the
* first occurrence of its rule after the day it was completed, at the
* series' own time of day — or, for a rule repeating within a day, after the
* completion itself. `COUNT` is the caller's to spend. Null when the rule
* has nothing after it, an `UNTIL` passed, or there is no `RRULE`.
* completion itself. Ticked early, it is still the first such occurrence
* after [after], the occurrence ticked, so a tick always moves the series
* on. `COUNT` is the caller's to spend. Null when the rule has nothing
* left, an `UNTIL` passed, or there is no `RRULE`.
*
* [floatingZone] is the user's zone: it decides which day the completion
* fell on, and the wall time of a series without a zone of its own.
* [floatingZone] is the user's zone: the day an all-day series was
* completed on, and the zone of a timed series without one of its own.
*/
fun nextAnchor(spec: RecurrenceSpec, completedAt: Instant, floatingZone: ZoneId): Instant? {
fun nextAnchor(spec: RecurrenceSpec, completedAt: Instant, floatingZone: ZoneId, after: Instant? = null): Instant? {
val parts = spec.rrule?.trim()?.removePrefix("RRULE:")?.split(';')
?.map(String::trim)?.filter(String::isNotEmpty)
?.takeIf { it.isNotEmpty() } ?: return null
val freq = parts.firstOrNull { it.substringBefore('=').equals("FREQ", ignoreCase = true) }
?.substringAfter('=')?.trim()?.uppercase() ?: return null
val rule = parts.filterNot { it.substringBefore('=').trim().equals("COUNT", ignoreCase = true) }.joinToString(";")
val completedDay = java.time.Instant.ofEpochMilli(completedAt.toEpochMilliseconds()).atZone(floatingZone).toLocalDate()
val zone = if (spec.isAllDay) floatingZone else dateZone(false, spec.timeZone, floatingZone)
val completedDay = java.time.Instant.ofEpochMilli(completedAt.toEpochMilliseconds()).atZone(zone).toLocalDate()
val base = when {
freq in SUB_DAY -> Instant.fromEpochSeconds(completedAt.epochSeconds)
spec.isAllDay -> Instant.fromEpochSeconds(completedDay.atStartOfDay(ZoneOffset.UTC).toEpochSecond())
else -> {
val zone = dateZone(false, spec.timeZone, floatingZone)
val time = java.time.Instant.ofEpochSecond(spec.anchor.epochSeconds).atZone(zone).toLocalTime()
Instant.fromEpochSeconds(LocalDateTime.of(completedDay, time).atZone(zone).toEpochSecond())
}
}
val floor = after?.let { maxOf(base, Instant.fromEpochSeconds(it.epochSeconds)) } ?: base
val fresh = spec.copy(rrule = rule, rdate = null, exdate = null, anchor = base)
return RecurrenceExpander.expand(
fresh,
ExpansionWindow(from = base, until = base + LOOKAHEAD, maxOccurrences = 2),
ExpansionWindow(from = floor, until = floor + LOOKAHEAD, maxOccurrences = 2),
floatingZone,
).firstOrNull { it > base }
).firstOrNull { it > floor }
}
private fun topLevelLines(residue: String): List<String> {
@@ -74,8 +74,9 @@ private enum class RecurrenceEndMode { Never, Until, Count }
* [current] is the bare RRULE value (or null for none); [startDate] anchors the
* "Next: …" previews — for a task, its start date or else its due date.
* [onSelect] gets the new RRULE value, or null for "Does not repeat".
* [fromCompletion], when not null, offers "Repeat from" below the rules; a
* choice there applies at once through [onFromCompletionChange] (#79).
* [fromCompletion], when not null, offers "Repeat from" (#79): below a chosen
* rule it applies at once through [onFromCompletionChange], in the custom step
* together with its rule on OK.
*/
@Composable
fun RecurrencePicker(
@@ -114,6 +115,8 @@ fun RecurrencePicker(
mutableStateOf(((parsed?.end as? RecurrenceEnd.Count)?.times ?: 10).toString())
}
var showUntilPicker by rememberSaveable { mutableStateOf(false) }
// The custom step's choice, applied with its rule on OK.
var customFrom by rememberSaveable { mutableStateOf(fromCompletion == true) }
val locale = currentLocale()
val untilDate = untilIso?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
@@ -150,7 +153,12 @@ fun RecurrencePicker(
if (customMode) {
TextButton(
enabled = customResult != null,
onClick = { customResult?.let(onSelect) },
onClick = {
customResult?.let { rule ->
if (fromCompletion != null && customFrom != fromCompletion) onFromCompletionChange(customFrom)
onSelect(rule)
}
},
) { Text(stringResource(android.R.string.ok)) }
}
},
@@ -165,7 +173,8 @@ fun RecurrencePicker(
onSelect = onSelect,
onCustom = { customMode = true },
)
fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
// Applies at once, to the rule already chosen.
if (current != null) fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
} else {
Column(modifier = Modifier.fillMaxWidth()) {
// Live read-out of exactly what OK would save; minLines keeps the
@@ -260,12 +269,7 @@ fun RecurrencePicker(
}
Column(modifier = Modifier.padding(top = 16.dp)) {
Text(
text = stringResource(R.string.recurrence_ends),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 16.dp, bottom = 8.dp),
)
SectionLabel(stringResource(R.string.recurrence_ends))
CheckRow(
title = stringResource(R.string.recurrence_end_never),
position = Position.Top,
@@ -315,7 +319,7 @@ fun RecurrencePicker(
}
}
}
fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
if (fromCompletion != null) RepeatFromSection(customFrom) { customFrom = it }
}
}
}
@@ -370,16 +374,21 @@ private fun PresetList(
)
}
@Composable
private fun SectionLabel(text: String) {
Text(
text = text,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 16.dp, bottom = 8.dp),
)
}
/** Whether the next occurrence keeps to the schedule or counts from completion. */
@Composable
private fun RepeatFromSection(fromCompletion: Boolean, onChange: (Boolean) -> Unit) {
Column(modifier = Modifier.padding(top = 16.dp)) {
Text(
text = stringResource(R.string.recurrence_repeat_from),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(start = 16.dp, bottom = 8.dp),
)
SectionLabel(stringResource(R.string.recurrence_repeat_from))
CheckRow(
title = stringResource(R.string.recurrence_from_due),
summary = stringResource(R.string.recurrence_from_due_summary),
@@ -794,7 +794,8 @@ private fun EditContent(
firstDayOfWeek = LocalFirstDayOfWeek.current.toKotlinDayOfWeek(),
onSelect = { viewModel.onRecurrenceChange(it); showRecurrencePicker = false },
onDismiss = { showRecurrencePicker = false },
fromCompletion = state.repeatFromCompletion.takeIf { state.repeatFromAvailable },
// A tick moves a recurring sub-task by an override, which a completion date cannot move.
fromCompletion = state.repeatFromCompletion.takeIf { state.repeatFromAvailable && state.parentId == null },
onFromCompletionChange = viewModel::onRepeatFromCompletionChange,
)
}
@@ -598,7 +598,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm(
url = url.ifBlank { null },
tags = withDraft(tagDraft),
rrule = rrule,
repeatFromCompletion = rrule != null && repeatFromCompletion,
repeatFromCompletion = repeatFromCompletion,
)
private fun TaskEditUiState.withDraft(draft: String): List<String> = normalizeTags(tags + draft.split(','))
@@ -142,6 +142,13 @@ class TaskFormWriterSeriesTest {
assertThat(plain.unknownProperties).isNull()
}
@Test
fun `a sub-task is not marked`() {
val sub = master.copy(parentId = 3)
assertThat(TaskFormWriter.withRule(sub, sub.rrule, fromCompletion = true).unknownProperties).isNull()
}
@Test
fun `an override carries no mark of its own`() {
val override = master.copy(id = 8, masterId = 7, rrule = null)
@@ -52,6 +52,24 @@ class RepeatFromCompletionTest {
assertThat(next(spec, "2026-03-02T12:00:00Z")).isEqualTo("2026-03-09T00:00:00Z")
}
@Test
fun `a tick always moves past the occurrence ticked`() {
val spec = allDay("FREQ=DAILY", "2026-03-11T00:00:00Z")
// Done on the 10th, a day early: the 11th is the one ticked, so the 12th.
assertThat(
RepeatFromCompletion.nextAnchor(spec, at("2026-03-10T12:00:00Z"), berlin, after = at("2026-03-11T00:00:00Z")).toString(),
).isEqualTo("2026-03-12T00:00:00Z")
}
@Test
fun `a timed series counts the day in its own zone`() {
val newYork = RecurrenceSpec("FREQ=DAILY", null, null, at("2026-03-02T03:00:00Z"), isAllDay = false, timeZone = "America/New_York")
// 22:00 in New York; ticked at 02:00 Tuesday in Berlin, still Monday 21:00 there.
assertThat(next(newYork, "2026-03-10T01:00:00Z")).isEqualTo("2026-03-11T02:00:00Z")
}
@Test
fun `weekdays pick the first one after the day it was done`() {
val spec = allDay("FREQ=WEEKLY;BYDAY=MO,TH", "2026-03-02T00:00:00Z")
@@ -168,15 +168,6 @@ class TaskEditViewModelTest {
assertThat(repository.saved?.repeatFromCompletion).isTrue()
}
@Test
fun `a task that does not repeat saves no completion mark`() {
val vm = editing()
vm.onRepeatFromCompletionChange(true)
vm.save()
assertThat(repository.saved?.repeatFromCompletion).isFalse()
}
private fun task(start: Instant?, due: Instant?) = Task(
taskId = TASK_ID,
listId = LIST_ID,