calendar: keep monthly weekday lists; mirror clamps month-end like todo
- Commit
4cce036d78a7e4814d73c41a0f256bc5b1c1ec8e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 08:35 UTC (15 days ago)
- Parents
f426977
RRule import rewrote monthly BYDAY lists to one occurrence derived from the start date, silently dropping the rest. Parsed ordinal BYDAY tokens are now preserved verbatim through parse and emit. Todo's monthly rules clamp month-end (Jan 31 -> Feb 28 -> Mar 31) but its calendar mirror emitted plain BYMONTHDAY=31, which the system provider expands as skip-short-months - mirrored tasks vanished in February. Mirror-originated rules now encode the clamp in RFC terms (BYMONTHDAY=day,-1 with BYSETPOS), imported rules keep RFC semantics. Yearly Feb 29 mirrors as Feb 29,-1 so non-leap years show Feb 28 like todo. Round-trip and provider-style expansion tests cover both. Verified: calendar and todo suites pass.
Diff
calendar/src/main/java/com/vayunmathur/calendar/domain/RRule.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/domain/RRule.kt b/calendar/src/main/java/com/vayunmathur/calendar/domain/RRule.ktindex ad188955f8..c718990590 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/domain/RRule.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/domain/RRule.kt@@ -152,8 +152,16 @@ sealed class RRule { // Preserve BYDAY days so type-0 round-trips; type 1/2 keep // type-derived emission in asString (generic byDay suppressed there). val parsedDays = byDayRaw?.split(",")?.mapNotNull { dayOfWeekByIcal[it.takeLast(2)] }+ // Preserve the ordinal BYDAY list verbatim (e.g. 2TU,4TU or+ // 1MO,-1FR): deriving a single occurrence from the start date+ // in asString would silently drop every other occurrence.+ val byDayTokens = byDayRaw?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() }+ val ordinalByDay = byDayTokens?.takeIf { tokens ->+ tokens.any { it.dropLast(2).toIntOrNull() != null }+ } return EveryXMonths(interval, type, endCondition, common.byMonthDay, common.byMonth,- common.bySetPos, common.byYearDay, common.byWeekNo, common.wkst, parsedDays)+ common.bySetPos, common.byYearDay, common.byWeekNo, common.wkst, parsedDays,+ ordinalByDay) } private fun parseYearly(@@ -268,10 +276,19 @@ sealed class RRule { override val byYearDay: List<Int>? = null, override val byWeekNo: List<Int>? = null, override val wkst: DayOfWeek? = null,- override val byDay: List<DayOfWeek>? = null+ override val byDay: List<DayOfWeek>? = null,+ /** Ordinal BYDAY tokens exactly as parsed (e.g. ["2TU", "4TU"]); null for rules built in-app. */+ val byDayRaw: List<String>? = null ) : RRule() { override fun asString(firstDay: LocalDate, timeZone: TimeZone): String { val base = "FREQ=MONTHLY;INTERVAL=$months"+ // A parsed ordinal BYDAY list round-trips verbatim: it may name+ // several occurrences (or a mix like 1MO,-1FR) that no single+ // start-date-derived token could represent.+ if (!byDayRaw.isNullOrEmpty()) {+ val withRaw = "$base;BYDAY=${byDayRaw.joinToString(",")}"+ return copy(byDay = null).buildRRuleString(withRaw, timeZone)+ } val byDayPart = when (typeE) { 1 -> { val dayOfWeek = firstDay.dayOfWeek.toIcal()
calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.ktindex 6c48579d3c..d129b44637 100644--- a/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleTest.kt@@ -284,6 +284,49 @@ class RRuleTest { assertEquals(listOf(DayOfWeek.MONDAY), yearly.byDay) } + @Test+ fun testMultiOrdinalByDayMonthlyRoundTrip() {+ // Neither occurrence is derivable from the supplied start date, so an+ // identical emit proves the parsed list itself was preserved.+ for (input in listOf(+ "FREQ=MONTHLY;INTERVAL=1;BYDAY=2TU,4TU",+ "FREQ=MONTHLY;INTERVAL=1;BYDAY=1MO,-1FR",+ "FREQ=MONTHLY;INTERVAL=2;BYDAY=2TU,4TU;COUNT=10",+ )) {+ val parsed = RRule.parse(input, timeZone)+ assertTrue(parsed is RRule.EveryXMonths, input)+ assertEquals(input, parsed.asString(LocalDate(2025, 1, 1), timeZone), input)+ }+ }++ @Test+ fun testSingleOrdinalByDayMonthlyRoundTripUnchanged() {+ for (input in listOf(+ "FREQ=MONTHLY;INTERVAL=1;BYDAY=2TU",+ "FREQ=MONTHLY;INTERVAL=1;BYDAY=-1MO",+ )) {+ val parsed = RRule.parse(input, timeZone)+ assertTrue(parsed is RRule.EveryXMonths, input)+ assertEquals(input, parsed.asString(LocalDate(2025, 1, 1), timeZone), input)+ }+ // Constructed (not parsed) rules still derive their single BYDAY from+ // the start date, as before.+ val derived = RRule.EveryXMonths(1, 1, RRule.EndCondition.Never)+ .asString(LocalDate(2025, 1, 14), timeZone) // second Tuesday+ assertTrue(derived.contains("BYDAY=2TU"), derived)+ }++ @Test+ fun testImportedMonthlyByMonthDayRoundTripsUnchanged() {+ // Calendar keeps RFC semantics for imported rules: BYMONTHDAY=31 is+ // not rewritten here. Clamp encoding is gated to todo-mirror rules+ // at emission (see todo Recurrence.toRRule).+ val input = "FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=31"+ val parsed = RRule.parse(input, timeZone)+ assertTrue(parsed is RRule.EveryXMonths)+ assertEquals(input, parsed.asString(LocalDate(2025, 1, 31), timeZone))+ }+ @Test fun testRoundTripParsing() { val original = RRule.EveryXWeeks(
todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.ktindex bfa33f424d..48429a4af4 100644--- a/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt+++ b/todo/src/main/java/com/vayunmathur/todo/domain/Recurrence.kt@@ -80,12 +80,54 @@ sealed interface Recurrence { return parts.joinToString(";") } - /** The plain RRULE for calendars, or null when the schedule depends on completion. */- fun toRRule(): String? = if (this is AfterCompletion) null else serialize()+ /**+ * The RRULE handed to calendars (the todo mirror), or null when the schedule+ * depends on completion.+ *+ * Gating decision for month-end/leap alignment: todo's own expansion clamps+ * (Jan 31 -> Feb 28 -> Mar 31; Feb 29 -> Feb 28 in non-leap years), but a+ * plain `BYMONTHDAY=31` / bare `FREQ=YEARLY` from a Feb-29 start is expanded+ * by the calendar provider with RFC 5545 skip-short-months semantics, so the+ * mirrored task vanished in February / non-leap years. The rule source is+ * distinguishable here — this function is only called for mirror-originated+ * rules ([serialize] stays the unchanged storage form, and imported calendar+ * rules keep their RFC semantics) — so the clamp is encoded only here, in+ * RFC terms the provider expands clamped:+ * - monthly anchor day 29-31: `BYMONTHDAY=<day>,-1` (plus `BYSETPOS=1` for+ * 29/30, where `-1` alone would add the 31st in long months) makes every+ * short month land on its last day instead of being skipped;+ * - yearly Feb-29 anchor: `BYMONTH=2;BYMONTHDAY=29,-1` lands on Feb 28 in+ * non-leap years.+ * [due] is the task's due date; it supplies the anchor day for a [Monthly]+ * with no explicit [Monthly.dayOfMonth] and detects a Feb-29 [Yearly].+ */+ fun toRRule(due: LocalDate? = null): String? {+ if (this is AfterCompletion) return null+ val parts = serialize().split(';').toMutableList()+ when (this) {+ is Monthly -> {+ val anchor = dayOfMonth ?: due?.day+ if (anchor != null && anchor >= FIRST_CLAMP_DAY) {+ parts.removeAll { it.startsWith("BYMONTHDAY=") }+ parts += "BYMONTHDAY=$anchor,-1"+ if (anchor < LAST_POSSIBLE_DAY) parts += "BYSETPOS=1"+ }+ }+ is Yearly -> if (due != null && due.month.number == 2 && due.day == 29) {+ parts += "BYMONTH=2"+ parts += "BYMONTHDAY=29,-1"+ }+ else -> Unit+ }+ return parts.joinToString(";")+ } /** Parsing, serialisation constants and limits for the RRULE-style recurrence format. */ companion object { const val LAST_DAY = -1+ /** First month day that some month is too short for (needs clamp encoding for calendars). */+ private const val FIRST_CLAMP_DAY = 29+ private const val LAST_POSSIBLE_DAY = 31 private const val X_FROM = "X-FROM" private const val MAX_INTERVAL = 999 private const val MAX_DAY = 31
todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt
diff --git a/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.ktindex 790147a14b..3d8c4e421b 100644--- a/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt+++ b/todo/src/main/java/com/vayunmathur/todo/sync/CalendarMirror.kt@@ -91,7 +91,9 @@ object CalendarMirror { private fun eventValues(todo: Todo, calendarId: Long, zone: TimeZone): ContentValues { val due = todo.dueAt!! val start = if (todo.dueAllDay) DueDates.startOfDay(DueDates.localDate(due, zone), TimeZone.UTC) else due- val rrule = Recurrence.parse(todo.recurrence)?.toRRule()+ // Pass the due date so mirror-originated rules encode todo's+ // clamp-to-month-end semantics (see Recurrence.toRRule).+ val rrule = Recurrence.parse(todo.recurrence)?.toRRule(DueDates.localDate(due, zone)) return ContentValues().apply { put(Events.CALENDAR_ID, calendarId) put(Events._SYNC_ID, todo.syncId)
todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt b/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.ktindex 4aad9cd707..bf74731059 100644--- a/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt+++ b/todo/src/test/java/com/vayunmathur/todo/domain/RecurrenceTest.kt@@ -1,10 +1,16 @@ package com.vayunmathur.todo.domain +import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate+import kotlinx.datetime.minus+import kotlinx.datetime.number+import kotlinx.datetime.plus import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNull+import kotlin.test.assertTrue class RecurrenceTest { private fun d(y: Int, m: Int, day: Int) = LocalDate(y, m, day)@@ -89,6 +95,45 @@ class RecurrenceTest { assertEquals("FREQ=MONTHLY;BYMONTHDAY=-1", Recurrence.Monthly(1, -1).toRRule()) } + @Test+ fun `mirror rule clamps monthly on the 31st instead of skipping February`() {+ val rule = Recurrence.Monthly().toRRule(d(2025, 1, 31))!!+ assertEquals("FREQ=MONTHLY;BYMONTHDAY=31,-1", rule)+ // RFC expansion of the emitted rule (what the calendar provider does):+ // February gets an occurrence, and the anchor day returns afterwards.+ val occurrences = expandRfc(rule, d(2025, 1, 31), d(2025, 1, 1), d(2025, 4, 30))+ assertEquals(+ listOf(d(2025, 1, 31), d(2025, 2, 28), d(2025, 3, 31), d(2025, 4, 30)),+ occurrences,+ )+ // The un-encoded storage form keeps RFC skip semantics, proving the+ // clamp is gated to mirror emission rather than applied generally.+ assertFalse(+ d(2025, 2, 28) in expandRfc(+ Recurrence.Monthly(1, 31).serialize(), d(2025, 1, 31), d(2025, 2, 1), d(2025, 2, 28),+ ),+ )+ }++ @Test+ fun `mirror rule clamps monthly on the 30th without adding the 31st`() {+ val rule = Recurrence.Monthly(1, 30).toRRule(d(2025, 1, 30))!!+ assertEquals("FREQ=MONTHLY;BYMONTHDAY=30,-1;BYSETPOS=1", rule)+ assertEquals(+ listOf(d(2025, 2, 28), d(2025, 3, 30)),+ expandRfc(rule, d(2025, 1, 30), d(2025, 2, 1), d(2025, 3, 31)),+ )+ }++ @Test+ fun `mirror rule clamps yearly Feb 29 to Feb 28 in non-leap years`() {+ val rule = Recurrence.Yearly().toRRule(d(2024, 2, 29))!!+ assertEquals("FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=29,-1", rule)+ val in2025 = expandRfc(rule, d(2024, 2, 29), d(2025, 1, 1), d(2025, 12, 31))+ assertEquals(listOf(d(2025, 2, 28)), in2025)+ assertTrue(d(2024, 2, 29) in expandRfc(rule, d(2024, 2, 29), d(2024, 1, 1), d(2024, 12, 31)))+ }+ @Test fun `garbage parses to null and bad intervals are clamped`() { assertNull(Recurrence.parse(null))@@ -109,3 +154,57 @@ class RecurrenceTest { assertEquals(d(2026, 3, 31), Recurrence.Monthly(1, Recurrence.LAST_DAY).firstOnOrAfter(d(2026, 3, 31))) } }++/**+ * Minimal RFC 5545 expansion of the monthly/yearly BYMONTHDAY shapes the+ * calendar mirror emits — BYMONTHDAY (incl. -1 = last day), BYMONTH and+ * BYSETPOS over INTERVAL steps — mirroring what the calendar provider does+ * with the stored RRULE. Invalid days (e.g. Feb 31) are skipped, per RFC.+ */+private fun expandRfc(rrule: String, dtstart: LocalDate, from: LocalDate, to: LocalDate): List<LocalDate> {+ val parts = rrule.split(';').associate { it.substringBefore('=') to it.substringAfter('=') }+ val interval = parts["INTERVAL"]?.toIntOrNull() ?: 1+ val byMonthDay = parts["BYMONTHDAY"]?.split(',')?.map { it.toInt() }+ val bySetPos = parts["BYSETPOS"]?.split(',')?.map { it.toInt() }.orEmpty()++ fun monthCandidates(year: Int, month: Int): List<LocalDate> {+ val first = LocalDate(year, month, 1)+ val length = first.plus(1, DateTimeUnit.MONTH).minus(1, DateTimeUnit.DAY).day+ val days = (byMonthDay ?: listOf(dtstart.day)).mapNotNull { wanted ->+ when {+ wanted > 0 -> wanted.takeIf { it <= length }+ wanted < 0 -> (length + 1 + wanted).takeIf { it >= 1 }+ else -> null+ }+ }+ val all = days.distinct().sorted().map { LocalDate(year, month, it) }+ if (bySetPos.isEmpty()) return all+ return bySetPos.mapNotNull { pos ->+ when {+ pos > 0 -> all.getOrNull(pos - 1)+ pos < 0 -> all.getOrNull(all.size + pos)+ else -> null+ }+ }+ }++ val out = mutableListOf<LocalDate>()+ when (parts["FREQ"]) {+ "MONTHLY" -> {+ var cursor = LocalDate(dtstart.year, dtstart.month.number, 1)+ while (cursor <= to) {+ out += monthCandidates(cursor.year, cursor.month.number)+ cursor = cursor.plus(interval, DateTimeUnit.MONTH)+ }+ }+ "YEARLY" -> {+ val months = parts["BYMONTH"]?.split(',')?.map { it.toInt() } ?: listOf(dtstart.month.number)+ var year = dtstart.year+ while (LocalDate(year, 1, 1) <= to) {+ months.forEach { out += monthCandidates(year, it) }+ year += interval+ }+ }+ }+ return out.filter { it in from..to && it >= dtstart }.distinct().sorted()+}