aboutsummaryrefslogtreecommitdiff
path: root/src/model/repetition.rs
blob: 07fc4d448c09e4100b5589e3c1d040b811d72746 (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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use chrono::{Datelike, Duration, NaiveDate, Weekday};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Repetition {
    pub frequency: Frequency,
    pub removed_occurences: HashSet<usize>,
    pub until: Option<NaiveDate>,
}

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

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DayOfMonth {
    Day { day: u8 },
    Weekday { week: u8, day: 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![];
            let mut iteration: usize = 0;
            let end = self.until.map(|u| u.min(end)).unwrap_or(end);
            while date <= end {
                if date >= event {
                    if date >= start && !self.removed_occurences.contains(&iteration) {
                        repetitions.push(date)
                    }
                    iteration += 1
                }
                date = next(date);
            }
            repetitions
        };

        match self.frequency {
            Frequency::Daily { period } => {
                let duration = Duration::days(period as i64);
                repeat(event, Box::new(|d| d + duration))
            }
            Frequency::Monthly {
                day: DayOfMonth::Day { day },
            } => match event.with_day(day as u32) {
                Some(first_repetition) => repeat(first_repetition, Box::new(next_month)),
                None => vec![],
            },
            Frequency::Monthly {
                day: DayOfMonth::Weekday { week, day },
            } => repeat(
                day_of_month(event, week, day),
                Box::new(|d| day_of_month(next_month(d), week, day)),
            ),
            Frequency::Yearly => repeat(
                // TODO: error handling
                NaiveDate::from_ymd_opt(event.year(), event.month(), event.day()).unwrap(),
                Box::new(|d| NaiveDate::from_ymd_opt(d.year() + 1, d.month(), d.day()).unwrap()),
            ),
        }
    }

    pub fn occurence_index(&self, event: NaiveDate, date: NaiveDate) -> Option<usize> {
        let mut without_removed_occurences = self.clone();
        without_removed_occurences.removed_occurences = HashSet::new();
        without_removed_occurences
            .between(event, event, date)
            .iter()
            .position(|d| d == &date)
    }
}

fn day_of_month(date: NaiveDate, week: u8, day: Weekday) -> NaiveDate {
    // TODO: error handling
    NaiveDate::from_weekday_of_month_opt(date.year(), date.month(), day, week).unwrap()
}

fn next_month(date: NaiveDate) -> NaiveDate {
    // TODO: error handling
    if date.month() == 12 {
        NaiveDate::from_ymd_opt(date.year() + 1, 1, date.day()).unwrap()
    } else {
        NaiveDate::from_ymd_opt(date.year(), date.month() + 1, date.day()).unwrap()
    }
}

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

    #[test]
    fn every_day_event_before() {
        let repetition = from_freq(Frequency::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 = from_freq(Frequency::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 = from_freq(Frequency::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 = from_freq(Frequency::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 = from_freq(Frequency::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 = from_freq(Frequency::Monthly {
            day: DayOfMonth::Weekday {
                week: 1,
                day: 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 = from_freq(Frequency::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))
        )
    }

    #[test]
    fn every_two_days_removed_occurence() {
        let repetition = Repetition {
            frequency: Frequency::Daily { period: 2 },
            removed_occurences: HashSet::from([0, 2, 3]),
            until: None,
        };
        assert_eq!(
            repetition.between(d(2020, 7, 1), d(2020, 7, 1), d(2020, 7, 9)),
            vec!(d(2020, 7, 3), d(2020, 7, 9))
        )
    }

    #[test]
    fn day_of_month_removed_occurence() {
        let repetition = Repetition {
            frequency: Frequency::Monthly {
                day: DayOfMonth::Day { day: 8 },
            },
            removed_occurences: HashSet::from([1, 3]),
            until: None,
        };
        assert_eq!(
            repetition.between(d(2020, 1, 8), d(2020, 1, 8), d(2020, 4, 8)),
            vec!(d(2020, 1, 8), d(2020, 3, 8))
        )
    }

    #[test]
    fn weekday_of_month_removed_occurence() {
        let repetition = Repetition {
            frequency: Frequency::Monthly {
                day: DayOfMonth::Weekday {
                    week: 1,
                    day: Weekday::Fri,
                },
            },
            removed_occurences: HashSet::from([1, 2, 3]),
            until: None,
        };
        assert_eq!(
            repetition.between(d(2020, 2, 1), d(2020, 2, 1), d(2020, 7, 1)),
            vec!(d(2020, 2, 7), d(2020, 6, 5))
        )
    }

    #[test]
    fn yearly_removed_occurence() {
        let repetition = Repetition {
            frequency: Frequency::Yearly,
            removed_occurences: HashSet::from([3]),
            until: None,
        };
        assert_eq!(
            repetition.between(d(2018, 5, 5), d(2019, 8, 1), d(2022, 5, 5)),
            vec!(d(2020, 5, 5), d(2022, 5, 5))
        )
    }

    #[test]
    fn occurence_index_after_removed_occurence() {
        let repetition = Repetition {
            frequency: Frequency::Yearly,
            removed_occurences: HashSet::from([1]),
            until: None,
        };
        assert_eq!(
            repetition.occurence_index(d(2020, 1, 1), d(2022, 1, 1)),
            Some(2)
        )
    }

    #[test]
    fn repetition_stops_after_until() {
        let repetition = Repetition {
            frequency: Frequency::Yearly,
            removed_occurences: HashSet::new(),
            until: Some(d(2022, 1, 1)),
        };
        assert_eq!(
            repetition.between(d(2020, 1, 1), d(2020, 1, 1), d(2024, 1, 1)),
            vec!(d(2020, 1, 1), d(2021, 1, 1), d(2022, 1, 1))
        )
    }

    #[test]
    fn repetition_daily_after_day() {
        let repetition = Repetition {
            frequency: Frequency::Daily { period: 1 },
            removed_occurences: HashSet::new(),
            until: Some(d(2022, 4, 17)),
        };
        assert_eq!(
            repetition.between(d(2022, 4, 4), d(2022, 3, 20), d(2022, 3, 20)),
            vec!()
        )
    }

    fn d(y: i32, m: u32, d: u32) -> NaiveDate {
        NaiveDate::from_ymd_opt(y, m, d).unwrap()
    }

    fn from_freq(frequency: Frequency) -> Repetition {
        Repetition {
            frequency,
            removed_occurences: HashSet::new(),
            until: None,
        }
    }
}