Delete open overrides a move from completion strands, back on undo; count early ticks against COUNT (#79)
This commit is contained in:
1 parent
3b94af47a8
commit
415622797d
8 files changed
+1255
-16
No files matched your search
File diff suppressed because it is too large.
Load diff
+43
@@ -364,6 +364,49 @@ class RoomTasksDataSourceTest {
|
||||
assertThat(db.tasks().entity(id)!!.status).isEqualTo(TaskStatus.COMPLETED)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOpenOverrideOffTheMovedScheduleIsDeletedUntilTheTickIsUndone() {
|
||||
val at = now - 10.days
|
||||
val id = fromCompletion(at, "FREQ=DAILY;INTERVAL=7")
|
||||
val edited = at + 7.days
|
||||
source.updateInstance(
|
||||
id,
|
||||
edited,
|
||||
TaskForm(title = "Just this once", listId = listId, start = edited, due = edited + 1.hours),
|
||||
listOf(TaskReminder(15)),
|
||||
)
|
||||
|
||||
source.setCompletedInstance(id, at, completed = true)
|
||||
|
||||
assertThat(db.tasks().overrides(id)).isEmpty()
|
||||
assertThat(db.tasks().allIn(listId).map { it.title }).doesNotContain("Just this once")
|
||||
|
||||
source.setCompletedInstance(id, at, completed = false)
|
||||
|
||||
val back = db.tasks().override(id, edited)!!
|
||||
assertThat(back.title).isEqualTo("Just this once")
|
||||
assertThat(back.uid).isEqualTo(db.tasks().entity(id)!!.uid)
|
||||
assertThat(db.alarms().forTask(back.id).map { it.minutesBefore }).containsExactly(15)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOccurrenceTickedEarlyCountsAgainstCountWhenTheSeriesMovesOffIt() {
|
||||
val at = now - 10.days
|
||||
val id = fromCompletion(at, "FREQ=DAILY;INTERVAL=7;COUNT=3")
|
||||
source.setCompletedInstance(id, at + 7.days, completed = true)
|
||||
|
||||
source.setCompletedInstance(id, at, completed = true)
|
||||
|
||||
assertThat(db.tasks().entity(id)!!.rrule).isEqualTo("FREQ=DAILY;INTERVAL=7;COUNT=1")
|
||||
val closed = db.tasks().allIn(listId).filter { it.id != id && it.status == TaskStatus.COMPLETED }
|
||||
assertThat(closed.map { it.dtstart }).containsExactly(at, at + 7.days)
|
||||
|
||||
source.setCompletedInstance(id, at, completed = false)
|
||||
|
||||
assertThat(db.tasks().entity(id)!!.rrule).isEqualTo("FREQ=DAILY;INTERVAL=7;COUNT=3")
|
||||
assertThat(db.tasks().override(id, at + 7.days)!!.status).isEqualTo(TaskStatus.COMPLETED)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun reopeningTheOccurrenceMovesTheSeriesBack() {
|
||||
val at = now
|
||||
|
||||
+12
@@ -210,6 +210,18 @@ class TasksDatabaseMigrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun addsAnEmptyTableForDeletedOverrides() {
|
||||
helper.createDatabase(TEST_DB, 7).close()
|
||||
|
||||
helper.runMigrationsAndValidate(TEST_DB, 8, true, TasksDatabase.MIGRATION_7_8).use { db ->
|
||||
db.query("SELECT COUNT(*) FROM advanced_deleted").use { c ->
|
||||
assertThat(c.moveToFirst()).isTrue()
|
||||
assertThat(c.getInt(0)).isEqualTo(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TEST_DB = "migration-test.db"
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ object DataProvideModule {
|
||||
// backed-up `.db` does not. The backup rules carry all three files and
|
||||
// the app checkpoints on ON_STOP.
|
||||
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
|
||||
.addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5, TasksDatabase.MIGRATION_5_6, TasksDatabase.MIGRATION_6_7)
|
||||
.addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5, TasksDatabase.MIGRATION_5_6, TasksDatabase.MIGRATION_6_7, TasksDatabase.MIGRATION_7_8)
|
||||
.build()
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.data.tasks.room
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
@@ -10,6 +11,8 @@ import androidx.room.OnConflictStrategy
|
||||
import androidx.room.PrimaryKey
|
||||
import androidx.room.Query
|
||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||
import java.net.URLDecoder
|
||||
import java.net.URLEncoder
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
@@ -83,6 +86,59 @@ data class AdvancedDetachedEntity(
|
||||
@ColumnInfo(name = "task_id") val taskId: Long?,
|
||||
)
|
||||
|
||||
/**
|
||||
* An open override a tick repeating from completion deleted (#79), as it stood:
|
||||
* the row and its alarms, so undoing the tick brings it back.
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "advanced_deleted",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AdvancedOccurrenceEntity::class,
|
||||
parentColumns = ["copy_id"],
|
||||
childColumns = ["copy_id"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [Index(value = ["copy_id"])],
|
||||
)
|
||||
data class AdvancedDeletedEntity(
|
||||
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Long = 0,
|
||||
@ColumnInfo(name = "copy_id") val copyId: Long,
|
||||
@ColumnInfo(name = "anchor") val anchor: Instant,
|
||||
@Embedded(prefix = "row_") val row: TaskEntity,
|
||||
/** The override's alarms, as [encodeAlarms] writes them. */
|
||||
@ColumnInfo(name = "alarms", defaultValue = "") val alarms: String = "",
|
||||
) {
|
||||
companion object {
|
||||
private const val NULL = "-"
|
||||
private const val VALUE = "+"
|
||||
|
||||
fun encodeAlarms(alarms: List<TaskAlarmEntity>): String = alarms.joinToString(";") { alarm ->
|
||||
listOf(alarm.minutesBefore.toString(), alarm.reference.name, alarm.message, alarm.uid, alarm.raw)
|
||||
.joinToString(",") { value -> value?.let { VALUE + URLEncoder.encode(it, Charsets.UTF_8.name()) } ?: NULL }
|
||||
}
|
||||
|
||||
/** The alarms [encodeAlarms] wrote, for [taskId]; an entry it cannot read is skipped. */
|
||||
fun decodeAlarms(raw: String, taskId: Long): List<TaskAlarmEntity> = raw.split(';').mapNotNull { entry ->
|
||||
val parts = entry.split(',').map { part ->
|
||||
if (part.startsWith(VALUE)) URLDecoder.decode(part.substring(1), Charsets.UTF_8.name()) else null
|
||||
}
|
||||
if (parts.size != 5) return@mapNotNull null
|
||||
val minutes = parts[0]?.toIntOrNull() ?: return@mapNotNull null
|
||||
val reference = AlarmReference.entries.firstOrNull { it.name == parts[1] } ?: return@mapNotNull null
|
||||
TaskAlarmEntity(
|
||||
taskId = taskId,
|
||||
minutesBefore = minutes,
|
||||
reference = reference,
|
||||
message = parts[2],
|
||||
uid = parts[3] ?: return@mapNotNull null,
|
||||
raw = parts[4],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Dao
|
||||
interface AdvancedOccurrenceDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
@@ -97,6 +153,12 @@ interface AdvancedOccurrenceDao {
|
||||
@Query("SELECT * FROM advanced_detached WHERE copy_id = :copyId")
|
||||
fun detachedFor(copyId: Long): List<AdvancedDetachedEntity>
|
||||
|
||||
@Insert
|
||||
fun insertDeleted(rows: List<AdvancedDeletedEntity>)
|
||||
|
||||
@Query("SELECT * FROM advanced_deleted WHERE copy_id = :copyId")
|
||||
fun deletedFor(copyId: Long): List<AdvancedDeletedEntity>
|
||||
|
||||
@Query("SELECT * FROM advanced_occurrences WHERE master_id = :masterId")
|
||||
fun forMaster(masterId: Long): List<AdvancedOccurrenceEntity>
|
||||
|
||||
|
||||
+55
-13
@@ -635,9 +635,9 @@ class RoomTasksDataSource @Inject constructor(
|
||||
* [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.
|
||||
* That leaves the old schedule behind: its `EXDATE`s go, and of the
|
||||
* overrides the new one does not generate a closed one becomes a task of its
|
||||
* own and an open one is deleted. Undoing the tick brings them all back.
|
||||
*/
|
||||
private fun advance(master: TaskEntity, anchor: Instant, override: TaskEntity?, completing: Boolean, close: (TaskEntity) -> TaskEntity): Boolean {
|
||||
val rule = master.rrule?.takeIf { it.isNotBlank() } ?: return false
|
||||
@@ -653,8 +653,9 @@ class RoomTasksDataSource @Inject constructor(
|
||||
val zone = master.timezone ?: zone()
|
||||
val fromCompletion = completing && master.repeatsFromCompletion
|
||||
val newAnchor: Instant
|
||||
val spent: Int
|
||||
var spent: Int
|
||||
val toDetach: List<Pair<Instant, TaskEntity>>
|
||||
var toDelete: List<TaskEntity> = emptyList()
|
||||
// Which EXDATEs the moved series keeps; the rest are recorded, to come back with an undo.
|
||||
val keepsExdate: (Instant) -> Boolean
|
||||
// Where the cycle the tick closes ends on the schedule, which measures it for the sub-tasks.
|
||||
@@ -662,9 +663,6 @@ class RoomTasksDataSource @Inject constructor(
|
||||
// Expansion drops the anchor's sub-second part; the series keeps it.
|
||||
val subSecond = spec.anchor - wholeSecond(spec.anchor)
|
||||
if (fromCompletion) {
|
||||
spent = spentBefore(spec, wholeSecond(anchor)) + 1
|
||||
val left = TaskFormWriter.countOf(rule)?.let { it - spent }
|
||||
if (left != null && left < 1) return true.also { closeSeries(master, override, close) }
|
||||
val floating = ZoneId.of(zone())
|
||||
// A rule lib-recur cannot follow keeps the override model rather than ending the series.
|
||||
fun nextAfter(at: Instant) = runCatching { RepeatFromCompletion.nextAnchor(spec, now, floating, after = at) }
|
||||
@@ -676,13 +674,30 @@ class RoomTasksDataSource @Inject constructor(
|
||||
}
|
||||
newAnchor = next + subSecond
|
||||
cycleEnd = leading.getOrNull(index + 1)
|
||||
val moved = spec.copy(rrule = TaskFormWriter.remainingCount(rule, spent), exdate = null, anchor = newAnchor)
|
||||
fun onMoved(at: Instant) = at >= newAnchor && RepeatFromCompletion.onSchedule(moved, at, floating)
|
||||
val others = overrides.values.filter { it.id != override?.id && it.recurrenceId != null }
|
||||
// Occurrences ticked early, past the one ticked, spent COUNT too unless the moved schedule keeps them.
|
||||
val ticked = spentBefore(spec, wholeSecond(anchor)) + 1
|
||||
val tickedEarly = others.filter { it.isClosed && it.recurrenceId!! > anchor }
|
||||
fun schedule(spending: Int): (Instant) -> Boolean {
|
||||
val moved = spec.copy(rrule = TaskFormWriter.remainingCount(rule, spending), exdate = null, anchor = newAnchor)
|
||||
return { at -> at >= newAnchor && RepeatFromCompletion.onSchedule(moved, at, floating) }
|
||||
}
|
||||
// A shorter COUNT keeps fewer of them, so this settles within tickedEarly.size steps.
|
||||
spent = ticked
|
||||
var onMoved = schedule(spent)
|
||||
while (true) {
|
||||
val counted = ticked + tickedEarly.count { !onMoved(it.recurrenceId!!) }
|
||||
if (counted == spent) break
|
||||
spent = counted
|
||||
onMoved = schedule(spent)
|
||||
}
|
||||
val left = TaskFormWriter.countOf(rule)?.let { it - spent }
|
||||
if (left != null && left < 1) return true.also { closeSeries(master, override, close) }
|
||||
// What the moved schedule still generates stays with it; the rest of the old one goes.
|
||||
keepsExdate = ::onMoved
|
||||
toDetach = overrides.values
|
||||
.filter { it.id != override?.id && it.recurrenceId != null && !onMoved(it.recurrenceId) }
|
||||
.map { it.recurrenceId!! to it }
|
||||
keepsExdate = onMoved
|
||||
val stranded = others.filter { !onMoved(it.recurrenceId!!) }
|
||||
toDetach = stranded.filter { it.isClosed }.map { it.recurrenceId!! to it }
|
||||
toDelete = stranded.filterNot { it.isClosed }
|
||||
} else {
|
||||
var nextIndex = index + 1
|
||||
while (nextIndex < leading.size && closedAt(leading[nextIndex])) nextIndex++
|
||||
@@ -695,6 +710,10 @@ class RoomTasksDataSource @Inject constructor(
|
||||
}
|
||||
}
|
||||
val detached = toDetach.map { (at, row) -> at to detach(row, now) }
|
||||
val deleted = toDelete.map { row ->
|
||||
AdvancedDeletedEntity(copyId = 0, anchor = row.recurrenceId!!, row = row, alarms = AdvancedDeletedEntity.encodeAlarms(alarms.forTask(row.id)))
|
||||
.also { tasks.delete(row.id) }
|
||||
}
|
||||
val (start, due) = occurrenceTimes(master, newAnchor)
|
||||
val ruleAfter = TaskFormWriter.remainingCount(rule, spent)
|
||||
tasks.update(
|
||||
@@ -741,6 +760,7 @@ class RoomTasksDataSource @Inject constructor(
|
||||
),
|
||||
)
|
||||
advanced.insertDetached(detached.map { (at, id) -> AdvancedDetachedEntity(copyId = copyId, anchor = at, taskId = id) })
|
||||
advanced.insertDeleted(deleted.map { it.copy(copyId = copyId) })
|
||||
writes.onWritten(setOf(master.listId) + resetLists)
|
||||
return true
|
||||
}
|
||||
@@ -890,6 +910,7 @@ class RoomTasksDataSource @Inject constructor(
|
||||
overrides.filter { it.recurrenceId in stranded }.forEach { detach(it, now) }
|
||||
}
|
||||
detached.forEach { (at, task) -> if (returns(task)) toOverride(task!!, back, at, now) }
|
||||
advanced.deletedFor(row.id).forEach { restoreDeleted(it, back, now) }
|
||||
advanced.delete(row.id)
|
||||
val plain = reopened.status == TaskStatus.NEEDS_ACTION && reopened.percentComplete == null
|
||||
if (record.fromOverride || !plain) toOverride(reopened, back, record.anchor, now)
|
||||
@@ -905,6 +926,27 @@ class RoomTasksDataSource @Inject constructor(
|
||||
return parts(a) == parts(b)
|
||||
}
|
||||
|
||||
/** An override [advance] deleted, back on [master] unless its occurrence has a row again. */
|
||||
private fun restoreDeleted(deleted: AdvancedDeletedEntity, master: TaskEntity, now: Instant) {
|
||||
if (tasks.byUid(master.listId, master.uid, deleted.anchor) != null) return
|
||||
val id = tasks.insert(
|
||||
deleted.row.copy(
|
||||
id = 0,
|
||||
listId = master.listId,
|
||||
uid = master.uid,
|
||||
masterId = master.id,
|
||||
recurrenceId = deleted.anchor,
|
||||
parentId = master.parentId,
|
||||
href = null,
|
||||
etag = null,
|
||||
isDeleted = false,
|
||||
isDirty = true,
|
||||
lastModified = now,
|
||||
),
|
||||
)
|
||||
AdvancedDeletedEntity.decodeAlarms(deleted.alarms, id).forEach { alarms.insert(it) }
|
||||
}
|
||||
|
||||
/** [row], a detached occurrence, back as [master]'s override for [anchor]. */
|
||||
private fun toOverride(row: TaskEntity, master: TaskEntity, anchor: Instant, now: Instant) {
|
||||
val back = row.copy(
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.util.UUID
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Agendula's own task store. Six tables, designed from
|
||||
* Agendula's own task store. Seven tables, designed from
|
||||
* what the app actually reads and writes plus RFC 5545's `VTODO`.
|
||||
*
|
||||
* Schemas are exported to `app/schemas/` and committed, so a future version can
|
||||
@@ -23,8 +23,9 @@ import kotlin.time.Instant
|
||||
TaskAlarmEntity::class,
|
||||
AdvancedOccurrenceEntity::class,
|
||||
AdvancedDetachedEntity::class,
|
||||
AdvancedDeletedEntity::class,
|
||||
],
|
||||
version = 7,
|
||||
version = 8,
|
||||
exportSchema = true,
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
@@ -218,5 +219,15 @@ abstract class TasksDatabase : RoomDatabase() {
|
||||
db.execSQL("ALTER TABLE tasks ADD COLUMN `untimed` TEXT")
|
||||
}
|
||||
}
|
||||
|
||||
/** v8 keeps the open overrides a tick repeating from completion deleted, for its undo (#79). */
|
||||
val MIGRATION_7_8 = object : Migration(7, 8) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `advanced_deleted` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `alarms` TEXT NOT NULL DEFAULT '', `row_id` INTEGER NOT NULL, `row_list_id` INTEGER NOT NULL, `row_uid` TEXT NOT NULL, `row_href` TEXT, `row_etag` TEXT, `row_title` TEXT, `row_description` TEXT, `row_location` TEXT, `row_url` TEXT, `row_color` INTEGER, `row_categories` TEXT NOT NULL DEFAULT '', `row_status` INTEGER NOT NULL DEFAULT 0, `row_percent_complete` INTEGER, `row_completed_at` INTEGER, `row_priority` INTEGER NOT NULL DEFAULT 0, `row_classification` INTEGER, `row_dtstart` INTEGER, `row_due` INTEGER, `row_duration` TEXT, `row_is_all_day` INTEGER NOT NULL DEFAULT 0, `row_untimed` TEXT, `row_timezone` TEXT, `row_rrule` TEXT, `row_rdate` TEXT, `row_exdate` TEXT, `row_recurrence_id` INTEGER, `row_master_id` INTEGER, `row_parent_id` INTEGER, `row_sort_order` INTEGER NOT NULL DEFAULT 0, `row_created_at` INTEGER, `row_last_modified` INTEGER, `row_sequence` INTEGER NOT NULL DEFAULT 0, `row_is_dirty` INTEGER NOT NULL DEFAULT 0, `row_is_deleted` INTEGER NOT NULL DEFAULT 0, `row_unknown_properties` TEXT, `row_reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
)
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_advanced_deleted_copy_id` ON `advanced_deleted` (`copy_id`)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package de.jeanlucmakiola.agendula.data.tasks.room
|
||||
|
||||
import com.google.common.truth.Truth.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class AdvancedDeletedEntityTest {
|
||||
|
||||
@Test
|
||||
fun alarmsRoundTripWithWhatTheirTextMightHoldInIt() {
|
||||
val alarms = listOf(
|
||||
TaskAlarmEntity(id = 4, taskId = 9, minutesBefore = 15, reference = AlarmReference.START, message = "a, b; c+%", uid = "u-1", raw = "BEGIN:VALARM\r\nEND:VALARM"),
|
||||
TaskAlarmEntity(id = 5, taskId = 9, minutesBefore = -30, message = null, uid = "u-2", raw = null),
|
||||
)
|
||||
|
||||
val back = AdvancedDeletedEntity.decodeAlarms(AdvancedDeletedEntity.encodeAlarms(alarms), taskId = 12)
|
||||
|
||||
assertThat(back).containsExactly(
|
||||
alarms[0].copy(id = 0, taskId = 12),
|
||||
alarms[1].copy(id = 0, taskId = 12),
|
||||
).inOrder()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noAlarmsDecodeToNone() {
|
||||
assertThat(AdvancedDeletedEntity.decodeAlarms(AdvancedDeletedEntity.encodeAlarms(emptyList()), taskId = 1)).isEmpty()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user