use axum::{ debug_handler, extract::{Extension, State}, http::StatusCode, response::{ErrorResponse, IntoResponse, Response, Result}, }; use axum_extra::extract::Query; use crate::{ app::Context, data::{self, db}, ron_extractor::ExtractRon, ron_utils::{ron_error, ron_response_ok}, translation::Sentence, }; #[debug_handler] pub async fn get_scheduled_recipes( State(connection): State, Extension(context): Extension, date_range: Query, ) -> Result { if let Some(user) = context.user { Ok(ron_response_ok(common::web_api::ScheduledRecipes { recipes: connection .get_scheduled_recipes(user.id, date_range.start_date, date_range.end_date) .await?, })) } else { Err(ErrorResponse::from(ron_error( StatusCode::UNAUTHORIZED, context.tr.t(Sentence::ActionNotAuthorized), ))) } } impl From for common::web_api::ScheduleRecipeResult { fn from(db_res: data::db::recipe::AddScheduledRecipeResult) -> Self { match db_res { db::recipe::AddScheduledRecipeResult::Ok => Self::Ok, db::recipe::AddScheduledRecipeResult::RecipeAlreadyScheduledAtThisDate => { Self::RecipeAlreadyScheduledAtThisDate } } } } #[debug_handler] pub async fn add_scheduled_recipe( State(connection): State, Extension(context): Extension, ExtractRon(ron): ExtractRon, ) -> Result { if let Some(user) = context.user { connection .add_scheduled_recipe( user.id, ron.recipe_id, ron.date, ron.servings, ron.add_ingredients_to_shopping_list, ) .await .map(|res| { ron_response_ok(common::web_api::ScheduleRecipeResult::from(res)).into_response() }) .map_err(ErrorResponse::from) } else { Ok(StatusCode::OK.into_response()) } } #[debug_handler] pub async fn rm_scheduled_recipe( State(connection): State, Extension(context): Extension, ExtractRon(ron): ExtractRon, ) -> Result { if let Some(user) = context.user { connection .rm_scheduled_recipe( user.id, ron.recipe_id, ron.date, ron.remove_ingredients_from_shopping_list, ) .await?; } Ok(StatusCode::OK) }