Added update and delete functionality to article with cascade for variants.

This commit is contained in:
2026-01-26 16:51:29 +01:00
parent b562c26a82
commit 7879f69255
7 changed files with 266 additions and 19 deletions
+53
View File
@@ -141,3 +141,56 @@ pub async fn insert_article(article: &Article, pool: PgPool) -> Option<Article>
} }
} }
} }
pub async fn update_article(article_id: i64, article: &Article, pool: PgPool) -> Option<Article> {
let mut args = PgArguments::default();
args.add(&article.id);
args.add(&article.name);
args.add(&article.bio);
args.add(&article.origin);
args.add(&article.description);
args.add(&article.ingredients);
let statement = format!(
"UPDATE {} SET name = $2, bio = $3, origin = $4, description = $5, ingredients = $6 WHERE id = $1 RETURNING *",
"article",
);
let res = sqlx::query_with(
statement.as_str(),
args)
.fetch_one(&pool).await;
info!("{:#?}", res);
match res {
Ok(record) => {
let variant = from_postgres_row_small(record);
Some(variant)
}
Err(err) => {
error!("Error while updating variant: {}", article_id);
None
}
}
}
pub async fn delete_article(article_id: i64, pool: PgPool) -> Option<()> {
let result = sqlx::query(
format!("DELETE FROM {} WHERE id = {}",
"article",
article_id
).as_str()
).execute(&pool).await;
match result {
Ok(_) => {
Some(())
}
Err(err) => {
println!("Error deleting article: {:#?}", err);
None
}
}
}
+110 -7
View File
@@ -1,16 +1,115 @@
<script setup lang="ts"> <script setup lang="ts">
import {useLabelEditorStore} from "~/store/labelEditorStore"; import {useLabelEditorStore} from "~/store/labelEditorStore";
import {originToString} from "~/types/origin"; import {originToString} from "~/types/origin";
import DeleteConfirm from "~/components/ui/deleteConfirm.vue";
import type {Ref} from "vue";
let store = useLabelEditorStore(); let store = useLabelEditorStore();
//const rules = [(v: string | any[]) => v.length <= 256 || 'Maximal 256 Zeichen.']; let edit: Ref<boolean> = ref<boolean>(false);
function toggleEdit() {
if (edit.value) {
disableEdit();
} else {
enableEdit();
}
}
function enableEdit() {
edit.value = true;
}
function disableEdit() {
edit.value = false;
store.articleEdit = JSON.parse(JSON.stringify(store.article));
}
async function updateArticle() {
if (store.articleEdit != null &&
store.articleEdit.name != null && store.articleEdit.name.trim().length > 0 &&
store.articleEdit.origin != null)
{
await store.updateArticle(store.articleEdit);
disableEdit();
}
}
async function deleteArticle() {
await store.deleteCurrentArticle();
}
</script> </script>
<template> <template>
<v-container> <v-container>
<v-card v-if="store.article != null"> <v-card v-if="store.article != null && store.articleEdit != null">
<v-card-title>{{ store.article.name }}</v-card-title> <v-card-title>
<v-row style="padding-top: 10px">
<v-text-field
v-model.trim="store.articleEdit.name"
:readonly="!edit"
/>
<v-spacer />
<v-divider vertical/>
<DeleteConfirm
title="Artikel löschen?"
:disable="!edit"
@delete="deleteArticle()"
/>
<v-divider vertical/>
<v-btn
:flat="true"
:disabled="!edit"
:hidden="edit"
@click="disableEdit()"
>
<v-icon>mdi-cancel</v-icon>
<v-tooltip
activator="parent"
location="bottom"
>
Abbrechen
</v-tooltip>
</v-btn>
<v-btn
:flat="true"
:disabled="!edit"
:hidden="edit"
@click="updateArticle()"
>
<v-icon>mdi-content-save</v-icon>
<v-tooltip
activator="parent"
location="bottom"
>
Speichern
</v-tooltip>
</v-btn>
<v-divider vertical/>
<v-btn
:flat="true"
@click="toggleEdit();"
>
<v-icon>mdi-pencil</v-icon>
<v-tooltip
activator="parent"
location="bottom"
>
Bearbeiten
</v-tooltip>
</v-btn>
</v-row>
</v-card-title>
<v-divider/> <v-divider/>
@@ -19,9 +118,9 @@
<v-col cols="2"> <v-col cols="2">
<v-row no-gutters> <v-row no-gutters>
<v-checkbox <v-checkbox
v-model="store.article.bio" v-model="store.articleEdit.bio"
label="BIO" label="BIO"
:readonly=true :readonly="!edit"
/> />
</v-row> </v-row>
@@ -41,13 +140,15 @@
<v-col cols="5" style="padding: 5px;"> <v-col cols="5" style="padding: 5px;">
<v-textarea <v-textarea
:model-value="store.article.description" v-model.trim="store.articleEdit.description"
:tile=true :tile=true
label="Beschreibung" label="Beschreibung"
counter counter
:persistentCounter=true :persistentCounter=true
rows="6" rows="6"
no-resize no-resize
:readonly="!edit"
persistent-placeholder
> >
<template v-slot:counter="{ counter }"> <template v-slot:counter="{ counter }">
<span>{{ counter }} von {{ store.ingredientsMaxChars }} Zeichen.</span> <span>{{ counter }} von {{ store.ingredientsMaxChars }} Zeichen.</span>
@@ -57,13 +158,15 @@
<v-col cols="5" style="padding: 5px;"> <v-col cols="5" style="padding: 5px;">
<v-textarea <v-textarea
:model-value="store.article.ingredients" v-model.trim="store.articleEdit.ingredients"
:tile=true :tile=true
label="Zutaten" label="Zutaten"
counter counter
:persistentCounter=true :persistentCounter=true
rows="6" rows="6"
no-resize no-resize
:readonly="!edit"
persistent-placeholder
> >
<template v-slot:counter="{ counter }"> <template v-slot:counter="{ counter }">
<span>{{ counter }} von {{ store.ingredientsMaxChars }} Zeichen.</span> <span>{{ counter }} von {{ store.ingredientsMaxChars }} Zeichen.</span>
@@ -12,9 +12,8 @@
watch(dialog, async (oldDialog) => { watch(dialog, async (oldDialog) => {
if (oldDialog) { if (oldDialog) {
console.log("Get articles");
articles.value = await loadArticles(); articles.value = await loadArticles();
console.log("Got articles"); selectedArticle.value = null;
} }
}) })
@@ -12,7 +12,6 @@
let edit: Ref<boolean> = ref<boolean>(false); let edit: Ref<boolean> = ref<boolean>(false);
JSON.parse(JSON.stringify(props.variant.weight))
let weight: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.weight))); let weight: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.weight)));
let ean: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.ean))); let ean: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.ean)));
let name: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.name))); let name: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.variant.name)));
+44 -8
View File
@@ -18,6 +18,7 @@ interface State {
// Article // Article
article: Article | null, article: Article | null,
articleEdit: Article | null,
origins: Array<Origin>, origins: Array<Origin>,
} }
@@ -36,6 +37,7 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
// Article // Article
article: null, article: null,
articleEdit: null,
origins: [ origins: [
Origin.EU, Origin.EU,
@@ -113,10 +115,13 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
method: 'GET', method: 'GET',
}); });
this.article = article; this.article = JSON.parse(JSON.stringify(article));
this.addNotification(false, 'Artikel geladen: ' + this.article.name); this.articleEdit = JSON.parse(JSON.stringify(article));
this.addNotification(false, 'Artikel geladen: ' + this.article!.name);
} catch { } catch {
this.article = null; this.article = null;
this.articleEdit = null;
this.addNotification(true, 'Fehler beim laden des Artikel. ID:' + articleID); this.addNotification(true, 'Fehler beim laden des Artikel. ID:' + articleID);
} }
}, },
@@ -139,12 +144,15 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
async createArticle(article: Article) { async createArticle(article: Article) {
try { try {
this.article = await $fetch<Article>(this.config.public.url + '/article', { let createdArticle = await $fetch<Article>(this.config.public.url + '/article', {
method: 'POST', method: 'POST',
body: JSON.stringify(article), body: JSON.stringify(article),
}); });
this.addNotification(false, 'Artikel "' + article.name + '" erstellt'); this.article = JSON.parse(JSON.stringify(createdArticle));
this.articleEdit = JSON.parse(JSON.stringify(createdArticle));
this.addNotification(false, 'Artikel "' + createdArticle.name + '" erstellt');
} catch { } catch {
this.addNotification(true, 'Fehler beim erstellen des Artikel: ' + article.name); this.addNotification(true, 'Fehler beim erstellen des Artikel: ' + article.name);
} }
@@ -152,21 +160,49 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
async updateArticle(article: Article) { async updateArticle(article: Article) {
if (this.article != null) { if (this.article != null) {
console.log(article);
try { try {
this.article = await $fetch<Article>(this.config.public.url + '/article/update', { let updatedArticle = await $fetch<Article>(this.config.public.url + '/article/' + article.id, {
method: 'POST', method: 'POST',
body: JSON.stringify(this.article), body: JSON.stringify(article),
}); });
this.addNotification(false, 'Artikel "' + this.article.name + '" aktualisiert'); this.article.name = updatedArticle.name;
this.article.bio = updatedArticle.bio;
this.article.origin = updatedArticle.origin;
this.article.description = updatedArticle.description;
this.article.ingredients = updatedArticle.ingredients;
this.addNotification(false, 'Artikel "' + article.name + '" aktualisiert');
} catch { } catch {
this.addNotification(true, 'Fehler beim aktualisieren des Artikel: ' + this.article.name); this.addNotification(true, 'Fehler beim aktualisieren des Artikel: ' + article.name);
} }
} else { } else {
this.addNotification(true, 'Es ist kein Artikel ausgewählt'); this.addNotification(true, 'Es ist kein Artikel ausgewählt');
} }
}, },
async deleteCurrentArticle() {
if(this.article != null) {
try {
await $fetch(this.config.public.url + '/article/' + this.article.id, {
method: 'DELETE',
});
this.article = null;
this.addNotification(false, 'Variante gelöscht.');
} catch {
this.addNotification(true, 'Fehler beim löschen der Variante.');
}
} else {
this.addNotification(true, 'Kann Variante nicht gelöscht werden. Es ist kein Artikel ausgewählt.');
}
},
// Variant // Variant
async addVariant(variant: Variant) { async addVariant(variant: Variant) {
if(this.article != null) { if(this.article != null) {
@@ -0,0 +1,7 @@
-- Add migration script here
ALTER TABLE public.variant
DROP CONSTRAINT variant_article_id_fkey,
ADD CONSTRAINT variant_article_id_fkey
foreign key (article_id)
references article(id)
on delete cascade;
+51 -1
View File
@@ -9,7 +9,7 @@ use axum::routing::delete;
use dotenv::dotenv; use dotenv::dotenv;
use env_logger::fmt::style::Reset; use env_logger::fmt::style::Reset;
use http::{header, Method}; use http::{header, Method};
use common::models::article::{insert_article, load_article, load_articles, Article}; use common::models::article::{delete_article, insert_article, load_article, load_articles, update_article, Article};
use common::models::origin::Origin; use common::models::origin::Origin;
use sqlx::{ postgres::PgPoolOptions, PgPool }; use sqlx::{ postgres::PgPoolOptions, PgPool };
use tower_http::cors::{AllowOrigin, Any, CorsLayer}; use tower_http::cors::{AllowOrigin, Any, CorsLayer};
@@ -49,6 +49,8 @@ async fn main() {
.route("/articles", get(get_articles)) .route("/articles", get(get_articles))
.route("/article", post(create_article)) .route("/article", post(create_article))
.route("/article/{id}", get(get_article)) .route("/article/{id}", get(get_article))
.route("/article/{id}", post(update_article_route))
.route("/article/{id}", delete(delete_article_route))
.route("/article/{id}/variant", post(add_variant)) .route("/article/{id}/variant", post(add_variant))
.route("/variant/{id}", post(update_variant_route)) .route("/variant/{id}", post(update_variant_route))
.route("/variant/{id}", delete(delete_variant_route)) .route("/variant/{id}", delete(delete_variant_route))
@@ -135,6 +137,54 @@ async fn create_article(
} }
} }
async fn update_article_route(
State(pool): State<PgPool>,
Path(article_id): Path<i64>,
Json(payload): Json<Article>,
) -> (StatusCode, Json<Article>) {
info!("Update article");
let update_article = update_article(article_id, &payload, pool).await;
match update_article {
Some(article) => {
(StatusCode::OK, Json(article))
}
None => {
let article = Article {
id: 0,
name: "".to_string(),
bio: false,
origin: Origin::EU,
description: None,
ingredients: None,
variants: vec![],
};
(StatusCode::INTERNAL_SERVER_ERROR, Json(article))
}
}
}
async fn delete_article_route(
State(pool): State<PgPool>,
Path(article_id): Path<i64>,
) -> StatusCode {
info!("Delete article");
let delete_article_result = delete_article(article_id, pool).await;
match delete_article_result {
Some(_) => {
StatusCode::OK
}
None => {
StatusCode::INTERNAL_SERVER_ERROR
}
}
}
async fn add_variant( async fn add_variant(
State(pool): State<PgPool>, State(pool): State<PgPool>,
Path(article_id): Path<i64>, Path(article_id): Path<i64>,