Fix is_on function for Periods

This commit is contained in:
Tobias Reisinger 2024-05-02 20:12:43 +02:00
parent fc4c1df09a
commit 98db89ce03
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE

View file

@ -1,10 +1,10 @@
use chrono::{NaiveTime, Timelike};
use serde::{Deserialize, Serialize};
use sqlx::{Decode, Encode, Sqlite, Type};
use sqlx::database::HasArguments;
use sqlx::encode::IsNull;
use sqlx::error::BoxDynError;
use sqlx::sqlite::{SqliteTypeInfo, SqliteValueRef};
use sqlx::{Decode, Encode, Sqlite, Type};
use crate::db::DbPeriods;
@ -51,13 +51,33 @@ impl Period {
}
}
pub fn is_always_on(&self) -> bool {
self.start.eq(&self.end)
}
pub fn is_on(&self, now: &NaiveTime) -> bool {
self.start.eq(&self.end) || (self.start.le(now) && self.end.gt(now))
if self.is_always_on() {
return true;
}
let start_after_now = self.start.gt(now);
// add check for end time being 00:00 because end being 00:00 would cause end_after_now to always be false
// this will handle end like 24:00 and end_after_now will be true
let end_after_now = self.end.gt(now) || self.end.eq(&NaiveTime::MIN);
let start_before_end = self.start.lt(&self.end);
match (start_after_now, end_after_now, start_before_end) {
(false, false, true) => false, // both before now; start before end means "normal" period before now
(false, false, false) => true, // both before now; end before start means "inversed" period around now
(true, false, _) => false, // only start after now
(false, true, _) => true, // only end after now
(true, true, true) => false, // both after now but start first
(true, true, false) => true, // both after now but end first
}
}
pub fn get_next_time(&self, now: &NaiveTime) -> Option<NaiveTime> {
if self.start.eq(&self.end) {
// this period is always on
if self.is_always_on() {
return None;
}