Refactor toggle_category into (dis)activate
This commit is contained in:
@ -35,7 +35,8 @@ fn main() -> io::Result<()> {
|
||||
routes::index,
|
||||
routes::history,
|
||||
routes::create_category,
|
||||
routes::toggle_category,
|
||||
routes::activate_category,
|
||||
routes::deactivate_category,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@ -32,8 +32,18 @@ pub fn create_category(category: Form<NewCategory>, db: State<'_, sled::Db>) ->
|
||||
Ok(Redirect::to(uri!(index)))
|
||||
}
|
||||
|
||||
#[post("/toggle_category/<category_uuid>")]
|
||||
pub fn toggle_category(category_uuid: String, db: State<'_, sled::Db>) -> Result<Redirect, StatusJson> {
|
||||
|
||||
#[post("/set_category/<category_uuid>/active")]
|
||||
pub fn activate_category(category_uuid: String, db: State<'_, sled::Db>) -> Result<StatusJson, StatusJson> {
|
||||
toggle_category(category_uuid, true, db)
|
||||
}
|
||||
|
||||
#[post("/set_category/<category_uuid>/inactive")]
|
||||
pub fn deactivate_category(category_uuid: String, db: State<'_, sled::Db>) -> Result<StatusJson, StatusJson> {
|
||||
toggle_category(category_uuid, false, db)
|
||||
}
|
||||
|
||||
pub fn toggle_category(category_uuid: String, set_active: bool, db: State<'_, sled::Db>) -> Result<StatusJson, StatusJson> {
|
||||
let category_uuid = Uuid::parse_str(&category_uuid)?;
|
||||
let category_uuid_s = sled::IVec::from(serialize(&category_uuid)?);
|
||||
|
||||
@ -49,8 +59,8 @@ pub fn toggle_category(category_uuid: String, db: State<'_, sled::Db>) -> Result
|
||||
let mut category: categories::V = dbg!(deserialize(&data).unwrap());
|
||||
let now = Utc::now().naive_utc();
|
||||
|
||||
match category.started.take() {
|
||||
Some(started) => {
|
||||
match (set_active, category.started.take()) {
|
||||
(false, Some(started)) => {
|
||||
// only save sessions longer than 5 minutes
|
||||
let duration = now - started;
|
||||
if duration > Duration::minutes(5) {
|
||||
@ -63,16 +73,20 @@ pub fn toggle_category(category_uuid: String, db: State<'_, sled::Db>) -> Result
|
||||
tx_past_sessions.insert(session_uuid, serialize(&past_session).unwrap())?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
(true, None) => {
|
||||
category.started = Some(now);
|
||||
}
|
||||
_ => {
|
||||
// Category is already in the correct state
|
||||
return Ok(Ok(Status::Ok.into()));
|
||||
}
|
||||
}
|
||||
|
||||
tx_categories.insert(&category_uuid_s, serialize(&category).unwrap())?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Ok(Redirect::to(uri!(index))))
|
||||
Ok(Ok(Status::Ok.into()))
|
||||
})??)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user