diff --git a/CHANGELOG.md b/CHANGELOG.md index 41a35f4..26bda44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h * A warning when the singular `--set-category`, `--add-category` or `--add-resource` is given a value with a comma in it, like `--set-category=boat,keyboard`, and when a plural option like `--set-categories` is given more than once with a comma in a value. Both give one category named `boat,keyboard`, while a single `--set-categories=boat,keyboard` gives two. The behaviour itself is unchanged (it is intended), but is now documented in the user guide. * `plann interactive check-pinned` goes through the past week's events pinning tasks to the calendar (as made by the panic planning in `interactive manage-tasks`) and asks if each task was done. A done task is completed (with its subtasks), and its event is marked as confirmed; its other pins may be cancelled. If not done, the event is cancelled. It is also run first in `interactive manage-tasks`. https://github.com/pycalendar/plann/pull/89 * After the tasks in the plan of `check-for-panic --interactive-fix-timeline` (and `interactive manage-tasks`) are pinned, it offers to plan again, leaving out the tasks just pinned. +* `select --priority` selects by priority: one number, a range or a list, like `--priority 5`, `--priority 1-3` or `--priority 1,5-9`. 0 matches tasks with no priority set. The filtering is done client-side, and needs icalendar-searcher 1.4.0 or later. ### Changed @@ -28,6 +29,7 @@ and I do try to adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.h * `plann add -l LINE event` dropped the extra iCalendar lines; they are now added to the event, as they were to tasks and journals. * A task with DTSTART as a date and DUE as a timestamp (or the other way around) made `interactive manage-tasks` and other selections crash with `KeyError: 'DTEND'`. The date is now made a timestamp at midnight, in the timezone of the other one if it has a named one, else in the local timezone; the time of day on the other one is kept (it used to be dropped), and the result is valid iCalendar. * `interactive check-due` (also run by `interactive manage-tasks`) silently left out the due tasks beyond the first 16, usually the low-priority ones. It now says how many tasks are due when it cannot show them all. +* Postponing (`edit --postpone`, `interactive manage-tasks`) left DTSTART behind on a task where DTSTART equals DUE, or where one of them is a date and the other a timestamp, so the duration (used as a time estimate) grew with every postponement. DTSTART now moves along with DUE, keeping the duration. A date DTSTART is first made a timestamp, as in selections: next to a DUE in UTC it becomes local midnight, so the duration that is kept depends on the local timezone. * `interactive manage-tasks`: a parent task postponed together with its child could be postponed once more in its own turn, and with caldav 3.6 this crashed with a "412 Precondition Failed" error. It is now skipped, with a note. A task changed on the server in the meantime is reloaded before it is postponed. * `interactive manage-tasks` no longer stops with a traceback when the server refuses to store a task it postpones, e.g. with "423 Locked" from a Xandikos server busy with another write. The task is reported and the rest are still postponed. diff --git a/TASK_MANAGEMENT.md b/TASK_MANAGEMENT.md index 425861e..b138cca 100644 --- a/TASK_MANAGEMENT.md +++ b/TASK_MANAGEMENT.md @@ -345,7 +345,7 @@ To interactively find and set the missing properties, it's possible to do `plann ### Listing tasks -The `select`-command can be used to list tasks. The `--todo`-flag will ensure that only pending tasks are listed. Say that it's a nice day for garden work, then `plann select --todo --category garden list` would probably be the right thing to do. +The `select`-command can be used to list tasks. The `--todo`-flag will ensure that only pending tasks are listed. Say that it's a nice day for garden work, then `plann select --todo --category garden list` would probably be the right thing to do. `--priority` selects by priority, like `plann select --todo --priority 1-3 list` for the most important tasks (`--priority 0` gives the tasks with no priority set). There exists some other ways too. `plann agenda` will list out events and tasks with `DTSTART` in the near-term future. `plann interactive check-due` will go through overdue and near-due tasks and interactively ask the user what to do with them. Then there is also the "panic planning mode" available, for instance `plann interactive dismiss-panic` - it will list overdue tasks and tasks that you probably won't have time to do within the planned `DUE`. More on that below. diff --git a/plann/cli.py b/plann/cli.py index 62cb85b..5ee2c7f 100755 --- a/plann/cli.py +++ b/plann/cli.py @@ -361,6 +361,7 @@ def freebusy_sync(ctx, to_section, summary, tag, days, hours, weekdays_only, dry @click.option('--offset', help='Skip the first objects', type=int) @click.option('--freebusyhack', help='DEPRECATED, use the freebusy-sync command. Removes almost everything from the ical and replaces the summary with the provided string. Leaks the details of recurrence exceptions.') @click.option('--pinned-tasks/--no-pinned-tasks', default=None, help='select all/no pinned tasks') +@click.option('--priority', help='select by priority: a number, a range or a list, like 5, 1-3 or 1,5-9. 1 is the highest priority, 9 the lowest, 0 undefined (also matches tasks without a priority)') @click.pass_context def select(*largs, **kwargs): """Search command, allows listing, editing, etc diff --git a/plann/commands.py b/plann/commands.py index c9d5d1c..c4b5250 100644 --- a/plann/commands.py +++ b/plann/commands.py @@ -33,6 +33,7 @@ _comma_list_tokens, _complete, _component_type, + _fix_mismatched_date_types, _is_comma_list_attr, _list, _process_set_arg, @@ -132,7 +133,28 @@ def _sort_value(comp, skey): value = comp.get(skey) return getattr(value, 'dt', value) -def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=None, warn_on_missing_uid=True, sort_key=[], skip_parents=None, skip_children=None, limit=None, offset=None, freebusyhack=None, pinned_tasks=None, **kwargs_): +def _parse_priority(spec): + """The priorities in ``spec``: a comma-separated list of numbers or + ranges, like ``5``, ``1-3`` or ``1,5-9``.""" + wanted = set() + for part in spec.split(','): + rx = re.fullmatch(r'\s*(\d)\s*(?:-\s*(\d)\s*)?', part) + if not rx: + raise click.BadParameter(f"expected priorities 0-9 like 5, 1-3 or 1,5-9, got {spec!r}", param_hint='--priority') + lo, hi = sorted((int(rx.group(1)), int(rx.group(rx.lastindex)))) + wanted.update(range(lo, hi + 1)) + return wanted + +def _filter_priority(objs, wanted): + """Keep the objects with a PRIORITY in ``wanted``. 0 is RFC 5545 + "undefined priority" and also matches a missing PRIORITY. Done + client-side, as CalDAV searches have no integer comparison.""" + searcher = Searcher() + searcher.add_property_filter('PRIORITY', wanted, operator='in') + return [obj for obj in objs + if searcher.check_component(obj) or (0 in wanted and 'PRIORITY' not in obj.icalendar_component)] + +def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=None, warn_on_missing_uid=True, sort_key=[], skip_parents=None, skip_children=None, limit=None, offset=None, freebusyhack=None, pinned_tasks=None, priority=None, **kwargs_): """ select/search/filter tasks/events, for listing/editing/deleting, etc """ @@ -185,6 +207,10 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N if uid: return + ## parsed before searching, so a typo costs no server round-trip + if priority is not None: + priority = _parse_priority(priority) + if pinned_tasks: kwargs['event'] = True kwargs['todo'] = None @@ -211,8 +237,14 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N if 'start' in kwargs and 'end' in kwargs: kwargs['expand'] = True + found = [] for c in ctx.obj['calendars']: - objs.extend(c.search(**kwargs)) + found.extend(c.search(**kwargs)) + ## with --pinned-tasks the search finds the pinning events, and the + ## priority filter waits for the tasks they pin, below + if priority is not None and pinned_tasks is None: + found = _filter_priority(found, priority) + objs.extend(found) if skip_children or skip_parents: i = 0 @@ -242,6 +274,8 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N children = _relships_by_type(obj, 'CHILD').get('CHILD',[]) if not any(x.icalendar_component.get('STATUS', '')!='CANCELLED' for x in children if isinstance(x, caldav.Event)): ret_objs.append(obj) + if priority is not None: + ret_objs = _filter_priority(ret_objs, priority) ctx.obj['objs'] = ret_objs ## OPTIMIZE TODO: sorting the list multiple times rather than once is a bit of brute force, if there are several sort keys and long list of objects, we should sort once and consider all sort keys while sorting @@ -274,42 +308,6 @@ def __select(ctx, extend_objects=False, all=None, uid=[], abort_on_missing_uid=N if attr == 'SUMMARY': comp[attr] = freebusyhack -def _fix_mismatched_date_types(comp): - """If one of DTSTART and DTEND/DUE is a date and the other a timestamp, - turn the date into a timestamp at midnight, so they can be compared: in - the timezone of the timestamp if it has a named one (TZID), floating if - it is floating, and in the implicit timezone if it is in UTC (also a - TZID naming UTC). The time - of day on the timestamp is kept. Logs an error if DTSTART comes after - DTEND/DUE.""" - endkey = 'DTEND' if 'DTEND' in comp else 'DUE' - dtstart = comp.get('DTSTART') - dtend = comp.get(endkey) - if not (dtstart and dtend): - return - start_is_ts = isinstance(dtstart.dt, datetime.datetime) - if start_is_ts != isinstance(dtend.dt, datetime.datetime): - logging.error(f"task with uuid {comp['uid']} has non-matching types on dtstart and dtend/due, setting both to timestamps") - date_key, d, other_key, other = (endkey, dtend, 'DTSTART', dtstart) if start_is_ts else ('DTSTART', dtstart, endkey, dtend) - d = d.dt - tz = other.dt.tzinfo - is_utc = tz is datetime.timezone.utc or str(tz) in ('UTC', 'Etc/UTC', 'Etc/Zulu', 'Zulu', 'Etc/UCT', 'UCT') - new_ts = datetime.datetime(d.year, d.month, d.day) - if tz and 'TZID' in other.params and not is_utc: - new_ts = new_ts.replace(tzinfo=tz) - ## re-add the other one too, so icalendar writes its own name for - ## the timezone (e.g. Europe/Berlin for "W. Europe Standard Time") - ## in both properties - comp.pop(other_key) - comp.add(other_key, other.dt) - elif tz: - new_ts = _ensure_ts(d) - ## replace the property rather than setting .dt, so VALUE=DATE goes away - comp.pop(date_key) - comp.add(date_key, new_ts) - if _ensure_ts(comp['DTSTART'].dt) > _ensure_ts(comp[endkey].dt): - logging.error(f"task with uuid {comp['uid']} has dtstart after dtend/due") - def _categories_in_use(objs): categories = set() for obj in objs: diff --git a/plann/lib.py b/plann/lib.py index acb5bb5..a1826e1 100644 --- a/plann/lib.py +++ b/plann/lib.py @@ -299,6 +299,43 @@ def _summary(obj): i = _icalendar_component(obj) return i.get('summary') or i.get('description') or i.get('uid') +def _fix_mismatched_date_types(comp): + """If one of DTSTART and DTEND/DUE is a date and the other a timestamp, + turn the date into a timestamp at midnight, so they can be compared: in + the timezone of the timestamp if it has a named one (TZID), floating if + it is floating, and in the implicit timezone if it is in UTC (also a + TZID naming UTC). The time + of day on the timestamp is kept. Logs an error if DTSTART comes after + DTEND/DUE.""" + endkey = 'DTEND' if 'DTEND' in comp else 'DUE' + dtstart = comp.get('DTSTART') + dtend = comp.get(endkey) + if not (dtstart and dtend): + return + start_is_ts = isinstance(dtstart.dt, datetime.datetime) + if start_is_ts != isinstance(dtend.dt, datetime.datetime): + logging.error(f"task with uuid {comp['uid']} has non-matching types on dtstart and dtend/due, setting both to timestamps") + date_key, d, other_key, other = (endkey, dtend, 'DTSTART', dtstart) if start_is_ts else ('DTSTART', dtstart, endkey, dtend) + d = d.dt + tz = other.dt.tzinfo + is_utc = tz is datetime.timezone.utc or str(tz) in ('UTC', 'Etc/UTC', 'Etc/Zulu', 'Zulu', 'Etc/UCT', 'UCT') + new_ts = datetime.datetime(d.year, d.month, d.day) + if tz and 'TZID' in other.params and not is_utc: + new_ts = new_ts.replace(tzinfo=tz) + ## re-add the other one too, so icalendar writes its own name for + ## the timezone (e.g. Europe/Berlin for "W. Europe Standard Time") + ## in both properties + comp.pop(other_key) + comp.add(other_key, other.dt) + elif tz: + new_ts = _ensure_ts(d) + ## replace the property rather than setting .dt, so VALUE=DATE goes away + comp.pop(date_key) + comp.add(date_key, new_ts) + if _ensure_ts(comp['DTSTART'].dt) > _ensure_ts(comp[endkey].dt): + logging.error(f"task with uuid {comp['uid']} has dtstart after dtend/due") + + childlike = {'CHILD', 'NEXT', 'FINISHTOSTART'} parentlike = {'PARENT', 'FIRST', 'DEPENDS-ON', 'STARTTOFINISH'} @@ -357,7 +394,16 @@ def _procrastinate(objs, delay, check_dependent="error", with_children=False, wi ## Let's force the due to be a timestamp if not isinstance(new_due, datetime.datetime): new_due = datetime.datetime(new_due.year, new_due.month, new_due.day) + comp = x.icalendar_component + _fix_mismatched_date_types(comp) + ## caldav leaves DTSTART alone if the duration is zero; a negative + ## one (DTSTART after DUE) is treated the same, so it is not saved + zero_duration = 'DTSTART' in comp and any(k in comp for k in ('DUE', 'DTEND', 'DURATION')) and x.get_duration() <= datetime.timedelta(0) parent = x.set_due(new_due, move_dtstart=True, check_dependent=chk_parent) + if zero_duration and not parent: + comp.pop('DTSTART') + ## set_due may have converted a naive new_due, DTSTART must match DUE + comp.add('DTSTART', comp['DUE'].dt) if parent: if check_dependent in ("error", "interactive"): i = x.icalendar_component diff --git a/pyproject.toml b/pyproject.toml index deff065..feecd09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,7 @@ dependencies = [ "dateparser>=1.2", "python-dateutil", "icalendar>=7.0.0", - "icalendar_searcher", + "icalendar_searcher>=1.4.0", ] [project.urls] diff --git a/tests/test_commands.py b/tests/test_commands.py index b4a488e..f13c3d7 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -1,5 +1,6 @@ from unittest.mock import MagicMock, patch # noqa: F401 +import click from caldav import Todo @@ -212,7 +213,7 @@ def test_mismatched_date_types_fixed_on_due(monkeypatch): from zoneinfo import ZoneInfo from plann import timespec - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types monkeypatch.setitem(vars(timespec.tz), "_implicit_timezone", ZoneInfo("America/New_York")) comp = _vtodo('mixed', "DTSTART;VALUE=DATE:20261116\nDUE:20261118T140000Z\n").icalendar_component @@ -229,7 +230,7 @@ def test_mismatched_date_types_floating_stays_floating(): floating midnight too""" import datetime - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types comp = _vtodo('floating', "DTSTART:20261116T100000\nDUE;VALUE=DATE:20261118\n").icalendar_component _fix_mismatched_date_types(comp) @@ -239,7 +240,7 @@ def test_mismatched_date_types_floating_stays_floating(): def test_aware_vs_floating_does_not_crash(caplog): """A floating DTSTART and a UTC DUE cannot be compared directly - but the check still works, and reports a DTSTART after the DUE""" - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types comp = _vtodo('aware-floating', "DTSTART:20261119T100000\nDUE:20261118T140000Z\n").icalendar_component _fix_mismatched_date_types(comp) @@ -249,7 +250,7 @@ def test_aware_vs_floating_does_not_crash(caplog): def test_mismatched_date_types_keeps_the_tzid(): """With a named timezone on the other side, the date becomes midnight in that timezone, not in the implicit one, so the task keeps one timezone""" - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types comp = _vtodo('tzid', "DTSTART;VALUE=DATE:20261101\nDUE;TZID=America/New_York:20261110T120000\n").icalendar_component _fix_mismatched_date_types(comp) @@ -267,7 +268,7 @@ def test_mismatched_date_types_utc_tzid_is_utc(monkeypatch): from zoneinfo import ZoneInfo from plann import timespec - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types monkeypatch.setitem(vars(timespec.tz), "_implicit_timezone", ZoneInfo("America/New_York")) for tzid in ('UTC', 'Etc/UTC'): @@ -279,7 +280,7 @@ def test_mismatched_date_types_utc_tzid_is_utc(monkeypatch): def test_mismatched_date_types_one_tzid_name(): """A TZID that icalendar knows under another name (a Windows name) is written under that name in both properties, not in one of them only""" - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types comp = _vtodo('windows', "DTSTART;VALUE=DATE:20261101\nDUE;TZID=W. Europe Standard Time:20261110T120000\n").icalendar_component _fix_mismatched_date_types(comp) @@ -291,8 +292,88 @@ def test_mismatched_date_types_one_tzid_name(): def test_mismatched_date_types_still_checks_the_order(caplog): """After the date is made a timestamp, a DTSTART after the DUE is still reported""" - from plann.commands import _fix_mismatched_date_types + from plann.lib import _fix_mismatched_date_types comp = _vtodo('late', "DTSTART;VALUE=DATE:20261201\nDUE;TZID=Europe/Oslo:20261110T120000\n").icalendar_component _fix_mismatched_date_types(comp) assert any('has dtstart after dtend/due' in r.getMessage() for r in caplog.records) + + +def _prio_todo(uid, priority=None): + extra = f"PRIORITY:{priority}\n" if priority is not None else "" + return Todo(data=( + "BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VTODO\n" + f"UID:{uid}\nSUMMARY:{uid}\n{extra}END:VTODO\nEND:VCALENDAR")) + + +def test_select_by_priority(): + """`select --priority` filters client-side: CalDAV has no integer + comparison, so the server cannot do it. 0 means undefined, matching + a missing PRIORITY as well; ranges and lists are accepted.""" + import pytest + + from plann.commands import _filter_priority, _parse_priority + + objs = [_prio_todo('absent'), _prio_todo('zero', 0), _prio_todo('one', 1), + _prio_todo('three', 3), _prio_todo('five', 5), _prio_todo('nine', 9)] + + def uids(spec): + return {x.icalendar_component['UID'] for x in _filter_priority(objs, _parse_priority(spec))} + + assert uids('5') == {'five'} + assert uids('0') == {'absent', 'zero'} + assert uids('1-3') == {'one', 'three'} + assert uids('3-1') == {'one', 'three'} + assert uids('1,5-9') == {'one', 'five', 'nine'} + with pytest.raises(click.BadParameter): + uids('high') + with pytest.raises(click.BadParameter): + uids('10') + + +def test_select_passes_priority_filter_not_to_server(): + """--priority must not reach caldav's search (it would become a text + match there), but must filter the search result.""" + from plann.commands import _select + + cal = MagicMock() + cal.search.return_value = [_prio_todo('one', 1), _prio_todo('five', 5)] + ctx = MagicMock() + ctx.obj = {'calendars': [cal]} + _select(ctx, todo=True, priority='5') + assert 'priority' not in cal.search.call_args.kwargs + assert [x.icalendar_component['UID'] for x in ctx.obj['objs']] == ['five'] + + +def test_select_priority_with_pinned_tasks_filters_the_tasks(): + """--pinned-tasks --todo searches the pinning events and returns their + parent tasks; --priority is about the tasks, not the events.""" + from caldav import Event + + from plann.commands import _select + + event = Event(data=( + "BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VEVENT\nUID:pin\n" + "DTSTART:20261113T100000Z\nDTEND:20261113T110000Z\n" + "END:VEVENT\nEND:VCALENDAR")) + cal = MagicMock() + cal.search.return_value = [event] + ctx = MagicMock() + ctx.obj = {'calendars': [cal]} + parents = [_prio_todo('one', 1), _prio_todo('five', 5)] + with patch('plann.commands._pinned_task_parents', return_value=parents): + _select(ctx, todo=True, pinned_tasks=True, priority='5') + assert [x.icalendar_component['UID'] for x in ctx.obj['objs']] == ['five'] + + +def test_select_rejects_bad_priority_before_searching(): + import pytest + + from plann.commands import _select + + cal = MagicMock() + ctx = MagicMock() + ctx.obj = {'calendars': [cal]} + with pytest.raises(click.BadParameter): + _select(ctx, todo=True, priority='high') + cal.search.assert_not_called() diff --git a/tests/test_lib.py b/tests/test_lib.py index c646036..2a3b42d 100644 --- a/tests/test_lib.py +++ b/tests/test_lib.py @@ -21,6 +21,7 @@ add_time_tracking, add_time_tracking_timew, ) +from plann.timespec import _ensure_ts utc=timezone.utc todo = """BEGIN:VCALENDAR @@ -988,3 +989,90 @@ def test_list_json_one_vtimezone_per_tzid(): _list([_event_in_oslo('a'), _event_in_oslo('b')], as_json=True) names = [comp[0] for comp in json.loads(echo.call_args.args[0])[2]] assert names == ['vtimezone', 'vevent', 'vevent'] + +def _todo_with(dtstart_line, end_line): + t = Todo() + t.data = ("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:x\nBEGIN:VTODO\nUID:a\nDTSTAMP:20261101T000000Z\n" + f"SUMMARY:x\n{dtstart_line}\n{end_line}\nEND:VTODO\nEND:VCALENDAR\n") + return t + +@pytest.mark.parametrize("dtstart_line,end_line,hours", [ + ## date-valued DTSTART on the same day as a timestamp DUE + ("DTSTART;VALUE=DATE:20261101", "DUE:20261101T120000Z", 12), + ("DTSTART;VALUE=DATE:20261101", "DUE:20261102T120000Z", 36), + ## DTSTART == DUE + ("DTSTART:20261101T120000Z", "DUE:20261101T120000Z", 0), + ("DTSTART:20261101T100000Z", "DUE:20261101T120000Z", 2), + ## the date next to a named timezone, or a floating timestamp + ("DTSTART;VALUE=DATE:20261101", "DUE;TZID=Europe/Oslo:20261101T120000", 12), + ("DTSTART;VALUE=DATE:20261101", "DUE:20261101T120000", 12), +]) +def test_procrastinate_moves_dtstart(dtstart_line, end_line, hours, monkeypatch): + ## a date next to a UTC timestamp becomes midnight in the implicit + ## timezone: make that UTC, so the hours above hold everywhere + from zoneinfo import ZoneInfo + + from plann import timespec + monkeypatch.setitem(vars(timespec.tz), "_implicit_timezone", ZoneInfo("UTC")) + _check_moves_dtstart(dtstart_line, end_line, hours, '14d') + +def test_procrastinate_zero_duration_to_absolute_date(): + """a naive postpone target must not leave DTSTART floating next to a UTC DUE""" + t = _todo_with("DTSTART:20261101T120000Z", "DUE:20261101T120000Z") + with patch.object(t, 'save'): + _procrastinate([t], '2027-01-05') + comp = t.icalendar_component + assert comp['DTSTART'].dt == comp['DUE'].dt + assert t.get_duration() == timedelta(0) + +def test_procrastinate_zero_duration_property(): + """DTSTART with DURATION:PT0S (no DUE) moves too, keeping the zero duration""" + t = _todo_with("DTSTART:20261101T120000Z", "DURATION:PT0S") + with patch.object(t, 'save'): + _procrastinate([t], '14d') + assert t.get_duration() == timedelta(0) + assert _ensure_ts(t.icalendar_component['DTSTART'].dt) > datetime.now(timezone.utc) + +def test_procrastinate_dtstart_only_left_alone(): + t = _todo_with("DTSTART:20261101T120000Z", "SUMMARY:y") + with patch.object(t, 'save'): + _procrastinate([t], '14d') + assert t.icalendar_component['DTSTART'].dt == datetime(2026, 11, 1, 12, tzinfo=timezone.utc) + +def _check_moves_dtstart(dtstart_line, end_line, hours, delay): + """DTSTART moves along with DUE, keeping the duration (which is + used as a time estimate), also when the duration is zero or the + DTSTART is a date and the DUE a timestamp""" + t = _todo_with(dtstart_line, end_line) + with patch.object(t, 'save'): + _procrastinate([t], delay) + comp = t.icalendar_component + assert comp['DUE'].dt - comp['DTSTART'].dt == timedelta(hours=hours) + assert _ensure_ts(comp['DTSTART'].dt) > datetime.now(timezone.utc) + +def test_procrastinate_never_leaves_dtstart_after_due(monkeypatch): + """West of UTC, a date next to an early-morning UTC DUE becomes a local + midnight after the DUE; the postponed task must not keep DTSTART after + DUE, but get DTSTART at the DUE, like a zero duration""" + from zoneinfo import ZoneInfo + + from plann import timespec + monkeypatch.setitem(vars(timespec.tz), "_implicit_timezone", ZoneInfo("America/New_York")) + t = _todo_with("DTSTART;VALUE=DATE:20261101", "DUE:20261101T020000Z") + with patch.object(t, 'save'): + _procrastinate([t], '14d') + comp = t.icalendar_component + assert comp['DTSTART'].dt == comp['DUE'].dt + +def test_fix_mismatched_date_types_on_event_with_dtend(): + """An event has DTEND rather than DUE""" + from caldav import Event + + from plann.lib import _fix_mismatched_date_types + e = Event(data=("BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:x\nBEGIN:VEVENT\nUID:e\n" + "DTSTAMP:20261101T000000Z\nDTSTART;VALUE=DATE:20261101\n" + "DTEND;TZID=Europe/Oslo:20261101T120000\nEND:VEVENT\nEND:VCALENDAR\n")) + comp = e.icalendar_component + _fix_mismatched_date_types(comp) + assert b'DTSTART;TZID=Europe/Oslo:20261101T000000' in comp.to_ical() + assert 'DUE' not in comp