1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4use super::TaskId;
5
6#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
11pub struct Task {
12 pub id: TaskId,
14
15 pub title: String,
17
18 pub completed: bool,
20
21 pub created_at: DateTime<Utc>,
23
24 pub completed_at: Option<DateTime<Utc>>,
26}
27
28impl Task {
29 pub fn new(title: impl Into<String>) -> Self {
31 use super::TaskBuilder;
32 TaskBuilder::new().title(title).build()
33 }
34
35 pub fn with_id(id: TaskId, title: impl Into<String>) -> Self {
37 use super::TaskBuilder;
38 TaskBuilder::new().id(id).title(title).build()
39 }
40
41 pub fn complete(&mut self) {
43 if !self.completed {
44 self.completed = true;
45 self.completed_at = Some(Utc::now());
46 }
47 }
48
49 pub const fn uncomplete(&mut self) {
51 self.completed = false;
52 self.completed_at = None;
53 }
54
55 #[must_use]
57 pub fn age(&self) -> chrono::Duration {
58 Utc::now() - self.created_at
59 }
60
61 #[must_use]
63 pub fn completion_duration(&self) -> Option<chrono::Duration> {
64 self.completed_at
65 .map(|completed| completed - self.created_at)
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn test_new_task() {
75 let task = Task::new("Test task");
76 assert_eq!(task.title, "Test task");
77 assert!(!task.completed);
78 assert!(task.completed_at.is_none());
79 }
80
81 #[test]
82 fn test_complete_task() {
83 let mut task = Task::new("Test task");
84 task.complete();
85
86 assert!(task.completed);
87 assert!(task.completed_at.is_some());
88 }
89
90 #[test]
91 fn test_uncomplete_task() {
92 let mut task = Task::new("Test task");
93 task.complete();
94 task.uncomplete();
95
96 assert!(!task.completed);
97 assert!(task.completed_at.is_none());
98 }
99}