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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use chrono::prelude::*;
use std::collections::HashSet;

use num_traits::FromPrimitive;

use crate::{year_group_range, YearMonth};

#[cfg(test)]
use mockall::automock;

/// Date constraints configuration
#[derive(Default, Debug, Clone, Builder)]
#[builder(setter(strip_option))]
#[builder(default)]
#[builder(build_fn(validate = "Self::validate"))]
pub struct DateConstraints {
    /// inclusive minimal date constraint
    /// the earliest date that can be selected
    min_date: Option<NaiveDate>,

    /// inclusive maximal date constraint
    /// the latest date that can be selected
    max_date: Option<NaiveDate>,

    /// disabled weekdays, that should not be selectable
    disabled_weekdays: HashSet<Weekday>,

    /// entire completely disabled months in every year
    disabled_months: HashSet<Month>,

    /// entire completely disabled years
    disabled_years: HashSet<i32>,

    /// disabled monthly periodically repeating dates, so it is just a day number
    /// starting from 1 for the first day of the month
    /// if unique dates in a certain year should not be selectable use `disabled_unique_dates`
    disabled_monthly_dates: HashSet<u32>,

    /// disabled yearly periodically repeating dates that should not be selectable,
    /// if unique dates in a certain year should not be selectable use `disabled_unique_dates`
    /// it is a `Vec` since we need to iterate over it anyway, since we hae no MonthDay type
    disabled_yearly_dates: Vec<NaiveDate>,

    /// disabled unique dates with a specific year, month and day that should not be selectable,
    /// if some periodically repeated dates should not be selectable use the correct option
    disabled_unique_dates: HashSet<NaiveDate>,
}

impl DateConstraintsBuilder {
    fn validate(&self) -> Result<(), String> {
        match (self.min_date, self.max_date) {
            (Some(min_date), Some(max_date)) => {
                if min_date > max_date {
                    return Err("min_date must be earlier or exactly at max_date".into());
                }
            }
            (_, _) => {}
        }
        Ok(())
    }
}

// TODO: find out how to place #[derive(Debug, Clone)] on the structure generated by automock
// this is a temporary workaround for tests
cfg_if::cfg_if! {
    if #[cfg(test)] {
        impl Clone for MockDateConstraints {
            fn clone(&self) -> Self {
                Self::new()
            }
        }

        use core::fmt;
        impl fmt::Debug for MockDateConstraints {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct("MockDateConstraints").finish()
            }
        }
    }
}

#[cfg_attr(test, automock)]
impl DateConstraints {
    pub fn is_day_forbidden(&self, date: &NaiveDate) -> bool {
        self.min_date.map_or(false, |min_date| &min_date > date)
            || self.max_date.map_or(false, |max_date| &max_date < date)
            || self.disabled_weekdays.contains(&date.weekday())
            || self
                .disabled_months
                .contains(&Month::from_u32(date.month()).unwrap())
            || self.disabled_years.contains(&date.year())
            || self.disabled_unique_dates.contains(&date)
            || self.disabled_monthly_dates.contains(&date.day())
            || self
                .disabled_yearly_dates
                .iter()
                .any(|disabled| disabled.day() == date.day() && disabled.month() == date.month())
    }

    pub fn is_month_forbidden(&self, year_month_info: &YearMonth) -> bool {
        self.disabled_years.contains(&year_month_info.year)
            || self.disabled_months.contains(&year_month_info.month)
            || year_month_info
                .first_day_of_month()
                .iter_days()
                .take_while(|date| date.month() == year_month_info.month.number_from_month())
                .all(|date| self.is_day_forbidden(&date))
    }

    pub fn is_year_forbidden(&self, year: i32) -> bool {
        self.disabled_years.contains(&year)
            || (Month::January.number_from_month()..=Month::December.number_from_month()).all(
                |month| {
                    self.is_month_forbidden(&YearMonth {
                        year,
                        month: Month::from_u32(month).unwrap(),
                    })
                },
            )
    }

    pub fn is_year_group_forbidden(&self, year: i32) -> bool {
        year_group_range(year).all(|year| self.is_year_forbidden(year))
    }
}

#[cfg(test)]
mod tests {
    use crate::year_month::YearMonth;

    use super::*;
    use chrono::Duration;
    use num_traits::FromPrimitive;
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn is_day_forbidden_default_no_bounds(day in 1..365*5000i32) {
            let date = NaiveDate::from_num_days_from_ce(day);
            assert!(!DateConstraints::default().is_day_forbidden(&date))
        }
    }

    proptest! {
        #[test]
        fn is_month_forbidden_default_no_bounds(year in 1..5000i32, month_num in 1..=12u32) {
            let month = Month::from_u32(month_num).unwrap();
            let year_month_info = YearMonth {
                year,
                month,
            };
            assert!(!DateConstraints::default().is_month_forbidden(&year_month_info))
        }
    }

    proptest! {
        #[test]
        fn is_year_forbidden_default_no_bounds(year in 1..5000i32) {
            assert!(!DateConstraints::default().is_year_forbidden(year))
        }
    }

    #[test]
    fn picker_config_min_date_greater_than_max_date() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .min_date(date.clone())
            .max_date(date.clone() - Duration::days(1))
            .build();
        assert!(config.is_err());
        assert_eq!(
            config.err(),
            Some("min_date must be earlier or exactly at max_date".into())
        );
    }

    #[test]
    fn picker_config_min_date_equals_max_date() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .min_date(date.clone())
            .max_date(date.clone())
            .build();
        assert!(config.is_ok());
    }

    #[test]
    fn is_day_forbidden_at_min_date_allowed() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .min_date(date.clone())
            .build()
            .unwrap();
        assert!(!config.is_day_forbidden(&date))
    }

    #[test]
    fn is_day_forbidden_before_min_date_not_allowed() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .min_date(date.clone())
            .build()
            .unwrap();
        assert!(config.is_day_forbidden(&(date - Duration::days(1))))
    }

    #[test]
    fn is_day_forbidden_at_max_date_allowed() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .max_date(date.clone())
            .build()
            .unwrap();
        assert!(!config.is_day_forbidden(&date))
    }

    #[test]
    fn is_day_forbidden_after_max_date_not_allowed() {
        let date = NaiveDate::from_ymd(2020, 10, 15);
        let config = DateConstraintsBuilder::default()
            .max_date(date.clone())
            .build()
            .unwrap();
        assert!(config.is_day_forbidden(&(date + Duration::days(1))))
    }

    proptest! {
        #[test]
        fn is_day_forbidden_disabled_weekday_not_allowed(weekday in 0..7u8, year in 1..5000i32, iso_week in 1..52u32) {
            let disabled_weekday = Weekday::from_u8(weekday).unwrap();
            let date = NaiveDate::from_isoywd(year, iso_week, disabled_weekday);
            let config = DateConstraintsBuilder::default()
                .disabled_weekdays([disabled_weekday].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_day_forbidden(&date));
        }
    }

    proptest! {
        #[test]
        fn is_day_forbidden_disabled_month_not_allowed(month_num in 1..=12u32, year in 1..5000i32, day in 1..=28u32) {
            let config = DateConstraintsBuilder::default()
                .disabled_months([Month::from_u32(month_num).unwrap()].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_day_forbidden(&NaiveDate::from_ymd(year, month_num, day)))
        }
    }

    proptest! {
        #[test]
        fn is_day_forbidden_disabled_year_not_allowed(month_num in 1..=12u32, year in 1..5000i32, day in 1..=28u32) {
            let config = DateConstraintsBuilder::default()
                .disabled_years([year].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_day_forbidden(&NaiveDate::from_ymd(year, month_num, day)))
        }
    }

    #[test]
    fn is_day_forbidden_disabled_unique_dates_not_allowed() {
        let date = NaiveDate::from_ymd(2020, 1, 16);
        let config = DateConstraintsBuilder::default()
            .disabled_unique_dates([date].iter().cloned().collect())
            .build()
            .unwrap();
        assert!(config.is_day_forbidden(&date))
    }

    #[test]
    fn is_day_forbidden_disabled_unique_dates_after_a_year_allowed() {
        let date = NaiveDate::from_ymd(2020, 1, 16);
        let config = DateConstraintsBuilder::default()
            .disabled_unique_dates([date].iter().cloned().collect())
            .build()
            .unwrap();
        assert!(!config.is_day_forbidden(&NaiveDate::from_ymd(2021, 1, 16)))
    }

    proptest! {
        #[test]
        fn is_day_forbidden_disabled_yearly_dates_not_allowed(year_in_disabled in 1..5000i32, year_in_input in 1..5000i32, month in 1..=12u32, day in 1..=28u32) {
            let disabled_yearly_date = NaiveDate::from_ymd(year_in_disabled, month, day);
            let config = DateConstraintsBuilder::default()
                .disabled_yearly_dates(vec![disabled_yearly_date])
                .build()
                .unwrap();
            assert!(config.is_day_forbidden(&NaiveDate::from_ymd(year_in_input, month, day)))
        }
    }

    proptest! {
        #[test]
        fn is_day_forbidden_disabled_monthly_dates_not_allowed(year in 1..5000i32, month in 1..=12u32, day in 1..=28u32) {
            let config = DateConstraintsBuilder::default()
                .disabled_monthly_dates([day].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_day_forbidden(&NaiveDate::from_ymd(year, month, day)))
        }
    }

    proptest! {
        #[test]
        fn is_month_forbidden_disabled_months_not_allowed(year in 1..5000i32, month_num in 1..=12u32) {
            let month = Month::from_u32(month_num).unwrap();
            let config = DateConstraintsBuilder::default()
                .disabled_months([month].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_month_forbidden(&YearMonth {
                year,
                month
            }))
        }
    }

    proptest! {
        #[test]
        fn is_month_forbidden_disabled_years_not_allowed(year in 1..5000i32, month_num in 1..=12u32) {
            let month = Month::from_u32(month_num).unwrap();
            let config = DateConstraintsBuilder::default()
                .disabled_years([year].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_month_forbidden(&YearMonth {
                year,
                month
            }))
        }
    }

    proptest! {
        #[test]
        fn is_year_forbidden_disabled_years_not_allowed(year in 1..5000i32) {
            let config = DateConstraintsBuilder::default()
                .disabled_years([year].iter().cloned().collect())
                .build()
                .unwrap();
            assert!(config.is_year_forbidden(year))
        }
    }
}