Fix second review round of repeat from completion (#79)

This commit is contained in:
makiolaj committed 2026-11-17 11:18:39 +01:00
1 parent b0885169e7
commit d59d4a3d44
15 files changed
+113 -49

No files matched your search

@@ -344,6 +344,16 @@ class RoomTasksDataSourceTest {
assertThat(db.tasks().allIn(listId).filter { !it.isDeleted }.map { it.id }).containsExactly(id)
}
@Test
fun skippingAnOccurrenceOfAFromCompletionSeriesKeepsToTheSchedule() {
val at = now - 10.days
val id = fromCompletion(at, "FREQ=WEEKLY")
source.setCancelledInstance(id, at, cancelled = true)
assertThat(db.tasks().entity(id)!!.dtstart).isEqualTo(at + 7.days)
}
@Test
fun theLastTickOfAFromCompletionSeriesClosesIt() {
val at = now - 1.days
@@ -45,6 +45,7 @@ object RoomTaskMapper {
seriesId: Long? = if (row.task.isRecurring) row.task.id else null,
recurrenceRule: String? = row.task.rrule,
repeatFromCompletion: Boolean = row.task.repeatsFromCompletion,
hasRecurrenceDates: Boolean = !row.task.rdate.isNullOrBlank(),
): Task = Task(
taskId = row.task.id,
listId = row.task.listId,
@@ -74,6 +75,7 @@ object RoomTaskMapper {
seriesId = seriesId,
recurrenceRule = recurrenceRule,
repeatFromCompletion = repeatFromCompletion,
hasRecurrenceDates = hasRecurrenceDates,
isReadOnly = row.listReadOnly,
)
@@ -97,6 +99,7 @@ object RoomTaskMapper {
rrule = task.rrule,
rdate = task.rdate,
parentId = task.parentId?.takeIf { it > 0 },
repeatFromCompletion = task.repeatsFromCompletion,
)
}
@@ -171,6 +171,7 @@ class RoomTasksDataSource @Inject constructor(
seriesId = row.task.masterId,
recurrenceRule = master?.rrule,
repeatFromCompletion = master?.repeatsFromCompletion == true,
hasRecurrenceDates = !master?.rdate.isNullOrBlank(),
)
}
@@ -229,6 +230,7 @@ class RoomTasksDataSource @Inject constructor(
seriesId = row.task.id,
recurrenceRule = row.task.rrule,
repeatFromCompletion = fromCompletion,
hasRecurrenceDates = !row.task.rdate.isNullOrBlank(),
)
} else {
RoomTaskMapper.task(
@@ -527,15 +529,15 @@ class RoomTasksDataSource @Inject constructor(
* instead would close the series.
*/
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = tx {
closeOccurrence(taskId, occurrenceStart, completed) { TaskFormWriter.completed(it, completed, clock.now()) }
closeOccurrence(taskId, occurrenceStart, completed, completing = true) { TaskFormWriter.completed(it, completed, clock.now()) }
}
/** Same model as [setCompletedInstance]. */
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = tx {
closeOccurrence(taskId, occurrenceStart, cancelled) { TaskFormWriter.cancelled(it, cancelled, clock.now()) }
closeOccurrence(taskId, occurrenceStart, cancelled, completing = false) { TaskFormWriter.cancelled(it, cancelled, clock.now()) }
}
private fun closeOccurrence(taskId: Long, occurrenceStart: Instant, closing: Boolean, close: (TaskEntity) -> TaskEntity) {
private fun closeOccurrence(taskId: Long, occurrenceStart: Instant, closing: Boolean, completing: Boolean, close: (TaskEntity) -> TaskEntity) {
val (row, master) = rowAndMaster(taskId)
if (master.recurrenceSpec() == null) {
// A plain task, or the copy a ticked occurrence left: this row is the occurrence.
@@ -566,7 +568,7 @@ class RoomTasksDataSource @Inject constructor(
if (reopensSeries) closeSeries(master, override, close) else writeInstance(master, override, anchor, close)
return
}
if (!closing || !advance(master, anchor, override, close)) writeInstance(master, override, anchor, close)
if (!closing || !advance(master, anchor, override, completing, close)) writeInstance(master, override, anchor, close)
}
/**
@@ -621,13 +623,14 @@ class RoomTasksDataSource @Inject constructor(
* the override model (anchoring on one would re-align the `RRULE`), and so do
* 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, and always past [anchor].
* [completing] an occurrence of a series repeating from completion (#79)
* moves it to the first occurrence of its rule after the day it was ticked
* instead, and always past [anchor]; skipping one keeps to the schedule.
* 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 {
private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, completing: Boolean, close: (TaskEntity) -> TaskEntity): Boolean {
val rule = master.rrule?.takeIf { it.isNotBlank() } ?: return false
if (!master.rdate.isNullOrBlank() || master.parentId != null) return false
val spec = master.recurrenceSpec() ?: return false
@@ -639,7 +642,7 @@ class RoomTasksDataSource @Inject constructor(
val now = clock.now()
val zone = master.timezone ?: zone()
val fromCompletion = master.repeatsFromCompletion
val fromCompletion = completing && master.repeatsFromCompletion
val newAnchor: Instant
val spent: Int
val toDetach: List<Pair<Instant, TaskEntity>>
@@ -659,6 +662,7 @@ class RoomTasksDataSource @Inject constructor(
RecurrenceExpander.expand(
moved,
ExpansionWindow(from = newAnchor, until = last + 1.seconds, maxOccurrences = SPLIT_COUNT_CEILING),
ZoneId.of(zone()),
).mapTo(HashSet()) { it.epochSeconds }
}.orEmpty()
toDetach = others.filter { it.recurrenceId!!.epochSeconds !in generated }.map { it.recurrenceId!! to it }
@@ -72,7 +72,8 @@ object TaskFormWriter {
/**
* [current] with its rule set to [rrule], repeating from completion when
* [fromCompletion] (#79), which a sub-task cannot. Only ever a master or a
* [fromCompletion] (#79), which a sub-task or a series with `RDATE`s
* cannot (see [repeatsFromCompletion]). 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 {
@@ -84,7 +85,7 @@ object TaskFormWriter {
rule == null -> current.copy(rrule = null, rdate = null, exdate = null)
else -> current.copy(rrule = rule)
}
val flagged = rule != null && fromCompletion && ruled.parentId == null
val flagged = rule != null && fromCompletion && ruled.parentId == null && ruled.rdate.isNullOrBlank()
if (RepeatFromCompletion.isSet(ruled.unknownProperties) == flagged) return ruled
return ruled.copy(unknownProperties = RepeatFromCompletion.applied(ruled.unknownProperties, flagged))
}
@@ -106,6 +106,8 @@ data class Task(
val recurrenceRule: String? = null,
/** The series' next occurrence counts from completion, not its schedule (#79). */
val repeatFromCompletion: Boolean = false,
/** The series has `RDATE`s, which a tick does not move past, so it cannot repeat from completion. */
val hasRecurrenceDates: Boolean = false,
/**
* The task's list is a read-only share. An edit here would never reach the
* server, and the dirty row would then block every later download of it.
@@ -43,6 +43,8 @@ data class ExportTask(
/** `tasks._id` of the parent, for `RELATED-TO;RELTYPE=PARENT`. */
val parentId: Long?,
val tags: List<String> = emptyList(),
/** The series repeats from completion (#79). */
val repeatFromCompletion: Boolean = false,
)
/** A task list and everything in it, ready to become one `.ics` document. */
@@ -5,6 +5,7 @@ import de.jeanlucmakiola.agendula.domain.TaskStatus
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.ical.ICalSerializer
import de.jeanlucmakiola.agendula.domain.ical.ICalValues
import de.jeanlucmakiola.agendula.domain.recurrence.RepeatFromCompletion
import de.jeanlucmakiola.agendula.domain.toICal
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
@@ -106,6 +107,7 @@ object ICalendarWriter {
// recurrence actually means.
task.rrule?.takeIf { it.isNotBlank() }?.let { rawProperty("RRULE", it) }
task.rdate?.takeIf { it.isNotBlank() }?.let { rawProperty("RDATE", it) }
if (task.repeatFromCompletion) rawProperty(RepeatFromCompletion.PROPERTY, RepeatFromCompletion.COMPLETION)
// Only emit the link when the parent is in this same document; a
// RELATED-TO pointing outside the file would dangle on import.
@@ -1,5 +1,6 @@
package de.jeanlucmakiola.agendula.domain.recurrence
import de.jeanlucmakiola.agendula.domain.ical.ICalParser
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
@@ -19,21 +20,20 @@ import kotlin.time.Instant
object RepeatFromCompletion {
const val PROPERTY = "X-AGENDULA-REPEAT-FROM"
private const val COMPLETION = "COMPLETION"
const val COMPLETION = "COMPLETION"
private const val LINE = "$PROPERTY:$COMPLETION"
/** Only bounds the search for the next occurrence. */
private val LOOKAHEAD = (366 * 1000).days
/** Only bounds the search for the next occurrence, so a rule that never fires again cannot hold a tick for long. */
private val LOOKAHEAD = (366 * 100).days
private val SUB_DAY = setOf("HOURLY", "MINUTELY", "SECONDLY")
/** Whether the stored residue [residue] marks its series as repeating from completion. */
fun isSet(residue: String?): Boolean {
if (residue == null || !residue.contains(PROPERTY, ignoreCase = true)) return false
return topLevelLines(residue).any { line ->
val value = valueOf(line)
value != null && value.equals(COMPLETION, ignoreCase = true)
}
// Parsed as VTodoMapper parses the residue: folded lines joined, nested components their own.
val parsed = runCatching { ICalParser.parse("BEGIN:VTODO\r\n$residue\r\nEND:VTODO\r\n") }.getOrNull() ?: return false
return parsed.properties(PROPERTY).any { it.value.trim().equals(COMPLETION, ignoreCase = true) }
}
/** [residue] with the marker set or cleared; null once nothing is left. */
@@ -53,7 +53,7 @@ object RepeatFromCompletion {
when {
line.startsWith("BEGIN:", ignoreCase = true) -> depth++
line.startsWith("END:", ignoreCase = true) -> depth--
depth == 0 && valueOf(line) != null -> dropping = true
depth == 0 && isMarker(line) -> dropping = true
}
!dropping && line.isNotEmpty()
}
@@ -91,29 +91,20 @@ object RepeatFromCompletion {
}
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 = floor, until = floor + LOOKAHEAD, maxOccurrences = 2),
floatingZone,
).firstOrNull { it > floor }
// lib-recur gives up on a rule that keeps matching nothing; that rule has nothing left.
return runCatching {
RecurrenceExpander.expand(
fresh,
ExpansionWindow(from = floor, until = floor + LOOKAHEAD, maxOccurrences = 2),
floatingZone,
)
}.getOrDefault(emptyList()).firstOrNull { it > floor }
}
private fun topLevelLines(residue: String): List<String> {
var depth = 0
return residue.split("\r\n", "\n").filter { line ->
when {
line.startsWith("BEGIN:", ignoreCase = true) -> { depth++; false }
line.startsWith("END:", ignoreCase = true) -> { depth--; false }
else -> depth == 0
}
}
}
/** The value of a [PROPERTY] content line, or null when [line] is another one. */
private fun valueOf(line: String): String? {
if (!line.startsWith(PROPERTY, ignoreCase = true)) return null
/** Whether [line] is a [PROPERTY] content line. */
private fun isMarker(line: String): Boolean {
if (!line.startsWith(PROPERTY, ignoreCase = true)) return false
val next = line.getOrNull(PROPERTY.length)
if (next != ':' && next != ';') return null
return line.substringAfter(':').trim()
return next == ':' || next == ';'
}
}
@@ -115,7 +115,7 @@ 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.
// The custom step's choice, taken on entering it and applied with its rule on OK.
var customFrom by rememberSaveable { mutableStateOf(fromCompletion == true) }
val locale = currentLocale()
@@ -171,7 +171,10 @@ fun RecurrencePicker(
startDate = startDate,
locale = locale,
onSelect = onSelect,
onCustom = { customMode = true },
onCustom = {
customFrom = fromCompletion == true
customMode = true
},
)
// Applies at once, to the rule already chosen.
if (current != null) fromCompletion?.let { RepeatFromSection(it, onFromCompletionChange) }
@@ -420,7 +420,7 @@ private fun EditContent(
)
Text(
text = stringResource(
if (state.rrule != null && state.repeatFromCompletion) {
if (state.repeatsFromCompletion) {
R.string.recurrence_from_completion_note
} else {
R.string.edit_recurrence_label
@@ -794,8 +794,7 @@ private fun EditContent(
firstDayOfWeek = LocalFirstDayOfWeek.current.toKotlinDayOfWeek(),
onSelect = { viewModel.onRecurrenceChange(it); showRecurrencePicker = false },
onDismiss = { showRecurrencePicker = false },
// 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 },
fromCompletion = state.repeatFromCompletion.takeIf { state.repeatFromOffered },
onFromCompletionChange = viewModel::onRepeatFromCompletionChange,
)
}
@@ -80,8 +80,10 @@ data class TaskEditUiState(
val repeatFromCompletion: Boolean = false,
/** [repeatFromCompletion] as loaded. */
val originalFromCompletion: Boolean = false,
/** Whether the active store can repeat from completion, so the picker offers it. */
/** Whether the active store can repeat from completion. */
val repeatFromAvailable: Boolean = false,
/** The series has `RDATE`s, so it cannot repeat from completion. */
val hasRecurrenceDates: Boolean = false,
/** Editing one occurrence of a series: saving asks how far the edit reaches. */
val isOccurrence: Boolean = false,
/** The series' rule as loaded; a changed rule rules out "only this task". */
@@ -109,8 +111,14 @@ data class TaskEditUiState(
/** Lists a task can be saved into: read-only shares drop out, except the one it is already in. */
val writableLists: List<TaskList> get() = lists.filter { it.acceptsWrites || it.id == listId }
/** Whether the picker offers "Repeat from": not where a tick never moves the series, a sub-task or one with `RDATE`s. */
val repeatFromOffered: Boolean get() = repeatFromAvailable && parentId == null && !hasRecurrenceDates
/** [repeatFromCompletion] as it will be saved. */
val repeatsFromCompletion: Boolean get() = rrule != null && repeatFromCompletion && repeatFromOffered
val recurrenceChanged: Boolean
get() = rrule != originalRule || (rrule != null && repeatFromCompletion) != originalFromCompletion
get() = rrule != originalRule || repeatsFromCompletion != originalFromCompletion
}
@HiltViewModel
@@ -274,6 +282,7 @@ class TaskEditViewModel @Inject constructor(
repeatFromCompletion = task.repeatFromCompletion,
originalFromCompletion = task.repeatFromCompletion,
repeatFromAvailable = repository.supportsRepeatFromCompletion(),
hasRecurrenceDates = task.hasRecurrenceDates,
isOccurrence = task.isOccurrence,
lists = lists,
parentCandidates = loadParents(task.listId, selfId = taskId),
@@ -506,7 +515,10 @@ class TaskEditViewModel @Inject constructor(
fun commitTagDraft() = update { it.copy(tags = it.withDraft(it.tagDraft), tagDraft = "") }
fun removeTag(name: String) = update { it.copy(tags = it.tags - name) }
fun onRecurrenceChange(rrule: String?) = update { it.copy(rrule = rrule, errors = emptySet()) }
/** "Does not repeat" also forgets "Repeat from", so a rule picked after it starts from the schedule. */
fun onRecurrenceChange(rrule: String?) = update {
it.copy(rrule = rrule, repeatFromCompletion = rrule != null && it.repeatFromCompletion, errors = emptySet())
}
fun onRepeatFromCompletionChange(value: Boolean) = update { it.copy(repeatFromCompletion = value) }
/** Dismiss the conflict prompt without saving (the user keeps editing). */
@@ -598,7 +610,7 @@ private fun TaskEditUiState.toForm(): TaskForm = TaskForm(
url = url.ifBlank { null },
tags = withDraft(tagDraft),
rrule = rrule,
repeatFromCompletion = repeatFromCompletion,
repeatFromCompletion = repeatsFromCompletion,
)
private fun TaskEditUiState.withDraft(draft: String): List<String> = normalizeTags(tags + draft.split(','))
@@ -143,10 +143,12 @@ class TaskFormWriterSeriesTest {
}
@Test
fun `a sub-task is not marked`() {
fun `a sub-task or a series with RDATEs is not marked`() {
val sub = master.copy(parentId = 3)
val dated = master.copy(rdate = "20260905T090000Z")
assertThat(TaskFormWriter.withRule(sub, sub.rrule, fromCompletion = true).unknownProperties).isNull()
assertThat(TaskFormWriter.withRule(dated, dated.rrule, fromCompletion = true).unknownProperties).isNull()
}
@Test
@@ -60,6 +60,13 @@ class ICalendarWriterTest {
assertThat(lines).containsAtLeast("VERSION:2.0", "BEGIN:VTODO", "END:VTODO")
}
@Test
fun `marks a series repeating from completion`() {
val marked = task(rrule = "FREQ=DAILY").copy(repeatFromCompletion = true)
assertThat(linesOf(write(marked))).contains("X-AGENDULA-REPEAT-FROM:COMPLETION")
assertThat(linesOf(write(task(rrule = "FREQ=DAILY"))).none { it.startsWith("X-AGENDULA") }).isTrue()
}
@Test
fun `writes the tags as one CATEGORIES line, escaped`() {
val lines = linesOf(write(task(tags = listOf("Work", "Home, Garden"))))
@@ -137,6 +137,7 @@ class RepeatFromCompletionTest {
fun `clearing the marker drops it with its folded lines`() {
val residue = "X-FOO:bar\r\nX-AGENDULA-REPEAT-FROM;X-P=1:COMP\r\n LETION\r\nX-BAZ:qux\r\n"
assertThat(RepeatFromCompletion.isSet(residue)).isTrue()
assertThat(RepeatFromCompletion.applied(residue, false)).isEqualTo("X-FOO:bar\r\nX-BAZ:qux\r\n")
assertThat(RepeatFromCompletion.applied("X-AGENDULA-REPEAT-FROM:COMPLETION\r\n", false)).isNull()
}
@@ -168,6 +168,31 @@ class TaskEditViewModelTest {
assertThat(repository.saved?.repeatFromCompletion).isTrue()
}
@Test
fun `does not repeat forgets repeating from completion`() {
repository.task = task(null, due).copy(isRecurring = true, recurrenceRule = "FREQ=DAILY", repeatFromCompletion = true)
val vm = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) }
vm.onRecurrenceChange(null)
vm.onRecurrenceChange("FREQ=WEEKLY")
assertThat(vm.state.value.repeatsFromCompletion).isFalse()
}
@Test
fun `a sub-task or a series with RDATEs is not offered repeating from completion`() {
repository.task = task(null, due).copy(isRecurring = true, recurrenceRule = "FREQ=DAILY", hasRecurrenceDates = true)
val vm = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) }
vm.onRepeatFromCompletionChange(true)
assertThat(vm.state.value.repeatFromOffered).isFalse()
assertThat(vm.state.value.repeatsFromCompletion).isFalse()
repository.task = task(null, due).copy(isRecurring = true, recurrenceRule = "FREQ=DAILY", parentId = 3)
val sub = TaskEditViewModel(repository, settingsPrefs()).apply { bindEdit(TASK_ID) }
assertThat(sub.state.value.repeatFromOffered).isFalse()
}
private fun task(start: Instant?, due: Instant?) = Task(
taskId = TASK_ID,
listId = LIST_ID,