90 lines
2.7 KiB
Rust
90 lines
2.7 KiB
Rust
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<db::Connection>,
|
|
Extension(context): Extension<Context>,
|
|
date_range: Query<common::web_api::DateRange>,
|
|
) -> Result<impl IntoResponse> {
|
|
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<data::db::recipe::AddScheduledRecipeResult> 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<db::Connection>,
|
|
Extension(context): Extension<Context>,
|
|
ExtractRon(ron): ExtractRon<common::web_api::ScheduleRecipe>,
|
|
) -> Result<Response> {
|
|
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<db::Connection>,
|
|
Extension(context): Extension<Context>,
|
|
ExtractRon(ron): ExtractRon<common::web_api::RemoveScheduledRecipe>,
|
|
) -> Result<impl IntoResponse> {
|
|
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)
|
|
}
|