Edit recipe

This commit is contained in:
eraden 2024-11-13 16:22:34 +01:00
parent 19b47b7988
commit 510376bb81
2 changed files with 172 additions and 8 deletions

View File

@ -10,10 +10,13 @@ use actix_web::HttpMessage;
use actix_web::{get, post, HttpRequest, HttpResponse, Responder}; use actix_web::{get, post, HttpRequest, HttpResponse, Responder};
use askama::Template; use askama::Template;
use askama_actix::TemplateToResponse; use askama_actix::TemplateToResponse;
use sea_orm::{prelude::*, DatabaseTransaction, QueryOrder, QuerySelect, TransactionTrait}; use sea_orm::{
prelude::*, DatabaseTransaction, JoinType, QueryOrder, QuerySelect, TransactionTrait,
};
use serde::Deserialize; use serde::Deserialize;
use std::collections::{BTreeMap, BTreeSet};
use serde_qs::actix::QsForm; use serde_qs::actix::QsForm;
use std::collections::HashMap;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Template, derive_more::Deref)] #[derive(Debug, Template, derive_more::Deref)]
#[template(path = "recipe_card.jinja")] #[template(path = "recipe_card.jinja")]
@ -87,6 +90,30 @@ struct RecipeForm {
page: Page, page: Page,
} }
#[derive(Debug, Template, Deserialize, Clone, PartialEq)]
#[template(path = "recipies/update_form.jinja", ext = "html")]
struct EditRecipeForm {
id: i32,
title: String,
summary: String,
ingredients: String,
steps: String,
tags: String,
selected_tags: Vec<String>,
image_url: String,
time: Option<String>,
author: Option<String>,
error: Option<String>,
#[serde(default)]
known_tags: Vec<entities::tags::Model>,
#[serde(default)]
known_ingredients: Vec<entities::ingredients::Model>,
#[serde(default)]
session: Option<User>,
#[serde(default)]
page: Page,
}
#[get("/sign-in")] #[get("/sign-in")]
async fn render_sign_in() -> SignInForm { async fn render_sign_in() -> SignInForm {
SignInForm { SignInForm {
@ -445,9 +472,11 @@ async fn save_recipe(form: RecipeForm, t: &mut DatabaseTransaction) -> Result<i3
// Tags // Tags
{ {
tracing::debug!("Selected tags: {:?}", form.selected_tags); tracing::debug!("Selected tags: {:?}", form.selected_tags);
let selected_tags = form let selected_tags = form.selected_tags;
.selected_tags; let selected_tags = selected_tags
let selected_tags = selected_tags.into_iter().filter_map(|s| s.parse().ok()).collect::<Vec<i32>>(); .into_iter()
.filter_map(|s| s.parse().ok())
.collect::<Vec<i32>>();
let text_tags = form let text_tags = form
.tags .tags
@ -607,6 +636,139 @@ async fn save_recipe(form: RecipeForm, t: &mut DatabaseTransaction) -> Result<i3
Ok(recipe_id) Ok(recipe_id)
} }
#[get("/recipe/{id}/edit")]
async fn edit_recipe(
id: actix_web::web::Path<i32>,
admin: Identity,
db: Data<DatabaseConnection>,
) -> Result<EditRecipeForm, Error> {
let id = id.into_inner();
let recipe = match Recipies::find()
.filter(entities::recipies::Column::Id.eq(id))
.one(&**db)
.await
{
Ok(Some(recipe)) => recipe,
Ok(_) => todo!("index & not found"),
Err(err) => {
todo!()
}
};
let recipe_tags = RecipeTags::find()
.filter(entities::recipe_tags::Column::RecipeId.eq(id))
.all(&**db)
.await
.unwrap_or_default()
.inspect_err(|e| tracing::error!("Failed to load recipe tags for edit recipe: {e}"))
.map_err(|_| Error::DatabaseError)?;
let tags = Tags::find()
.join(
JoinType::InnerJoin,
entities::tags::Relation::RecipeTags.def(),
)
.filter(entities::recipe_tags::Column::RecipeId.eq(id))
.all(&**db)
.await
.unwrap_or_default()
.inspect_err(|e| tracing::error!("Failed to load ingredients for edit recipe: {e}"))
.map_err(|_| Error::DatabaseError)?;
let recipe_ingredients = RecipeIngredients::find()
.filter(entities::recipe_ingredients::Column::RecipeId.eq(id))
.all(&**db)
.await
.unwrap_or_default()
.inspect_err(|e| tracing::error!("Failed to load ingredients for edit recipe: {e}"))
.map_err(|_| Error::DatabaseError)?;
let ingredients = Ingredients::find()
.join_rev(
JoinType::InnerJoin,
entities::ingredients::Relation::RecipeIngredients.def(),
)
.filter(entities::recipe_ingredients::Column::RecipeId.eq(id))
.all(&**db)
.await
.unwrap_or_default()
.inspect_err(|e| tracing::error!("Failed to load ingredients for edit recipe: {e}"))
.map_err(|_| Error::DatabaseError)?
.into_iter()
.fold(HashMap::new(), |mut agg, ing| {
agg.insert(ing.id, ing);
agg
});
Ok(EditRecipeForm {
id,
title: recipe.title,
summary: recipe.summary,
ingredients: recipe_ingredients
.into_iter()
.filter_map(|ingredient| {
format!(
"{} {} {}",
ingredient.qty,
ingredient.unit,
ingredients.get(&ingredient.id)?.name
)
})
.collect::<Vec<_>>()
.join("\n"),
steps,
tags,
selected_tags,
image_url: recipe.image_url,
time: recipe.time,
author: recipe.author,
error: None,
known_tags: recipe_tags.iter().map(|tag| tag.tag_id)).collect(),
known_ingredients: recipe_ingredients.iter().map(|ing| ing.ingredient_id).collect(),
session: admin.id(),
page: Page::Index,
})
}
#[post("/recipe/{id}/edit")]
async fn update_recipe(
id: actix_web::web::Path<i32>,
admin: Identity,
db: Data<DatabaseConnection>,
form: QsForm<RecipeForm>,
) -> Result<HttpResponse, Error> {
let mut form = form.into_inner();
form.session = admin.id().ok();
form.page = Page::Index;
let mut failure = form.clone();
let mut t = db
.begin()
.await
.inspect_err(|e| tracing::error!("Create recipe transaction: {e}"))
.map_err(|_| Error::DatabaseError)?;
match save_recipe(form, &mut t).await {
Err(e) => {
failure.error = Some(e.to_string());
let _ = t.rollback().await;
failure.known_tags = Tags::find().all(&**db).await.unwrap_or_default();
failure.known_ingredients = Ingredients::find().all(&**db).await.unwrap_or_default();
Ok(failure.to_response())
}
Ok(recipe_id) => {
let _ = t.commit().await;
let Ok(_) = tokio::fs::copy(
format!("/tmp{}", failure.image_url),
format!(".{}", failure.image_url),
)
.await
.inspect_err(|e| tracing::error!("Failed to copy {}: {e}", failure.image_url)) else {
tracing::error!("Failed to copy file: {}", failure.image_url);
return Ok(HttpResponse::InternalServerError().finish());
};
Ok(HttpResponse::SeeOther()
.append_header(("location", format!("/recipe/{recipe_id}").as_str()))
.finish())
}
}
}
#[get("/styles.css")] #[get("/styles.css")]
async fn styles_css() -> HttpResponse { async fn styles_css() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
@ -651,6 +813,8 @@ pub fn configure(config: &mut actix_web::web::ServiceConfig) {
.service(show) .service(show)
.service(search_page) .service(search_page)
.service(search_results) .service(search_results)
.service(update_recipe)
.service(edit_recipe)
.service(recipe_form) .service(recipe_form)
.service(create_recipe) .service(create_recipe)
.service(recipe_image_upload) .service(recipe_image_upload)

View File

@ -36,10 +36,10 @@
<p class="text-base font-semibold">Summary supports Markdown</p> <p class="text-base font-semibold">Summary supports Markdown</p>
</blockquote> </blockquote>
<label for="ingeredients" class="flex gap-4"> <label for="ingredients" class="flex gap-4">
<span class="w-24 shrink-0">Ingeredients:</span> <span class="w-24 shrink-0">Ingredients</span>
<div class="flex gap-2 w-full"> <div class="flex gap-2 w-full">
<textarea id="ingeredients" name="ingeredients" class="textarea-without-view" required>{{ingeredients}}</textarea> <textarea id="ingredients" name="ingredients" class="textarea-without-view" required>{{ingredients}}</textarea>
</div> </div>
</label> </label>
<div class="w-full flex gap-4 flex-wrap"> <div class="w-full flex gap-4 flex-wrap">