aimcal_core/
todo.rs

1// SPDX-FileCopyrightText: 2025 Zexin Yuan <aim@yzx9.xyz>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{fmt::Display, num::NonZeroU32, str::FromStr};
6
7use chrono::{DateTime, Duration, Local, Utc};
8use icalendar::Component;
9
10use crate::{Config, LooseDateTime, Priority, SortOrder};
11
12/// Trait representing a todo item.
13pub trait Todo {
14    /// The short identifier for the todo.
15    /// It will be `None` if the event does not have a short ID.
16    /// It is used for display purposes and may not be unique.
17    fn short_id(&self) -> Option<NonZeroU32> {
18        None
19    }
20
21    /// Returns the unique identifier for the todo item.
22    fn uid(&self) -> &str;
23
24    /// Returns the description of the todo item.
25    fn completed(&self) -> Option<DateTime<Local>>;
26
27    /// Returns the description of the todo item, if available.
28    fn description(&self) -> Option<&str>;
29
30    /// Returns the due date and time of the todo item, if available.
31    fn due(&self) -> Option<LooseDateTime>;
32
33    /// The percent complete, from 0 to 100.
34    fn percent_complete(&self) -> Option<u8>;
35
36    /// The priority from 1 to 9, where 1 is the highest priority.
37    fn priority(&self) -> Priority;
38
39    /// Returns the status of the todo item.
40    fn status(&self) -> TodoStatus;
41
42    /// Returns the summary of the todo item.
43    fn summary(&self) -> &str;
44}
45
46impl Todo for icalendar::Todo {
47    fn uid(&self) -> &str {
48        self.get_uid().unwrap_or("")
49    }
50
51    fn completed(&self) -> Option<DateTime<Local>> {
52        self.get_completed().map(|dt| dt.with_timezone(&Local))
53    }
54
55    fn description(&self) -> Option<&str> {
56        self.get_description()
57    }
58
59    fn due(&self) -> Option<LooseDateTime> {
60        self.get_due().map(Into::into)
61    }
62
63    fn percent_complete(&self) -> Option<u8> {
64        self.get_percent_complete()
65    }
66
67    fn priority(&self) -> Priority {
68        self.get_priority()
69            .map(|p| Priority::from(p as u8))
70            .unwrap_or_default()
71    }
72
73    fn status(&self) -> TodoStatus {
74        self.get_status().map(Into::into).unwrap_or_default()
75    }
76
77    fn summary(&self) -> &str {
78        self.get_summary().unwrap_or("")
79    }
80}
81
82/// Darft for a todo item, used for creating new todos.
83#[derive(Debug)]
84pub struct TodoDraft {
85    /// The description of the todo item, if available.
86    pub description: Option<String>,
87
88    /// The due date and time of the todo item, if available.
89    pub due: Option<LooseDateTime>,
90
91    /// The percent complete, from 0 to 100, if available.
92    pub percent_complete: Option<u8>,
93
94    /// The priority of the todo item, if available.
95    pub priority: Option<Priority>,
96
97    /// The status of the todo item, if available.
98    pub status: Option<TodoStatus>,
99
100    /// The summary of the todo item.
101    pub summary: String,
102}
103
104impl TodoDraft {
105    /// Creates a new empty patch.
106    pub(crate) fn default(config: &Config, now: DateTime<Local>) -> Self {
107        Self {
108            description: None,
109            due: config
110                .default_due
111                .map(|d| LooseDateTime::Local(d.datetime(now))),
112            percent_complete: None,
113            priority: Some(config.default_priority),
114            status: Some(TodoStatus::NeedsAction),
115            summary: "".to_string(),
116        }
117    }
118
119    /// Converts the draft into a icalendar Todo component.
120    pub(crate) fn into_todo(
121        self,
122        config: &Config,
123        now: DateTime<Local>,
124        uid: &str,
125    ) -> icalendar::Todo {
126        let mut todo = icalendar::Todo::with_uid(uid);
127
128        if let Some(description) = self.description {
129            Component::description(&mut todo, &description);
130        }
131
132        if let Some(due) = self.due {
133            icalendar::Todo::due(&mut todo, due);
134        } else if let Some(duration) = config.default_due {
135            icalendar::Todo::due(&mut todo, LooseDateTime::Local(duration.datetime(now)));
136        }
137
138        if let Some(percent) = self.percent_complete {
139            icalendar::Todo::percent_complete(&mut todo, percent);
140        }
141
142        if let Some(priority) = self.priority {
143            Component::priority(&mut todo, priority.into());
144        } else {
145            Component::priority(&mut todo, config.default_priority.into());
146        }
147
148        let status = self.status.unwrap_or(TodoStatus::NeedsAction).into();
149        icalendar::Todo::status(&mut todo, status);
150
151        Component::summary(&mut todo, &self.summary);
152
153        todo
154    }
155}
156
157/// Patch for a todo item, allowing partial updates.
158#[derive(Debug, Default, Clone)]
159pub struct TodoPatch {
160    /// The description of the todo item, if available.
161    pub description: Option<Option<String>>,
162
163    /// The due date and time of the todo item, if available.
164    pub due: Option<Option<LooseDateTime>>,
165
166    /// The percent complete, from 0 to 100.
167    pub percent_complete: Option<Option<u8>>,
168
169    /// The priority of the todo item, from 1 to 9, where 1 is the highest priority.
170    pub priority: Option<Priority>,
171
172    /// The status of the todo item, if available.
173    pub status: Option<TodoStatus>,
174
175    /// The summary of the todo item, if available.
176    pub summary: Option<String>,
177}
178
179impl TodoPatch {
180    /// Is this patch empty, meaning no fields are set
181    pub fn is_empty(&self) -> bool {
182        self.description.is_none()
183            && self.due.is_none()
184            && self.percent_complete.is_none()
185            && self.priority.is_none()
186            && self.status.is_none()
187            && self.summary.is_none()
188    }
189
190    /// Applies the patch to a mutable todo item, modifying it in place.
191    pub(crate) fn apply_to<'a>(&self, t: &'a mut icalendar::Todo) -> &'a mut icalendar::Todo {
192        if let Some(description) = &self.description {
193            match description {
194                Some(desc) => t.description(desc),
195                None => t.remove_description(),
196            };
197        }
198
199        if let Some(due) = &self.due {
200            match due {
201                Some(d) => t.due(*d),
202                None => t.remove_due(),
203            };
204        }
205
206        if let Some(percent) = self.percent_complete {
207            t.percent_complete(percent.unwrap_or(0));
208        }
209
210        if let Some(priority) = self.priority {
211            t.priority(priority.into());
212        }
213
214        if let Some(status) = self.status {
215            t.status(status.into());
216
217            match status {
218                TodoStatus::Completed => t.completed(Utc::now()),
219                _ if t.get_completed().is_some() => t.remove_completed(),
220                _ => t,
221            };
222        }
223
224        if let Some(summary) = &self.summary {
225            t.summary(summary);
226        }
227
228        t
229    }
230}
231
232/// The status of a todo item, which can be one of several predefined states.
233#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
234#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
235pub enum TodoStatus {
236    /// The todo item needs action.
237    #[default]
238    NeedsAction,
239
240    /// The todo item has been completed.
241    Completed,
242
243    /// The todo item is currently in process.
244    InProcess,
245
246    /// The todo item has been cancelled.
247    Cancelled,
248}
249
250const STATUS_NEEDS_ACTION: &str = "NEEDS-ACTION";
251const STATUS_COMPLETED: &str = "COMPLETED";
252const STATUS_IN_PROCESS: &str = "IN-PROGRESS";
253const STATUS_CANCELLED: &str = "CANCELLED";
254
255impl AsRef<str> for TodoStatus {
256    fn as_ref(&self) -> &str {
257        match self {
258            TodoStatus::NeedsAction => STATUS_NEEDS_ACTION,
259            TodoStatus::Completed => STATUS_COMPLETED,
260            TodoStatus::InProcess => STATUS_IN_PROCESS,
261            TodoStatus::Cancelled => STATUS_CANCELLED,
262        }
263    }
264}
265
266impl Display for TodoStatus {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        write!(f, "{}", self.as_ref())
269    }
270}
271
272impl FromStr for TodoStatus {
273    type Err = ();
274
275    fn from_str(value: &str) -> Result<Self, Self::Err> {
276        match value {
277            STATUS_NEEDS_ACTION => Ok(TodoStatus::NeedsAction),
278            STATUS_COMPLETED => Ok(TodoStatus::Completed),
279            STATUS_IN_PROCESS => Ok(TodoStatus::InProcess),
280            STATUS_CANCELLED => Ok(TodoStatus::Cancelled),
281            _ => Err(()),
282        }
283    }
284}
285
286impl From<TodoStatus> for icalendar::TodoStatus {
287    fn from(item: TodoStatus) -> icalendar::TodoStatus {
288        match item {
289            TodoStatus::NeedsAction => icalendar::TodoStatus::NeedsAction,
290            TodoStatus::Completed => icalendar::TodoStatus::Completed,
291            TodoStatus::InProcess => icalendar::TodoStatus::InProcess,
292            TodoStatus::Cancelled => icalendar::TodoStatus::Cancelled,
293        }
294    }
295}
296
297impl From<icalendar::TodoStatus> for TodoStatus {
298    fn from(status: icalendar::TodoStatus) -> Self {
299        match status {
300            icalendar::TodoStatus::NeedsAction => TodoStatus::NeedsAction,
301            icalendar::TodoStatus::Completed => TodoStatus::Completed,
302            icalendar::TodoStatus::InProcess => TodoStatus::InProcess,
303            icalendar::TodoStatus::Cancelled => TodoStatus::Cancelled,
304        }
305    }
306}
307
308/// Conditions for filtering todo items, such as current time, status, and due date.
309#[derive(Debug, Clone, Copy)]
310pub struct TodoConditions {
311    /// The status of the todo item to filter by, if any.
312    pub status: Option<TodoStatus>,
313
314    /// The priority of the todo item to filter by, if any.
315    pub due: Option<Duration>,
316}
317
318/// Conditions for filtering todo items, such as current time, status, and due date.
319#[derive(Debug, Clone, Copy)]
320pub(crate) struct ParsedTodoConditions {
321    /// The status of the todo item to filter by, if any.
322    pub status: Option<TodoStatus>,
323
324    /// The priority of the todo item to filter by, if any.
325    pub due: Option<DateTime<Local>>,
326}
327
328impl ParsedTodoConditions {
329    pub fn parse(now: &DateTime<Local>, conds: &TodoConditions) -> Self {
330        let status = conds.status;
331        let due = conds.due.map(|d| *now + d);
332        ParsedTodoConditions { status, due }
333    }
334}
335
336/// The default sort key for todo items, which is by due date.
337#[derive(Debug, Clone, Copy)]
338pub enum TodoSort {
339    /// Sort by the due date and time of the todo item.
340    Due(SortOrder),
341
342    /// Sort by the priority of the todo item.
343    Priority {
344        /// Sort order, either ascending or descending.
345        order: SortOrder,
346
347        /// Put items with no priority first or last. If none, use the default
348        none_first: Option<bool>,
349    },
350}
351
352#[derive(Debug, Clone, Copy)]
353pub(crate) enum ParsedTodoSort {
354    /// Sort by the due date and time of the todo item.
355    Due(SortOrder),
356
357    /// Sort by the priority of the todo item.
358    Priority {
359        /// Sort order, either ascending or descending.
360        order: SortOrder,
361
362        /// Put items with no priority first or last.
363        none_first: bool,
364    },
365}
366
367impl ParsedTodoSort {
368    pub fn parse(config: &Config, sort: TodoSort) -> Self {
369        match sort {
370            TodoSort::Due(order) => ParsedTodoSort::Due(order),
371            TodoSort::Priority { order, none_first } => ParsedTodoSort::Priority {
372                order,
373                none_first: none_first.unwrap_or(config.default_priority_none_fist),
374            },
375        }
376    }
377
378    pub fn parse_vec(config: &Config, sort: &[TodoSort]) -> Vec<Self> {
379        sort.iter()
380            .map(|s| ParsedTodoSort::parse(config, *s))
381            .collect()
382    }
383}