aboutsummaryrefslogtreecommitdiff
path: root/src/model/repetition.rs
blob: 52883585c4be6568c15f4c3619019b2befaf3129 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use chrono::{Datelike, Duration, NaiveDate, Weekday};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Repetition {
    Daily { period: u32 },
    Monthly { day: DayOfMonth },
    Yearly,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DayOfMonth {
    Day { day: u8 },
    Weekday { weekday: Weekday },
}

pub fn validate_period(str: &str) -> Result<u32, String> {
    let n = str.parse::<u32>().map_err(|_| format!("{} n’est pas une période valide.", str))?;
    if n == 0 {
        Err("La periode doit être positive.".to_string())
    } else {
        Ok(n)
    }
}


pub fn validate_day(str: &str) -> Result<u8, String> {
    let n = str.parse::<u8>().map_err(|_| format!("« {} » n’est pas un jour valide.", str))?;
    if (1..=31).contains(&n) {
        Ok(n)
    } else {
        Err("Le jour devrait se situer entre le 1er et le 31 du mois.".to_string())
    }
}

impl Repetition {
    pub fn between(&self, event: NaiveDate, start: NaiveDate, end: NaiveDate) -> Vec<NaiveDate> {
        let repeat = |mut date, next: Box<dyn Fn(NaiveDate) -> NaiveDate>| {
            let mut repetitions = vec![];
            while date <= end {
                if date >= event && date >= start {
                    repetitions.push(date)
                }
                date = next(date)
            }
            repetitions
        };

        match self {
            Repetition::Daily { period } => {
                let n = start.signed_duration_since(event).num_days() % (*period as i64);
                let duration = Duration::days(*period as i64);
                repeat(start - Duration::days(n), Box::new(|d| d + duration))
            }
            Repetition::Monthly {
                day: DayOfMonth::Day { day },
            } => match start.with_day(*day as u32) {
                Some(first_repetition) => repeat(first_repetition, Box::new(next_month)),
                None => vec![],
            },
            Repetition::Monthly {
                day: DayOfMonth::Weekday { weekday },
            } => repeat(
                first_weekday_of_month(start, *weekday),
                Box::new(|d| first_weekday_of_month(next_month(d), *weekday)),
            ),
            Repetition::Yearly => repeat(
                NaiveDate::from_ymd(start.year(), event.month(), event.day()),
                Box::new(|d| NaiveDate::from_ymd(d.year() + 1, d.month(), d.day())),
            ),
        }
    }
}

fn first_weekday_of_month(date: NaiveDate, weekday: Weekday) -> NaiveDate {
    NaiveDate::from_weekday_of_month(date.year(), date.month(), weekday, 1)
}

fn next_month(date: NaiveDate) -> NaiveDate {
    if date.month() == 12 {
        NaiveDate::from_ymd(date.year() + 1, 1, date.day())
    } else {
        NaiveDate::from_ymd(date.year(), date.month() + 1, date.day())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_day_event_before() {
        let repetition = Repetition::Daily { period: 1 };
        assert_eq!(
            repetition.between(d(2022, 6, 1), d(2022, 7, 1), d(2022, 8, 31)),
            d(2022, 7, 1)
                .iter_days()
                .take(62)
                .collect::<Vec<NaiveDate>>()
        )
    }

    #[test]
    fn every_day_event_between() {
        let repetition = Repetition::Daily { period: 1 };
        assert_eq!(
            repetition.between(d(2022, 8, 10), d(2022, 7, 1), d(2022, 8, 31)),
            d(2022, 8, 10)
                .iter_days()
                .take(22)
                .collect::<Vec<NaiveDate>>()
        )
    }

    #[test]
    fn every_day_event_after() {
        let repetition = Repetition::Daily { period: 1 };
        assert!(repetition
            .between(d(2022, 9, 1), d(2022, 7, 1), d(2022, 8, 31))
            .is_empty())
    }

    #[test]
    fn every_three_days() {
        let repetition = Repetition::Daily { period: 3 };
        assert_eq!(
            repetition.between(d(2022, 2, 16), d(2022, 2, 21), d(2022, 3, 6)),
            vec!(
                d(2022, 2, 22),
                d(2022, 2, 25),
                d(2022, 2, 28),
                d(2022, 3, 3),
                d(2022, 3, 6)
            )
        )
    }

    #[test]
    fn day_of_month() {
        let repetition = Repetition::Monthly {
            day: DayOfMonth::Day { day: 8 },
        };
        assert_eq!(
            repetition.between(d(2022, 2, 7), d(2022, 1, 1), d(2022, 4, 7)),
            vec!(d(2022, 2, 8), d(2022, 3, 8))
        )
    }

    #[test]
    fn weekday_of_month() {
        let repetition = Repetition::Monthly {
            day: DayOfMonth::Weekday {
                weekday: Weekday::Tue,
            },
        };
        assert_eq!(
            repetition.between(d(2022, 1, 5), d(2022, 1, 1), d(2022, 4, 4)),
            vec!(d(2022, 2, 1), d(2022, 3, 1))
        )
    }

    #[test]
    fn yearly() {
        let repetition = Repetition::Yearly;
        assert_eq!(
            repetition.between(d(2020, 5, 5), d(2018, 1, 1), d(2022, 5, 5)),
            vec!(d(2020, 5, 5), d(2021, 5, 5), d(2022, 5, 5))
        )
    }

    fn d(y: i32, m: u32, d: u32) -> NaiveDate {
        NaiveDate::from_ymd(y, m, d)
    }
}