Added settings to backend and frontend.

This commit is contained in:
2026-02-02 03:41:56 +01:00
parent 2fb74839e4
commit c34b2391eb
10 changed files with 429 additions and 0 deletions
+1
View File
@@ -3,3 +3,4 @@ pub mod article;
pub mod variant;
pub mod unit;
pub mod label;
pub mod settings;
+70
View File
@@ -0,0 +1,70 @@
use log::{error, info};
use serde::{Deserialize, Serialize};
use sqlx::{Arguments, Decode, Encode, FromRow, PgPool, Row};
use sqlx::postgres::{PgArguments, PgRow};
#[derive(Debug, Deserialize, Serialize, Clone, FromRow, Decode, Encode)]
pub struct Settings {
pub id: i64,
pub mhd: String,
pub bio: String,
}
fn from_postgres_row_small(row: PgRow) -> Settings {
Settings {
id: row.get(0),
mhd: row.get(1),
bio: row.get(2),
}
}
pub async fn load_settings(pool: &PgPool) -> Option<Settings> {
let statement = format!(
"SELECT * FROM {}",
"settings",
);
let res = sqlx::query(
statement.as_str())
.fetch_one(pool).await;
match res {
Ok(record) => {
Some(from_postgres_row_small(record))
}
Err(err) => {
error!("Error while loading settings.");
None
}
}
}
pub async fn update_settings(settings: &Settings, pool: PgPool) -> Option<Settings> {
let mut args = PgArguments::default();
args.add(&settings.id);
args.add(&settings.mhd);
args.add(&settings.bio);
let statement = format!(
"UPDATE {} SET mhd = $2, bio = $3 WHERE id = $1 RETURNING *",
"settings",
);
let res = sqlx::query_with(
statement.as_str(),
args)
.fetch_one(&pool).await;
info!("{:#?}", res);
match res {
Ok(record) => {
let label = from_postgres_row_small(record);
Some(label)
}
Err(err) => {
error!("Error while updating settings.");
None
}
}
}
+4
View File
@@ -2,12 +2,16 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './app.vue'
import {useLabelEditorStore} from "~/store/labelEditorStore";
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
let store = useLabelEditorStore();
await store.loadSettings();
</script>
<template>
@@ -14,6 +14,12 @@
:vertical="true"
/>
<Settings/>
<v-divider
:vertical="true"
/>
<Label/>
<v-divider
@@ -0,0 +1,132 @@
<script setup lang="ts">
import {useLabelEditorStore} from "~/store/labelEditorStore";
import type {Ref} from "vue";
import LabelCreate from "~/components/label/labelCreate.vue";
import DeleteConfirm from "~/components/ui/deleteConfirm.vue";
import {Label} from "~/types/label";
import {Settings} from "~/types/settings";
let store = useLabelEditorStore();
let dialog: Ref<boolean> = ref<boolean>(false);
let loading: Ref<boolean> = ref<boolean>(false);
watch(dialog, async (oldDialog) => {
if (oldDialog) {
loading.value = true;
await store.loadSettings();
loading.value = false;
}
})
async function updateSettings(name: string, value: string) {
if (store.settings != null) {
switch (name) {
case "MHD":
console.log("Update MHD: " + value);
const settingsMhd = new Settings(store.settings.id, value, store.settings.bio);
await store.updateSettings(settingsMhd);
break;
case "BIO":
console.log("Update BIO: " + value);
const settingsBio = new Settings(store.settings.id, store.settings.mhd, value);
await store.updateSettings(settingsBio);
break;
default:
console.log("Error: Unbekannter Wert für Einstellungen");
}
}
}
function closeDialog() {
dialog.value = false;
}
</script>
<template>
<v-dialog
v-model="dialog"
:scrollable="true"
width="800"
max-height="750"
height="750"
>
<template v-slot:activator="{ props }">
<v-btn
:flat="true"
v-bind="props"
size="small"
>
<v-icon>mdi-archive</v-icon>
<v-tooltip
activator="parent"
location="bottom"
>
Einstellungen
</v-tooltip>
</v-btn>
</template>
<v-card>
<v-card-title>
<v-row style="padding-top: 10px">
<v-icon size="small">
mdi-archive
</v-icon>
Einstellungen
<v-progress-circular v-if="loading" indeterminate :size="15" :width="2"></v-progress-circular>
<v-spacer/>
<v-divider vertical/>
<LabelCreate/>
</v-row>
</v-card-title>
<v-divider/>
<v-card-text v-if="store.settings != null">
<SettingsRow
key="mhd"
name="MHD"
v-bind:value="store.settings.mhd"
@update="updateSettings"
/>
<SettingsRow
key="bio"
name="BIO"
v-bind:value="store.settings.bio"
@update="updateSettings"
/>
</v-card-text>
<v-card-text v-else>
Fehler beim laden der Einstellungen
</v-card-text>
<v-divider/>
<v-card-actions>
<v-spacer/>
<v-btn
variant="text"
:disabled="loading"
@click="closeDialog()"
>
Schließen
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</template>
<style scoped>
</style>
@@ -0,0 +1,110 @@
<script setup lang="ts">
const props = defineProps({
name: {type: String, required: true},
value: {type: String, required: true},
});
const emit = defineEmits(['update']);
let edit: Ref<boolean> = ref<boolean>(false);
let value: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.value)));
function toggleEdit() {
if (edit.value) {
disableEdit();
} else {
enableEdit();
}
}
function enableEdit() {
edit.value = true;
}
function disableEdit() {
value.value = JSON.parse(JSON.stringify(props.value));
edit.value = false;
}
async function updateSetting() {
if (value.value != null && value.value.trim().length > 0) {
emit('update', props.name, value.value);
disableEdit();
}
}
</script>
<template>
<v-card>
<v-card-title>
<v-row style="padding-top: 10px">
{{ props.name }}
<v-spacer />
<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="updateSetting()"
>
<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-card-text>
<v-text-field
v-model.trim="value"
:readonly="!edit"
/>
</v-card-text>
</v-card>
</template>
<style scoped>
</style>
+34
View File
@@ -6,6 +6,7 @@ import {Origin} from "~/types/origin";
import type {Variant} from "~/types/variant";
import {Unit} from "~/types/unit";
import type {Label} from "~/types/label";
import type {Settings} from "~/types/settings";
interface State {
config: RuntimeConfig,
@@ -24,6 +25,8 @@ interface State {
labels: Array<Label>,
settings: Settings | null,
origins: Array<Origin>,
units: Array<Unit>,
}
@@ -46,6 +49,8 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
labels: [],
settings: null,
origins: [
Origin.EU,
Origin.NonEU,
@@ -122,6 +127,35 @@ export const useLabelEditorStore = defineStore('label_editor_store', {
this.addNotification(false, "Benachrichtigungen gelöscht")
},
// Settings
async loadSettings() {
try {
this.settings = await $fetch<Settings>(this.config.public.url + '/settings', {
method: 'GET',
});
this.addNotification(false, 'Einstellungen geladen');
} catch {
this.addNotification(true, 'Fehler beim laden der Einstellungen');
}
},
async updateSettings(settings: Settings) {
try {
this.settings = await $fetch<Settings>(this.config.public.url + '/settings', {
method: 'POST',
body: JSON.stringify(settings),
});
this.addNotification(false, 'Einstellungen aktualisiert.');
} catch {
this.addNotification(true, 'Fehler beim aktualisieren der Einstellungen.');
}
},
// Labels:
async loadLabels() {
try {
const labels: Array<Label> = await $fetch<Array<Label>>(this.config.public.url + '/label', {
+11
View File
@@ -0,0 +1,11 @@
export class Settings {
readonly id: number;
mhd: string;
bio: string;
constructor(id: number, mhd: string, bio: string) {
this.id = id;
this.mhd = mhd;
this.bio = bio;
}
}
@@ -0,0 +1,12 @@
-- Add migration script here
-- Create Label
CREATE TABLE settings
(
id bigint NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 ),
mhd text NOT NULL,
bio text NOT NULL
);
-- Insert default values
INSERT INTO settings (mhd, bio) VALUES ('Mindestens haltbar bis:', 'DE-ÖKO 006');
+49
View File
@@ -17,6 +17,7 @@ use tracing::info;
use http::header::{AUTHORIZATION, ACCEPT, ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE, ACCESS_CONTROL_ALLOW_CREDENTIALS};
use common::models::article;
use common::models::label::{delete_label, insert_label, load_labels, update_label, Label};
use common::models::settings::{load_settings, update_settings, Settings};
use common::models::unit::Unit;
use common::models::variant::{delete_variant, insert_variant, update_variant, Variant};
@@ -60,6 +61,9 @@ async fn main() {
.route("/label", post(add_label_route))
.route("/label/{id}", post(update_label_route))
.route("/label/{id}", delete(delete_label_route))
.route("/settings", get(get_settings_route))
.route("/settings", post(update_settings_route))
.with_state(pool)
.layer(cors);
@@ -352,3 +356,48 @@ async fn delete_label_route(
}
}
}
#[tracing::instrument(ret)]
async fn get_settings_route(
State(pool): State<PgPool>,
) -> (StatusCode, Json<Settings>) {
info!("Get settings");
match load_settings(&pool).await {
Some(settings) => {
(StatusCode::OK, Json(settings))
}
None => {
(StatusCode::INTERNAL_SERVER_ERROR, Json(
Settings {
id: 0,
mhd: "".to_string(),
bio: "".to_string(),
}
))
}
}
}
#[tracing::instrument(ret)]
async fn update_settings_route(
State(pool): State<PgPool>,
Json(payload): Json<Settings>,
) -> (StatusCode, Json<Settings>) {
info!("Update settings");
match update_settings(&payload, pool).await {
Some(settings) => {
(StatusCode::OK, Json(settings))
}
None => {
(StatusCode::INTERNAL_SERVER_ERROR, Json(
Settings {
id: 0,
mhd: "".to_string(),
bio: "".to_string(),
}
))
}
}
}